Skip to content

Improve type checking in tests - #684

Merged
marcpaterno merged 37 commits into
masterfrom
improve-type-checking-in-tests
Oct 28, 2026
Merged

marcpaterno merged 37 commits into
masterfrom
improve-type-checking-in-tests

Conversation

@marcpaterno

@marcpaterno marcpaterno commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Enable strict mypy checking for tests/ and give test functions, fixtures, mocks, and callbacks explicit types. Shared fixture aliases and records in tests/_types.py keep the annotations consistent. The follow-up annotations in the cluster, relocation, and base-likelihood tests are folded into the bottom commit.

This PR changes tests and developer guidance; it does not change library code or public API.

Evidence

  • Before: The test package opted out of disallow_untyped_defs; the remaining annotations produced mypy errors.
  • After: make lint passes, including mypy across 339 source files. The 36 targeted tests pass.

Merge Danger

Door: Two-way. The changes can be reverted without a data migration.

Blast Radius: Tests. Strict checking may expose future untyped test definitions in CI.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

PR revision: 1210152d34b65369a5757499e9684082e986d0ae
Target: master

No breaking API changes detected.

PR public API verdict

No breaking API changes detected.

Target: master
Revision: 1210152d34b65369a5757499e9684082e986d0ae
Baseline: 93676810d8b36a0fafc9d41a7671429618ae2f4a

Static analysis only: no behavioral compatibility guarantee or external-dependency signature analysis.

Public API changes: 9367681 -> HEAD

Executive summary

No breaking API changes detected.

Breaking changes

None.

New public API

None.

Complete report artifact and workflow run | API job

@codecov

codecov Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.0%. Comparing base (9367681) to head (1210152).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #684   +/-   ##
=======================================
  Coverage   100.0%   100.0%           
=======================================
  Files         163      163           
  Lines        9979     9979           
  Branches     1199     1199           
=======================================
  Hits         9979     9979           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@marcpaterno
marcpaterno requested a review from vitenti October 16, 2026 23:31
@marcpaterno

Copy link
Copy Markdown
Collaborator Author

Because this is a large PR (touching many files), here is an AI-generated summary (generated by gpt-6.1-sol at high effort level). My prompt was:

Search through all the commits in https://github.com/LSSTDESC/firecrown/pull/684. 
Several of the commits affect the behavior of code.
Give me a list of links to all of the PRs that affect code behavior.

The "I" in the following is gpt-6.1-sol.

I reviewed the diffs of all 36 commits in PR #684. The relevant changes are individual commits within that PR, so the links below point to commits. None changes production-library code under firecrown/.

Test Logic And Fixtures

  • 5171418: Strengthen metadata tests: Adds executable TomographicBin assertions and moves dictionary-membership assertions before lookups, changing missing-key failures from KeyError to AssertionError.
  • 154b08e: Strengthen NumCosmo fixtures: Changes map_cosmo_spec_nl to use the real XCDM cosmology fixture instead of a mock. This fixture appears unused.
  • ad8537f: Annotate two-point integration tests: Changes FakeSource.create_tracers() from returning [] to raising NotImplementedError.
  • 5958782: Clarify single-bin fixtures: Changes six fixtures from (sacc_data, z, dndz) to (sacc_data, TomographicBin), with copied arrays; makes TrivialSourceGalaxy.create_tracers() raise NotImplementedError; and changes the CMB read test to use an empty SACC object.
  • 5e32439: Clarify no-data setup: Renames the lens no-data fixture, changes its return value from a tuple to a SACC object, removes an array construction, and renames two tests.

Mock Calling Contracts
These narrow accepted arguments, although the existing valid calls still produce the same results:

Other Non-Annotation Changes

The remaining commits contain annotations, behavior-preserving casts or rewrites, formatting, imports needed for annotations, or documentation changes.

Annotate test returns, mock fixtures, fixture parameters, and source
update/reset callbacks to improve static type checking.

Remove the unused FakeSource implementation and source_pair fixture
from the two-point theory tests. (requiring type annotations noted
that it was returning the wrong type; only because it was unused was
it not causing runtime failures).
Add precise fixture types and return annotations to improve static type
checking. Move a tracer-pair membership assertion before its lookup.
Add a shared TypedDict for cosmology fixtures and annotate fixture
returns, test parameters, and dynamically selected fixture values.

Use the real XCDM fixture instead of the mock in map_cosmo_spec_nl.
Move imports to module scope and document local Pylint suppressions
for introspected NumCosmo APIs and intentional protected access.
Annotate FakeSource methods and both integration tests with explicit
types (sacc.Sacc, ParamsMap, ModelingTools, Tracer, -> None).

FakeSource.create_tracers now raises NotImplementedError instead of
returning an empty list, so any accidental call fails loudly. The
update and reset tests do not exercise create_tracers.
Replace the .conda-env-specific instructions in docs/agents/python.md
with a generic requirement to run checks in an active, isolated
environment (conda, venv, or agent sandbox) and verify that python,
mypy, and black resolve to that same environment. Also fix two typos
in the monkeypatching guidance ("monkeypatching it the" and the
missing colon after "Avoid monkeypatching").
Represent expected galaxy redshift distributions with TomographicBin
rather than two bare NumPy arrays. The domain type makes the fixture
contract explicit: a named tomographic bin with redshift samples,
distribution values, and supported measurement types.

