Skip to content

Testing

quivers.testing runs the in-language tests of QVR modules: their test, property and example declarations and the examples written in their doc comments. run_paths discovers modules and packages and runs every test on the reference machine; mutate_module runs a module's tests against every mutant of its code. The meaning of a test, an exact run, and a mutation run is stated in Tests and exact evaluation.

runner

Discover and run a module's tests, properties, and examples.

run_module checks one .qvr module and runs every test it declares (Module.tests): its test, property and example declarations and the examples written in its doc comments. run_paths does so for files and directories (a directory is a package: every module under it), and returns a TestReport whose TestReport.to_data is the machine-readable report qvr test --json prints.

A test's body runs once. A property's body runs once per assignment of its variables: every assignment when each variable ranges over a finite set, checked exhaustively up to the declaration's limit; otherwise cases assignments drawn from the declaration's seed, with sizes growing up to size, and a failing assignment shrunk to a minimal one. All of these are pinned in the declaration's options; nothing on the command line changes them.

A test evaluates exactly, over the rationals, unless an expectation states a tolerance with within, which makes it floating (float64), or its options say numbers=float64 or numbers=float32. An equality of reals states which it means: exactly in an exact test, within in a floating one.

Numbers

Numbers = Literal['exact', 'float64', 'float32']

The number domain a test runs in.

Status

Status = Literal['passed', 'failed', 'error']

How a test ended.

SourceLoader

SourceLoader = Callable[[Path], tuple[bytes, tuple[TestDecl, ...]]]

Read one module file: its QVR source, and any tests its format carries beyond the source (the checked examples of a literate module).

TestSettings didactic-model

TestSettings(*, numbers: Numbers, cases: int = 100, seed: int = 0, size: int = 20, limit: int = 10000, fuel: int = 1000000, shrinks: int = 1000)

Bases: Model

A test declaration's pinned options.

PARAMETER DESCRIPTION
numbers

The number domain: exact (rational) or a floating dtype.

TYPE: Numbers

cases

How many assignments a property draws when a variable ranges over an infinite type.

TYPE: int DEFAULT: 100

seed

The seed of those draws and of every program run.

TYPE: int DEFAULT: 0

size

The largest size a drawn value has.

TYPE: int DEFAULT: 20

limit

The most assignments an exhaustive check enumerates.

TYPE: int DEFAULT: 10000

fuel

The step budget of each run.

TYPE: int DEFAULT: 1000000

shrinks

The most candidates shrinking tries.

TYPE: int DEFAULT: 1000

TestDeclarationError

Bases: ValueError

A test declaration whose options or expectations are ill-formed.

ExpectationResult didactic-model

ExpectationResult(*, line: int, passed: bool, relation: str = '', left: str = '', right: str = '')

Bases: Model

One evaluated expectation.

PARAMETER DESCRIPTION
line

Its source line.

TYPE: int

passed

Whether it held.

TYPE: bool

relation

The comparison it checked, or "" for a truth value.

TYPE: str DEFAULT: ''

left

The rendered left side, or the truth value.

TYPE: str DEFAULT: ''

right

The rendered right side, or "".

TYPE: str DEFAULT: ''

describe

describe() -> str

The expectation as one line.

RETURNS DESCRIPTION
str

left relation right with the values it compared.

Source code in src/quivers/testing/runner.py
def describe(self) -> str:
    """The expectation as one line.

    Returns
    -------
    str
        ``left relation right`` with the values it compared.
    """
    if not self.relation:
        return f"line {self.line}: expected true, got {self.left}"
    verdict = "holds" if self.passed else "does not hold"
    return f"line {self.line}: {self.left} {self.relation} {self.right} {verdict}"

TestResult didactic-model

TestResult(*, kind: str, name: str, line: int, status: Status, subject: str = '', numbers: str = 'exact', message: str = '', expectations: tuple[ExpectationResult, ...] = (), cases: int = 0, exhaustive: bool = False, counterexample: dict[str, str] = field(default_factory=dict), shrinks: int = 0, cached: bool = False, digest: str = '', seconds: float = 0.0)

Bases: Model

The outcome of one test, property, or example.

