diff --git a/src/sist/argspec.py b/src/sist/argspec.py index a681f15..29586ba 100644 --- a/src/sist/argspec.py +++ b/src/sist/argspec.py @@ -12,7 +12,9 @@ from dataclasses import dataclass from typing import Any -ALGORITHM_CHOICES = ("M", "Z", "C", "A") +from sist.transitions import ALGORITHMS + +ALGORITHM_CHOICES = tuple(ALGORITHMS) @dataclass(frozen=True) @@ -131,6 +133,16 @@ class ArgSpec: default=None, help="Write output to this file instead of printing to stdout.", ), + ArgSpec( + dest="json_file", + flags=("--json",), + type=str, + default=None, + help=( + "Write the result as structured JSON to this file. The text output " + "is then only written if -o is also given." + ), + ), ) diff --git a/src/sist/cli.py b/src/sist/cli.py index 6fc6f4b..68954be 100644 --- a/src/sist/cli.py +++ b/src/sist/cli.py @@ -46,6 +46,11 @@ def main(argv: list[str] | None = None) -> None: argument_parser = SistArgumentParser() parser = argument_parser.build_parser() args = parser.parse_args(argv) + program = Path(sys.argv[0]).name + command = [ + program if argv is None and program != "__main__.py" else parser.prog, + *(sys.argv[1:] if argv is None else argv), + ] try: argument_parser.validate(args) @@ -62,6 +67,8 @@ def main(argv: list[str] | None = None) -> None: print_parameters=args.print_parameters, print_ensemble_average=args.print_ensemble_average, output_file=args.output_file, + json_file=args.json_file, + command=command, ) runner.run() except Exception: diff --git a/src/sist/runner.py b/src/sist/runner.py index 56734b3..a680a0b 100644 --- a/src/sist/runner.py +++ b/src/sist/runner.py @@ -1,22 +1,132 @@ -"""Orchestration that dispatches a SIST calculation to the qsidd binaries. +"""Run a SIST calculation with the qsidd binaries. -Melting (M) and Z-DNA (Z) calculations run the single-transition -``qsidd`` binary directly; cruciform (C) and competition (A) calculations -first score candidate inverted repeats via :mod:`sist.ir_finder`, then run -the single-transition or competition ``qsidd`` binary respectively. +A run goes through these steps: + +1. Look up the algorithm for the ``-a`` flag in :mod:`sist.transitions`. +2. For algorithms with cruciforms, score candidate inverted repeats with + :mod:`sist.ir_finder`. +3. Run qsidd with the binary and flags the algorithm gives. +4. Write or print qsidd's text output, or, with ``--json``, build the + structured result with :mod:`sist.results` and write it. + +From Python, a run looks like:: + + SistRunner( + file="seq.fa", + algorithm="M", + temperature=310, + superhelical_density=0.06, + salt=0.01, + energy_threshold=12, + circular=False, + nearest_neighbor=False, + print_base_pair=False, + print_parameters=False, + print_ensemble_average=False, + output_file=None, + json_file="result.json", + ).run() """ from __future__ import annotations import subprocess +from dataclasses import dataclass from pathlib import Path from sist.binaries import BinaryLocator from sist.ir_finder import IRFinder +from sist.results.builder import ResultBuilder +from sist.results.diagnostics import ErrorCode, ResultError +from sist.results.model import RunSettings +from sist.results.qsidd_output import QsiddOutput +from sist.results.sequence import SequenceInput +from sist.results.writer import ResultWriter +from sist.transitions import ALGORITHMS, Algorithm + + +@dataclass(frozen=True) +class ScoredRepeats: + """Inverted repeats scored for qsidd, and the IRF version that found them. + + Attributes: + ir_string: The scored inverted repeats in the form ``qsidd -X`` + expects, such as ``"1,0,10000,|2982,25,17.27,|"``. Each entry is + a start position, length and energy, ending in ``|``. + irf_version: The IRF version, such as ``"3.09"``, if it could be read. + """ + + ir_string: str + irf_version: str | None + + +class IRFinderScorer: + """Score inverted repeats with the IR finder and IRF. + + IRF finds the candidate repeats in the sequence, and :class:`IRFinder` + works out the energy of each one as a cruciform. + + Attributes: + temperature: Temperature in kelvin. + shape: ``"linear"`` or ``"circular"``. + """ + + def __init__(self, *, temperature: float, shape: str) -> None: + """Set up the scorer with the conditions the energies are worked out at. + + Args: + temperature: Temperature in kelvin. + shape: ``"linear"`` or ``"circular"``. + """ + self.temperature = temperature + self.shape = shape + + def score(self, file: str) -> ScoredRepeats: + """Score the inverted repeats in a sequence file. + + Args: + file: Path to the FASTA sequence file. + + Returns: + The scored inverted repeats, and the IRF version that found them. + + Raises: + FileNotFoundError: If IRF is not installed. + """ + finder = IRFinder(temperature=self.temperature, shape=self.shape) + ir_string = finder.compute_cruciform_energy_string(file) + + return ScoredRepeats(ir_string, finder.irf_version) + + +class SubprocessQsidd: + """Run qsidd as a subprocess. + + The exit code is returned rather than raised, so the runner can report a + failed qsidd run as text or as a structured result. + """ + + def run(self, command: list[str]) -> subprocess.CompletedProcess[str]: + """Run a qsidd command line and capture its output. + + Args: + command: The command line to run, as built by + :meth:`SistRunner._build_command`. + + Returns: + The finished process, with its exit code and its stdout and stderr + as text. + """ + return subprocess.run(command, capture_output=True, text=True, check=False) class SistRunner: - """Coordinate a single SIST calculation: build, run, and report on it. + """Run one SIST calculation and write or print its output. + + The attributes match the ``sist`` command's options. Text output works as + it did before ``--json``: qsidd's output goes to ``output_file``, or to + stdout. With ``json_file`` set, a structured result is written instead, + and the text output only as well when ``output_file`` is also set. Attributes: file: Path to the input FASTA sequence file. @@ -33,6 +143,8 @@ class SistRunner: print_parameters: Print algorithm parameters. print_ensemble_average: Print ensemble average results. output_file: Path to write output to, or None to print to stdout. + json_file: Path to write the structured result to, or None to skip it. + command: The command line as given, recorded in the structured result. """ def __init__( @@ -50,8 +162,20 @@ def __init__( print_parameters: bool, print_ensemble_average: bool, output_file: str | None, + json_file: str | None = None, + command: list[str] | None = None, + ir_scorer: IRFinderScorer | None = None, + qsidd: SubprocessQsidd | None = None, + result_writer: ResultWriter | None = None, ) -> None: - """Initialise the runner with a single calculation's configuration.""" + """Set up the runner with one calculation's settings. + + The settings are described under the class attributes. The last three + arguments set how inverted repeats are scored, how qsidd is run and + how results are written. When they are None, an + :class:`IRFinderScorer`, a :class:`SubprocessQsidd` and a + :class:`ResultWriter` are used. + """ self.file = file self.algorithm = algorithm self.temperature = temperature @@ -64,101 +188,311 @@ def __init__( self.print_parameters = print_parameters self.print_ensemble_average = print_ensemble_average self.output_file = output_file + self.json_file = json_file + self.command = command self._binaries = BinaryLocator() + self._ir_scorer = ir_scorer or IRFinderScorer( + temperature=temperature, shape=self.shape + ) + self._qsidd = qsidd or SubprocessQsidd() + self._result_writer = result_writer or ResultWriter() @property def shape(self) -> str: - """Molecule shape as the qsidd binaries expect it: linear or circular.""" + """Molecule shape as the IR finder expects it. + + ``"circular"`` for a circular molecule, otherwise ``"linear"``. + """ return "circular" if self.circular else "linear" def run(self) -> None: """Run the calculation and write or print its output. + Without a JSON file this writes qsidd's text output, exactly as before. + With one, the structured result is written to it, and the text output + is only written as well if ``output_file`` is set. The text output then + comes from a second qsidd run with the flags the user chose, reusing + the inverted repeats already scored. + Raises: ValueError: If ``algorithm`` is not one of M, Z, C, or A. subprocess.CalledProcessError: If the qsidd binary exits - non-zero. + non-zero while writing text output. + ResultError: If the run failed while writing a structured result. + The failed result is written before this is raised. + """ + algorithm = self._algorithm() + + if self.json_file: + repeats = self._run_json(algorithm) + + if self.output_file: + self._write_text(algorithm, repeats) + + return + + repeats = ( + self._ir_scorer.score(self.file) + if algorithm.needs_inverted_repeats + else None + ) + self._write_text(algorithm, repeats) + + def _algorithm(self) -> Algorithm: + """Look up the algorithm for the ``-a`` flag in :data:`ALGORITHMS`. + + Returns: + The algorithm, with its transitions, engine and qsidd flags. + + Raises: + ValueError: If the algorithm flag is not known. """ - command = self._build_command() - result = subprocess.run(command, capture_output=True, text=True, check=True) + algorithm = ALGORITHMS.get(self.algorithm) + + if algorithm is None: + raise ValueError( + f"Unknown algorithm: {self.algorithm!r}. Expected one of " + f"{', '.join(ALGORITHMS)}." + ) + + return algorithm + + def _write_text(self, algorithm: Algorithm, repeats: ScoredRepeats | None) -> None: + """Run qsidd as usual and write or print its text output. + + The output goes to ``output_file`` if it is set, otherwise to stdout. + + Args: + algorithm: The algorithm to run. + repeats: The scored inverted repeats, if the algorithm uses them. + + Raises: + subprocess.CalledProcessError: If qsidd exits non-zero. + """ + command = self._build_command(algorithm, repeats, precise=False) + completed = self._qsidd.run(command) + + if completed.returncode != 0: + raise subprocess.CalledProcessError( + completed.returncode, command, completed.stdout, completed.stderr + ) if self.output_file: - Path(self.output_file).write_text(result.stdout, encoding="utf-8") + Path(self.output_file).write_text(completed.stdout, encoding="utf-8") else: - print(result.stdout, end="") - - def _build_command(self) -> list[str]: - """Build the qsidd command line for this calculation's algorithm.""" - shared_parameters = self._shared_parameters() - - if self.algorithm == "M": - return [ - str(self._binaries.trans_three_binary()), - *self._flags(nearest_neighbor=self.nearest_neighbor), - *shared_parameters, - "-f", - self.file, - ] - - if self.algorithm == "Z": - return [ - str(self._binaries.trans_three_binary()), - *self._flags(nearest_neighbor=False), - *shared_parameters, - "-Z", - "-f", - self.file, - ] - - if self.algorithm == "C": - ir_string = self._cruciform_energy_string() - - return [ - str(self._binaries.trans_three_binary()), - *self._flags(nearest_neighbor=False), - *shared_parameters, - "-C", - "-X", - ir_string, - "-f", - self.file, - ] - - if self.algorithm == "A": - ir_string = self._cruciform_energy_string() - - return [ - str(self._binaries.trans_compete_binary()), - *self._flags(nearest_neighbor=self.nearest_neighbor), - *shared_parameters, - "-X", - ir_string, - "-f", - self.file, - ] - - raise ValueError( - f"Unknown algorithm: {self.algorithm!r}. Expected one of M, Z, C, A." + print(completed.stdout, end="") + + def _run_json(self, algorithm: Algorithm) -> ScoredRepeats | None: + """Run qsidd at full precision and write the structured result. + + The steps are: read the sequence, score inverted repeats if needed, + run qsidd with ``-b -p -r -P``, build the result and check it against + the schema. A failure at any step, including a result that fails the + check, becomes a failed result. That is written to ``json_file`` + before the error is raised again. Errors that are not a + ``ResultError`` are recorded as ``INTERNAL_ERROR``. + + Args: + algorithm: The algorithm to run. + + Returns: + The scored inverted repeats, for reuse by a text run. + + Raises: + ResultError: If the run failed. + """ + builder = ResultBuilder(self._settings(algorithm), command=self.command) + sequence: SequenceInput | None = None + output: QsiddOutput | None = None + repeats: ScoredRepeats | None = None + + try: + sequence = builder.read_sequence() + repeats = self._score_for_json(algorithm) + output = self._run_precise_qsidd(algorithm, repeats) + result = builder.success( + output, + sequence, + ir_string=repeats.ir_string if repeats else None, + irf_version=repeats.irf_version if repeats else None, + ) + self._result_writer.check(result) + except Exception as error: + failure = ( + error + if isinstance(error, ResultError) + else ResultError(ErrorCode.INTERNAL_ERROR, str(error)) + ) + self._result_writer.write( + builder.failure( + failure, + sequence=sequence, + output=output, + irf_version=repeats.irf_version if repeats else None, + ), + Path(str(self.json_file)), + ) + + if failure is error: + raise + + raise failure from error + + self._result_writer.write(result, Path(str(self.json_file))) + + return repeats + + def _settings(self, algorithm: Algorithm) -> RunSettings: + """Collect the settings a structured result records. + + These fill in the ``calculation``, ``input`` and ``parameters`` + sections of the result. + + Args: + algorithm: The algorithm being run. + + Returns: + The run's settings. + """ + return RunSettings( + file=self.file, + algorithm=algorithm, + temperature=self.temperature, + superhelical_density=self.superhelical_density, + salt=self.salt, + energy_threshold=self.energy_threshold, + circular=self.circular, + nearest_neighbor=self.nearest_neighbor, ) - def _cruciform_energy_string(self) -> str: - """Score candidate inverted repeats for the C/A algorithms.""" - finder = IRFinder(temperature=self.temperature, shape=self.shape) + def _score_for_json(self, algorithm: Algorithm) -> ScoredRepeats | None: + """Score inverted repeats, reporting a missing IRF as a result error. + + A missing IRF is recorded as ``IRF_NOT_FOUND`` in the failed result. + + Args: + algorithm: The algorithm being run. + + Returns: + The scored inverted repeats, or None if the algorithm does not use + them. + + Raises: + ResultError: If IRF is not installed. + """ + if not algorithm.needs_inverted_repeats: + return None - return finder.compute_cruciform_energy_string(self.file) + try: + return self._ir_scorer.score(self.file) + except FileNotFoundError as error: + raise ResultError( + ErrorCode.IRF_NOT_FOUND, + f"The Inverted Repeats Finder executable '{IRFinder.IRF_EXECUTABLE}' " + "was not found on PATH. Algorithms that need inverted repeats " + "cannot run without it.", + ) from error - def _flags(self, *, nearest_neighbor: bool) -> list[str]: - """Build the qsidd boolean flags.""" + def _run_precise_qsidd( + self, algorithm: Algorithm, repeats: ScoredRepeats | None + ) -> QsiddOutput: + """Run qsidd with every output option and full precision. + + Args: + algorithm: The algorithm to run. + repeats: The scored inverted repeats, if the algorithm uses them. + + Returns: + The parsed qsidd output. + + Raises: + ResultError: ``QSIDD_NOT_FOUND`` if the binary cannot be found, or + ``QSIDD_FAILED`` with qsidd's exit code and stderr if it exits + with an error. + """ + try: + command = self._build_command(algorithm, repeats, precise=True) + except FileNotFoundError as error: + raise ResultError(ErrorCode.QSIDD_NOT_FOUND, str(error)) from error + + completed = self._qsidd.run(command) + + if completed.returncode != 0: + raise ResultError( + ErrorCode.QSIDD_FAILED, + f"qsidd exited with code {completed.returncode}.", + exit_code=completed.returncode, + stderr=completed.stderr or None, + ) + + return QsiddOutput.parse(completed.stdout) + + def _build_command( + self, algorithm: Algorithm, repeats: ScoredRepeats | None, *, precise: bool + ) -> list[str]: + """Build the qsidd command line for an algorithm. + + The parts come in this order: the binary, the boolean flags, the + numeric parameters, the algorithm's own flags, the inverted repeats + and the sequence file. For cruciform at full precision on a linear + molecule this gives:: + + trans_three -b -p -r -P -T 310.0 -s 0.06 -i 0.01 -t 12.0 -C \\ + -X -f seq.fa + + Args: + algorithm: The algorithm to run. + repeats: The scored inverted repeats, if the algorithm uses them. + precise: Ask for every output section at full precision, in place + of the flags the user chose. + + Returns: + The qsidd command line. + + Raises: + FileNotFoundError: If the qsidd binary cannot be found. + """ + command = [ + str(self._binaries.binary(algorithm.engine)), + *self._flags(algorithm, precise=precise), + *self._shared_parameters(), + *algorithm.qsidd_flags, + ] + + if algorithm.needs_inverted_repeats: + command.extend(["-X", repeats.ir_string if repeats else ""]) + + return [*command, "-f", self.file] + + def _flags(self, algorithm: Algorithm, *, precise: bool) -> list[str]: + """Build the qsidd boolean flags. + + For a structured result this is always ``-b -p -r -P``. For text output it + is whichever of ``-b``, ``-p`` and ``-r`` were asked for. ``-n`` is added + when nearest-neighbor energetics were asked for and the algorithm supports + them, and ``-c`` for a circular molecule. + + Args: + algorithm: The algorithm being run. + precise: Ask for every output section at full precision. + + Returns: + The flags. + """ flags = [] - if self.print_base_pair: - flags.append("-b") - if self.print_parameters: - flags.append("-p") - if self.print_ensemble_average: - flags.append("-r") - if nearest_neighbor: + if precise: + flags.extend(["-b", "-p", "-r", "-P"]) + else: + if self.print_base_pair: + flags.append("-b") + if self.print_parameters: + flags.append("-p") + if self.print_ensemble_average: + flags.append("-r") + + if self.nearest_neighbor and algorithm.supports_nearest_neighbor: flags.append("-n") if self.circular: flags.append("-c") @@ -166,7 +500,14 @@ def _flags(self, *, nearest_neighbor: bool) -> list[str]: return flags def _shared_parameters(self) -> list[str]: - """Build the qsidd numeric parameter flags shared by every algorithm.""" + """Build the qsidd numeric parameter flags shared by every algorithm. + + Returns: + The temperature, superhelical density, salt concentration and + energy threshold, as ``-T``, ``-s``, ``-i`` and ``-t`` with their + values, such as ``["-T", "310.0", "-s", "0.06", "-i", "0.01", "-t", + "12.0"]``. + """ return [ "-T", str(self.temperature), diff --git a/src/sist/schema_cli.py b/src/sist/schema_cli.py index 3aa23d0..7e3f238 100644 --- a/src/sist/schema_cli.py +++ b/src/sist/schema_cli.py @@ -26,8 +26,7 @@ def main(argv: list[str] | None = None) -> None: """Check each SIST result file and print what was found. - Every file is checked before exiting, so one bad file does not hide - problems in the others. + Every file is checked before exiting. Args: argv: Result file paths, or None to use ``sys.argv[1:]``. @@ -93,9 +92,8 @@ def _report(validator: ResultValidator, path: Path) -> bool: def _read_result(path: Path) -> dict[str, Any]: """Read a result file, refusing anything that is not strict JSON. - Python's json module accepts ``NaN`` and ``Infinity`` by default, even - though they are not valid JSON and other tools cannot read them. Refusing - them means a file that passes here can be read anywhere. + Refuses ``NaN`` and ``Infinity``, which Python's json module accepts by + default but are not valid JSON. Args: path: Path to the result file. diff --git a/tests/regression/conftest.py b/tests/regression/conftest.py index d5854a7..61573f6 100644 --- a/tests/regression/conftest.py +++ b/tests/regression/conftest.py @@ -11,19 +11,43 @@ REPOSITORY_ROOT = Path(__file__).resolve().parents[2] -SIST_TRANSITIONS = ( - pytest.param(("melting", "M"), id="melting"), - pytest.param(("z-dna", "Z"), id="z-dna"), - pytest.param(("cruciform", "C"), id="cruciform"), -) +REGRESSION_DATA = Path(__file__).resolve().parent / "data" / "pbr322.toy.fa" @dataclass(frozen=True) -class SistRun: - """Result of running a SIST calculation.""" +class RegressionCase: + """One algorithm run on the regression sequence. + + Attributes: + name: Name used in test ids and output file names. + algorithm: The ``-a`` flag. + reference: File name of its 1.0.0 text reference. + """ name: str algorithm: str + reference: str + + +REGRESSION_CASES = ( + RegressionCase("melting", "M", "melting.txt"), + RegressionCase("z-dna", "Z", "z-dna.txt"), + RegressionCase("cruciform", "C", "cruciform.txt"), + RegressionCase("competition", "A", "competition.rebuilt.txt"), +) + + +@dataclass(frozen=True) +class SistRun: + """Result of running a SIST calculation. + + Attributes: + case: The algorithm that was run. + process: The finished ``sist`` process. + output_path: The file it wrote. + """ + + case: RegressionCase process: subprocess.CompletedProcess[str] output_path: Path @@ -161,79 +185,84 @@ def sist_command( return [sys.executable, "-m", "sist"] -def run_sist_calculation( +def run_sist( sist_command: list[str], tmp_path_factory: pytest.TempPathFactory, + case: RegressionCase, *, - name: str, - algorithm: str, + output_flag: str, + output_name: str, ) -> SistRun: - """Run one SIST calculation using the regression test sequence.""" + """Run one SIST calculation on the regression sequence. - runtime_directory = tmp_path_factory.mktemp(f"sist-{name}") + Args: + sist_command: The SIST command under test. + tmp_path_factory: Factory for the run's working directory. + case: The algorithm to run. + output_flag: ``"-o"`` for text output or ``"--json"`` for a result. + output_name: File name to write. - source_input = Path(__file__).resolve().parent / "data" / "pbr322.toy.fa" - runtime_input = runtime_directory / "pbr322.toy.fa" - - shutil.copy2(source_input, runtime_input) - - output_path = runtime_directory / f"{name}.txt" + Returns: + The finished run. + """ + runtime_directory = tmp_path_factory.mktemp(f"sist-{case.name}") + shutil.copy2(REGRESSION_DATA, runtime_directory) - result = run_command( + process = run_command( [ *sist_command, "-f", - runtime_input.name, + REGRESSION_DATA.name, "-a", - algorithm, - "-o", - output_path.name, + case.algorithm, "-b", "-p", "-r", + output_flag, + output_name, ], cwd=runtime_directory, ) + require_success(process, description=f"The {case.name} calculation") - return SistRun( - name=name, - algorithm=algorithm, - process=result, - output_path=output_path, - ) + return SistRun(case, process, runtime_directory / output_name) + + +@pytest.fixture(scope="session", params=REGRESSION_CASES, ids=lambda case: case.name) +def regression_case(request: pytest.FixtureRequest) -> RegressionCase: + """Each algorithm, run once per session.""" + case: RegressionCase = request.param + + return case @pytest.fixture(scope="session") -def competition_run( +def text_run( + regression_case: RegressionCase, sist_command: list[str], tmp_path_factory: pytest.TempPathFactory, ) -> SistRun: - """Run the SIST competition calculation once.""" - - return run_sist_calculation( + """Run an algorithm with text output, as the 1.0.0 references were made.""" + return run_sist( sist_command, tmp_path_factory, - name="competition", - algorithm="A", + regression_case, + output_flag="-o", + output_name=f"{regression_case.name}.txt", ) -@pytest.fixture( - scope="session", - params=SIST_TRANSITIONS, -) -def transition_run( - request: pytest.FixtureRequest, +@pytest.fixture(scope="session") +def json_run( + regression_case: RegressionCase, sist_command: list[str], tmp_path_factory: pytest.TempPathFactory, ) -> SistRun: - """Run each supported individual SIST transition calculation once.""" - - name, algorithm = request.param - - return run_sist_calculation( + """Run an algorithm with a structured JSON result.""" + return run_sist( sist_command, tmp_path_factory, - name=name, - algorithm=algorithm, + regression_case, + output_flag="--json", + output_name=f"{regression_case.name}.json", ) diff --git a/tests/regression/reference/v1.0.0/README.md b/tests/regression/reference/v1.0.0/README.md index 73c2e3b..4159425 100644 --- a/tests/regression/reference/v1.0.0/README.md +++ b/tests/regression/reference/v1.0.0/README.md @@ -76,27 +76,14 @@ regardless of which implementation produced them. ## Scientific regression comparison -The regression suite compares deterministic scientific output against these references with zero relative and absolute tolerance. +Each calculation is run twice on `pbr322.toy.fa`: once with text output and once with a structured JSON result. -For individual transition calculations, the comparison includes: - -- Reported deterministic scientific metrics. -- Every sequence position. -- The base reported at every position. -- P(x) at every position. -- G(x) where it is produced by the calculation. - -For the competition calculation, the comparison includes: - -- Reported deterministic scientific metrics. -- Every sequence position. -- The base reported at every position. -- P_melt, P_Z, and P_cruciform at every position. - -The structure of the scientific profile output is also checked so that unexpected changes to the reported columns cause the regression tests to fail. +The text output must match its reference line for line, with zero tolerance. That covers every reported metric, every sequence position and base, P(x) or P_melt, P_Z and P_cruciform at every position, G(x) where the calculation produces it, and the layout of the output. The variable Run time line is deliberately ignored because execution time is not scientific output. +The JSON result must hold the same bases, per-position probabilities, G(x) and total state count. The references print 6 significant figures while the JSON holds full precision, so its values are compared to that precision. + ## Historical competition output The maintained competition output and the inherited executable output matched exactly for all values common to both, excluding the variable Run time line. diff --git a/tests/regression/test_cli.py b/tests/regression/test_cli.py deleted file mode 100644 index b745d11..0000000 --- a/tests/regression/test_cli.py +++ /dev/null @@ -1,105 +0,0 @@ -from __future__ import annotations - -import pytest -from conftest import SistRun - -pytestmark = pytest.mark.regression - - -def assert_command_succeeds(sist_run: SistRun) -> None: - """Assert that a SIST calculation completed successfully.""" - - process = sist_run.process - - assert process.returncode == 0, ( - f"{sist_run.name} command failed with exit code " - f"{process.returncode}\n\n" - f"stdout:\n{process.stdout}\n\n" - f"stderr:\n{process.stderr}" - ) - - -def assert_output_is_created(sist_run: SistRun) -> None: - """Assert that a SIST calculation created a non-empty output file.""" - - output_path = sist_run.output_path - - assert output_path.is_file(), f"Expected output file was not created: {output_path}" - - assert output_path.stat().st_size > 0, f"Output file is empty: {output_path}" - - -def test_competition_command_succeeds( - competition_run: SistRun, -) -> None: - """The competition calculation should complete successfully.""" - - assert_command_succeeds(competition_run) - - -def test_competition_output_is_created( - competition_run: SistRun, -) -> None: - """The competition calculation should create a non-empty output file.""" - - assert_output_is_created(competition_run) - - -def test_competition_output_contains_expected_sections( - competition_run: SistRun, -) -> None: - """Competition output should contain the expected calculation sections.""" - - output = competition_run.output_path.read_text(encoding="utf-8") - - expected_sections = ( - "Sequence Length =", - "Total Partition Function =", - "Prob_M =", - "Prob_Z =", - "Prob_C =", - "Position", - "P_melt", - "P_Z", - "P_cruciform", - ) - - for section in expected_sections: - assert section in output, f"Expected output section was not found: {section!r}" - - -def test_transition_command_succeeds( - transition_run: SistRun, -) -> None: - """Each individual transition calculation should complete successfully.""" - - assert_command_succeeds(transition_run) - - -def test_transition_output_is_created( - transition_run: SistRun, -) -> None: - """Each transition calculation should create a non-empty output file.""" - - assert_output_is_created(transition_run) - - -def test_transition_output_contains_expected_sections( - transition_run: SistRun, -) -> None: - """Transition output should contain the expected calculation sections.""" - - output = transition_run.output_path.read_text(encoding="utf-8") - - expected_sections = ( - "Sequence Length =", - "Total Partition Function =", - "Transition Probability =", - "Position", - "P(x)", - ) - - for section in expected_sections: - assert section in output, ( - f"{transition_run.name}: expected output section was not found: {section!r}" - ) diff --git a/tests/regression/test_regression.py b/tests/regression/test_regression.py index c146d10..a36aa69 100644 --- a/tests/regression/test_regression.py +++ b/tests/regression/test_regression.py @@ -1,468 +1,85 @@ +"""Regression tests against the SIST 1.0.0 reference outputs. + +Every algorithm is run on the regression sequence twice: once with text output +and once with a structured JSON result. The text output must match its +reference exactly, apart from the run time. The JSON result must hold the same +values, compared to the 6 significant figures the references print. +""" + from __future__ import annotations -from dataclasses import dataclass +import json from pathlib import Path import pytest from conftest import SistRun -pytestmark = pytest.mark.regression - - -REFERENCE_VERSION = "v1.0.0" - -REFERENCE_DIRECTORY = Path(__file__).resolve().parent / "reference" / REFERENCE_VERSION - -COMPETITION_REFERENCE = REFERENCE_DIRECTORY / "competition.rebuilt.txt" - -# The baselines reproduced all shared printed values exactly. -RELATIVE_TOLERANCE = 0.0 -ABSOLUTE_TOLERANCE = 0.0 - +from sist.results.qsidd_output import QsiddOutput +from sist.transitions import ALGORITHMS -@dataclass(frozen=True) -class CompetitionProfileRow: - """One position from the SIST competition probability profile.""" - - base: str - p_melt: float - p_z: float - p_cruciform: float - - -@dataclass(frozen=True) -class ParsedCompetitionOutput: - """Parsed deterministic content from a SIST competition result.""" - - metadata: tuple[str, ...] - metrics: dict[str, float] - profile: dict[int, CompetitionProfileRow] - - -@dataclass(frozen=True) -class TransitionProfileRow: - """One position from an individual SIST transition profile.""" +pytestmark = pytest.mark.regression - base: str - probability: float - energy: float | None +REFERENCE_DIRECTORY = Path(__file__).resolve().parent / "reference" / "v1.0.0" +REFERENCE_RTOL = 5e-6 +"""Relative tolerance for JSON values, which hold more digits than the text.""" -@dataclass(frozen=True) -class ParsedTransitionOutput: - """Parsed deterministic content from an individual SIST transition.""" - metadata: tuple[str, ...] - metrics: dict[str, float] - profile: dict[int, TransitionProfileRow] +def _scientific_lines(text: str) -> list[str]: + """Split output into lines, leaving out the run time, which always varies. + Args: + text: SIST text output. -def parse_numeric_value(value: str) -> float | None: + Returns: + The lines that must match the reference. """ - Parse the first token as a number. + return [line for line in text.splitlines() if not line.startswith("Run time")] - This handles values followed by units, such as: - '-0.06' - '310 K' - '1.4748e-54' - """ - first_token = value.strip().split()[0] - - try: - return float(first_token) - except ValueError: - return None - - -def parse_competition_output(path: Path) -> ParsedCompetitionOutput: - """Parse deterministic metrics and profile rows from competition output.""" - - metadata: list[str] = [] - metrics: dict[str, float] = {} - profile: dict[int, CompetitionProfileRow] = {} - - reading_profile = False - - for line_number, raw_line in enumerate( - path.read_text(encoding="utf-8").splitlines(), - start=1, - ): - line = raw_line.strip() - - if not line: - continue - - # Runtime varies between executions and is not scientific output. - if line.startswith("Run time ="): - continue - - if line.startswith("Position"): - columns = line.split() - - expected_columns = ( - "Position", - "Base", - "P_melt", - "P_Z", - "P_cruciform", - ) - - if tuple(columns) != expected_columns: - raise AssertionError( - f"{path}:{line_number}: unexpected competition " - f"profile header: {line!r}" - ) - - reading_profile = True - continue - - if reading_profile: - columns = line.split() - - if len(columns) != 5: - raise AssertionError( - f"{path}:{line_number}: expected five profile columns, " - f"found {len(columns)}: {line!r}" - ) +def test_text_output_matches_the_reference(text_run: SistRun) -> None: + reference = REFERENCE_DIRECTORY / text_run.case.reference - position_text, base, p_melt, p_z, p_cruciform = columns - position = int(position_text) + actual = _scientific_lines(text_run.output_path.read_text(encoding="utf-8")) + expected = _scientific_lines(reference.read_text(encoding="utf-8")) - profile[position] = CompetitionProfileRow( - base=base, - p_melt=float(p_melt), - p_z=float(p_z), - p_cruciform=float(p_cruciform), - ) + assert actual == expected - continue - if line.startswith("Scaling factor "): - value = parse_numeric_value(line.removeprefix("Scaling factor ")) - - if value is None: - raise AssertionError( - f"{path}:{line_number}: could not parse scaling factor" - ) - - metrics["Scaling factor"] = value - continue - - # Some lines contain more than one key/value pair separated by ';'. - parsed_segment = False - - for segment in line.split(";"): - if " = " not in segment: - continue - - key, raw_value = segment.split(" = ", maxsplit=1) - numeric_value = parse_numeric_value(raw_value) - - if numeric_value is None: - continue - - metrics[key.strip()] = numeric_value - parsed_segment = True - - if not parsed_segment: - metadata.append(line) - - if not profile: - raise AssertionError(f"No position profile was found in {path}") - - return ParsedCompetitionOutput( - metadata=tuple(metadata), - metrics=metrics, - profile=profile, +def test_json_output_matches_the_reference(json_run: SistRun) -> None: + algorithm = ALGORITHMS[json_run.case.algorithm] + reference = QsiddOutput.parse( + (REFERENCE_DIRECTORY / json_run.case.reference).read_text(encoding="utf-8") ) + result = json.loads(json_run.output_path.read_text(encoding="utf-8")) -def parse_transition_output(path: Path) -> ParsedTransitionOutput: - """Parse deterministic metrics and profile rows from transition output.""" - - metadata: list[str] = [] - metrics: dict[str, float] = {} - profile: dict[int, TransitionProfileRow] = {} - - reading_profile = False - profile_has_energy: bool | None = None - - for line_number, raw_line in enumerate( - path.read_text(encoding="utf-8").splitlines(), - start=1, - ): - line = raw_line.strip() - - if not line: - continue - - # Runtime varies between executions and is not scientific output. - if line.startswith("Run time ="): - continue - - if line.startswith("Position"): - columns = line.split() - - if columns == ["Position", "Base", "P(x)"]: - profile_has_energy = False - elif columns == ["Position", "Base", "P(x)", "G(x)"]: - profile_has_energy = True - else: - raise AssertionError( - f"{path}:{line_number}: unexpected transition " - f"profile header: {line!r}" - ) - - reading_profile = True - continue - - if reading_profile: - if profile_has_energy is None: - raise AssertionError( - f"{path}:{line_number}: profile format was not determined" - ) - - columns = line.split() - expected_column_count = 4 if profile_has_energy else 3 - - if len(columns) != expected_column_count: - raise AssertionError( - f"{path}:{line_number}: expected " - f"{expected_column_count} profile columns, " - f"found {len(columns)}: {line!r}" - ) - - position = int(columns[0]) - base = columns[1] - probability = float(columns[2]) - - energy = float(columns[3]) if profile_has_energy else None - - profile[position] = TransitionProfileRow( - base=base, - probability=probability, - energy=energy, - ) - - continue - - if line.startswith("Scaling factor "): - value = parse_numeric_value(line.removeprefix("Scaling factor ")) - - if value is None: - raise AssertionError( - f"{path}:{line_number}: could not parse scaling factor" - ) - - metrics["Scaling factor"] = value - continue - - # Some lines contain more than one key/value pair separated by ';'. - parsed_segment = False - - for segment in line.split(";"): - if " = " not in segment: - continue - - key, raw_value = segment.split(" = ", maxsplit=1) - numeric_value = parse_numeric_value(raw_value) - - if numeric_value is None: - continue - - metrics[key.strip()] = numeric_value - parsed_segment = True - - if not parsed_segment: - metadata.append(line) - - if not profile: - raise AssertionError(f"No position profile was found in {path}") - - return ParsedTransitionOutput( - metadata=tuple(metadata), - metrics=metrics, - profile=profile, - ) - - -def assert_number_matches( - *, - name: str, - expected: float, - actual: float, -) -> None: - """Compare a numerical value with the documented baseline tolerance.""" - - assert actual == pytest.approx( - expected, - rel=RELATIVE_TOLERANCE, - abs=ABSOLUTE_TOLERANCE, - ), f"{name} changed: expected {expected!r}, actual {actual!r}" - - -def assert_metadata_matches( - *, - name: str, - expected: tuple[str, ...], - actual: tuple[str, ...], -) -> None: - """Compare deterministic non-numerical output metadata.""" - - assert actual == expected, ( - f"{name} non-numerical metadata changed:\n" - f"expected: {expected!r}\n" - f"actual: {actual!r}" - ) - - -def assert_metrics_match( - *, - name: str, - expected: dict[str, float], - actual: dict[str, float], -) -> None: - """Compare all deterministic scientific metrics.""" - - assert actual.keys() == expected.keys(), ( - f"{name} reported scientific metrics changed:\n" - f"missing: {expected.keys() - actual.keys()}\n" - f"extra: {actual.keys() - expected.keys()}" - ) - - for metric_name, expected_value in expected.items(): - assert_number_matches( - name=f"{name} {metric_name}", - expected=expected_value, - actual=actual[metric_name], - ) - - -def test_competition_scientific_results_match_baseline( - competition_run: SistRun, -) -> None: - """The competition calculation should reproduce its 1.0.0 baseline.""" - - process = competition_run.process - - assert process.returncode == 0, ( - f"Competition calculation failed with exit code " - f"{process.returncode}\n\n" - f"stdout:\n{process.stdout}\n\n" - f"stderr:\n{process.stderr}" - ) - - expected = parse_competition_output(COMPETITION_REFERENCE) - actual = parse_competition_output(competition_run.output_path) - - assert_metadata_matches( - name="competition", - expected=expected.metadata, - actual=actual.metadata, - ) - - assert_metrics_match( - name="competition", - expected=expected.metrics, - actual=actual.metrics, + assert result["input"]["analysed_sequence"] == "".join(reference.column("Base")) + assert result["summary"]["state_counts"]["total"] == reference.count( + "Total number of states" ) - assert actual.profile.keys() == expected.profile.keys(), ( - "Competition reported sequence positions changed" - ) - - for position, expected_row in expected.profile.items(): - actual_row = actual.profile[position] - - assert actual_row.base == expected_row.base, ( - f"Competition base changed at position {position}: " - f"expected {expected_row.base!r}, " - f"actual {actual_row.base!r}" - ) - - assert_number_matches( - name=f"competition position {position} P_melt", - expected=expected_row.p_melt, - actual=actual_row.p_melt, - ) - - assert_number_matches( - name=f"competition position {position} P_Z", - expected=expected_row.p_z, - actual=actual_row.p_z, - ) - - assert_number_matches( - name=f"competition position {position} P_cruciform", - expected=expected_row.p_cruciform, - actual=actual_row.p_cruciform, - ) - - -def test_transition_scientific_results_match_baseline( - transition_run: SistRun, -) -> None: - """Each individual transition should reproduce its 1.0.0 baseline.""" - - process = transition_run.process - - assert process.returncode == 0, ( - f"{transition_run.name} calculation failed with exit code " - f"{process.returncode}\n\n" - f"stdout:\n{process.stdout}\n\n" - f"stderr:\n{process.stderr}" - ) - - reference_output = REFERENCE_DIRECTORY / f"{transition_run.name}.txt" + for transition in algorithm.transitions: + names = transition.names(competition=algorithm.competition) + profile = result["transitions"][transition.name]["profile"] + expected = [float(value) for value in reference.column(names.profile_column)] - assert reference_output.is_file(), ( - f"Reference output does not exist: {reference_output}" - ) - - expected = parse_transition_output(reference_output) - actual = parse_transition_output(transition_run.output_path) - - assert_metadata_matches( - name=transition_run.name, - expected=expected.metadata, - actual=actual.metadata, - ) - - assert_metrics_match( - name=transition_run.name, - expected=expected.metrics, - actual=actual.metrics, - ) - - assert actual.profile.keys() == expected.profile.keys(), ( - f"{transition_run.name} reported sequence positions changed" - ) - - for position, expected_row in expected.profile.items(): - actual_row = actual.profile[position] - - assert actual_row.base == expected_row.base, ( - f"{transition_run.name} base changed at position {position}: " - f"expected {expected_row.base!r}, " - f"actual {actual_row.base!r}" - ) - - assert_number_matches( - name=f"{transition_run.name} position {position} P(x)", - expected=expected_row.probability, - actual=actual_row.probability, + assert profile["probability"] == pytest.approx( + expected, rel=REFERENCE_RTOL, abs=0 ) - assert (actual_row.energy is None) == (expected_row.energy is None), ( - f"{transition_run.name} energy output changed at position {position}" - ) - - if expected_row.energy is not None: - assert actual_row.energy is not None - - assert_number_matches( - name=f"{transition_run.name} position {position} G(x)", - expected=expected_row.energy, - actual=actual_row.energy, - ) + if "G(x)" in reference.columns: + free_energy = [ + float(value) + for value, probability in zip( + reference.column("G(x)"), expected, strict=True + ) + if probability != 0 + ] + written = [ + value + for value in profile["free_energy_kcal_per_mol"] + if value is not None + ] + + assert written == pytest.approx(free_energy, rel=REFERENCE_RTOL, abs=0) diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py new file mode 100644 index 0000000..2c00c73 --- /dev/null +++ b/tests/unit/test_cli.py @@ -0,0 +1,103 @@ +"""Unit tests for sist.cli and running sist as a module.""" + +from __future__ import annotations + +import runpy +from typing import Any + +import pytest + +from sist import cli + + +class FakeRunner: + """Stand-in for SistRunner that records how it was made. + + Attributes: + settings: Keyword arguments of the most recent runner. + error: Exception to raise when run, if any. + """ + + settings: dict[str, Any] = {} + error: Exception | None = None + + def __init__(self, **settings: Any) -> None: + """Record the settings. + + Args: + **settings: The runner's keyword arguments. + """ + FakeRunner.settings = settings + + def run(self) -> None: + """Do nothing, or raise the configured error. + + Raises: + Exception: The configured error, if set. + """ + if FakeRunner.error is not None: + raise FakeRunner.error + + +@pytest.fixture +def fake_runner(monkeypatch: pytest.MonkeyPatch) -> type[FakeRunner]: + """Replace SistRunner in the CLI with a stand-in.""" + FakeRunner.settings = {} + FakeRunner.error = None + monkeypatch.setattr(cli, "SistRunner", FakeRunner) + + return FakeRunner + + +def test_main_passes_the_settings_to_the_runner(fake_runner: type[FakeRunner]) -> None: + cli.main(["-f", "seq.fa", "-a", "Z", "--json", "result.json"]) + + assert fake_runner.settings["algorithm"] == "Z" + assert fake_runner.settings["json_file"] == "result.json" + assert fake_runner.settings["command"] == [ + "sist", + "-f", + "seq.fa", + "-a", + "Z", + "--json", + "result.json", + ] + + +def test_main_exits_on_an_invalid_setting(fake_runner: type[FakeRunner]) -> None: + with pytest.raises(SystemExit) as raised: + cli.main(["-f", "seq.fa", "-a", "M", "-T", "0"]) + + assert raised.value.code == 1 + + +def test_main_exits_when_the_run_fails(fake_runner: type[FakeRunner]) -> None: + fake_runner.error = RuntimeError("broken") + + with pytest.raises(SystemExit) as raised: + cli.main(["-f", "seq.fa", "-a", "M"]) + + assert raised.value.code == 1 + + +def test_main_warns_when_run_by_its_old_name( + fake_runner: type[FakeRunner], + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setattr(cli.sys, "argv", ["master.pl", "-f", "seq.fa", "-a", "M"]) + + cli.main() + + assert "deprecated alias" in capsys.readouterr().err + assert fake_runner.settings["command"][0] == "master.pl" + + +def test_running_the_package_calls_main(monkeypatch: pytest.MonkeyPatch) -> None: + calls = [] + monkeypatch.setattr(cli, "main", lambda: calls.append(True)) + + runpy.run_module("sist", run_name="__main__") + + assert calls == [True] diff --git a/tests/unit/test_runner.py b/tests/unit/test_runner.py new file mode 100644 index 0000000..ff519e3 --- /dev/null +++ b/tests/unit/test_runner.py @@ -0,0 +1,386 @@ +"""Unit tests for sist.runner, using stand-ins for IRF and qsidd. + +These cover the runner's own jobs: building qsidd commands, choosing between +text and JSON output, and turning failures into failed results. What goes into +a result is covered by the sist.results tests. +""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest + +from sist.results.diagnostics import ResultError +from sist.runner import ScoredRepeats, SistRunner, SubprocessQsidd + +QSIDD_PATH = Path(__file__).resolve().parent / "data" / "qsidd" + + +class FakeQsidd: + """Stand-in for qsidd that prints a saved output and records each command. + + Attributes: + output_name: File name of the saved qsidd output to print. + returncode: Exit code to report. + stderr: Standard error to report. + replace: Text to swap in the saved output, as ``(old, new)``. + commands: Every command line it was asked to run. + """ + + def __init__( + self, + output_name: str, + *, + returncode: int = 0, + stderr: str = "", + replace: tuple[str, str] = ("", ""), + ) -> None: + """Set up the stand-in. + + Args: + output_name: File name of the saved qsidd output to print. + returncode: Exit code to report. + stderr: Standard error to report. + replace: Text to swap in the saved output, as ``(old, new)``. + """ + self.output_name = output_name + self.returncode = returncode + self.stderr = stderr + self.replace = replace + self.commands: list[list[str]] = [] + + def run(self, command: list[str]) -> subprocess.CompletedProcess[str]: + """Record the command and report the saved output. + + Args: + command: The command line to run. + + Returns: + The saved output as a finished process. + """ + self.commands.append(command) + stdout = (QSIDD_PATH / self.output_name).read_text(encoding="utf-8") + + if self.replace[0]: + stdout = stdout.replace(*self.replace) + + return subprocess.CompletedProcess( + command, self.returncode, stdout, self.stderr + ) + + +class FakeScorer: + """Stand-in for the IR finder. + + Attributes: + missing_irf: Whether to behave as if IRF is not installed. + """ + + def __init__(self, *, missing_irf: bool = False) -> None: + """Set up the stand-in. + + Args: + missing_irf: Whether to behave as if IRF is not installed. + """ + self.missing_irf = missing_irf + + def score(self, file: str) -> ScoredRepeats: + """Return the scored inverted repeats saved for the fragment. + + Args: + file: Path to the sequence file. + + Returns: + The saved inverted repeats. + + Raises: + FileNotFoundError: If behaving as if IRF is not installed. + """ + if self.missing_irf: + raise FileNotFoundError("irf") + + ir_string = (QSIDD_PATH / "fragment.ir").read_text(encoding="utf-8").strip() + + return ScoredRepeats(ir_string, "3.09") + + +@pytest.fixture +def directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Point SIST at placeholder qsidd binaries.""" + placeholder = tmp_path / "qsidd" + placeholder.write_text("", encoding="utf-8") + monkeypatch.setenv("SIST_TRANS_THREE_BIN", str(placeholder)) + monkeypatch.setenv("SIST_TRANS_COMPETE_BIN", str(placeholder)) + + return tmp_path + + +def _runner(directory: Path, qsidd: FakeQsidd, **overrides: Any) -> SistRunner: + """Make a runner for the 20 bp fragment, using the stand-ins. + + Args: + directory: Directory holding the sequence and the output files. + qsidd: The stand-in for qsidd. + **overrides: Settings to change from the defaults. + + Returns: + The runner. + """ + sequence_path = directory / "fragment.fa" + shutil.copy2(QSIDD_PATH / "fragment.fa", sequence_path) + + settings: dict[str, Any] = { + "file": str(sequence_path), + "algorithm": "M", + "temperature": 310.0, + "superhelical_density": 0.06, + "salt": 0.01, + "energy_threshold": 12.0, + "circular": False, + "nearest_neighbor": False, + "print_base_pair": False, + "print_parameters": False, + "print_ensemble_average": False, + "output_file": None, + "json_file": str(directory / "result.json"), + "command": ["sist", "-a", "M", "-f", "fragment.fa"], + "ir_scorer": FakeScorer(), + "qsidd": qsidd, + } + settings.update(overrides) + + return SistRunner(**settings) + + +def _read_result(directory: Path) -> dict[str, Any]: + """Read the result the runner wrote. + + Args: + directory: Directory the result was written to. + + Returns: + The result. + """ + return json.loads((directory / "result.json").read_text(encoding="utf-8")) + + +@pytest.mark.parametrize( + ("flag", "output_name", "algorithm_flags"), + [ + ("M", "melting.txt", []), + ("Z", "z-dna.txt", ["-Z"]), + ("C", "cruciform.txt", ["-C", "-X"]), + ("A", "competition.txt", ["-X"]), + ], +) +def test_run_builds_the_command_from_the_algorithm( + directory: Path, flag: str, output_name: str, algorithm_flags: list[str] +) -> None: + qsidd = FakeQsidd(output_name) + + _runner(directory, qsidd, algorithm=flag).run() + + command = qsidd.commands[0] + + assert command[1:5] == ["-b", "-p", "-r", "-P"] + assert [part for part in command if part in ("-Z", "-C", "-X")] == algorithm_flags + assert _read_result(directory)["calculation"]["algorithm"] == flag + + +def test_run_passes_nearest_neighbor_only_where_supported(directory: Path) -> None: + qsidd = FakeQsidd("z-dna.txt") + + _runner(directory, qsidd, algorithm="Z", nearest_neighbor=True).run() + + assert "-n" not in qsidd.commands[0] + + +def test_run_records_the_command_line(directory: Path) -> None: + _runner(directory, FakeQsidd("melting.txt")).run() + + command = _read_result(directory)["provenance"]["command"] + + assert command == ["sist", "-a", "M", "-f", "fragment.fa"] + + +def test_run_with_only_json_prints_no_text( + directory: Path, capsys: pytest.CaptureFixture[str] +) -> None: + _runner(directory, FakeQsidd("melting.txt")).run() + + assert capsys.readouterr().out == "" + + +def test_run_writes_text_from_a_second_normal_run(directory: Path) -> None: + qsidd = FakeQsidd("melting.txt") + output_path = directory / "result.txt" + + _runner(directory, qsidd, output_file=str(output_path), print_base_pair=True).run() + + assert output_path.read_text(encoding="utf-8").startswith("DNA sequence file") + assert "-P" in qsidd.commands[0] + assert "-P" not in qsidd.commands[1] + assert "-b" in qsidd.commands[1] + + +def test_run_without_json_prints_the_text_output( + directory: Path, capsys: pytest.CaptureFixture[str] +) -> None: + _runner(directory, FakeQsidd("melting.txt"), json_file=None).run() + + expected = (QSIDD_PATH / "melting.txt").read_text(encoding="utf-8") + + assert capsys.readouterr().out == expected + assert not (directory / "result.json").exists() + + +def test_run_without_json_raises_when_qsidd_fails(directory: Path) -> None: + runner = _runner(directory, FakeQsidd("melting.txt", returncode=3), json_file=None) + + with pytest.raises(subprocess.CalledProcessError): + runner.run() + + +def test_run_rejects_an_unknown_algorithm(directory: Path) -> None: + with pytest.raises(ValueError): + _runner(directory, FakeQsidd("melting.txt"), algorithm="X").run() + + +@pytest.mark.parametrize( + ("overrides", "qsidd", "code"), + [ + ({}, FakeQsidd("melting.txt", returncode=3, stderr="broken"), "qsidd_failed"), + ({}, FakeQsidd("fragment.fa"), "internal_error"), + ( + {}, + FakeQsidd( + "melting.txt", + replace=("Average number of runs = ", "Average number of runs = -nan "), + ), + "internal_error", + ), + ( + {"algorithm": "C", "ir_scorer": FakeScorer(missing_irf=True)}, + FakeQsidd("cruciform.txt"), + "irf_not_found", + ), + ], + ids=["qsidd-fails", "unreadable-output", "nan-in-output", "irf-missing"], +) +def test_run_writes_a_failed_result( + directory: Path, overrides: dict[str, Any], qsidd: FakeQsidd, code: str +) -> None: + with pytest.raises(ResultError) as raised: + _runner(directory, qsidd, **overrides).run() + + error = _read_result(directory)["error"] + + assert raised.value.code == code + assert error["code"] == code + + if code == "qsidd_failed": + assert (error["exit_code"], error["stderr"]) == (3, "broken") + + +def test_run_writes_a_failed_result_when_qsidd_is_missing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("SIST_TRANS_THREE_BIN", str(tmp_path / "missing-qsidd")) + + with pytest.raises(ResultError): + _runner(tmp_path, FakeQsidd("melting.txt")).run() + + assert _read_result(tmp_path)["error"]["code"] == "qsidd_not_found" + + +def test_run_passes_the_chosen_text_flags(directory: Path) -> None: + qsidd = FakeQsidd("melting.txt") + + _runner( + directory, + qsidd, + json_file=None, + print_parameters=True, + print_ensemble_average=True, + nearest_neighbor=True, + circular=True, + ).run() + + assert qsidd.commands[0][1:5] == ["-p", "-r", "-n", "-c"] + + +def test_ir_finder_scorer_returns_the_string_and_version( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class FakeIRFinder: + """Stand-in for IRFinder that records the shape it was given.""" + + irf_version = "3.09" + + def __init__(self, *, temperature: float, shape: str) -> None: + """Record the settings. + + Args: + temperature: Temperature in kelvin. + shape: ``"linear"`` or ``"circular"``. + """ + self.shape = shape + + def compute_cruciform_energy_string(self, file: str) -> str: + """Return a string naming the shape and file. + + Args: + file: Path to the sequence file. + + Returns: + The string. + """ + return f"{self.shape},{file}" + + monkeypatch.setattr("sist.runner.IRFinder", FakeIRFinder) + runner = _runner_without_stand_ins(circular=True) + + repeats = runner._ir_scorer.score("fragment.fa") + + assert repeats == ScoredRepeats("circular,fragment.fa", "3.09") + + +def test_subprocess_qsidd_runs_a_command() -> None: + completed = SubprocessQsidd().run([sys.executable, "-c", "print('ran')"]) + + assert completed.returncode == 0 + assert completed.stdout == "ran\n" + + +def _runner_without_stand_ins(**overrides: Any) -> SistRunner: + """Make a runner with its default IR scorer and qsidd executor. + + Args: + **overrides: Settings to change from the defaults. + + Returns: + The runner. + """ + settings: dict[str, Any] = { + "file": "fragment.fa", + "algorithm": "C", + "temperature": 310.0, + "superhelical_density": 0.06, + "salt": 0.01, + "energy_threshold": 12.0, + "circular": False, + "nearest_neighbor": False, + "print_base_pair": False, + "print_parameters": False, + "print_ensemble_average": False, + "output_file": None, + } + settings.update(overrides) + + return SistRunner(**settings) diff --git a/tests/unit/test_schema_cli.py b/tests/unit/test_schema_cli.py index c6ca5ea..e483b0b 100644 --- a/tests/unit/test_schema_cli.py +++ b/tests/unit/test_schema_cli.py @@ -89,3 +89,22 @@ def test_main_exits_2_without_files(capsys: pytest.CaptureFixture[str]) -> None: assert raised.value.code == 2 assert "usage: sist-validate" in capsys.readouterr().err + + +def test_main_exits_1_on_an_unexpected_error( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + def broken_validator() -> None: + """Fail as an unexpected error would. + + Raises: + RuntimeError: Always. + """ + raise RuntimeError("broken") + + monkeypatch.setattr("sist.schema_cli.ResultValidator", broken_validator) + + with pytest.raises(SystemExit) as raised: + main([str(tmp_path / "result.json")]) + + assert raised.value.code == 1