Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159#!/usr/bin/env python3"""Refuses a property test that bypasses the project's wrappers or libraries.
Each language runs its property library through one wrapper, which applies thegate's fixed seed, the case budget, and the discovery overrides, and keeps thelibrary's failure store out of the tree. A test that calls the library directlyruns a random seed in the gate and ignores `ALBEDO_PROPERTY_SEED`, so a CIfailure cannot be replayed. A second property library splits that convention.See robot-docs/testing.md#seeds-and-budgets.
Usage: test/property_wrappers.py [path ...]. With no paths it checks everytracked file. It prints each violation and exits 1 when there is one."""
from __future__ import annotations
import fnmatchimport reimport subprocessimport sysfrom collections.abc import Iteratorfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
# The wrappers themselves call the libraries.WRAPPERS = { "packages/albedo_property/src/albedo_property.gleam", "cli/internal/property/property.go", "web/scripts/property.mjs", "test/hypothesis_profiles.py", "native/render/src/property.rs",}
DOCS = "robot-docs/testing.md#seeds-and-budgets"
def rule(pattern: str, message: str) -> tuple[re.Pattern[str], str]: return re.compile(pattern, re.MULTILINE), message
GLEAM = [ rule( r"\bqcheck\.(run|given)\b", "call albedo_property.run, not qcheck.run", ),]GO = [ rule(r"\brapid\.(Check|MakeCheck|MakeFuzz)\(", "call property.Check, not rapid"), rule(r'"testing/quick"', "use rapid through property.Check, not testing/quick"), rule(r'"github.com/leanovate/gopter', "use rapid through property.Check"),]JS = [ rule(r"\bfc\.(assert|check)\(", "call check from web/scripts/property.mjs"), rule(r"""from ["'](jsverify|testcheck)["']""", "use fast-check through check"),]# Only in a module that imports Hypothesis, where `settings` is its own.HYPOTHESIS = [ rule( r"max_examples\s*=\s*(?!hypothesis_profiles\.cases\(|cases\()", "set max_examples with hypothesis_profiles.cases(n)", ), rule( r"\bsettings\([^)]*\b(derandomize|database|seed)\s*=|@seed\(", "leave seeds and the example database to the profile", ),]PYTHON = [ rule(r"^\s*(from|import) (pytest_quickcheck|schemathesis)\b", "use Hypothesis"),]RUST = [ rule( r"^\s*(use|extern crate) quickcheck\b", "use proptest through property::config" ),]
def violations(path: str, text: str) -> Iterator[str]: """Each rule `text`, the contents of `path`, breaks, as `path:line: why`.""" if path in WRAPPERS or "/build/" in f"/{path}" or "node_modules/" in path: return rules: list[tuple[re.Pattern[str], str]] = [] if path.endswith(".gleam"): rules = GLEAM elif path.endswith("_test.go"): rules = GO elif path.endswith((".mjs", ".js", ".ts")) and path.startswith( ("web/", "tools/photon/") ): rules = JS elif path.endswith(".py"): hypothesis = re.search(r"^\s*(from|import) hypothesis\b", text, re.MULTILINE) rules = PYTHON + HYPOTHESIS if hypothesis else PYTHON if ( hypothesis and "@given(" in text and not (re.search(r"^\s*import hypothesis_profiles\b", text, re.MULTILINE)) ): yield f"{path}:1: import hypothesis_profiles to run a property ({DOCS})" elif path.endswith(".rs"): rules = RUST for match in re.finditer(r"proptest!\s*\{\s*(?P<head>[^\n]*)", text): if "crate::property::config(" not in match.group("head"): yield ( f"{path}:{line(text, match.start())}: start proptest! with " f"#![proptest_config(crate::property::config(n))] ({DOCS})" ) for pattern, message in rules: for match in pattern.finditer(text): yield f"{path}:{line(text, match.start())}: {message} ({DOCS})"
def line(text: str, offset: int) -> int: return text.count("\n", 0, offset) + 1
def tracked() -> list[str]: patterns = [ "*.gleam", "*.go", "*.py", "*.rs", "tools/photon/*.mjs", "web/*.mjs", "web/*.js", "web/*.ts", ] git = subprocess.run( ["git", "ls-files", *patterns], cwd=ROOT, capture_output=True, text=True ) if git.returncode == 0: return git.stdout.splitlines() # A jj workspace without .git: the working copy's tracked files, filtered # by the same pathspecs. out = subprocess.run( ["jj", "file", "list"], cwd=ROOT, check=True, capture_output=True, text=True ).stdout return [ path for path in out.splitlines() if any(fnmatch.fnmatch(path, pattern) for pattern in patterns) ]
def main(argv: list[str]) -> int: found = [ problem for path in (argv or tracked()) if (ROOT / path).is_file() for problem in violations(path, (ROOT / path).read_text(errors="replace")) ] for problem in found: print(problem) return 1 if found else 0
if __name__ == "__main__": sys.exit(main(sys.argv[1:]))