PARAMETER DESCRIPTION
kind

test, property or example.

TYPE: str

name

Its title.

TYPE: str

line

Its source line.

TYPE: int

status

passed, failed (an expectation did not hold) or error (the test could not be evaluated).

TYPE: Status

subject

For a doc-comment example, the declaration it documents.

TYPE: str DEFAULT: ''

numbers

The number domain it ran in.

TYPE: str DEFAULT: 'exact'

message

Why it failed or erred; empty when it passed.

TYPE: str DEFAULT: ''

expectations

The expectations evaluated, up to the first that failed.

TYPE: tuple[ExpectationResult, ...] DEFAULT: ()

cases

How many assignments a property checked (1 for a test).

TYPE: int DEFAULT: 0

exhaustive

Whether a property enumerated every assignment.

TYPE: bool DEFAULT: False

counterexample

A failing property's minimal assignment, rendered by variable.

TYPE: dict[str, str] DEFAULT: field(default_factory=dict)

shrinks

How many shrinking steps reduced the counterexample.

TYPE: int DEFAULT: 0

cached

Whether the pass was read from the cache.

TYPE: bool DEFAULT: False

digest

The test's own content hash.

TYPE: str DEFAULT: ''

seconds

The wall time it took.

TYPE: float DEFAULT: 0.0

to_data

to_data() -> dict[str, str | int | float | bool | list | dict]

The result as JSON data.

RETURNS DESCRIPTION
dict

Every field, expectations as lists of their fields.

Source code in src/quivers/testing/runner.py
def to_data(self) -> dict[str, str | int | float | bool | list | dict]:
    """The result as JSON data.

    Returns
    -------
    dict
        Every field, expectations as lists of their fields.
    """
    data: dict[str, str | int | float | bool | list | dict] = {
        "kind": self.kind,
        "name": self.name,
        "line": self.line,
        "status": self.status,
        "numbers": self.numbers,
        "cases": self.cases,
        "exhaustive": self.exhaustive,
        "cached": self.cached,
        "digest": self.digest,
        "seconds": round(self.seconds, 6),
        "expectations": [
            {
                "line": item.line,
                "passed": item.passed,
                "relation": item.relation,
                "left": item.left,
                "right": item.right,
            }
            for item in self.expectations
        ],
    }
    if self.subject:
        data["subject"] = self.subject
    if self.message:
        data["message"] = self.message
    if self.counterexample:
        data["counterexample"] = dict(self.counterexample)
        data["shrinks"] = self.shrinks
    return data

ModuleReport didactic-model

ModuleReport(*, path: str, digest: str = '', results: tuple[TestResult, ...] = (), error: str = '')

Bases: Model

The tests of one module and how they ended.

PARAMETER DESCRIPTION
path

The module's file.

TYPE: str

digest

The content hash of the module's code, tests excluded.

TYPE: str DEFAULT: ''

results

One result per test, in source order.

TYPE: tuple[TestResult, ...] DEFAULT: ()

error

Why the module could not be tested (a parse or compile error); empty otherwise.

TYPE: str DEFAULT: ''

ok property

ok: bool

Whether the module loaded and every test passed.

RETURNS DESCRIPTION
bool

The verdict.

to_data

to_data() -> dict[str, str | bool | list]

The module's report as JSON data.

RETURNS DESCRIPTION
dict

Its path, digest, verdict, error, and results.

Source code in src/quivers/testing/runner.py
def to_data(self) -> dict[str, str | bool | list]:
    """The module's report as JSON data.

    Returns
    -------
    dict
        Its path, digest, verdict, error, and results.
    """
    data: dict[str, str | bool | list] = {
        "path": self.path,
        "digest": self.digest,
        "ok": self.ok,
        "results": [item.to_data() for item in self.results],
    }
    if self.error:
        data["error"] = self.error
    return data

TestReport didactic-model

TestReport(*, modules: tuple[ModuleReport, ...] = (), packages: tuple[str, ...] = ())

Bases: Model

The report of one qvr test run.

PARAMETER DESCRIPTION
modules

One report per module, in discovery order.

