Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
422 lines
17 KiB
Python
422 lines
17 KiB
Python
#!/usr/bin/env python3
|
|
"""Acceptance for refactor-shop. Usage: python3 accept.py WORKSPACE
|
|
|
|
Exit 0 = every check passed. The workspace is copied to a private temporary directory first and is
|
|
never modified. Standard library only; runs on Python 3.9 .. 3.14.
|
|
"""
|
|
|
|
import ast
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
HIDDEN = os.path.join(HERE, "hidden")
|
|
|
|
RESULTS = [] # (ok, name, detail)
|
|
|
|
|
|
def record(ok, name, detail=""):
|
|
RESULTS.append((bool(ok), name, detail))
|
|
print(("PASS %s" % name) if ok else ("FAIL %s :: %s" % (name, " ".join(str(detail).split())[:400])))
|
|
|
|
|
|
def check(name):
|
|
"""Decorator: run a check function; an exception or a returned string means failure."""
|
|
|
|
def deco(fn):
|
|
try:
|
|
problem = fn()
|
|
except Exception as exc: # noqa: BLE001 - any crash of a check is a failed check
|
|
record(False, name, "%s: %s" % (type(exc).__name__, exc))
|
|
else:
|
|
record(problem is None, name, problem or "")
|
|
return fn
|
|
|
|
return deco
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------ helpers
|
|
|
|
|
|
def parse(path):
|
|
with open(path, encoding="utf-8") as fh:
|
|
text = fh.read()
|
|
return ast.parse(text, filename=path), text
|
|
|
|
|
|
def shop_modules(root):
|
|
"""{module file name: (tree, text)} for every shop/*.py."""
|
|
result = {}
|
|
folder = os.path.join(root, "shop")
|
|
for name in sorted(os.listdir(folder)):
|
|
if name.endswith(".py"):
|
|
result[name] = parse(os.path.join(folder, name))
|
|
return result
|
|
|
|
|
|
def defined_functions(tree):
|
|
return {n.name for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
|
|
|
|
|
def referenced_names(tree):
|
|
names = set()
|
|
for n in ast.walk(tree):
|
|
if isinstance(n, ast.Name):
|
|
names.add(n.id)
|
|
elif isinstance(n, ast.Attribute):
|
|
names.add(n.attr)
|
|
elif isinstance(n, (ast.ImportFrom, ast.Import)):
|
|
for alias in n.names:
|
|
names.add(alias.name.split(".")[-1])
|
|
if isinstance(n, ast.ImportFrom) and n.module:
|
|
names.add(n.module.split(".")[-1])
|
|
return names
|
|
|
|
|
|
def call_name(node):
|
|
f = node.func
|
|
if isinstance(f, ast.Name):
|
|
return f.id
|
|
if isinstance(f, ast.Attribute):
|
|
return f.attr
|
|
return None
|
|
|
|
|
|
def contains_number(node):
|
|
for n in ast.walk(node):
|
|
if isinstance(n, ast.Constant) and isinstance(n.value, (int, float)) and not isinstance(n.value, bool):
|
|
return True
|
|
if isinstance(n, ast.Call) and call_name(n) == "Decimal":
|
|
return True
|
|
return False
|
|
|
|
|
|
def is_frozen_dataclass(cls):
|
|
for dec in cls.decorator_list:
|
|
target = dec.func if isinstance(dec, ast.Call) else dec
|
|
name = target.id if isinstance(target, ast.Name) else getattr(target, "attr", None)
|
|
if name == "dataclass":
|
|
if isinstance(dec, ast.Call):
|
|
for kw in dec.keywords:
|
|
if kw.arg == "frozen" and isinstance(kw.value, ast.Constant) and kw.value.value is True:
|
|
return True
|
|
return False
|
|
|
|
|
|
def class_fields(cls):
|
|
return [n.target.id for n in cls.body if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)]
|
|
|
|
|
|
def run(cmd, cwd, timeout=300, env_extra=None):
|
|
env = dict(os.environ)
|
|
env.update({"PYTHONDONTWRITEBYTECODE": "1", "PYTHONHASHSEED": "0", "PYTHONIOENCODING": "utf-8"})
|
|
env.pop("PYTHONPATH", None)
|
|
if env_extra:
|
|
env.update(env_extra)
|
|
return subprocess.run(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------- the checks
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) != 2 or not os.path.isdir(sys.argv[1]):
|
|
print("usage: accept.py WORKSPACE", file=sys.stderr)
|
|
return 2
|
|
workspace = os.path.abspath(sys.argv[1])
|
|
tmp = tempfile.mkdtemp(prefix="accept-refactor-shop-")
|
|
root = os.path.join(tmp, "ws")
|
|
try:
|
|
shutil.copytree(
|
|
workspace, root, ignore=shutil.ignore_patterns("__pycache__", ".git", "*.pyc", ".pytest_cache", ".mypy_cache")
|
|
)
|
|
evaluate(root, tmp)
|
|
finally:
|
|
shutil.rmtree(tmp, ignore_errors=True)
|
|
failed = [r for r in RESULTS if not r[0]]
|
|
print("%d checks, %d failed" % (len(RESULTS), len(failed)))
|
|
return 1 if failed else 0
|
|
|
|
|
|
def evaluate(root, tmp):
|
|
if not os.path.isdir(os.path.join(root, "shop")):
|
|
record(False, "layout", "no shop/ package in the workspace")
|
|
return
|
|
|
|
try:
|
|
modules = shop_modules(root)
|
|
except SyntaxError as exc:
|
|
record(False, "syntax", "shop/ does not parse: %s" % exc)
|
|
return
|
|
others = {k: v for k, v in modules.items()}
|
|
|
|
# ---- pristine tests (with the textual rename applied) must pass
|
|
@check("pristine_tests_pass")
|
|
def _():
|
|
probe = os.path.join(tmp, "probe")
|
|
shutil.copytree(root, probe)
|
|
shutil.rmtree(os.path.join(probe, "tests"), ignore_errors=True)
|
|
shutil.copytree(os.path.join(HIDDEN, "tests"), os.path.join(probe, "tests"))
|
|
for dirpath, _dirs, files in os.walk(os.path.join(probe, "tests")):
|
|
for fname in files:
|
|
if fname.endswith(".py"):
|
|
path = os.path.join(dirpath, fname)
|
|
with open(path, encoding="utf-8") as fh:
|
|
text = fh.read()
|
|
with open(path, "w", encoding="utf-8", newline="") as fh:
|
|
fh.write(re.sub(r"\bCust\b", "Customer", text))
|
|
proc = run([sys.executable, "-m", "unittest", "discover", "-s", "tests"], probe)
|
|
out = proc.stdout.decode("utf-8", "replace")
|
|
m = re.search(r"Ran (\d+) tests?", out)
|
|
if proc.returncode != 0 or not m:
|
|
tail = [l for l in out.splitlines() if l.strip()][-6:]
|
|
return "unittest exit %s: %s" % (proc.returncode, " | ".join(tail))
|
|
if int(m.group(1)) < 100:
|
|
return "only %s tests ran" % m.group(1)
|
|
return None
|
|
|
|
# ---- step 1
|
|
@check("s1_pricing_module")
|
|
def _():
|
|
path = os.path.join(root, "shop", "pricing.py")
|
|
if not os.path.exists(path):
|
|
return "shop/pricing.py is missing"
|
|
tree, _text = modules["pricing.py"]
|
|
if "price_order" not in {n.name for n in tree.body if isinstance(n, ast.FunctionDef)}:
|
|
return "price_order is not a module-level function of pricing.py"
|
|
cls = [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "PriceBreakdown"]
|
|
if not cls:
|
|
return "class PriceBreakdown missing"
|
|
if not is_frozen_dataclass(cls[0]):
|
|
return "PriceBreakdown is not a frozen dataclass"
|
|
missing = {"subtotal", "discount", "tax", "shipping", "total"} - set(class_fields(cls[0]))
|
|
return "PriceBreakdown lacks fields %s" % sorted(missing) if missing else None
|
|
|
|
@check("s1_duplicates_deleted")
|
|
def _():
|
|
gone = {"calc_total", "compute_order_total", "order_total_with_tax"}
|
|
for name, (tree, _t) in modules.items():
|
|
defined = defined_functions(tree) & gone
|
|
used = referenced_names(tree) & gone
|
|
if defined or used:
|
|
return "%s still has %s" % (name, sorted(defined | used))
|
|
return None
|
|
|
|
@check("s1_modules_use_price_order")
|
|
def _():
|
|
for name in ("invoices.py", "reports.py", "loyalty.py", "returns.py"):
|
|
if name not in modules:
|
|
return "%s is missing" % name
|
|
refs = referenced_names(modules[name][0])
|
|
if "price_order" not in refs and "pricing" not in refs:
|
|
return "%s does not use pricing.price_order" % name
|
|
return None
|
|
|
|
@check("s1_no_inline_rounding")
|
|
def _():
|
|
for name, (tree, _t) in modules.items():
|
|
if name in ("currency.py", "pricing.py"):
|
|
continue
|
|
for n in ast.walk(tree):
|
|
if isinstance(n, ast.Call) and call_name(n) == "quantize":
|
|
return "%s rounds with .quantize() itself" % name
|
|
tree = modules["invoices.py"][0]
|
|
for n in ast.walk(tree):
|
|
if isinstance(n, ast.Call) and call_name(n) == "money":
|
|
return "invoices.py still rounds money amounts inline"
|
|
return None
|
|
|
|
# ---- step 2
|
|
@check("s2_config_module")
|
|
def _():
|
|
if "config.py" not in modules:
|
|
return "shop/config.py is missing"
|
|
tree, _t = modules["config.py"]
|
|
cls = [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "Config"]
|
|
if not cls or not is_frozen_dataclass(cls[0]):
|
|
return "Config is missing or not a frozen dataclass"
|
|
assigned = set()
|
|
for n in tree.body:
|
|
if isinstance(n, ast.Assign):
|
|
assigned |= {t.id for t in n.targets if isinstance(t, ast.Name)}
|
|
elif isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
|
|
assigned.add(n.target.id)
|
|
return None if "DEFAULT_CONFIG" in assigned else "DEFAULT_CONFIG is not defined"
|
|
|
|
@check("s2_no_numeric_constants_outside_config")
|
|
def _():
|
|
pattern = re.compile(r"^_?[A-Z][A-Z0-9_]*$")
|
|
for name, (tree, _t) in modules.items():
|
|
if name in ("config.py", "sample.py"):
|
|
continue
|
|
for node in tree.body:
|
|
if isinstance(node, ast.Assign):
|
|
targets, value = node.targets, node.value
|
|
elif isinstance(node, ast.AnnAssign) and node.value is not None:
|
|
targets, value = [node.target], node.value
|
|
else:
|
|
continue
|
|
for t in targets:
|
|
if isinstance(t, ast.Name) and pattern.match(t.id) and contains_number(value):
|
|
return "%s defines %s" % (name, t.id)
|
|
return None
|
|
|
|
# ---- step 3
|
|
@check("s3_customer_rename")
|
|
def _():
|
|
tree = modules["customers.py"][0]
|
|
if "Customer" not in {n.name for n in tree.body if isinstance(n, ast.ClassDef)}:
|
|
return "class Customer is not defined in customers.py"
|
|
pattern = re.compile(r"\bCust\b")
|
|
for name, (_tree, text) in modules.items():
|
|
if pattern.search(text):
|
|
return "%s still mentions Cust" % name
|
|
tests_dir = os.path.join(root, "tests")
|
|
if os.path.isdir(tests_dir):
|
|
for fname in sorted(os.listdir(tests_dir)):
|
|
if fname.endswith(".py"):
|
|
with open(os.path.join(tests_dir, fname), encoding="utf-8") as fh:
|
|
if pattern.search(fh.read()):
|
|
return "tests/%s still mentions Cust" % fname
|
|
return None
|
|
|
|
# ---- step 4
|
|
@check("s4_reports_do_not_print")
|
|
def _():
|
|
tree, text = modules["reports.py"]
|
|
for n in ast.walk(tree):
|
|
if isinstance(n, ast.Call) and call_name(n) == "print":
|
|
return "reports.py calls print (line %d)" % n.lineno
|
|
if isinstance(n, ast.Attribute) and n.attr in ("stdout", "stderr"):
|
|
return "reports.py touches sys.%s" % n.attr
|
|
names = defined_functions(tree)
|
|
need = {"sales_report", "customer_report", "inventory_report", "tax_summary", "aging_report"}
|
|
return "missing %s" % sorted(need - names) if need - names else None
|
|
|
|
@check("s4_cli_prints")
|
|
def _():
|
|
tree = modules["cli.py"][0]
|
|
prints = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and call_name(n) == "print"]
|
|
return None if prints else "cli.py never prints"
|
|
|
|
# ---- step 5
|
|
@check("s5_single_date_parser")
|
|
def _():
|
|
if "dates.py" not in modules:
|
|
return "shop/dates.py is missing"
|
|
if "parse_date" not in {n.name for n in modules["dates.py"][0].body if isinstance(n, ast.FunctionDef)}:
|
|
return "parse_date is not defined in dates.py"
|
|
old = {"parse_joined", "parse_order_date", "parse_due_date", "_to_date"}
|
|
for name, (tree, _t) in modules.items():
|
|
found = (defined_functions(tree) | referenced_names(tree)) & old
|
|
if found:
|
|
return "%s still has %s" % (name, sorted(found))
|
|
if name == "dates.py":
|
|
continue
|
|
for n in ast.walk(tree):
|
|
if not isinstance(n, ast.Call):
|
|
continue
|
|
cn = call_name(n)
|
|
if cn in ("strptime", "fromisoformat"):
|
|
return "%s calls %s (line %d)" % (name, cn, n.lineno)
|
|
if cn in ("date", "datetime") and (n.args or n.keywords):
|
|
return "%s builds a date by hand with %s(...) (line %d)" % (name, cn, n.lineno)
|
|
return None
|
|
|
|
# ---- step 6
|
|
@check("s6_dead_code_removed")
|
|
def _():
|
|
dead = {"legacy_price_lookup", "dump_stock_csv", "old_order_summary", "estimate_zone_v1", "slugify"}
|
|
for name, (tree, _t) in modules.items():
|
|
found = (defined_functions(tree) | referenced_names(tree)) & dead
|
|
if found:
|
|
return "%s still has %s" % (name, sorted(found))
|
|
return None
|
|
|
|
# ---- step 7
|
|
@check("s7_hints_and_docstrings")
|
|
def _():
|
|
for fname in ("pricing.py", "config.py", "dates.py"):
|
|
if fname not in modules:
|
|
return "%s is missing" % fname
|
|
tree = modules[fname][0]
|
|
public = []
|
|
for n in tree.body:
|
|
if isinstance(n, ast.ClassDef) and not n.name.startswith("_"):
|
|
if not ast.get_docstring(n):
|
|
return "%s: class %s has no docstring" % (fname, n.name)
|
|
public += [m for m in n.body if isinstance(m, ast.FunctionDef) and not m.name.startswith("_")]
|
|
elif isinstance(n, ast.FunctionDef) and not n.name.startswith("_"):
|
|
public.append(n)
|
|
if fname != "config.py" and not public:
|
|
return "%s has no public function" % fname
|
|
for fn in public:
|
|
if not ast.get_docstring(fn):
|
|
return "%s: %s has no docstring" % (fname, fn.name)
|
|
if fn.returns is None:
|
|
return "%s: %s has no return annotation" % (fname, fn.name)
|
|
args = fn.args.posonlyargs + fn.args.args + fn.args.kwonlyargs
|
|
if fn.args.vararg:
|
|
args.append(fn.args.vararg)
|
|
if fn.args.kwarg:
|
|
args.append(fn.args.kwarg)
|
|
for a in args:
|
|
if a.arg in ("self", "cls"):
|
|
continue
|
|
if a.annotation is None:
|
|
return "%s: argument %s of %s has no annotation" % (fname, a.arg, fn.name)
|
|
return None
|
|
|
|
# ---- step 8
|
|
@check("s8_architecture_doc")
|
|
def _():
|
|
path = os.path.join(root, "docs", "ARCHITECTURE.md")
|
|
if not os.path.exists(path):
|
|
return "docs/ARCHITECTURE.md is missing"
|
|
with open(path, encoding="utf-8") as fh:
|
|
text = fh.read()
|
|
for need in ("pricing.py", "config.py", "dates.py", "price_order", "Customer"):
|
|
if need not in text:
|
|
return "does not mention %s" % need
|
|
gone = [
|
|
"calc_total", "compute_order_total", "order_total_with_tax", "parse_joined", "parse_order_date",
|
|
"parse_due_date", "_to_date", "legacy_price_lookup", "dump_stock_csv", "old_order_summary",
|
|
"estimate_zone_v1", "slugify", "TAX_RATE", "FREE_SHIPPING_THRESHOLD", "TIER_RATES", "REGION_RATES",
|
|
"VOLUME_DISCOUNT_RATE", "RESTOCKING_FEE_RATE",
|
|
]
|
|
for word in gone:
|
|
if re.search(r"(?<![A-Za-z0-9_])%s(?![A-Za-z0-9_])" % re.escape(word), text):
|
|
return "still mentions %s" % word
|
|
if re.search(r"\bCust\b", text):
|
|
return "still mentions Cust"
|
|
return None
|
|
|
|
# ---- hidden behaviour checks
|
|
proc = None
|
|
try:
|
|
proc = run([sys.executable, "-B", os.path.join(HIDDEN, "behaviour.py"), root], root, timeout=240)
|
|
out = proc.stdout.decode("utf-8", "replace")
|
|
except subprocess.TimeoutExpired:
|
|
record(False, "behaviour", "hidden behaviour checks timed out")
|
|
return
|
|
seen = 0
|
|
for line in out.splitlines():
|
|
if line.startswith("PASS "):
|
|
record(True, "behaviour_" + line[5:].strip())
|
|
seen += 1
|
|
elif line.startswith("FAIL "):
|
|
name, _, detail = line[5:].partition(" :: ")
|
|
record(False, "behaviour_" + name.strip(), detail)
|
|
seen += 1
|
|
if seen < 12:
|
|
tail = [l for l in out.splitlines() if l.strip()][-6:]
|
|
record(False, "behaviour_run", "only %d behaviour checks reported (exit %s): %s" % (seen, proc.returncode, " | ".join(tail)))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|