"""Acceptance test for time-to-green task T01 (written for the 2026-10-30 bench; the protocol names it, does not ship it). T01: tally: add a --json flag to `stats` that prints the same seven fields as one JSON object on stdout; text output unchanged when the flag is absent. Green: python -m unittest tasks.t01_test (run from the repo root) Shape follows the published page: main(["stats", path, "--col", "price", "--json"]), json.loads on the captured stdout, an equality check on the seven keys. Values are compared as numbers (a number or a numeric string both pass: the task does not fix the JSON type). "Text output unchanged" is the shipped suite, run from a frozen copy in tasks/ so edits to the root test file cannot weaken it. """ from __future__ import annotations import importlib.util import io import json import os import tempfile import unittest from tasks.regress_tally import HeadTests, StatsTests # noqa: F401 (collected as regression tests) ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) _spec = importlib.util.spec_from_file_location( "tally_t01", os.path.join(ROOT, "build-a-cli-tool-with-an-agent-from-a-spec.py")) tally = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(tally) SAMPLE = "name,price,qty\nbolt,1.5,10\nnut,,4\nwasher,0.25,100\nscrew,2,\n" SEVEN = {"column", "count", "blank", "min", "max", "mean", "median"} def run(argv, text=SAMPLE): with tempfile.TemporaryDirectory() as tmp: path = os.path.join(tmp, "data.csv") with open(path, "w", encoding="utf-8", newline="") as fh: fh.write(text) argv = [path if a == "FILE" else a for a in argv] out, err = io.StringIO(), io.StringIO() code = tally.main(argv, out=out, err=err) return code, out.getvalue(), err.getvalue() class StatsJsonTests(unittest.TestCase): def test_json_flag_prints_one_object_with_the_seven_fields(self): code, out, err = run(["stats", "FILE", "--col", "price", "--json"]) self.assertEqual(code, 0, err) obj = json.loads(out) self.assertIsInstance(obj, dict) self.assertEqual(set(obj), SEVEN) self.assertEqual(obj["column"], "price") for key, want in {"count": 3, "blank": 1, "min": 0.25, "max": 2, "mean": 1.25, "median": 1.5}.items(): with self.subTest(key=key): self.assertAlmostEqual(float(obj[key]), want) def test_text_output_unchanged_without_the_flag(self): code, out, _ = run(["stats", "FILE", "--col", "price"]) self.assertEqual(code, 0) self.assertEqual(out, "column: price\ncount: 3\nblank: 1\nmin: 0.25\n" "max: 2\nmean: 1.25\nmedian: 1.5\n") if __name__ == "__main__": unittest.main()