TYPE: tuple[ModuleReport, ...] DEFAULT: ()

packages

The directories given, each a package of the modules under it.

TYPE: tuple[str, ...] DEFAULT: ()

ok property

ok: bool

Whether every module loaded and every test passed.

RETURNS DESCRIPTION
bool

The verdict.

counts

counts(modules: Iterable[ModuleReport] | None = None) -> dict[str, int]

Tests by status.

PARAMETER DESCRIPTION
modules

The modules counted; every module when None.

TYPE: Iterable[ModuleReport] | None DEFAULT: None

RETURNS DESCRIPTION
dict[str, int]

passed, failed, error, cached, and modules_failed (modules that did not load).

Source code in src/quivers/testing/runner.py
def counts(self, modules: Iterable[ModuleReport] | None = None) -> dict[str, int]:
    """Tests by status.

    Parameters
    ----------
    modules : Iterable[ModuleReport] | None
        The modules counted; every module when ``None``.

    Returns
    -------
    dict[str, int]
        ``passed``, ``failed``, ``error``, ``cached``, and
        ``modules_failed`` (modules that did not load).
    """
    chosen = list(self.modules if modules is None else modules)
    results = [item for module in chosen for item in module.results]
    return {
        "passed": sum(item.status == "passed" for item in results),
        "failed": sum(item.status == "failed" for item in results),
        "error": sum(item.status == "error" for item in results),
        "cached": sum(item.cached for item in results),
        "modules_failed": sum(bool(module.error) for module in chosen),
    }

to_data

to_data() -> dict[str, bool | list | dict]

The machine-readable report.

RETURNS DESCRIPTION
dict

ok, summary counts, per-package counts, and every module's report.

Source code in src/quivers/testing/runner.py
def to_data(self) -> dict[str, bool | list | dict]:
    """The machine-readable report.

    Returns
    -------
    dict
        ``ok``, ``summary`` counts, per-package counts, and every
        module's report.
    """
    return {
        "ok": self.ok,
        "summary": self.counts(),
        "packages": {
            package: self.counts(
                module
                for module in self.modules
                if Path(module.path)
                .resolve()
                .is_relative_to(Path(package).resolve())
            )
            for package in self.packages
        },
        "modules": [module.to_data() for module in self.modules],
    }

CheckedModule didactic-model

CheckedModule(*, path: str, parsed: Module, checked: QiecModule = field(opaque=True, extras=OPAQUE_BY_VALUE), digest: str)

Bases: ValueModel

A parsed module and its checked QIEC module, ready for its tests.

PARAMETER DESCRIPTION
path

The file.

TYPE: str

parsed

The parsed module after its meta phase, tests included: the generated declarations spliced in and generated properties among the tests.

TYPE: Module

checked

The checked module, with one computation per property whose parameters are its variables.

TYPE: QiecModule DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

digest

The content hash of the module's code, tests excluded.

TYPE: str

binder_types

binder_types(test: TestDecl) -> tuple[TypeExpr, ...]

The checked types of a property's variables.

PARAMETER DESCRIPTION
test

A property of this module.

TYPE: TestDecl

RETURNS DESCRIPTION
tuple[TypeExpr, ...]

One type per variable.

Source code in src/quivers/testing/runner.py
def binder_types(self, test: TestDecl) -> tuple[TypeExpr, ...]:
    """The checked types of a property's variables.

    Parameters
    ----------
    test : TestDecl
        A property of this module.

    Returns
    -------
    tuple[TypeExpr, ...]
        One type per variable.
    """
    index = self.parsed.tests.index(test)
    name = f"{RUNNER_PREFIX}{index}"
    computation = next(
        item for item in self.checked.computations if item.name == name
    )
    return tuple(parameter.type for parameter in computation.parameters)

settings_of

settings_of(test: TestDecl) -> TestSettings

Read and check a declaration's options.

PARAMETER DESCRIPTION
test

The declaration.

TYPE: TestDecl

RETURNS DESCRIPTION
TestSettings

The settings, with the documented defaults for options not given.

RAISES DESCRIPTION
TestDeclarationError

