Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions src/fanbase/contrib.py
Original file line number Diff line number Diff line change
Expand Up @@ -546,9 +546,20 @@ def cleanup(self) -> None:
GRACE = 10 # seconds a batch that began in time may overrun the budget


def _fuzz(fandango: str, spec: Path, n: int, out: Path, library: Path, seed: int | None, timeout: float):
"""One run of `fandango fuzz`; None if it did not finish in time."""
def _extension(entry: Entry) -> str | None:
"""The file name extension of a spec's files, as `fandango fuzz -x` takes it (".png"), from its metadata; None if it has none."""
extensions = entry.meta.get("extensions")
first = str(extensions[0]).lstrip(".") if isinstance(extensions, list) and extensions else ""
return f".{first}" if first else None


def _fuzz(fandango: str, spec: Path, n: int, out: Path, library: Path, seed: int | None, timeout: float,
extension: str | None = None):
"""One run of `fandango fuzz`; None if it did not finish in time. The files get the extension of the format, as
`fandango -F` gives them: a parser that goes by the name of a file must see the name it would see in use."""
cmd = [fandango, "fuzz", "-f", str(spec), "-n", str(n), "-d", str(out)]
if extension:
cmd += ["-x", extension]
env = {**os.environ, "FANDANGO_PATH": str(library)}
if seed is not None:
cmd += ["--random-seed", str(seed)]
Expand Down Expand Up @@ -578,14 +589,14 @@ def produce(reg: Registry, entry: Entry, ctx: Context, *, count: int, timeout: i

if budget is None:
started = time.monotonic()
done = _fuzz(fandango, spec, count, out, library, seed, timeout)
done = _fuzz(fandango, spec, count, out, library, seed, timeout, _extension(entry))
if done is None:
return Produced([], time.monotonic() - started, tmp, error=f"fandango did not finish in {timeout} seconds")
files = sorted(p for p in out.glob("*") if p.is_file()) if out.is_dir() else []
produced = Produced(files, time.monotonic() - started, tmp, returncode=done.returncode,
tail=" | ".join((done.stderr or done.stdout).strip().splitlines()[-2:]))
else:
produced = _produce_within(fandango, spec, count, out, library, seed, budget, tmp)
produced = _produce_within(fandango, spec, count, out, library, seed, budget, tmp, _extension(entry))

if not produced.files:
produced.error = produced.error or "fandango produced no files"
Expand All @@ -595,7 +606,7 @@ def produce(reg: Registry, entry: Entry, ctx: Context, *, count: int, timeout: i


def _produce_within(fandango: str, spec: Path, count: int, out: Path, library: Path, seed: int | None,
budget: float, tmp: Path) -> Produced:
budget: float, tmp: Path, extension: str | None = None) -> Produced:
import hashlib

started = time.monotonic()
Expand All @@ -609,7 +620,7 @@ def _produce_within(fandango: str, spec: Path, count: int, out: Path, library: P
stopped = f"the budget of {budget:g}s ran out with {len(files)} of the {count} inputs"
break
folder = out / f"batch-{batch}"
done = _fuzz(fandango, spec, wanted, folder, library, None if seed is None else seed + batch, left + GRACE)
done = _fuzz(fandango, spec, wanted, folder, library, None if seed is None else seed + batch, left + GRACE, extension)
if done is None:
stopped = f"the budget of {budget:g}s ran out with {len(files)} of the {count} inputs"
break
Expand Down
6 changes: 3 additions & 3 deletions src/fanbase/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def _rows(r: SpecReport) -> list[list[str]]:
continue
res = t.result
rows.append([t.name, f"{res.accepted}/{res.total}"] + [str(res.counts[c]) for c in _COLUMNS[1:]]
+ [f"{res.per_second:.0f}", clean(t.version or "")])
+ [quality_results.speed(res.per_second), clean(t.version or "")])
return rows


Expand Down Expand Up @@ -295,7 +295,7 @@ def as_text(reports: list[SpecReport], args) -> str:
if r.error:
out += [f"{head}: no inputs: {clean(r.error)}", ""]
continue
out.append(f"{head}: {r.produced} inputs from seed {args.seed} in {r.seconds:.1f}s ({r.per_second:.1f}/s)")
out.append(f"{head}: {r.produced} inputs from seed {args.seed} in {r.seconds:.1f}s ({quality_results.speed(r.per_second)}/s)")
if r.note:
out.append(f" note: {clean(r.note)}")
if r.unjudged:
Expand Down Expand Up @@ -332,7 +332,7 @@ def as_markdown(reports: list[SpecReport], args) -> str:
if r.error:
out += [f"**No inputs:** {clean(r.error)}", ""]
continue
out.append(f"{r.produced} inputs in {r.seconds:.1f}s ({r.per_second:.1f}/s)." + (f" {clean(r.note)}." if r.note else ""))
out.append(f"{r.produced} inputs in {r.seconds:.1f}s ({quality_results.speed(r.per_second)}/s)." + (f" {clean(r.note)}." if r.note else ""))
out.append("")
if r.unjudged:
out += [f"_{r.unjudged}_", ""]
Expand Down
7 changes: 6 additions & 1 deletion src/fanbase/quality.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,11 @@ def of(doc: dict, entry: Entry, sha256: str) -> tuple[dict, bool] | None:
return None if row is None else (row, row["sha256"] == sha256)


def speed(per_second: float) -> str:
"""Files per second in few digits: 41, 1.3, 0.05. A slow spec must not read as 0."""
return f"{per_second:.0f}" if per_second >= 10 else f"{per_second:.1f}" if per_second >= 1 else f"{per_second:.2f}"


def summary(row: dict, current: bool = True) -> str:
"""A spec's quality in a few words."""
parts = []
Expand All @@ -216,7 +221,7 @@ def summary(row: dict, current: bool = True) -> str:
if lines:
parts.append(f"covers {max(lines):.1%}")
if row.get("per_second"):
parts.append(f"{row['per_second']:.0f}/s")
parts.append(f"{speed(row['per_second'])}/s")
text = ", ".join(parts) or "measured"
return text if current else f"{text} (for an earlier version)"

Expand Down
76 changes: 76 additions & 0 deletions tests/test_extension.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""The files evaluate and check ask Fandango for have the extension of their format, as they do under `fandango -F`."""

import subprocess

import pytest
import yaml
from conftest import build_registry
from helpers import REAL_RUN, STRICT, FakeFandango, settle, target

from fanbase import contrib, quality
from fanbase.cli import main


@pytest.fixture(autouse=True)
def real_subprocess(monkeypatch):
monkeypatch.setattr(subprocess, "run", REAL_RUN)


@pytest.fixture
def fake(monkeypatch):
fandango = FakeFandango()
monkeypatch.setattr(contrib, "find_fandango", lambda: "/fake/fandango")
monkeypatch.setattr(contrib, "_run", fandango)
monkeypatch.setattr("fanbase.evaluate.find_fandango", lambda: "/fake/fandango")
return fandango


@pytest.fixture
def reg(tmp_path):
root = build_registry(tmp_path / "reg", {
("png", "png"): dict(version="1.0", description="PNG", extensions=["png"]),
("jpeg", "jpeg"): dict(version="1.0", description="JPEG", extensions=[".jpg", "jpeg"]),
("txt", "txt"): dict(version="1.0", description="Plain text"),
})
target(root, "strict", STRICT, formats=("png", "jpeg", "txt"))
(root / "specs/png/format.yml").write_text(yaml.safe_dump({"targets": ["strict"]})) # evaluate needs a target to judge by
settle(root)
return root


def asked(fake, capsys, reg, spec, *extra):
fake.calls.clear()
code = main(["--registry", str(reg), "check", spec, "--no-requirements", *extra])
capsys.readouterr()
assert code == 0 and fake.calls
return fake.calls[0]["cmd"]


def test_fandango_is_asked_for_files_with_the_extension_of_the_format(fake, capsys, reg):
cmd = asked(fake, capsys, reg, "png")
assert cmd[cmd.index("-x") + 1] == ".png"


def test_the_first_extension_is_used_and_a_dot_in_front_of_it_is_not_doubled(fake, capsys, reg):
cmd = asked(fake, capsys, reg, "jpeg")
assert cmd[cmd.index("-x") + 1] == ".jpg"


def test_a_format_without_an_extension_gets_none_asked_for(fake, capsys, reg):
assert "-x" not in asked(fake, capsys, reg, "txt")


def test_with_a_budget_every_batch_asks_for_the_extension(fake, capsys, reg):
# evaluate works in batches within a budget; each of them is a run of fandango fuzz
fake.calls.clear()
code = main(["--registry", str(reg), "evaluate", "png", "-n", "20", "--budget", "30"])
capsys.readouterr()
assert code in (0, 1) and fake.calls
assert all(call["cmd"][call["cmd"].index("-x") + 1] == ".png" for call in fake.calls)


@pytest.mark.parametrize("per_second, shown", [(163.35, "163"), (41.2, "41"), (10.0, "10"), (9.96, "10.0"), (1.36, "1.4"), (1.0, "1.0"),
(0.9, "0.90"), (0.05, "0.05")])
def test_a_slow_spec_does_not_read_as_zero(per_second, shown):
assert quality.speed(per_second) == shown
assert quality.summary({"per_second": per_second}).endswith(f"{shown}/s")
2 changes: 1 addition & 1 deletion tests/test_quality.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def test_list_shows_how_each_spec_does(capsys, reg, results):
code, out, _ = run(capsys, "--registry", str(reg), "list", "png", "--quality", str(results))
assert code == 0
assert "PNG [accepts 100%, 16/s]" in out
assert "Animated [accepts 50%, 3/s (for an earlier version)]" in out # not measured on the spec as it is
assert "Animated [accepts 50%, 3.0/s (for an earlier version)]" in out # not measured on the spec as it is


def test_list_in_json(capsys, reg, results):
Expand Down
Loading