From 7393a204c38b8a94cc8191fde0acaed77edb5f2f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 16:47:22 +0000 Subject: [PATCH] Let other packages use the test fixtures as a pytest plugin A package that counts or generates with mapFolding registers `pytest_plugins = ('mapFolding.tests.conftest',)` and receives the fixtures by name. - `testing` extra: installs everything `mapFolding.tests` imports, including dulwich, without which `mapFolding.oeis` cannot be imported. The `testing` group now builds on it. - Package data: the `.album` and `.pkl` samples in `tests/dataSamples`. Without the `.pkl` files, the released `getDataFrameFoldings` and the `arrayFoldings` fixture fail outside a checkout. - `identifiers` fixture: a `Default` whose `pathRoot` is a directory one test owns, changed in place, so a generator and its entry point write there. - `argv` fixture removed: the `OEIS_for_n` tests set `sys.argv` with `monkeypatch`. - README: how to test your own algorithms, and corrected test module names and install command. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GMd3z8bGZQ5aV7bsZxiFzi --- README.md | 38 +++++++++++++++++++++++++++++------ mapFolding/tests/__init__.py | 11 +++++++++- mapFolding/tests/conftest.py | 21 ++++++++++++------- mapFolding/tests/test_oeis.py | 12 +++++++---- pyproject.toml | 6 +++--- 5 files changed, 67 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 4aa70f25..da37a612 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ You can use the package to calculate sequence terms, dissect an algorithm's stat | Inspect or change a computation | [`dataBaskets.py`](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/dataBaskets.py) describes the state containers; [`algorithms/`](https://github.com/hunterhogan/mapFolding/tree/main/mapFolding/algorithms/) contains source implementations. | | Transform or specialize an algorithm | [`kitAST/`](https://github.com/hunterhogan/mapFolding/tree/main/mapFolding/kitAST/) generates variants and jobs, with derived implementations in [`synthesized/`](https://github.com/hunterhogan/mapFolding/tree/main/mapFolding/synthesized/). | | Explore a different search strategy | [`algorithms/`](https://github.com/hunterhogan/mapFolding/tree/main/mapFolding/algorithms/) contains elimination, constraint propagation, and insertion; package modules provide search-space analysis. | -| Validate a new implementation | [`test_algorithms.py`](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/tests/test_algorithms.py) compares implementations with known sequence values. | +| Validate a new implementation | [`tests/`](https://github.com/hunterhogan/mapFolding/tree/main/mapFolding/tests/) compares implementations with known sequence values; [another package can use its fixtures](#test-your-own-algorithms-with-the-mapfolding-tests). | The module, function, and class docstrings explain parameters, state layouts, mathematical relationships, and implementation details. Use them when choosing an experiment or following a computation through the package. @@ -233,7 +233,7 @@ NumPy and Numba are included in the base dependencies. Optional extras add other | `pandas` | Pandas and Arrow meander implementations | | `codon` | [Codon](https://docs.exaloop.io/)-compiled jobs on Linux | | `ortools` | Experimental constraint propagation; installed only on Python versions below 3.15 | -| `testing` | Test dependencies and optional implementations exercised by the tests | +| `testing` | Everything that `mapFolding.tests` imports, for testing your own algorithms | | `development` | Profiling, notebooks, type stubs, and development tools | For example: @@ -266,19 +266,45 @@ On a POSIX shell: . .venv/bin/activate ``` -Then install the development and testing extras: +Then install the package with the development and testing dependency groups: ```console -pip install -e ".[development,testing]" +pip install -e . --group development --group testing ``` Run project commands from the repository root with the environment active. For example, to check the main counting implementations: ```console -pytest mapFolding/tests/test_algorithms.py +pytest mapFolding/tests/test_basecamp.py ``` -The tests compare algorithm variants with known OEIS values and exercise generated jobs. When adding a counting implementation, extend the relevant test cases in [`test_algorithms.py`](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/tests/test_algorithms.py). Triangle conversions, OEIS updates, and sequence formulas have dedicated checks in `test_dataStructures.py`, `test_oeis.py`, and `test_oeis_byFormula.py`; supporting behavior has its own tests in `mapFolding/tests`. +The tests compare algorithm variants with known OEIS values and exercise generated jobs. When adding a counting implementation, add its `flow` to the parametrization of the relevant test in [`test_basecamp.py`](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/tests/test_basecamp.py). Triangle conversions, OEIS updates, and sequence formulas have dedicated checks in `test_dataStructures.py`, `test_oeis.py`, and `test_byFormula.py`; supporting behavior has its own tests in `mapFolding/tests`. + +### Test your own algorithms with the mapFolding tests + +A package that counts with `mapFolding`, or generates its own modules with `mapFolding.kitAST`, can use the fixtures of `mapFolding.tests` as an ordinary pytest plugin. Add `mapFolding[testing]` to its testing dependencies, then register the plugin in the root `conftest.py` of its tests: + +```python +pytest_plugins = ('mapFolding.tests.conftest',) +``` + +Each test receives the fixtures by name. `expected` is a(n) of the test's `oeisID` and `n` parameters, read from the b-file that `mapFolding.oeis` stores, and `identifiers` gives a module generator a `pathRoot` that one test owns: + +```python +from itertools import product as CartesianProduct +from hunterMakesPy.tests import assertEqualTo +from mapFolding.dataBaskets import StateMapFolding +from mapFolding.oeis import makeMapShape +from yourPackage import counting +import pytest + +@pytest.mark.parametrize('oeisID, n', tuple(CartesianProduct(('A001417',), range(3, 7)))) +def test_doTheNeedful(oeisID: str, n: int, expected: int) -> None: + mapShape: tuple[int, ...] = makeMapShape(oeisID, n) + assertEqualTo(counting.doTheNeedful(StateMapFolding(mapShape)).totalFolds, expected, counting.doTheNeedful.__name__, mapShape) +``` + +Each fixture in [`mapFolding/tests/conftest.py`](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/tests/conftest.py) documents what it yields, and [`mapFolding/tests/__init__.py`](https://github.com/hunterhogan/mapFolding/blob/main/mapFolding/tests/__init__.py) describes the samples that the distribution includes. ## The supplemental guides explain the notation and how to type it diff --git a/mapFolding/tests/__init__.py b/mapFolding/tests/__init__.py index e9dc8941..f7a9bb46 100644 --- a/mapFolding/tests/__init__.py +++ b/mapFolding/tests/__init__.py @@ -2,7 +2,8 @@ Test package organization (in mapFolding/tests/): - conftest.py: Fixtures: job directories, album directories, b-file directories, known values, the processor total, written - files, Numba jobs, enumerated foldings, and expected values and triangle cells from OEIS + files, Numba jobs, output directories of module generators, enumerated foldings, and expected values and triangle cells + from OEIS - conftestAnnex.py: Assertion helpers for mapFolding's own domain objects, re-exported here - dataSamples/: Samples shared by several test modules, and facts about them - test_A400429.py: Diagonals of the semi-meander triangle, the A005315 anchors, and rational-series coefficients @@ -30,6 +31,14 @@ Each test module holds its own parametrization, imports its assertion helpers from `mapFolding.tests` and its shared samples from `mapFolding.tests.dataSamples`, and receives the fixtures in `conftest.py` by name. + +Another package that counts or generates with `mapFolding` tests its own algorithms with this infrastructure: +- Its testing dependencies include `mapFolding[testing]`, which installs everything that this package's tests import. +- Its root `conftest.py` registers this suite's fixtures as a plugin: `pytest_plugins = ('mapFolding.tests.conftest',)`. +- Its `tests/__init__.py` re-exports the assertion helpers of `hunterMakesPy.tests`, and the helpers here that it uses. +- Its tests receive the fixtures by name. `expected` is a(n) of the `oeisID` and `n` parameters, from the stored b-file; + `identifiers` gives a generator a `pathRoot` that one test owns; `albumKnown`, `arrayFoldings`, and `pathAlbum` read the + albums and enumerated foldings in `dataSamples`, which the distribution includes. """ from __future__ import annotations diff --git a/mapFolding/tests/conftest.py b/mapFolding/tests/conftest.py index 83881b82..4b75384e 100644 --- a/mapFolding/tests/conftest.py +++ b/mapFolding/tests/conftest.py @@ -1,4 +1,8 @@ -"""Fixtures that own temporary files, package state, the processor total, and expensive immutable objects.""" +"""Fixtures that own temporary files, package state, the processor total, and expensive immutable objects. + +Another package that counts with `mapFolding` receives these fixtures by registering this module as a plugin in its root +`conftest.py`: `pytest_plugins = ('mapFolding.tests.conftest',)`. +""" from __future__ import annotations from functools import partial @@ -23,12 +27,11 @@ from unittest.mock import patch import numpy import pytest -import sys if TYPE_CHECKING: from collections.abc import Iterator from mapFolding.oeis import OEISid - from mapFolding.theTypes import Folding, 形Triangle + from mapFolding.theTypes import Default, Folding, 形Triangle from numpy.typing import NDArray @pytest.fixture @@ -126,10 +129,14 @@ def job(request: pytest.FixtureRequest, tmp_path: Path) -> RecipeJobTheorem2: , pathFilenameTotalFolds=PurePosixPath(tmp_path, 'jobNumba.totalFolds'), totalFoldsMultiplier=state.totalLeaves) @pytest.fixture -def argv(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> list[str]: - """Command-line arguments `request.param` in `sys.argv` for one test.""" - monkeypatch.setattr(sys, 'argv', list(request.param)) - return sys.argv +def identifiers(request: pytest.FixtureRequest, tmp_path: Path) -> Iterator[Default]: + """The `Default` in `request.param`, whose `pathRoot` is a directory owned by one test. + + `pathRoot` changes in place, so a generator that reads the same `Default` from its package also writes there. `pathRoot` is + restored after the test. + """ + with patch.dict(request.param['filesystem'], pathRoot=PurePosixPath(tmp_path)): + yield request.param @pytest.fixture def cpuTotal(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> Iterator[int]: diff --git a/mapFolding/tests/test_oeis.py b/mapFolding/tests/test_oeis.py index 6bcc28c5..09bb3b9d 100644 --- a/mapFolding/tests/test_oeis.py +++ b/mapFolding/tests/test_oeis.py @@ -16,6 +16,7 @@ from typing import TYPE_CHECKING import pytest import re as regex +import sys if TYPE_CHECKING: from _pytest.capture import CaptureResult @@ -156,9 +157,10 @@ def test_getOEISids(capsys: pytest.CaptureFixture[str], oeisID: OEISid) -> None: , pytest.param(('OEIS_for_n', 'A001415', '6'), 10512, id='A001415-6') , pytest.param(('OEIS_for_n', 'A000560', '3'), 2, id='A000560-3') , pytest.param(('OEIS_for_n', 'A001418', '1'), 1, id='A001418-1') -), indirect=['argv']) -def test_OEIS_for_n(capsys: pytest.CaptureFixture[str], argv: list[str], expected: int) -> None: +)) +def test_OEIS_for_n(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch, argv: tuple[str, ...], expected: int) -> None: """Reference: A000136(3), A001415(3), the documented example A001415(6), A000560(3), and A001418(1) in the OEIS b-files.""" + monkeypatch.setattr(sys, 'argv', list(argv)) OEIS_for_n() printed: CaptureResult[str] = capsys.readouterr() assertEqualTo(printed.err, '', OEIS_for_n.__name__, argv) @@ -172,11 +174,13 @@ def test_OEIS_for_n(capsys: pytest.CaptureFixture[str], argv: list[str], expecte , pytest.param(('OEIS_for_n', 'A001415', 'NE'), 2, '', r'(?s).*invalid int value.*', id='stringNE') , pytest.param(('OEIS_for_n', 'A001418', '0'), 1, '', r'(?s)Error: .*not defined.*offset.*', id='belowOffset') , pytest.param(('OEIS_for_n', '--help'), 0, r'(?s).*Available OEIS sequences:.*Usage examples:.*', '', id='help') -), indirect=['argv']) -def test_OEIS_for_nError(capsys: pytest.CaptureFixture[str], argv: list[str], exitCode: int, patternOut: str, patternErr: str) -> None: +)) +def test_OEIS_for_nError(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch, argv: tuple[str, ...], exitCode: int, patternOut: str + , patternErr: str) -> None: """Reference: `argparse` exits with code 2 and its usage error, or with code 0 after `--help`; `OEIS_for_n` exits with code 1 and its message. """ + monkeypatch.setattr(sys, 'argv', list(argv)) with pytest.raises(SystemExit) as exitInformation: OEIS_for_n() printed: CaptureResult[str] = capsys.readouterr() diff --git a/pyproject.toml b/pyproject.toml index 113801e7..1ec95837 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,7 +56,7 @@ dependencies = [ "tqdm", "typing_extensions>=4.16.0", ] -optional-dependencies = { codon = ["codon-jit>=0.4.6; sys_platform == 'linux'", "lief; sys_platform == 'linux'"], oeisdata = ["dulwich>=1.2.21"], ortools = ["ortools"], pandas = ["pandas", "pyarrow"], polars = ["polars>=1.44.2"] } +optional-dependencies = { codon = ["codon-jit>=0.4.6; sys_platform == 'linux'", "lief; sys_platform == 'linux'"], oeisdata = ["dulwich>=1.2.21"], ortools = ["ortools"], pandas = ["pandas", "pyarrow"], polars = ["polars>=1.44.2"], testing = ["dulwich>=1.2.21", "hypothesis", "pandas", "pyarrow", "pytest>=9.0", "pytest-xdist"] } [project.urls] Context7 = "https://context7.com/hunterhogan/mapfolding" @@ -69,7 +69,7 @@ Repository = "https://github.com/hunterhogan/mapFolding.git" [dependency-groups] development = ["gmpy2-stubs", "google-api-python-client-stubs>=1.35.0", "ipykernel", "ipywidgets", "matplotlib", "memray; sys_platform == 'linux'", "mpmath>=1.4.0", "networkx", "pandas-stubs", "py-spy", "pyarrow-stubs", "pytest-cov", "setuptools", "types-networkx", "types-tqdm"] -testing = ["dulwich", "hypothesis", "ortools", "pandas", "polars>=1.44.2", "pyarrow", "pytest>=9.0", "pytest-env", "pytest-xdist"] +testing = ["mapFolding[testing]", "ortools", "polars>=1.44.2", "pytest-env"] [build-system] requires = ["setuptools"] @@ -307,7 +307,7 @@ skip-magic-trailing-comma = true # === OK_EDIT: path-sync hunterhogan === [tool.setuptools] -package-data = { "*" = ["py.typed"], mapFolding = ["_semiotics.md", "_symbols.md", "oeis/oeisdata/**/*", "oeis/terms/**/*"] } +package-data = { "*" = ["py.typed"], mapFolding = ["_semiotics.md", "_symbols.md", "oeis/oeisdata/**/*", "oeis/terms/**/*", "tests/dataSamples/*.album", "tests/dataSamples/*.pkl"] } packages = { find = { include = ["mapFolding*"] } } # === DO_NOT_EDIT: path-sync hunterhogan ===