If an option is unknown, repeated, or of the wrong kind; or an expectation's exactly or within does not fit the test's numbers or its term.

Source code in src/quivers/testing/runner.py
def settings_of(test: TestDecl) -> TestSettings:
    """Read and check a declaration's options.

    Parameters
    ----------
    test : TestDecl
        The declaration.

    Returns
    -------
    TestSettings
        The settings, with the documented defaults for options not given.

    Raises
    ------
    TestDeclarationError
        If an option is unknown, repeated, or of the wrong kind; or an
        expectation's ``exactly`` or ``within`` does not fit the test's
        numbers or its term.
    """
    values: dict[str, int] = dict(_DEFAULTS)
    numbers: Numbers | None = None
    seen: set[str] = set()
    for entry in test.options:
        if entry.key in seen:
            raise TestDeclarationError(
                f"line {entry.line}: option {entry.key!r} is given twice"
            )
        seen.add(entry.key)
        if entry.key == "numbers":
            value = entry.value
            name = value.value if isinstance(value, OptionName | OptionString) else ""
            if name not in _NUMBER_NAMES:
                raise TestDeclarationError(
                    f"line {entry.line}: numbers is one of {', '.join(_DOMAINS)}"
                )
            numbers = _NUMBER_NAMES[name]
            continue
        if entry.key not in _DEFAULTS:
            raise TestDeclarationError(
                f"line {entry.line}: unknown test option {entry.key!r}; the options "
                f"are numbers, {', '.join(_DEFAULTS)}"
            )
        value = entry.value
        if not isinstance(value, OptionNumber) or not float(value.value).is_integer():
            raise TestDeclarationError(
                f"line {entry.line}: option {entry.key!r} takes an integer"
            )
        number = int(value.value)
        if number < (0 if entry.key == "seed" else 1):
            raise TestDeclarationError(
                f"line {entry.line}: option {entry.key!r} must be positive"
            )
        values[entry.key] = number
    expectations = [step for step in test.steps if isinstance(step, TestExpect)]
    tolerant = any(step.tolerance is not None for step in expectations)
    if numbers is None:
        numbers = "float64" if tolerant else "exact"
    for step in expectations:
        modified = step.exact or step.tolerance is not None
        if modified and not (
            isinstance(step.subject, LetExprBinOp) and step.subject.op in ("==", "!=")
        ):
            word = "exactly" if step.exact else "within"
            raise TestDeclarationError(
                f"line {step.line}: `{word}` qualifies an equality (== or !=)"
            )
        if step.exact and numbers != "exact":
            raise TestDeclarationError(
                f"line {step.line}: `exactly` needs exact numbers, but this test runs "
                f"in {numbers}"
            )
        if step.tolerance is not None and numbers == "exact":
            raise TestDeclarationError(
                f"line {step.line}: `within` states a floating tolerance, but this "
                "test declares exact numbers"
            )
    return TestSettings(numbers=numbers, **values)

check_module

check_module(parsed: Module, path: str) -> CheckedModule

Check a parsed module for its tests.

PARAMETER DESCRIPTION
parsed

The parsed module. Its meta phase runs first, so the properties a splice generates are among the tests and the declarations it generates are checked with the module.

TYPE: Module

path

Its file, for diagnostics.

TYPE: str

RETURNS DESCRIPTION
CheckedModule

The checked module.

RAISES DESCRIPTION
ValueError

If the module has no checked QIEC part to run.

Source code in src/quivers/testing/runner.py
def check_module(parsed: Module, path: str) -> CheckedModule:
    """Check a parsed module for its tests.

    Parameters
    ----------
    parsed : Module
        The parsed module. Its meta phase runs first, so the properties a
        splice generates are among the tests and the declarations it
        generates are checked with the module.
    path : str
        Its file, for diagnostics.

    Returns
    -------
    CheckedModule
        The checked module.

    Raises
    ------
    ValueError
        If the module has no checked QIEC part to run.
    """
    parsed = expand_meta(parsed, module_name=Path(path).stem, file_path=path).module
    extended = Module(statements=(*parsed.statements, *_binder_declarations(parsed)))
    compiler = Compiler(extended, module_name=Path(path).stem, file_path=path)
    checked = compiler.qiec_module
    if checked is None:
        raise ValueError(f"{path} has no computations, programs, or data to test")
    return CheckedModule(
        path=path, parsed=parsed, checked=checked, digest=code_digest(checked)
    )

