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 f91ac3ff..56e51d50 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, expected values and triangle cells from OEIS, and the command that runs `importModules.py` + files, Numba jobs, output directories of module generators, enumerated foldings, expected values and triangle cells from + OEIS, and the command that runs `importModules.py` - 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 @@ -34,6 +35,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 f51f5303..b3d22f01 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, a command, and expensive immutable objects.""" +"""Fixtures that own temporary files, package state, the processor total, a command, 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 @@ -33,7 +37,7 @@ 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 from typing import Any @@ -132,10 +136,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/mapFolding/tests/test_pyproject.py b/mapFolding/tests/test_pyproject.py index 1c8e344a..96b711f9 100644 --- a/mapFolding/tests/test_pyproject.py +++ b/mapFolding/tests/test_pyproject.py @@ -41,14 +41,18 @@ def test_dependencies(commandImport: list[str], extra: str, expected: Mapping[st pytest.param('oeisdata', {'mapFolding.kitGit'}, id='oeisdata'), pytest.param('ortools', {'mapFolding.algorithms.constraintPropagation'}, id='ortools'), pytest.param('pandas', {'mapFolding.algorithms.matrixMeandersPandas', 'mapFolding.synthesized.matrixMeanders.prunePandas'}, id='pandas'), + pytest.param('testing', {'mapFolding.tests', 'mapFolding.tests.conftest', 'mapFolding.tests.conftestAnnex'}, id='testing'), )) def test_optionalDependencies(commandImport: list[str], extra: str, boxOfModule: set[str]) -> None: """After `pip install mapFolding[extra]`, each module in `boxOfModule` imports. Reference: the modules in the `expected` of `test_dependencies` that lack an import name that `extra` supplies. A distribution in `extra` can require a distribution in another extra, as `ortools` requires `pandas`, so this test ignores other modules. + `testing` also supplies the plugin `mapFolding.tests.conftest` and the annex that `mapFolding.tests` re-exports, which + another package's tests import. - Gap: the `testing` dependency group does not install the distributions of the `codon` extra. No module imports `polars`. + Gap: the `testing` dependency group does not install the distributions of the `codon` extra. No module imports `polars`. The + fixtures that read `dataSamples` call `pandas` and `pyarrow`, which the `testing` extra supplies, only when they run. """ assertEqualTo(boxOfModule.intersection(json.loads(subprocess.run(commandImport, check=True, stdout=subprocess.PIPE).stdout)) , set(), 'import_module', extra=extra) diff --git a/pyproject.toml b/pyproject.toml index 16977b73..7d40c8c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,7 +66,14 @@ optional-dependencies = { codon = [ ], pandas = [ "pandas", "pyarrow", -], polars = ["polars>=1.44.2"] } +], polars = ["polars>=1.44.2"], testing = [ + "hypothesis", + "packaging", + "pandas", + "pyarrow", + "pytest>=9.0", + "pytest-xdist", +] } [project.urls] Context7 = "https://context7.com/hunterhogan/mapfolding" @@ -79,7 +86,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", "packaging", "pandas", "polars>=1.44.2", "pyarrow", "pytest>=9.0", "pytest-env", "pytest-xdist"] +testing = ["dulwich", "mapFolding[testing]", "ortools", "polars>=1.44.2", "pytest-env"] [build-system] requires = ["setuptools"] @@ -317,7 +324,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 ===