Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
88 kB

afluent/afluent

Project Overview

AFLuent is an automated fault localization tool distributed as a Pytest plugin for Python projects. Its purpose is to shorten debugging cycles: whenever one or more test cases fail during a Pytest session, the plugin activates, gathers code-coverage information collected through Coverage.py, and produces a ranked list of suspicious source statements where the fault most likely resides. Statements are ordered in descending order of suspiciousness, computed from the pass/fail spectrum of the run; if all tests pass, no diagnosis is performed.

Functionally, AFLuent implements spectrum-based fault localization with four classic ranking equations: Tarantula, Ochiai, Ochiai2, and DStar (the latter with a configurable exponent). Several equations can be requested together, with results sorted by the first one given. Because Pytest discovers the plugin via its pytest11 entry point, options integrate directly into the pytest command: --afl or --afl-debug enable the tool, --afl-ignore excludes paths (typically test code) from scoring, --afl-results caps the printed ranking (default 20), --tiebreaker selects random, cyclomatic, logical, or enhanced strategies for resolving equal scores, --report writes json, csv, or eval-mode outputs, and --per-test-report dumps per-test coverage. Warnings flag conflicts with pytest-cov and early-exit flags such as -x/--maxfail that would skew results.

Architecturally, the package is small and cohesive. main.py is the plugin entry point, registering the command-line group, wrapping each test's execution with coverage collection, recording pass/fail/skip outcomes, and on session finish building a Spectrum to print and persist results. spectrum_parser.py reassembles the per-test coverage data into files and lines, computes totals, applies the ranking equations, and renders a color-coded, severity-shaded report table. line.py and proj_file.py model the domain: Line objects track which passing and failing tests executed each statement and hold their suspiciousness and tiebreaker scores, while ProjFile groups them per source file and populates tiebreaker datasets. tiebreak_generator.py supplies those static-analysis datasets, using libcst and radon to derive cyclomatic complexity and logical-operator counts per line. Supporting infrastructure includes a tests/ suite, flake8/pylint/mypy configuration, GitHub Actions CI, Poetry packaging, and an MIT license.

Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.

Submission Constraints (read carefully — the evaluation depends on these)