run_test

run_test(module: CheckedModule, test: TestDecl, cache: ResultCache | None = None) -> TestResult

Run one test, property, or example.

PARAMETER DESCRIPTION
module

The checked module it belongs to.

TYPE: CheckedModule

test

The declaration.

TYPE: TestDecl

cache

Where passes are remembered by content hash; None to always run.

TYPE: ResultCache | None DEFAULT: None

RETURNS DESCRIPTION
TestResult

The outcome.

Source code in src/quivers/testing/runner.py
def run_test(
    module: CheckedModule, test: TestDecl, cache: ResultCache | None = None
) -> TestResult:
    """Run one test, property, or example.

    Parameters
    ----------
    module : CheckedModule
        The checked module it belongs to.
    test : TestDecl
        The declaration.
    cache : ResultCache | None
        Where passes are remembered by content hash; ``None`` to always run.

    Returns
    -------
    TestResult
        The outcome.
    """
    started = time.perf_counter()
    digest = declaration_digest(test)
    base = {
        "kind": test.kind,
        "name": test.name,
        "line": test.line,
        "subject": test.subject,
        "digest": digest,
    }
    try:
        settings = settings_of(test)
    except TestDeclarationError as error:
        return TestResult(status="error", message=str(error), **base)
    key = (digest, module.digest, settings.model_dump_json())
    if cache is not None and cache.passed(*key):
        return TestResult(
            status="passed",
            numbers=settings.numbers,
            cached=True,
            seconds=time.perf_counter() - started,
            **base,
        )
    evaluator = TermEvaluator(
        module.checked,
        RunSettings(
            numbers=_DOMAINS[settings.numbers], fuel=settings.fuel, seed=settings.seed
        ),
    )
    names = {item.id: item.name for item in module.checked.constructors}
    body = _Body(test, evaluator, names)
    result = _evaluate(module, test, settings, evaluator, body)
    result = result.with_(seconds=time.perf_counter() - started, **base)
    if cache is not None and result.status == "passed":
        cache.record(*key)
    return result

register_source_loader

register_source_loader(suffix: str, loader: SourceLoader) -> None

Teach run_paths to read modules of another file format.

A literate module format registers its suffix here; its loader tangles the file into QVR source and returns the examples its prose blocks declare, which run beside the source's own tests.

PARAMETER DESCRIPTION
suffix

The file suffix, such as ".qvr.md".

TYPE: str

loader

Reads a file of that format.

TYPE: SourceLoader

RAISES DESCRIPTION
ValueError

If the suffix is .qvr or already registered.

Source code in src/quivers/testing/runner.py
def register_source_loader(suffix: str, loader: SourceLoader) -> None:
    """Teach `run_paths` to read modules of another file format.

    A literate module format registers its suffix here; its loader tangles
    the file into QVR source and returns the examples its prose blocks
    declare, which run beside the source's own tests.

    Parameters
    ----------
    suffix : str
        The file suffix, such as ``".qvr.md"``.
    loader : SourceLoader
        Reads a file of that format.

    Raises
    ------
    ValueError
        If the suffix is ``.qvr`` or already registered.
    """
    if suffix == ".qvr" or suffix in _LOADERS:
        raise ValueError(f"a loader for {suffix!r} is already registered")
    _LOADERS[suffix] = loader

discover

discover(paths: Sequence[Path]) -> tuple[Path, ...]

The module files named by paths: files, and every module under a directory.

PARAMETER DESCRIPTION
paths

Files and directories.

TYPE: Sequence[Path]

RETURNS DESCRIPTION
tuple[Path, ...]

The module files, each once, directories expanded in sorted order.

RAISES DESCRIPTION
FileNotFoundError

If a path does not exist.