Migrate six single-galaxy-bin fixtures to return (sacc_data, expected_bin).
Construct expected bins directly from known inputs, with copied arrays
and explicit measurement types. Update consumers to use expected_bin.z
and expected_bin.dndz while preserving extraction calls and assertions.

Add explicit type annotations to test fixtures and functions.

Make TrivialSourceGalaxy.create_tracers raise NotImplementedError because
the test subclass only supports source argument handling. Remove the
unnecessary galaxy-fixture dependency from test_cmb_convergence_read and
create a local empty sacc.Sacc() instead.
Reflow multi-line function signatures in fctools tests onto single lines
to match the project's formatter. No behavior or test logic changes.
Annotate test methods, fixtures, and mock functions in
tests/fctools/test_list_tools.py with parameter and return types
(Path, pytest.MonkeyPatch, NoReturn, object). Adds the typing and
pytest imports needed for these annotations. No test logic changes.
Annotate test functions in test_statistic.py with `-> None` return types
and parameter types (sacc.Sacc, list[stat.TrivialStatistic]) for mypy
coverage. No test logic changes.
Add explicit parameter and return types to two-point tests and fixtures.

Rename and simplify the lens0 no-data fixture to return only its SACC
tracer. Clarify test names, variables, and docstrings to distinguish
theta-grid setup without measurements from physical predictions.
Annotate test function signatures and fixtures in
test_const_gaussianPM.py so mypy checks the file. Add typed imports
(Callable, cast, TwoPointFactory, GuardedStatistic). Wrap mock statistic
containers in cast(GuardedStatistic, ...) where they are passed to PM
internals, and annotate the attributes of IncompleteStatistic. No runtime
behavior changes.
Annotate fixtures, test functions, and their parameters in
tests/likelihood/test_weak_lensing.py with Mock, WeakLensingArgs, and
None return types so the module can be checked by mypy.
Compose fixture annotations from redshift distribution and windowed
spectrum aliases, and reuse them across Gaussian and metadata tests.
Keep NumCosmo imports type-only and complete ConstGaussian test
annotations.
Add type hints to test functions, fixtures, and helper callbacks in
tests/fctools so they pass mypy strict checking. Parameters are annotated
with pytest types (MonkeyPatch, CaptureFixture) and Path, and mock
callbacks with requests.Session and Callable. Move the Path import in
test_symbol_reference_checker.py to module level, and give the invalid
symbol-map test a typed local variable. No test logic changes.
Add parameter and return annotations to test functions, fixtures, and
helpers across tests/, so the test suite passes stricter mypy checks.
Annotations use project types where available (ModelingTools,
TrivialStatistic, CCLCreationMode, sacc.Sacc) and numpy.typing arrays.

Where annotations cannot express the code's behavior, add targeted
suppressions and a cast:
- test_descriptors.py: __str__ returning None is kept as a deliberate
  negative-test double, marked with type: ignore[override].
- test_modeling_tools_ccl_factory.py: cast the cosmology dict to
  dict[str, float] before passing it to ParamsMap.
- test_utils.py: read pytestmark via type: ignore[attr-defined] in the
  two YAML serialization tests that check parametrization coverage.

No runtime behavior changes; only test annotations, a cast, and
suppression comments were added, plus imports needed for the annotations.
Annotate parameters and return types in the likelihood test scripts,
lkdir fixtures, and test functions under tests/likelihood/. Script
factories now declare NamedParameters inputs and typed
(likelihood, ModelingTools) return tuples. Test helpers in
test_binned_cluster_number_counts.py and test_student_t.py take typed
arguments, with Completeness and Purity imported from crow. No runtime
behavior changes.
Comment out the `[[tool.mypy.overrides]]` block for `tests` that set
`disallow_untyped_defs = false`. Tests now inherit the global
`disallow_untyped_defs = true`, so mypy requires type annotations on
test function definitions. The commented-out replacement line sets
`disallow_untyped_defs = true`, which matches the inherited value.
@marcpaterno
marcpaterno force-pushed the improve-type-checking-in-tests branch from af86271 to 45c7d5a Compare October 25, 2026 01:06
@marcpaterno
marcpaterno added this pull request to stack #699 October 25, 2026 01:06
@vitenti

vitenti commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Hello @marcpaterno , three things:

  1. map_cosmo_spec_nl is no longer being used by anything, should we just remove it?
  2. .conda-env instructions were dropped in favor to a more generic activate environment, do we want that?
  3. in 4de8ad1 the NumCosmo import in tests/_types.py was moved behind TYPE_CHECKING, but numcosmo_py is a required dependency in pyproject.toml, and tests/conftest.py imports it anyway through firecrown, so the guard changes nothing at runtime. Can we go back to a plain from numcosmo_py import Nc, or was there another reason for it?

Import numcosmo_py.Nc directly in tests/_types.py so
NumCosmoCosmologyFixture annotations no longer need string
forward references. Remove the unused map_cosmo_spec_nl
fixture from test_numcosmo_mapping.py.
@marcpaterno
marcpaterno merged commit 15043d4 into master Oct 28, 2026
16 checks passed
@marcpaterno
marcpaterno deleted the improve-type-checking-in-tests branch October 28, 2026 02:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants