Files
leleka/scripts/e2e/codex/tasks/feature-query/accept.py
T

139 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""Acceptance check for task feature-query.
Usage: python3 accept.py WORKSPACE
Exit 0 when the task is done; any other exit code means not done. The workspace is never modified: everything runs in a temporary copy.
"""
import ast
import hashlib
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
PRISTINE = HERE / "hidden" / "pristine_tests"
HIDDEN_TESTS = HERE / "hidden" / "test_hidden_spec.py"
SPEC_SHA256 = hashlib.sha256((HERE / "seed" / "SPEC.md").read_bytes()).hexdigest()
MIN_TEST_METHODS = 25
IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".git")
failed = []
def check(name, ok, detail=""):
if ok:
print("PASS " + name)
else:
print("FAIL %s :: %s" % (name, detail.strip()[-1500:]))
failed.append(name)
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def run_unittest(cwd, start_dir, pattern="test*.py", timeout=100):
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONHASHSEED="0")
try:
proc = subprocess.run(
[sys.executable, "-m", "unittest", "discover", "-s", start_dir, "-p", pattern],
cwd=str(cwd), env=env, capture_output=True, text=True, timeout=timeout,
)
except subprocess.TimeoutExpired:
return False, "timeout", 0
output = proc.stdout + proc.stderr
match = re.search(r"^Ran (\d+) tests? in", output, re.M)
return proc.returncode == 0, output, int(match.group(1)) if match else 0
def count_assertive_tests(path):
"""Number of test methods (in classes) that contain at least one assertion call."""
tree = ast.parse(Path(path).read_text(encoding="utf-8"))
total = 0
for node in ast.walk(tree):
if not isinstance(node, ast.ClassDef):
continue
for item in node.body:
if isinstance(item, ast.FunctionDef) and item.name.startswith("test"):
asserts = [
n for n in ast.walk(item)
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
and (n.func.attr.startswith("assert") or n.func.attr in ("fail", "subTest"))
]
if asserts:
total += 1
return total
def main():
if len(sys.argv) != 2:
print("usage: accept.py WORKSPACE")
return 2
workspace = Path(sys.argv[1]).resolve()
if not workspace.is_dir():
print("FAIL workspace :: not a directory")
return 2
# 1. pristine tests and the specification are untouched
for src in sorted(PRISTINE.rglob("*")):
if not src.is_file() or "__pycache__" in src.parts:
continue
rel = src.relative_to(PRISTINE)
target = workspace / "tests" / rel
check("tests-untouched:" + rel.as_posix(), target.is_file() and digest(target) == digest(src),
"tests/%s is missing or was modified" % rel.as_posix())
spec = workspace / "SPEC.md"
check("spec-untouched", spec.is_file() and digest(spec) == SPEC_SHA256, "SPEC.md is missing or was modified")
with tempfile.TemporaryDirectory() as tmp:
# 2. the existing behaviour, tested with the pristine tests only
pristine_ws = Path(tmp) / "pristine"
shutil.copytree(workspace, pristine_ws, ignore=IGNORE)
shutil.rmtree(pristine_ws / "tests", ignore_errors=True)
shutil.copytree(PRISTINE, pristine_ws / "tests", ignore=IGNORE)
ok, out, ran = run_unittest(pristine_ws, "tests")
check("existing-tests", ok and ran > 0, out)
# 3. spec conformance, tested with hidden cases
hidden_dir = pristine_ws / "_hidden"
hidden_dir.mkdir()
shutil.copy(HIDDEN_TESTS, hidden_dir / "test_hidden_spec.py")
ok, out, ran = run_unittest(pristine_ws, "_hidden")
check("spec-conformance", ok and ran > 0, out)
# 4. the agent's own tests
own = workspace / "tests" / "test_query.py"
exists = own.is_file()
check("own-tests-exist", exists, "tests/test_query.py does not exist")
if exists:
try:
assertive = count_assertive_tests(own)
except SyntaxError as exc:
assertive = 0
print("note: tests/test_query.py does not parse: %s" % exc)
check("own-tests-count", assertive >= MIN_TEST_METHODS,
"%d test methods with assertions, need at least %d" % (assertive, MIN_TEST_METHODS))
text = own.read_text(encoding="utf-8")
check("own-tests-use-feature", "minidb" in text and "where" in text,
"tests/test_query.py does not exercise the where language")
own_ws = Path(tmp) / "own"
shutil.copytree(workspace, own_ws, ignore=IGNORE)
ok, out, ran = run_unittest(own_ws, "tests", pattern="test_query.py")
check("own-tests-pass", ok and ran >= MIN_TEST_METHODS, "ran %d tests; %s" % (ran, out))
# 5. documentation
readme = workspace / "README.md"
text = readme.read_text(encoding="utf-8") if readme.is_file() else ""
check("readme-mentions-where-option", "--where" in text, "README.md does not mention --where")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())