Source code in src/quivers/testing/runner.py
def discover(paths: Sequence[Path]) -> tuple[Path, ...]:
    """The module files named by paths: files, and every module under a directory.

    Parameters
    ----------
    paths : Sequence[Path]
        Files and directories.

    Returns
    -------
    tuple[Path, ...]
        The module files, each once, directories expanded in sorted order.

    Raises
    ------
    FileNotFoundError
        If a path does not exist.
    """
    found: list[Path] = []
    for path in paths:
        if not path.exists():
            raise FileNotFoundError(f"{path} does not exist")
        if path.is_dir():
            found.extend(
                item
                for item in sorted(path.rglob("*"))
                if item.is_file() and _loader_for(item) is not None
            )
        else:
            found.append(path)
    unique: list[Path] = []
    for item in found:
        if item not in unique:
            unique.append(item)
    return tuple(unique)

load_program

load_program(path: Path) -> FlatProgram

Read a module file as it runs: its module graph as one flat program.

The file is the root of its module graph. A module of a package is read in its package's build (quivers.packages.workspace.load_package_file), as qvr check reads it; any other file's imports are found below its own directory and in the standard library. The graph is interpreted into one flat program, as quivers.dsl.load interprets it, so a test names the module's own declarations by their names and an imported one through the import that reaches it. The tests are the root module's, with any tests its file format carries beyond the source.

PARAMETER DESCRIPTION
path

The module file.

TYPE: Path

RETURNS DESCRIPTION
FlatProgram

The flat program, with the root module's tests, and the source map from its lines to each module's file.

RAISES DESCRIPTION
OSError

If a file cannot be read.

ParseError

If the module or one it imports does not parse.

ModuleError

If an import names no module, the imports form a cycle, or a name does not resolve.

ManifestError

If the manifest of the file's package is malformed.

PackageError

If an import of a package module crosses a package boundary the rules forbid, or its lockfile does not match the packages.

ValueError

If the file is not a module the loaders read.

Source code in src/quivers/testing/runner.py
def load_program(path: Path) -> FlatProgram:
    """Read a module file as it runs: its module graph as one flat program.

    The file is the root of its module graph. A module of a package is read
    in its package's build
    (`quivers.packages.workspace.load_package_file`), as `qvr check` reads
    it; any other file's imports are found below its own directory and in
    the standard library. The
    graph is interpreted into one flat program, as `quivers.dsl.load`
    interprets it, so a test names the module's own declarations by their
    names and an imported one through the import that reaches it. The tests
    are the root module's, with any tests its file format carries beyond
    the source.

    Parameters
    ----------
    path : Path
        The module file.

    Returns
    -------
    FlatProgram
        The flat program, with the root module's tests, and the source map
        from its lines to each module's file.

    Raises
    ------
    OSError
        If a file cannot be read.
    ParseError
        If the module or one it imports does not parse.
    ModuleError
        If an import names no module, the imports form a cycle, or a name
        does not resolve.
    ManifestError
        If the manifest of the file's package is malformed.
    PackageError
        If an import of a package module crosses a package boundary the
        rules forbid, or its lockfile does not match the packages.
    ValueError
        If the file is not a module the loaders read.
    """
    suffix = _suffix_of(path)
    loader = _LOADERS.get(suffix, _plain_loader)
    source, extra = loader(path)
    packaged = load_package_file(path)
    if packaged is not None:
        graph = packaged
    else:
        root = ModuleSource(
            identity=SourceModule(path=(path.name.removesuffix(suffix),)),
            label=str(path),
            text=source.decode("utf-8"),
        )
        imports = ChainLoader(
            (StandardLibraryLoader(), FileSystemLoader((path.parent.resolve(),)))
        )
        graph = load_graph(root, imports)
    flat = interpret(graph)
    resolve = module_name_resolver(graph, graph.root, 0)
    tests = (
        *(
            _resolved_example(test, resolve) if test.subject else test
            for test in flat.module.tests
        ),
        *(_resolved_example(test, resolve) for test in extra),
    )
    return flat.with_(module=flat.module.with_(tests=tests))

load_module

load_module(path: Path) -> Module

Read a module file as it runs, as load_program reads it.

PARAMETER DESCRIPTION
path

The module file.

TYPE: Path