This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:

  1. Do NOT create or modify any files under the test directories (e.g. tests/, test/, testing/, or files named test_*.py / conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.

  2. Your package MUST be importable by the name the tests use. The hidden tests import your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid pyproject.toml / setup.py / setup.cfg and lay out your modules so that pip install -e . succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.

  3. Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.

Install / Reconstruction Contract

Follow this contract before implementing the documented APIs:

  • Project root: /workspace/repo at runtime; the submitted repository root is ..
  • Package/distribution name: afluent
  • Package roots: .
  • Install strategy: editable-install
  • Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
  • Provision commands:
    python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
    programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
    export -f programgen_pip_install
    programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
    programgen_pip_install python3 -m pip install 'poetry-core>=1.0.0'
    (
    programgen_install_report="$(mktemp)"
    trap 'rm -f "$programgen_install_report"' EXIT
    SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
    python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n    metadata=item.get('"'"'metadata'"'"', {})\n    name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n    provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n    selected={'"'"''"'"'} | (provided & requested)\n    parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n    while True:\n        added=set()\n        for requirement in parsed:\n            if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n                continue\n            if canonicalize_name(requirement.name)==name:\n                if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n                    raise ValueError('"'"'local extra requires a different target distribution'"'"')\n                extras={canonicalize_name(value) for value in requirement.extras}\n                if not extras <= provided:\n                    raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n                added.update(extras - selected)\n        if not added:\n            break\n        selected.update(added)\n    for requirement in parsed:\n        if canonicalize_name(requirement.name)==name:\n            continue\n        if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n            requirement.marker=None\n            requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report"
    )
    
  • Runtime setup:
    {
      [ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; };
      SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
    }
    
  • Project root for installation: .
  • Build-version environment: SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0, PDM_BUILD_SCM_VERSION=0.0.0, POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0, UV_DYNAMIC_VERSIONING_BYPASS=0.0.0
  • Test directory: tests, tests/test_data
  • Test command: bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_line.py tests/test_proj_file.py tests/test_spectrum_parser.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_line.py tests/test_proj_file.py tests/test_spectrum_parser.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_line.py tests/test_proj_file.py tests/test_spectrum_parser.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?'
  • Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.

Environment & Project Structure

  • Language: python
  • Build system: python
  • Test command: bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_line.py tests/test_proj_file.py tests/test_spectrum_parser.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_line.py tests/test_proj_file.py tests/test_spectrum_parser.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_line.py tests/test_proj_file.py tests/test_spectrum_parser.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?

Project Directory Structure

.flake8
.github/workflows/main .yml
.github/workflows/release.yml
.gitignore
.pylintrc
LICENSE
README.md
afluent/__init__.py
afluent/line.py
afluent/main.py
afluent/proj_file.py
afluent/spectrum_parser.py
afluent/tiebreak_generator.py
images/afluent_logo2.png
poetry.lock
pyproject.toml

API Usage Guide

Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.

Capability: Pytest plugin integration and CLI options

Pytest plugin integration and CLI options

Purpose

This capability turns AFLuent from a library into an opt-in pytest plugin. Because the distribution declares a pytest11 entry point named afluent pointing at afluent.main, pytest imports the module at startup and calls its hook functions automatically; no conftest wiring is needed. pytest_addoption builds the entire CLI surface up front, and pytest_cmdline_main decides — before collection — whether the runtime half of the plugin (the Afluent hook object) should be instantiated and registered. Every other feature of the tool (spectrum math, tie-breaking, report files) executes only when this two-stage handshake works.

Option group semantics

All options are added to one argparse group keyed afluent (display title Automated Fault Localization (AFLuent)), so they render as a single pytest --help section. Details a re-implementation must preserve:

  • The enable switch is one option with two spellings, --afl and --afl-debug, both stored into dest afl_enable as a store_true bool defaulting to False. They are aliases, not separate flags, and neither implies anything else.
  • Equation selectors --tarantula, --ochiai, --ochiai2, and --dstar share dest afl_methods using append_const. Each occurrence appends its constant to a list, so repeats and combinations accumulate in user-specified order. When nothing was passed the dest is None, and the plugin substitutes the canonical list dstar, tarantula, ochiai, ochiai2. The order matters downstream: the spectrum layer sorts results by the first equation given, so --ochiai --dstar ranks by Ochiai.
  • --dstar-pow (int, default 3) and --afl-results (int, default 20) are plain stored values. Argparse coerces the type but the option layer performs no range validation, so values such as --afl-results 0 or a negative power flow through unchanged into the plugin.
  • --afl-ignore uses action=extend with nargs=*: patterns accumulate across repeated occurrences, and one occurrence may carry several space-separated patterns, so a run with at least one occurrence yields a flat string list used as the coverage omit list. When the flag never appears, argparse leaves the afl_ignore dest at its default — None, since no default is supplied — not an empty list, so the coverage omit value is None at registration.
  • --report is choice-restricted to json, csv, eval (default None). Choosing eval additionally flips an eval-mode flag on the plugin, changing what the spectrum layer computes and persists.
  • --tiebreaker defaults to random and is restricted to random, cyclomatic, logical, enhanced. The logical and enhanced spellings dispatch to LogicalTieBreaker and EnhancedTieBreaker from afluent.tiebreak_generator, respectively. Both classes share one store-then-find contract: each stores the full syntax mutant density data set it is given, and a calculate_mutant_density call on it drives the finder invocation. The two classes are distinguished here only by name — this capability asserts no behavioral difference beyond that shared contract — and they run only on the exit-status-1 diagnosis path.
  • --per-test-report is a plain store_true flag with no default expression.

Registration flow in pytest_cmdline_main

The order of operations is test-visible and should be replicated exactly:

  1. Conflict scan (unconditional). For each name in CONFLICTING_PLUGINS (currently only pytest_cov), config.pluginmanager.hasplugin(name) is checked; when true, a WARNING-styled banner prints advising the user to disable the conflicting plugin for accuracy. This runs before and independently of the enable check, so merely having pytest-cov loaded prints the warning even for runs that never enable AFLuent.
  2. Early-exit scan (enabled only). When AFLuent is enabled, config.getoption("--maxfail") is inspected. Its default of 0 is falsy, so the warning fires only when -x or --maxfail was given; the banner explains that exiting after the first failure skews results and suggests removing those flags. Note the lookup is by the flag string, while other options are read by dest.
  3. Registration. When config.getoption("afl_enable") is true, an Afluent(config) object is constructed and registered on the plugin manager under the name Afluent. Registration is what arms the per-test coverage hooks; without it the session is an ordinary pytest run plus warnings.
  4. Disabled path. Otherwise a WARNING banner prints that AFLuent is disabled and how to enable it. This message appears on every run lacking --afl/--afl-debug, a detail easy to overlook.

The hook does not set an exit status and does not stop the normal main; the hook chain simply continues afterward.

State created at registration

Constructing the plugin copies every option value onto the object at init time; later config mutation has no effect. It also builds an in-memory coverage.Coverage with data_file=None, auto_data=False, branch=True, config_file=False, and omit set to the ignore patterns (which is None when --afl-ignore was never passed) — branch coverage is always on and no .coveragerc is honored. The session spectrum dict starts empty and is keyed per test as <module>_<testname> (the item's parent name plus the item name), with a notSet result field that the report hook later overwrites with pass, fail, or skip. Eval mode is decided here from the report choice.

Interaction with the surrounding run

Because coverage is wrapped around each test's function call, collection is excluded and results reflect executed lines per test. On session finish the pytest exit status drives behavior: 0 prints the green all-passed banner and performs no diagnosis; 1 prints the red banner and runs the spectrum with the recorded methods, DStar power, tiebreaker, and eval mode — the tiebreaker dispatching to the LogicalTieBreaker/EnhancedTieBreaker classes of afluent.tiebreak_generator when logical or enhanced was selected — printing at most the configured result count and writing the chosen report type. Two side-effect files land in the current working directory: afluent_timings.json is always written (test wall time from the terminal reporter's session start, plus localization time, which is 0 when diagnosis is skipped), and afluent_per_test_report.json is written additionally when --per-test-report was given, even when all tests passed.

Edge cases and test-sensitive behavior

  • Warnings are emitted with print as styled banners, not through pytest's terminal writer or the warnings system, so capture settings change whether they appear in test output.
  • Equation selectors have no argparse default, so the dest is None rather than an empty list; the substitution check must be falsiness-based, not len().
  • Invalid --report or --tiebreaker values fail at argparse time with pytest's standard usage error before any hook runs; there is no runtime validation of combinations such as --report without --afl (the report is then simply never produced).
  • The conflict warning and the disabled banner can co-occur in the same run; the maxfail warning only co-occurs with them when AFLuent is enabled.
  • Options remain readable by both dest and long-name spellings, which matters for tests that assert on config values before registration.

Exact API Reference

afluent.main.pytest_addoption

  • Import Path: from afluent.main import pytest_addoption
  • Signature:
def pytest_addoption(parser)
  • Behavior: Add AFLuent command line group and arguments to accept.

afluent.main.pytest_cmdline_main

  • Import Path: from afluent.main import pytest_cmdline_main
  • Signature:
def pytest_cmdline_main(config)
  • Behavior: Check if AFLuent is enabled and register the plugin object.

afluent.tiebreak_generator.EnhancedTieBreaker

  • Import Path: from afluent.tiebreak_generator import EnhancedTieBreaker
  • Signature:
class EnhancedTieBreaker:
    def calculate_mutant_density(self)
  • Behavior: Store the full syntax mutant density data set and call the finder.

afluent.tiebreak_generator.LogicalTieBreaker

  • Import Path: from afluent.tiebreak_generator import LogicalTieBreaker
  • Signature:
class LogicalTieBreaker:
    def calculate_mutant_density(self)
  • Behavior: Store the full syntax mutant density data set and call the finder.

Capability: Per-test coverage collection during test runs

Per-test coverage collection during test runs

Purpose and data contract

This capability turns a pytest session into a per-test coverage trace: for every test function that actually executes, AFLuent records (a) which files and statement lines Coverage.py measured while that one test ran, and (b) whether the test passed, failed, or was skipped. The accumulated state lives on the plugin instance as session_spectrum, a dict keyed by test id whose values are two-field records:

  • "coverage": dict mapping each measured file's absolute path to the list of integer line numbers executed by this test only.
  • "result": "passed", "failed", "skipped", or the sentinel "notSet" until a call-phase outcome arrives.

Keys are built as f"{pyfuncitem.parent.name}_{pyfuncitem.name}", so a method inside a class becomes TestThing_test_case, and parametrized cases keep their bracket suffix (test_case[3-True]). Insertion order follows execution order, so the dict doubles as a chronological log. This exact shape is simultaneously the plugin's internal state, the content of afluent_per_test_report.json, and the config argument of Spectrum. Offline consumers can replay a session by loading the per-test JSON back into Spectrum(config, ...) only once every record's "result" is a final outcome: Spectrum.__init__ runs reassemble() first, which indexes totals keyed only by passed/failed/skipped, so a record still carrying "notSet" (or any non-trio value) raises KeyError there and calculate_sus() never runs. Remove or repair such records before replay.

Activation and the shared Coverage object

pytest_cmdline_main instantiates the plugin only when --afl/--afl-debug set afl_enable, registering it under the plugin name "Afluent". __init__ builds one coverage.Coverage reused for the whole session with deliberately strict options: data_file=None (no .coverage file is ever produced), auto_data=False, branch=True (branch data is enabled even though only statement lines are consumed), config_file=False (any project coverage config is ignored so it cannot perturb the spectrum), and omit taken from the --afl-ignore patterns (typically tests/*) so test code itself is not scored. The same __init__ snapshots the option defaults that shape downstream behavior: methods default to ["dstar", "tarantula", "ochiai", "ochiai2"] when no equation flag is passed, results_num defaults to 20, tiebreaker to "random", dstar_pow to 3, and eval_mode is true only for --report eval.

Collecting around each test

pytest_pyfunc_call is a hook wrapper that brackets the test invocation:

  1. cov.start() before yield.
  2. cov.stop() immediately after the test function returns normally.
  3. cov.get_data() is read; the key's record is created with "result": "notSet" and an empty "coverage" dict, then filled by iterating coverage_data.measured_files() and storing cov.get_data().lines(file) per file.
  4. The body catches only coverage.exceptions.CoverageWarning; any other exception the test raises (including Skipped from pytest.skip() inside the body) propagates before stop() and before the record exists, so that test contributes no entry.
  5. cov.erase() runs after the try/except, resetting accumulated data so the next test's snapshot contains only its own execution.

Consequences: each record is exclusive to one test (no cross-contamination between tests), code pytest runs outside pytest_pyfunc_call (fixtures, setup/teardown protocol) is never captured, and tests skipped in setup (e.g. @pytest.mark.skip) never enter the spectrum at all — although "skipped" remains a fully supported result downstream (totals["skipped"], Line.skipped_by).

Attaching the outcome

pytest_runtest_makereport is also a wrapper: it yields to let the report be produced, then — only when report.when == "call" and the key already exists in session_spectrum — overwrites "result" with report.outcome. Both guards matter: setup/teardown-phase reports never clobber the value, and tests without a coverage record are ignored. The mapping from pytest outcomes to spectrum values is identity (passed/failed/skipped).

Session finish and emitted artifacts

At pytest_sessionfinish the plugin, in order:

  1. If --per-test was passed, dumps session_spectrum to afluent_per_test_report.json with indent=4. This happens before the exit-status branch, so the per-test dump is written even when the whole suite passes — and it preserves any "notSet" sentinel verbatim (see the replay caveat above).
  2. If exitstatus == 1 (at least one failure), builds Spectrum(session_spectrum, dstar_pow=..., tiebreaker=..., eval_mode=(report == "eval")), calls print_report(methods, results_num) and, when --report was given, store_report(report). Any other status — notably 0, which prints the "All tests passed, no need to diagnose using AFLuent." banner — skips diagnosis entirely.
  3. Always writes afluent_timings.json containing test_time (measured from the terminal reporter's session start) and localization_time (0 when no diagnosis ran).

--report output is derived entirely from Spectrum.sorted_lines, an attribute populated only inside generate_report() — i.e., as a side effect of print_report(). The plugin's own flow prints before storing, so its files are non-empty, but a standalone store_report() call made first serializes an empty list and writes an empty ranking. Two further properties: sorted_lines is captured before the max_items truncation used for printing, so the stored ranking is the full line list (results_num truncates only the printed table, never the report file); and store_report("eval") does not produce a single artifact — it delegates to produce_full_eval_report(), which re-ranks the captured list for every method/tiebreaker pair and writes 16 CSV files named f"{method}_{tiebreaker}_report.csv".

How the record is consumed

Spectrum.reassemble() walks the dict: each test's result increments totals[result] (the three totals keys therefore assume only passed/failed/skipped; anything else surfaces as a KeyError there, and ProjFile.update_file rejects values outside the trio), then per measured file creates one ProjFile — eagerly populating the static tiebreaker datasets when eval_mode or a non-random tiebreaker is configured — and calls update_file(lines, result, test_name), which creates Line objects on first sight and appends the test name to passed_by/failed_by/skipped_by. calculate_sus() then scores every collected line for all four equations using those totals. Because a Line exists only if some test executed it, only covered statements are ever ranked.

Test-sensitive behaviors worth knowing

  • Coverage wraps only the call phase, so a line covered exclusively by fixtures never appears.
  • measured_files() yields absolute paths; those paths are the keys inside each record's "coverage" dict (and hence in report rows). The per-test JSON's top-level keys remain the test-id strings f"{parent.name}_{name}".
  • The per-test JSON preserves the "notSet" sentinel — the observable symptom of a test whose call report never landed, and a record to prune or repair before replaying the dump into Spectrum.
  • --afl-ignore patterns reach Coverage's omit, so ignored files vanish from every record rather than being filtered later.
  • Diagnosis is all-or-nothing on exitstatus == 1; an interrupted run (status 2) or a no-tests run (status 5) produces no ranking, only the timings file.
  • Rankings under the default "random" tiebreaker are nondeterministic among tied scores: generate_rankings() shuffles the line list before a stable descending-score sort, so equal-score lines — and repeated re-rankings of the same list, as in the eval report — land in a different order every run. Deterministic order requires a static tiebreaker (cyclomatic, logical, enhanced) or eval_mode, the configurations that trigger the per-ProjFile dataset population described above.

Exact API Reference

afluent.spectrum_parser.Spectrum

  • Import Path: from afluent.spectrum_parser import Spectrum
  • Required Test Import Paths:
    • afluent.spectrum_parser.Spectrum
  • Exact Test Import Statements:
    • from afluent import spectrum_parser
  • Kind: class
  • Signature:
class Spectrum:
    def __init__(self, config, dstar_pow=3, tiebreaker='random', eval_mode=False) -> None
    def generate_report(self, methods: List[str], max_items=-1) -> List[Tuple[Any, ...]]
    def reassemble(self)
    def calculate_sus(self)
    def as_dict(self)
    def print_report(self, methods: List[str], items_num: int)
    def store_report(self, report_type)
    def produce_full_eval_report(self)
    @staticmethod
    def generate_rankings(all_lines: List[line.Line], method: str, tiebreaker='random') -> List[line.Line]
    @staticmethod
    def calculate_severity(method: str, sus_score: float, rank: int, out_of: int)
    config: Any
    reassembled_data: Dict[str, proj_file.ProjFile]
    sorted_lines: List[line.Line]
    totals: dict
    dstar_pow: Any
    tiebreaker: Any
    eval_mode: Any
  • Behavior: Store all the information for individual files and lines coverage.

afluent.line

  • Import Path: from afluent import line
  • Required Test Import Paths:
    • afluent.line
  • Exact Test Import Statements:
    • from afluent import line
    • from afluent import line, proj_file
  • Kind: module
  • Behavior: Module required during hidden-test collection.

afluent.proj_file

  • Import Path: from afluent import proj_file
  • Required Test Import Paths:
    • afluent.proj_file
  • Exact Test Import Statements:
    • from afluent import line, proj_file
  • Kind: module
  • Behavior: Module required during hidden-test collection.

afluent.spectrum_parser

  • Import Path: from afluent import spectrum_parser
  • Required Test Import Paths:
    • afluent.spectrum_parser
  • Exact Test Import Statements:
    • from afluent import spectrum_parser
  • Kind: module
  • Behavior: Module required during hidden-test collection.

Capability: File and line coverage data model

File and line coverage data model

Purpose

This capability is the in-memory spine of AFLuent: it converts raw per-test coverage — a list of executed line numbers plus one verdict (passed / failed / skipped) per test — into two collaborating object types. ProjFile owns one file under test; Line owns one executed statement and accumulates exactly which tests touched it and how. Once populated, a Line is self-sufficient for scoring: the ranking equations read only len(failed_by) / len(passed_by) plus run-wide totals supplied by the caller, and the report writers read only the serialized dictionaries. The module-level constants (TARAN, OCHIAI, OCHIAI2, DSTAR for equations; RANDOM, CYCLOMATIC, LOGICAL, ENHANCED for tiebreakers) are plain strings that double as dictionary keys everywhere, so any code touching scores must use these constants, not ad-hoc literals.

Realistic workflow

  1. Build one ProjFile(name) per source file, where name is the file path stored verbatim on the object and reused as the static-analysis target.
  2. Optionally populate tiebreaker datasets before any coverage arrives: get_cyclomatic_tiebreaker_dataset(), get_logical_tiebreaker_dataset(), get_enhanced_tiebreaker_dataset() each delegate to a generator over self.name and overwrite the corresponding attribute (cyclomatic_complexity_data: dict[int,int], logical_tiebreak_data: dict[int,int], enhanced_tiebreak_data: dict[int,float]).
  3. Call update_file(covered_lines, test_result, test_case_name) once per test execution.
  4. After the run, compute suspiciousness per line (sus / sus_all) and serialize via as_dict().

update_file semantics (the test-sensitive core)

  • Empty input is a silent no-op. update_file([], <any verdict>, name) — even an invalid verdict — performs no validation and no state change: the case-sensitive verdict check lives inside the per-line loop, so an empty covered_lines creates no Line and never raises.
  • Lazy creation. The first sighting of a line number constructs Line(self.name, line_number) and inserts it into lines keyed by the int line number.
  • Tiebreaker seeding happens at creation only. If a dataset dict is non-empty, its value for that line is copied into tiebreakers["cyclomatic"|"logical"|"enhanced"] by direct indexing — a non-empty dataset missing the line number (e.g., coverage of blank lines or continuation lines absent from the AST) raises KeyError before the new Line is inserted into lines: the partially constructed object is discarded, the offending line number is absent from ProjFile.lines, and earlier line numbers in the same call keep their updates. An empty dataset is skipped, leaving the default 0.0. Lines created before a dataset was populated are never retroactively seeded.
  • Exact, case-sensitive verdicts. "passed" appends to passed_by, "failed" to failed_by, "skipped" to skipped_by. Anything else raises Exception(f"Unknown test result for {test_case_name}") — a bare Exception, not ValueError. The raise occurs mid-loop: lines already processed keep their updates, and — the mirror image of the KeyError case — the Line for the offending line number already exists in lines with empty *_by attribution.
  • Appends, never sets. Re-reporting the same test appends its name again; a duplicated line number inside covered_lines double-appends too. Callers must guarantee one update per (test, verdict) pair — deduplication is not the model's job.
  • Skipped tests are recorded but never scored. skipped_by is populated, yet every equation reads only failed_by and passed_by, so skip coverage is invisible to suspiciousness.

Line state, defaults, and scoring behavior

  • sus_scores starts all four equations at -1.0, a sentinel meaning not computed. Genuine scores are >= 0 (DStar can be +inf), so consumers must treat -1.0 as absence of data, not a low score.
  • tiebreakers starts cyclomatic/logical/enhanced at 0.0; RANDOM is documented to always stay zero in the model — randomization happens later at ranking time, never here.
  • sus(method, passed_total, failed_total, power=3) lowercases method before matching against the constants (so "Tarantula" works); an unrecognized name raises Exception("ERROR: unknown suspiciousness method"). Only the requested entry is written; siblings stay -1.0. sus_all fills all four, passing power (default 3) to DStar alone.
  • passed_total / failed_total are run-wide counts across all tests, not per-file; the model never computes them.
  • Edge cases baked into the equations: Tarantula returns 1 when total_passed == 0 and 0 when total_failed == 0; Ochiai returns 0 when total_failed == 0 or the line was never failed; DStar returns float("inf") when passed_cover + (total_failed - failed_cover) == 0; Ochiai2 short-circuits total_passed == 0 → 1.0, total_uncover == 0 → 0, total_failed == 0 → 0, total_cover == 0 → 0. All finite results are rounded to 4 decimal places — compare with tolerance or exact rounded values in tests.

Serialization

  • ProjFile.as_dict() returns {str(line_number): line.as_dict()}: keys are strings because JSON object keys must be, while the number field inside each value remains an int. Tiebreaker datasets and name are not serialized.
  • Line.as_dict() returns the live self.__dict__ — no copy. Mutating the returned mapping mutates the Line, and it always contains path, number, the three *_by lists, sus_scores, and tiebreakers. There is no from_dict reverse constructor.
  • Line.as_csv() fixes the column order [path, number, tarantula, ochiai, ochiai2, dstar] — note Ochiai2 precedes DStar, unlike the sus_scores insertion order.
  • Line.sus_text(methods) returns (path, number, [scores in the requested order]) for the ranked table; unknown method names here simply KeyError rather than raising the friendly sus message.
  • Both are pure readers, never calculators. as_csv() and sus_text(methods) emit sus_scores values exactly as stored — neither computes scores. Unscored equations therefore surface as the -1.0 sentinel in CSV/text output, and sus_text's unknown-name KeyError originates from the sus_scores dictionary lookup itself; call sus/sus_all before reporting.

Edge cases worth asserting

  • ProjFile with no update_file calls serializes to {}.
  • update_file([], "nonsense", "test_x") neither raises nor leaves any state behind.
  • Test names are opaque strings; nothing enforces uniqueness or format.
  • Calling a get_*_tiebreaker_dataset method twice replaces the previous dataset wholesale; only newly created Lines observe the replacement.

Exact API Reference

afluent.proj_file.ProjFile

  • Import Path: from afluent.proj_file import ProjFile
  • Required Test Import Paths:
    • afluent.proj_file.ProjFile
  • Exact Test Import Statements:
    • from afluent import line, proj_file
  • Kind: class
  • Signature:
class ProjFile:
    def __init__(self, name: str) -> None
    def update_file(self, covered_lines: list[int], test_result: str, test_case_name: str)
    def get_cyclomatic_tiebreaker_dataset(self)
    def get_logical_tiebreaker_dataset(self)
    def get_enhanced_tiebreaker_dataset(self)
    def as_dict(self)
    name: Any
    lines: Dict[int, line.Line]
    cyclomatic_complexity_data: Dict[int, int]
    logical_tiebreak_data: Dict[int, int]
    enhanced_tiebreak_data: Dict[int, float]
  • Behavior: Store coverage information about python files under test.

afluent.tiebreak_generator.CyclomaticComplexityGenerator

  • Import Path: from afluent.tiebreak_generator import CyclomaticComplexityGenerator
  • Signature:
class CyclomaticComplexityGenerator:
    def calculate_syntax_complexity(self)
  • Behavior: Store the dataset for cyclomatic complexity in the file.

afluent.line.CYCLOMATIC

  • Import Path: from afluent.line import CYCLOMATIC
  • Required Test Import Paths:
    • afluent.line.CYCLOMATIC
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
CYCLOMATIC: str
  • Behavior: Module-level value required by the test import contract.

afluent.line.DSTAR

  • Import Path: from afluent.line import DSTAR
  • Required Test Import Paths:
    • afluent.line.DSTAR
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
DSTAR: str
  • Behavior: Module-level value required by the test import contract.

afluent.line.ENHANCED

  • Import Path: from afluent.line import ENHANCED
  • Required Test Import Paths:
    • afluent.line.ENHANCED
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
ENHANCED: str
  • Behavior: Module-level value required by the test import contract.

afluent.line.LOGICAL

  • Import Path: from afluent.line import LOGICAL
  • Required Test Import Paths:
    • afluent.line.LOGICAL
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
LOGICAL: str
  • Behavior: Module-level value required by the test import contract.

afluent.line.OCHIAI

  • Import Path: from afluent.line import OCHIAI
  • Required Test Import Paths:
    • afluent.line.OCHIAI
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
OCHIAI: str
  • Behavior: Module-level value required by the test import contract.

afluent.line.OCHIAI2

  • Import Path: from afluent.line import OCHIAI2
  • Required Test Import Paths:
    • afluent.line.OCHIAI2
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
OCHIAI2: str
  • Behavior: Module-level value required by the test import contract.

afluent.line.RANDOM

  • Import Path: from afluent.line import RANDOM
  • Required Test Import Paths:
    • afluent.line.RANDOM
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
RANDOM: str
  • Behavior: Module-level value required by the test import contract.

afluent.line.TARAN

  • Import Path: from afluent.line import TARAN
  • Required Test Import Paths:
    • afluent.line.TARAN
  • Exact Test Import Statements:
    • from afluent import line
  • Kind: constant
  • Signature:
TARAN: str
  • Behavior: Module-level value required by the test import contract.

Capability: Suspiciousness score calculations

What this capability does

Turns the raw pass/fail membership of a source statement into per-equation suspiciousness numbers. A Line accumulates the names of tests that executed it in passed_by / failed_by (skips go to skipped_by and never influence scores). At report time, session-wide totals (passed_total, failed_total) are supplied once, and each equation reads only len(self.failed_by), len(self.passed_by), and those totals. Results are written into Line.sus_scores under the canonical lowercase keys tarantula, ochiai, dstar, ochiai2.

Workflow and state changes

  • A fresh Line initializes every score to the sentinel -1.0. That value means "never computed"; a line that is covered but never scored still prints -1.0 in report columns, so consumers must treat -1.0 as absent, not as a low score.
  • sus(method, ...) computes and overwrites exactly one key. The method name is matched case-insensitively (method.lower()), but the result is always stored under the lowercase canonical key, so sus("DStar", ...) and sus("dstar", ...) are equivalent.
  • sus_all(passed_total, failed_total, power=3) fills all four keys in the fixed order tarantula -> ochiai -> dstar -> ochiai2. The power argument is forwarded only to DStar; the other three equations ignore it.
  • Scores are not recomputed lazily. If tests are appended to passed_by/failed_by after scoring, the stored values are stale until sus/sus_all runs again.
  • Membership lists drive the counts directly: duplicate test names inflate failed_cover/passed_cover, and a test registered in both lists counts toward both sides.

Equation semantics and edge cases (test-sensitive)

All four static equations are pure functions and can be called with raw counts without a Line instance. Every finite result is round(..., 4).

  • Tarantula — (ff/tf) / ((pp/tp) + (ff/tf)). Early returns: total_passed == 0 -> the int 1 (not 1.0); total_failed == 0 -> the int 0, even if failed_cover > 0. The plugin guarantees at least one failure, so the total_failed == 0 branch is defensive only. One remaining failure mode: with both totals positive, if failed_cover == 0 and passed_cover == 0 the denominator (pp/tp) + (ff/tf) is 0 and tarantula raises ZeroDivisionError (with exactly one cover zero the result is still finite: 0.0 when only failing coverage is zero, 1.0 when only passing coverage is zero). That raising input cannot occur when scoring a Line with at least one registered test (ff + pp >= 1), but it is reachable via direct static calls with raw counts — Tarantula is the only equation that can raise; Ochiai, DStar, and Ochiai2 have guards that keep them total.
  • Ochiai — ff / sqrt(tf * (pp + ff)); pp enters only through the total coverage of the line. Returns 0 when total_failed == 0 or failed_cover == 0 (a line no failing test executed scores zero, unlike Tarantula).
  • DStar — ff**power / (pp + (tf - ff)); total_passed is not used at all. DStar's zero-denominator check precedes the score computation: if pp + (tf - ff) == 0 — the line was executed by every failing test and no passing test — it returns float("inf") unrounded. inf therefore sorts above every finite score in the final ranking. failed_cover == 0 yields 0.0 for any positive power only when that guard does not fire (i.e. pp + (tf - ff) > 0); the all-zero input dstar(0, 0, 0) satisfies pp + (tf - ff) == 0, so the guard fires first and the function returns unrounded float("inf"), not 0.0. Default power=3.
  • Ochiai2 — (ff * passed_uncover) / sqrt(total_cover * total_uncover * tf * tp) where total_cover = pp + ff and total_uncover = (tp - pp) + (tf - ff). Guard order matters and is observable: total_passed == 0 -> 1.0; then total_uncover == 0 -> 0 (every test in the session covered the line, so it carries no signal); then total_failed == 0 -> 0; then total_cover == 0 -> 0.
  • An unrecognized method name raises a bare Exception with the exact message ERROR: unknown suspiciousness method; nothing is written to sus_scores in that case, so a failed call leaves the -1.0 sentinel (or any previous value) intact.

Reading results back

  • as_dict() returns self.__dict__ directly — JSON-writable, and includes the score dict plus membership lists and tiebreakers.
  • as_csv() emits [path, number, tarantula, ochiai, ochiai2, dstar]; note the column order puts ochiai2 before dstar, which differs from the score-dict insertion order and from sus_all's computation order.
  • sus_text(methods) returns (path, number, [score per requested method]) in the caller's order; this is what lets a multi-equation run render columns in the order the equations were requested on the command line, with ranking sorted descending by the first one. It does not validate names — an unknown key raises KeyError rather than the sus error string.

Defaults recap

power=3 everywhere it appears; totals are plain ints supplied by the caller; there is no caching, locking, or automatic invalidation — recomputation is always explicit.

Exact API Reference

afluent.line.Line

  • Import Path: from afluent.line import Line
  • Required Test Import Paths:
    • afluent.line.Line
  • Exact Test Import Statements:
    • from afluent import line
    • from afluent import line, proj_file
  • Kind: class
  • Signature:
class Line:
    def __init__(self, file_path: str, line_num: int) -> None
    def sus(self, method: str, passed_total: int, failed_total: int, power=3)
    def sus_all(self, passed_total: int, failed_total: int, power=3)
    def as_dict(self)
    def as_csv(self)
    def sus_text(self, methods)
    @staticmethod
    def tarantula(failed_cover: int, passed_cover: int, total_passed: int, total_failed: int) -> float
    @staticmethod
    def ochiai(failed_cover: int, passed_cover: int, total_failed: int) -> float
    @staticmethod
    def dstar(failed_cover: int, passed_cover: int, total_failed: int, power=3) -> float
    @staticmethod
    def ochiai2(failed_cover: int, passed_cover: int, total_passed: int, total_failed: int) -> float
    path: Any
    number: Any
    passed_by: List[str]
    failed_by: List[str]
    skipped_by: List[str]
    sus_scores: dict
    tiebreakers: dict
  • Raises (implementation must reproduce these exact messages):
    • ERROR: unknown suspiciousness method
  • Behavior: Implement the line object and suspiciousness calculation.

Capability: Tie-breaking analysis generators

Tie-breaking analysis generators

Purpose

When several executed statements end up with identical suspiciousness scores, AFLuent re-ranks them with secondary metrics. The generators in this capability compute three per-line datasets from a source file's syntax: cyclomatic complexity (radon), logical mutant density (operator-mutant count per line), and enhanced mutant density (a block-averaged score that also counts data-bearing constructs). ProjFile calls one generator per requested strategy, stores the resulting dicts, and pushes each line's value into Line.tiebreakers when the line object is first created.

How the pieces fit together

A realistic flow for one scored file:

  1. ProjFile.get_cyclomatic_tiebreaker_dataset() / get_logical_tiebreaker_dataset() / get_enhanced_tiebreaker_dataset() each construct the matching generator with the file path held by the ProjFile, run the single calculate method, and copy the result into cyclomatic_complexity_data, logical_tiebreak_data, or enhanced_tiebreak_data. For the enhanced strategy the stored result is EnhancedTieBreaker.score — the per-line rounded floats — not the raw per-line metadata lists the generator also holds in .data.
  2. Later, update_file creates a Line for every newly seen covered line and, at creation time, copies dataset[line_number] into line_obj.tiebreakers["cyclomatic"|"logical"|"enhanced"] — but only if that dataset dict is non-empty.
  3. The tiebreaker strategies named --tiebreaker cyclomatic/logical/enhanced then compare those stored values.

Ordering is load-bearing: datasets are consulted only in the Line-creation branch of update_file. Lines recorded before their dataset is computed keep no tiebreaker value, and existing lines are never back-filled. Compute the datasets (or call all three getters) before coverage update begins — the plugin does this once per file, up front.

CyclomaticComplexityGenerator

calculate_syntax_complexity() reads the file, runs radon.complexity.cc_visit and cc.sorted_results(..., cc.LINES), then flattens results into self.data: Dict[int, int] keyed by every line 1..N (N = len(file_string.splitlines())), defaulting to 0. Only results that are radon.visitors.Function instances fill entries: lines item.lineno..item.endline (inclusive) all receive that function's item.complexity. Radon reports nested functions — including functions nested inside methods — as separate Function results whose ranges sit inside their enclosing function's, and since results are flattened in ascending start-line order, a nested result is processed after its parent: lines shared by nested functions end up holding the innermost function's complexity. Class results are skipped by the isinstance check, but methods themselves are Functions, so method bodies are covered; a class's own aggregate complexity never appears. Blank lines, headers, and module-level code outside functions stay 0.

LogicalTieBreaker and StatementVisitor

calculate_mutant_density() parses the file with cst.parse_module, builds a filler dict {i: 0 for i in 1..N}, and drives a StatementVisitor through libcst.metadata.MetadataWrapper.visit. The wrapper is mandatory: the visitor declares PositionProvider as a metadata dependency, so visiting a bare module object fails.

StatementVisitor only implements visit_SimpleStatementLine. For each simple statement line it records a metadata dict whose complexity is count_mutants(node) — the number of matches of the 43 matcher classes in the module-level MUTANTS list (unary/bitwise/arithmetic/comparison operators plus augmented assignments). fill_locations_range overwrites each line in [start, end] with that integer, so a line covered by several ranges ends up holding the value of the last-visited statement; in practice each physical line belongs to at most one simple statement. Crucially, compound statements whose header occupies its own physical line (if ...:, for ...:, while ...:, with ...:) are not SimpleStatementLines and are never visited, so those header lines keep 0 in the logical dataset even when their conditions contain many mutant operators. One-line compound statements such as if x: y = 1 are the exception: libcst's inline SimpleStatementSuite contains a SimpleStatementLine on the same physical line as the header, so per the overwrite rule that line ends up holding the inline statement's mutant count instead of 0. The final per-line ints are read back from finder.mutants_by_location into self.score (the visitor has no score attribute, unlike FullVisitor).

EnhancedTieBreaker and FullVisitor

calculate_mutant_density() mirrors the logical flow but seeds {i: [] for i in 1..N} and runs FullVisitor, then calls finder.calculate_score() — which computes the per-line averages and populates the visitor's score attribute — and copies both self.data = finder.mutants_by_location (the raw per-line list of node-metadata dicts) and self.score = finder.score (the aggregated per-line floats). ProjFile's enhanced dataset is that score dict, not data.

FullVisitor records metadata for six node kinds — If, FunctionDef, SimpleStatementLine, While, For, With — each entry being {start, end, type, complexity} where complexity comes from the COMPLEXITY_FUNC dispatch on type(node).__name__:

  • FunctionDef: len(node.params.params) — count of positional parameters, not cyclomatic complexity.
  • If/While: mutant count over the test expression only, using ENHANCED_MUTANTS (MUTANTS plus ten data-construct matchers: AnnAssign, Assign, Call, Subscript, Tuple, List, SimpleString, Dict, Integer, Float).
  • For: mutant count over target plus iter.
  • With: get_with_complexity iterates node.items counting mutants but returns 0 unconditionally, discarding that count — so every recorded With entry carries complexity 0. The entry is still recorded, though, and fill_locations_range still appends it to every line in the node's [start, end]; a cst.With node spans its header and its entire body block, so every line the statement covers, header and body alike, gains a complexity-0 entry in the "other" group of calculate_score(), lowering that group's mean and depressing those lines' scores. Only the discarded mutant count over node.items contributes nothing; the With entries themselves do affect the score.
  • SimpleStatementLine: mutant count over the whole line with ENHANCED_MUTANTS.

fill_locations_range appends the metadata dict to every line in [start, end] already present in the filler dict; line numbers outside 1..N are silently dropped, which is why the filler must enumerate all physical lines.

calculate_score() folds each line's list with get_average_score: iterating the (reversed) list, it averages complexity over SimpleStatementLine entries and over all other entries separately, substitutes denominator 1 for either empty group, and stores round(((stmt_avg) + (other_avg)) / 2, 5) as that line's value in score. Consequences worth testing against:

  • A line inside a function body and inside an if accumulates three entries (statement + enclosing block nodes); its score averages the statement density with the mean enclosing-block complexity.
  • A bare top-level statement gets (density + 0)/2 — exactly half its raw mutant count, because the empty "other" group contributes 0/1.
  • A never-covered line scores round(0.0, 5).
  • On the shared line of a one-line compound statement, the inline statement's entry is joined by the enclosing block node's entry — If/While/For, or a complexity-0 With entry — so that line's score averages the statement density against the enclosing node's complexity.
  • Scores are 5-decimal floats; logical and cyclomatic scores are ints.

Defaults, edge cases, and failures

  • Files are opened with encoding="utf-8"; unparseable files raise libcst's ParserSyntaxError from the CST generators, and missing paths raise FileNotFoundError. Radon silently tolerates files libcst would reject.
  • count_mutants instantiates each matcher class (mutant()) and sums matchers.findall lengths. Matching is type-based and the per-class hit counts are summed without deduplication: a node of one listed type nested inside a node of another listed type is counted once for each of the two classes.
  • get_node_metadata_dict indexes COMPLEXITY_FUNC by node type name; only the six visited types ever reach it, so no KeyError occurs in normal use.
  • Line.tiebreakers entries appear only for strategies whose dataset dict was populated before the line existed; an empty dataset (e.g. a file with zero lines matched) suppresses that strategy entirely for the file.

Exact API Reference

afluent.tiebreak_generator.FullVisitor

  • Import Path: from afluent.tiebreak_generator import FullVisitor
  • Signature:
class FullVisitor:
    def visit_If(self, node: cst.If) -> None
    def visit_FunctionDef(self, node: cst.FunctionDef) -> None
    def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine) -> None
    def visit_While(self, node: cst.While) -> None
    def visit_For(self, node: cst.For) -> None
    def visit_With(self, node: cst.With) -> None
    def get_node_metadata_dict(self, node)
    def fill_locations_range(self, node_metadata)
    def calculate_score(self)
    def get_average_score(items_list: List[Dict[str, Any]]) -> float
    def count_mutants(node, mutant_set)
    def get_funcdef_complexity(node)
    def get_if_complexity(node)
    def get_statement_complexity(node)
    def get_while_complexity(node)
    def get_for_complexity(node)
    def get_with_complexity(node)
  • Behavior: Locate specific nodes and organize by line number and calculate their complexity.

afluent.tiebreak_generator.StatementVisitor

  • Import Path: from afluent.tiebreak_generator import StatementVisitor
  • Signature:
class StatementVisitor:
    def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine) -> None
    def get_node_metadata_dict(self, node)
    def fill_locations_range(self, node_metadata)
    def get_statement_complexity(node)
    def count_mutants(node)
  • Behavior: Locate specific nodes and organize by line number and calculate their complexity.

Capability: Spectrum aggregation and line ranking

Spectrum aggregation and line ranking

Purpose

Spectrum is the aggregation engine of the localization pipeline: it converts the raw per-test coverage dictionary captured during the pytest session into ProjFile/Line objects, computes every covered statement's suspiciousness under all four equations, and ranks statements from most to least suspicious so the printed table and the persisted files share one ordering. PALETTE is the module-level severity color scheme applied when that ranking is rendered.

Construction and immediate state changes

Spectrum(config, dstar_pow=3, tiebreaker='random', eval_mode=False) performs all aggregation work inside __init__: it stores the arguments, then immediately calls reassemble() and calculate_sus(). After construction self.reassembled_data maps each file path to a ProjFile, self.totals holds {passed, failed, skipped} counts, and every Line already carries all four scores in sus_scores (each initialized to -1.0 before calculation, so a -1.0 value means 'never computed').

An empty config is legal: reassemble returns early, totals stay zero, no lines exist, and later report calls produce empty tables/files instead of raising. (The all-tests-pass gate lives in the plugin layer, not here — Spectrum itself will happily rank an all-pass spectrum.)

Aggregation (reassemble)

Each config entry must have the shape {'result': ..., 'coverage': {file_path: [line numbers]}}. For every test the matching total is incremented, then each covered file is updated. The first time a file appears a ProjFile is created; in eval_mode all three tiebreaker datasets (cyclomatic, logical, enhanced) are loaded so every ranking variant is available later, otherwise only the dataset matching the selected tiebreaker is loaded, and the random tiebreaker loads nothing.

ProjFile.update_file lazily creates Line objects — seeding their tiebreaker values from the file-level datasets whenever that dataset is non-empty — and appends the test name to passed_by, failed_by, or skipped_by. Two subtle behaviors matter for tests:

  • A result string outside the three known values hits the totals increment first, surfacing as a KeyError; update_file's own guard (Exception('Unknown test result for {test_case_name}')) is reachable only when driving ProjFile directly.
  • Skipped tests still record coverage in skipped_by, but skipped_by never enters any equation — only the passed/failed totals influence scores.

Scoring (calculate_sus)

Every line gets sus_all(passed_total, failed_total, power=dstar_pow), so all four scores always exist regardless of which equation drives ranking. Sentinel edge cases: tarantula returns 1 when total_passed == 0 and 0 when total_failed == 0; ochiai returns 0 when total_failed or failed_cover is zero; dstar returns float('inf') when passed_cover + (total_failed - failed_cover) == 0; ochiai2 returns 1.0 when total_passed == 0 and 0 when total_uncover, total_failed, or total_cover is zero. Normal results are rounded to 4 decimals; the sentinel returns are not. Line.sus matches method names case-insensitively and raises Exception('ERROR: unknown suspiciousness method') otherwise.

Ranking and tie-breakers

generate_rankings(all_lines, method, tiebreaker='random') sorts in place and returns the same list. With random it shuffles the list first and then stable-sorts descending by sus_scores[method], so equal scores end up in random order. Any other strategy sorts by the tuple (sus_scores[method], tiebreakers[tiebreaker]) descending, meaning ties go to the higher secondary value (higher cyclomatic complexity, more logical operators, higher enhanced score). Because the sort mutates its argument, callers must pass a list they can afford to reorder — and the report entry points re-invoke it on Spectrum's own line list (see Reports and errors).

generate_report(methods, max_items=-1) always ranks by methods[0]; extra method names only add score columns. Crucially, it stores the full ranking in self.sorted_lines before truncating the displayed rows to max_items (truncation happens only when max_items > 0; -1 or 0 means no cap). This ordering is test-sensitive: store_report serializes self.sorted_lines, so JSON/CSV/eval outputs contain the complete ranking even when the printed table was capped.

Severity shading

calculate_severity picks the row color from the methods[0] score: safe for scores <= 0, severe for exactly 1 under tarantula/ochiai/ochiai2 or inf under dstar, risky while rank / out_of <= 0.2, else mild. The ratio is computed over the (possibly truncated) displayed list, so rows at ranks 0 through floor(0.2 * out_of) — one more row than a strict top-20% cut (ranks 0–2 of a 10-row table = 30%, ranks 0–4 of 20 = 25%) — are shaded risky, and severe/safe take precedence over risky even inside that band. One formatter per row is applied to every score cell, including columns from other equations. Rows wrap the path and line number in PALETTE['location_line'].

Reports and errors

print_report(methods, items_num) validates every name against METHOD_NAMES first and raises Exception('ERROR: Invalid method name {method_name}') before printing anything. It then delegates to generate_report(methods, max_items=items_num), so printing is not a read-only view: it re-ranks from scratch (re-shuffling tie order when tiebreaker='random'), replaces self.sorted_lines with the full ranking under the new methods[0], and applies the max_items semantics to items_num (items_num <= 0 shows everything). A test that ranks with one equation, prints with another, then stores JSON will observe the print's ordering, not the original one.

store_report(report_type) writes afluent_report.json ({'ranking': [line dicts]}), afluent_report.csv (fixed header covering all four equations), or, for eval, 16 files named {method}_{tiebreaker}_report.csv via produce_full_eval_report, each re-ranking self.sorted_lines with one equation/tiebreaker pair and reporting each line's sus_scores[method] and tiebreakers[tiebreaker]. Any other type raises Exception('Error:Unknown report type {report_type}.') — note there is no space after the colon. Calling store_report('eval') before generate_report writes header-only files because self.sorted_lines is still empty.

store_report('eval') passes self.sorted_lines itself into generate_rankings for all 16 METHOD_NAMES × TIEBREAKERS pairs, so after the call self.sorted_lines is left reordered by the last pair (dstar with random: shuffled, then dstar-descending). A subsequent store_report('json') or store_report('csv') serializes that mutated ordering, and each repeated eval call reshuffles the random columns.

Exact API Reference

afluent.spectrum_parser.PALETTE

  • Import Path: from afluent.spectrum_parser import PALETTE
  • Required Test Import Paths:
    • afluent.spectrum_parser.PALETTE
  • Exact Test Import Statements:
    • from afluent import spectrum_parser
  • Kind: constant
  • Signature:
PALETTE: dict
  • Behavior: Module-level value required by the test import contract.

Detailed Implementation Nodes

Node: Pytest plugin integration and CLI options

Functional constraints

  • Package as a pytest11 entry point named afluent mapping to afluent.main so pytest auto-loads the hooks; no conftest or explicit -p activation is required.
  • pytest_addoption must create exactly one group with key afluent and title Automated Fault Localization (AFLuent) and attach every option to it.
  • The enable flag is a single store_true option with two aliases (--afl, --afl-debug) sharing dest afl_enable, default False.
  • The four equation options share dest afl_methods via append_const and must preserve invocation order; none has a default, so the plugin replaces a falsy value with dstar, tarantula, ochiai, ochiai2 at construction time, never at parse time.
  • --dstar-pow defaults to 3 (int); --afl-results defaults to 20 (int); neither is range-checked.
  • --afl-ignore must use extend with nargs=* so both repeated flags and multi-pattern lists accumulate into one flat list; when the flag is absent the dest stays at its argparse default None (no default is supplied), so the registration-time omit value is None, not an empty list.
  • --report choices are json, csv, eval (default None); eval implies eval mode on the plugin object. --tiebreaker choices are random, cyclomatic, logical, enhanced (default random); logical and enhanced select LogicalTieBreaker and EnhancedTieBreaker from afluent.tiebreak_generator, classes that store the full syntax mutant density data set they receive and invoke the finder via calculate_mutant_density during the exit-status-1 diagnosis path; no behavioral difference between the two classes is asserted beyond this shared store-then-find contract.
  • pytest_cmdline_main performs, in order: (1) conflict warning for any name in CONFLICTING_PLUGINS via hasplugin — printed regardless of whether AFLuent is enabled; (2) when enabled, an early-exit warning if the --maxfail lookup is truthy (default 0 is falsy); (3) construct and register the plugin object under the name Afluent only when afl_enable is set; (4) otherwise print the disabled banner.
  • Warnings are styled print banners; exit status and the remaining hook chain are untouched.
  • Registration constructs an in-memory coverage object: data_file=None, auto_data=False, branch=True, config_file=False, omit=ignore patterns (None when --afl-ignore was never passed), and copies all option values onto the plugin at init.

Usage example

def test_plugin_enabled_and_diagnoses(pytester):
    pytester.makepyfile("def test_bad(): assert False")
    result = pytester.runpytest(
        '--afl', '--ochiai', '--dstar', '--afl-ignore', 'tests/*',
        '--afl-results', '5', '--tiebreaker', 'cyclomatic',
    )
    result.stdout.fnmatch_lines(['*Failing tests detected. Diagnosing using AFLuent...*'])

def test_plugin_disabled_banner(pytester):
    pytester.makepyfile("def test_ok(): assert True")
    result = pytester.runpytest()  # no --afl/--afl-debug
    result.stdout.fnmatch_lines(['*AFLuent is disabled*'])

Node: Per-test coverage collection during test runs

Functional constraints

  1. Record shape is contractual: session_spectrum[key] = {"coverage": {path: [line ints]}, "result": "passed"|"failed"|"skipped"} with key = f"{item.parent.name}_{item.name}". Spectrum(config) consumes exactly this shape, and --per-test serializes it verbatim to afluent_per_test_report.json (indent=4, written before the exit-status branch). Replay caveat: Spectrum.__init__ runs reassemble() first, which indexes the fixed {passed, failed, skipped} totals with each record's result — a "notSet" (or any non-trio) value raises KeyError there, so prune or repair records before replay.
  2. One coverage.Coverage(data_file=None, auto_data=False, branch=True, config_file=False, omit=ignored_patterns) instance serves the whole session; config_file=False isolates the run from project coverage config; omit comes from --afl-ignore (action="extend", nargs="*").
  3. pytest_pyfunc_call wrapper order: start → yield → stop → create entry with "result": "notSet" → fill from measured_files()/lines(); catch only coverage.exceptions.CoverageWarning; cov.erase() after every test keeps snapshots disjoint.
  4. pytest_runtest_makereport wrapper: set record["result"] = report.outcome only when report.when == "call" and the key exists; pytest outcomes map identically to the three result values.
  5. pytest_sessionfinish order: per-test dump (if --per-test) → diagnosis only when exitstatus == 1 (build Spectrum, print_report(methods, results_num), store_report if --report) → always write afluent_timings.json with test_time and localization_time.
  6. Report-file semantics: store_report serializes self.sorted_lines, populated only by generate_report() (invoked from print_report()), so a standalone call beforehand stores an empty ranking; sorted_lines is captured before max_items truncation, so stored rankings are full-length while results_num truncates only the printed table; store_report("eval") delegates to produce_full_eval_report(), writing 16 CSVs named f"{method}_{tiebreaker}_report.csv" (all four methods × all four tiebreakers), each re-ranking the same captured list.
  7. Ranking determinism: under "random", generate_rankings() shuffles before a stable descending sort, so tied-score order is nondeterministic per run, including eval re-rankings; deterministic order requires cyclomatic/logical/enhanced or eval_mode.
  8. Consumption invariants: Spectrum.__init__ runs reassemble() then calculate_sus(); totals is exactly {"passed": 0, "failed": 0, "skipped": 0} and is indexed by the recorded result; ProjFile.update_file raises on any result outside the trio. Tiebreaker datasets are populated per new ProjFile when eval_mode or a static tiebreaker is configured; Line.tiebreakers["random"] must stay 0.
  9. All-pass runs emit no ranking; tests skipped in setup produce no record at all.

Usage example

from afluent import spectrum_parser

spectrum = {  # same shape as afluent_per_test_report.json; each "result" must
              # be passed/failed/skipped or Spectrum() raises KeyError on replay
    "test_calc_add": {"coverage": {"calc.py": [1, 2, 3, 10]}, "result": "passed"},
    "test_calc_sub": {"coverage": {"calc.py": [1, 2, 5, 11]}, "result": "failed"},
}
sp = spectrum_parser.Spectrum(spectrum, dstar_pow=3, tiebreaker="random")
sp.print_report(["ochiai", "dstar"], 20)  # ranked, color-coded table
sp.store_report("json")  # writes afluent_report.json with the full ranking

Node: File and line coverage data model

Functional constraints

  • ProjFile.lines maps int line numbers to Line objects internally; ProjFile.as_dict() re-keys them as strings for JSON, leaving Line.number an int inside each value.
  • update_file requires test_result to be exactly one of "passed", "failed", "skipped" (case-sensitive); any other value raises a bare Exception whose message embeds the test case name, after already creating the current Line and updating all prior lines — the offending Line therefore remains in lines with empty *_by attribution.
  • An empty covered_lines is a silent no-op: the case-sensitive verdict check is per-line inside the loop, so no Line is created and an invalid test_result does not raise.
  • Tiebreaker datasets must be populated before the first update_file call; seeding copies values into new Line.tiebreakers by direct indexing, so a non-empty dataset missing a covered line number raises KeyError before insertion — the partially constructed Line is discarded and absent from ProjFile.lines (prior lines keep their updates). Already-created lines are never re-seeded.
  • Attribution is append-only: duplicate test names or duplicate line numbers inside covered_lines produce duplicate list entries; dedup is the caller's responsibility.
  • skipped_by is recorded but excluded from every equation; sus/sus_all read only len(failed_by), len(passed_by), and caller-supplied run-wide totals.
  • sus_scores uses -1.0 as the "not computed" sentinel for all four equations; DStar may legitimately return float("inf"); all finite scores are rounded to 4 decimals. tiebreakers[RANDOM] must remain 0.0 in the model.
  • sus lowercases its method argument and raises Exception("ERROR: unknown suspiciousness method") on unrecognized names; it writes only the requested equation's slot.
  • Line.as_dict() returns the live __dict__ (mutations alias back into the object); Line.as_csv() orders columns [path, number, tarantula, ochiai, ochiai2, dstar]; sus_text(methods) returns (path, number, score_list). Both as_csv() and sus_text(methods) are pure readers of the cached sus_scores — they never calculate — so unscored equations surface as the -1.0 sentinel in their output, and sus_text's unknown-name KeyError comes from the sus_scores lookup.

Usage example

from afluent import proj_file, line

pf = proj_file.ProjFile("sample.py")
pf.get_cyclomatic_tiebreaker_dataset()      # optional; must precede update_file
pf.update_file([10, 11], "failed", "test_a")
pf.update_file([10], "passed", "test_b")

ln = pf.lines[10]                            # int key internally
ln.sus_all(passed_total=1, failed_total=1)   # fills all four equations
assert ln.sus_scores[line.OCHIAI] == 0.7071  # rounded to 4 decimals

report = pf.as_dict()
assert set(report) == {"10", "11"}           # JSON-safe string keys
assert report["10"]["failed_by"] == ["test_a"]

Node: Suspiciousness score calculations

Functional constraints

  • Counts are derived at call time from len(failed_by) / len(passed_by); register tests on the Line before scoring, and re-sus after any membership change (no auto-refresh).
  • All finite outputs are rounded to 4 decimal places; DStar's degenerate case returns unrounded float("inf") when passed_cover + (total_failed - failed_cover) == 0 (line hit by all failing, no passing tests) — including the all-zero input dstar(0, 0, 0).
  • Sentinel: uncomputed scores are -1.0 in sus_scores; treat -1.0 as "not scored".
  • Guard precedence: Tarantula checks total_passed == 0 (returns int 1) then total_failed == 0 (int 0); there is no third guard — with both totals positive and both failed_cover == 0 and passed_cover == 0, the denominator (pp/tp) + (ff/tf) is 0 and tarantula raises ZeroDivisionError (unreachable through sus/sus_all on a Line with at least one registered test, since ff + pp >= 1, but reachable via direct static calls with raw counts; Tarantula is the only equation that can raise). Ochiai returns 0 if total_failed == 0 or failed_cover == 0; Ochiai2 checks total_passed == 0 -> 1.0, then total_uncover == 0 -> 0, then total_failed == 0 -> 0, then total_cover == 0 -> 0, in that exact order. DStar's zero-denominator check (passed_cover + (total_failed - failed_cover) == 0 -> unrounded float("inf"), as for dstar(0, 0, 0)) precedes the score computation, so failed_cover == 0 yields 0.0 only when that guard does not fire.
  • DStar alone consumes power (default 3); sus_all forwards it only there. The other equations need total_failed (Ochiai, DStar) or both totals (Tarantula, Ochiai2).
  • sus rejects unknown names with a bare Exception carrying exactly ERROR: unknown suspiciousness method; sus_text instead raises KeyError for unknown score keys.
  • as_csv column order is [path, number, tarantula, ochiai, ochiai2, dstar] (ochiai2 before dstar); as_dict is the raw __dict__.
  • skipped_by membership never affects any equation.

Usage example

from afluent.line import Line

ln = Line("app.py", 42)
ln.failed_by += ["test_a", "test_b"]
ln.passed_by += ["test_c"]

ln.sus_all(passed_total=2, failed_total=2)   # power defaults to 3
# ln.sus_scores == {"tarantula": 0.6667, "ochiai": 0.8165,
#                   "dstar": 8.0, "ochiai2": 0.5774}

ln.sus("DSTAR", 2, 2, power=2)               # case-insensitive key
# ln.sus_scores["dstar"] == 4.0

Line.ochiai(failed_cover=2, passed_cover=1, total_failed=2)  # 0.8165 (pure call)

Node: Tie-breaking analysis generators

Functional constraints

  • All three generators take the file path at construction and expose results only after their single calculate method runs; nothing is computed in __init__.
  • CST visitors require libcst.metadata.MetadataWrapper(module).visit(...) because of the PositionProvider dependency; visiting a raw module fails.
  • Line coverage of every dataset spans exactly 1..len(text.splitlines()); ranges outside are dropped, and the filler dicts ([], 0, 0) define the zero defaults.
  • Logical (StatementVisitor) counts only the 43 MUTANTS operator matchers, visits only SimpleStatementLine, and overwrites covered lines. Compound statements whose header occupies its own line keep 0; one-line compounds (if x: y = 1) share the header line with the inline body's SimpleStatementLine, whose count overwrites it. It reports via mutants_by_location, not a score field.
  • Enhanced (FullVisitor) uses ENHANCED_MUTANTS (43 operator + 10 data-construct matchers), records six node types with type-dispatched complexity (FunctionDef = positional param count; If/While = mutants in test; For = mutants in target+iter; With records complexity 0 across the with statement's full line range, diluting the "other" average), appends per line, and averages statement vs. enclosing-block complexities, rounding to 5 decimals (round(x, 5)). calculate_score() populates FullVisitor.score; the generator copies it into EnhancedTieBreaker.score, and that score dict — not the raw metadata lists in .data — is what ProjFile stores. On a one-line compound's shared line, the inline statement entry coexists with the enclosing If/While/For entry.
  • Cyclomatic uses radon cc_visit + sorted_results(..., cc.LINES); only radon.visitors.Function results fill lineno..endline inclusive, and with nested functions the innermost function's complexity wins (deeper results are processed after their parents and overwrite the shared lines); classes ignored; everything else 0.
  • ProjFile consumes the dicts at Line-creation time only — datasets must exist before update_file runs or lines get no tiebreaker values.

Example

from afluent.tiebreak_generator import (
    CyclomaticComplexityGenerator, LogicalTieBreaker, EnhancedTieBreaker)

cgen = CyclomaticComplexityGenerator("mod.py")
cgen.calculate_syntax_complexity()      # {1: 0, 2: 3, ...} per-line ints
egen = EnhancedTieBreaker("mod.py")
egen.calculate_mutant_density()         # egen.score: {line: round(float, 5)} — the dict ProjFile stores
lgen = LogicalTieBreaker("mod.py")
lgen.calculate_mutant_density()         # lgen.score: {line: int} via mutants_by_location

Node: Spectrum aggregation and line ranking

Functional constraints

  • Spectrum(config, dstar_pow=3, tiebreaker='random', eval_mode=False) aggregates and scores inside __init__ (reassemble() then calculate_sus()); constructing it is sufficient — no separate trigger call.
  • Config shape: {test_name: {'result': 'passed'|'failed'|'skipped', 'coverage': {file_path: [line ints]}}}. Unknown result values raise from the totals increment during aggregation; ProjFile.update_file raises Exception('Unknown test result for {test_case_name}') when driven directly.
  • eval_mode loads all three tiebreaker datasets at first sight of each file; otherwise only the selected tiebreaker's dataset loads, and random loads none. Line tiebreaker values are copied from the file datasets only when those datasets are non-empty.
  • calculate_sus fills all four scores for every line (rounded to 4 decimals, dstar uses dstar_pow; inf when passed_cover + (total_failed - failed_cover) == 0). Initial score is -1.0.
  • generate_report(methods, max_items=-1) ranks by methods[0] using self.tiebreaker, saves the full ranking to self.sorted_lines, then truncates only the displayed rows when max_items > 0. Call it before store_report; store_report('eval') re-ranks self.sorted_lines for all 16 method/tiebreaker pairs.
  • print_report(methods, items_num) delegates to generate_report(methods, max_items=items_num): printing re-ranks from scratch, refreshes self.sorted_lines under the new methods[0], re-shuffles ties when tiebreaker='random', and treats items_num <= 0 as showing everything.
  • store_report('eval') mutates self.sorted_lines in place, leaving it in the final (dstar/random) pair's order — shuffled, then dstar-descending — for any later json/csv serialization; repeated eval calls reshuffle the random columns.
  • generate_rankings mutates its input list: random = shuffle then descending score sort; other strategies = descending (score, tiebreaker_score) tuple sort, so ties favor the higher secondary value.
  • Severity per row uses the methods[0] score: safe if <= 0, severe at 1 (tarantula/ochiai/ochiai2) or inf (dstar), risky while rank/out_of <= 0.2 (ranks 0 through floor(0.2*out_of), one more than a strict 20% cut, and only when the row is not already safe/severe), else mild; the ratio uses the truncated list length.
  • Literal error strings: 'ERROR: Invalid method name {method_name}' (validated before printing), 'Error:Unknown report type {report_type}.' (no space after colon), 'ERROR: unknown suspiciousness method'.
  • PALETTE keys: severe, risky, mild, safe, location_line — importable as afluent.spectrum_parser.PALETTE.

Usage example

from afluent import spectrum_parser

config = {
    'test_a': {'result': 'passed', 'coverage': {'app.py': [1, 2, 3]}},
    'test_b': {'result': 'failed', 'coverage': {'app.py': [2, 5]}},
}
spec = spectrum_parser.Spectrum(config, dstar_pow=3, tiebreaker='cyclomatic')
rows = spec.generate_report(['ochiai', 'dstar'], max_items=20)  # fills spec.sorted_lines
spec.print_report(['ochiai'], items_num=20)
spec.store_report('json')  # afluent_report.json keeps the full, uncapped ranking