RETURNS DESCRIPTION
Module

The flat program, with the root module's tests.

RAISES DESCRIPTION
OSError

If a file cannot be read.

ParseError

If the module or one it imports does not parse.

ModuleError

If an import names no module, the imports form a cycle, or a name does not resolve.

ValueError

If the file is not a module the loaders read.

Source code in src/quivers/testing/runner.py
def load_module(path: Path) -> Module:
    """Read a module file as it runs, as `load_program` reads it.

    Parameters
    ----------
    path : Path
        The module file.

    Returns
    -------
    Module
        The flat program, with the root module's tests.

    Raises
    ------
    OSError
        If a file cannot be read.
    ParseError
        If the module or one it imports does not parse.
    ModuleError
        If an import names no module, the imports form a cycle, or a name
        does not resolve.
    ValueError
        If the file is not a module the loaders read.
    """
    return load_program(path).module

run_module

run_module(path: Path, cache: ResultCache | None = None, select: Callable[[TestDecl], bool] | None = None) -> ModuleReport

Run every test of one module file.

PARAMETER DESCRIPTION
path

The module.

TYPE: Path

cache

Where passes are remembered; None to always run.

TYPE: ResultCache | None DEFAULT: None

select

Which tests to run; all when None.

TYPE: Callable[[TestDecl], bool] | None DEFAULT: None

RETURNS DESCRIPTION
ModuleReport

The module's report.

Source code in src/quivers/testing/runner.py
def run_module(
    path: Path,
    cache: ResultCache | None = None,
    select: Callable[[TestDecl], bool] | None = None,
) -> ModuleReport:
    """Run every test of one module file.

    Parameters
    ----------
    path : Path
        The module.
    cache : ResultCache | None
        Where passes are remembered; ``None`` to always run.
    select : Callable[[TestDecl], bool] | None
        Which tests to run; all when ``None``.

    Returns
    -------
    ModuleReport
        The module's report.
    """
    try:
        flat = load_program(path)
    except (OSError, ParseError, ModuleError, ValueError) as error:
        return ModuleReport(path=str(path), error=str(error))
    try:
        parsed = expand_meta(
            flat.module, module_name=path.stem, file_path=str(path)
        ).module
    except Exception as error:  # noqa: BLE001 - every meta-phase failure is reported
        return ModuleReport(path=str(path), error=_reported(error, flat))
    tests = tuple(test for test in parsed.tests if select is None or select(test))
    if not tests:
        return ModuleReport(path=str(path))
    try:
        checked = check_module(parsed, str(path))
    except Exception as error:  # noqa: BLE001 - every compile failure is reported
        return ModuleReport(path=str(path), error=_reported(error, flat))
    return ModuleReport(
        path=str(path),
        digest=checked.digest,
        results=tuple(run_test(checked, test, cache) for test in tests),
    )

run_paths

run_paths(paths: Sequence[Path], cache: ResultCache | None = None, select: Callable[[TestDecl], bool] | None = None) -> TestReport

Run the tests of every module named by paths.

PARAMETER DESCRIPTION
paths

Module files and package directories.

TYPE: Sequence[Path]

cache

Where passes are remembered; None to always run.

TYPE: ResultCache | None DEFAULT: None

select

Which tests to run; all when None.

TYPE: Callable[[TestDecl], bool] | None DEFAULT: None

RETURNS DESCRIPTION
TestReport

The report.

Source code in src/quivers/testing/runner.py
def run_paths(
    paths: Sequence[Path],
    cache: ResultCache | None = None,
    select: Callable[[TestDecl], bool] | None = None,
) -> TestReport:
    """Run the tests of every module named by paths.

    Parameters
    ----------
    paths : Sequence[Path]
        Module files and package directories.
    cache : ResultCache | None
        Where passes are remembered; ``None`` to always run.
    select : Callable[[TestDecl], bool] | None
        Which tests to run; all when ``None``.

    Returns
    -------
    TestReport
        The report.
    """
    return TestReport(
        modules=tuple(run_module(path, cache, select) for path in discover(paths)),
        packages=tuple(str(path) for path in paths if path.is_dir()),
    )