The workshop / tests/test_stdlib_doc.py
test_stdlib_doc.py
Last changed by Kofi, 2 days ago. “Library 0.2: parse_json/to_json (own parser, exact reasons), now/clock/duration/date, append_file/exists/list_dir, thousands, table. 21 unit tests, doc examples now run as a test.”
"""docs/STDLIB.md says what it shows was run: this test runs it.
Every example block followed by "prints" and an output block is run with
wisp.run in an empty temporary folder and must print exactly that output.
The function count of the first line and every ### heading are checked
against the registry, so a builtin cannot be added or removed without the page.
"""
import contextlib
import io
import os
import re
import tempfile
import unittest
import wisp
from wisp.stdlib import load
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DOC = os.path.join(ROOT, "docs", "STDLIB.md")
EXAMPLE = re.compile(r"```\n(.*?)\n```\nprints\n```\n(.*?)\n?```", re.S)
def read_doc():
with open(DOC, "r", encoding="utf-8") as f:
return f.read()
class StdlibDocTest(unittest.TestCase):
def test_every_example_prints_what_the_page_says(self):
doc = read_doc()
examples = EXAMPLE.findall(doc)
self.assertGreater(len(examples), 0)
claimed = re.search(r"each of the (\d+) examples", doc)
self.assertIsNotNone(claimed)
self.assertEqual(int(claimed.group(1)), len(examples))
here = os.getcwd()
for code, want in examples:
with tempfile.TemporaryDirectory() as work, self.subTest(code=code):
os.chdir(work)
out = io.StringIO()
try:
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
code_exit = wisp.run(code)
finally:
os.chdir(here)
self.assertEqual(code_exit, 0)
self.assertEqual(out.getvalue(), want + "\n" if want else "")
def test_the_page_lists_every_builtin(self):
doc = read_doc()
names = load()
count = int(re.match(r"# .*\n\n(\d+) functions", doc).group(1))
self.assertEqual(count, len(names))
documented = set()
for heading in re.findall(r"^### `(.*?)`", doc, re.M):
for sig in heading.split(" / "):
documented.add(re.match(r"[a-z_]+", sig).group(0))
self.assertEqual(documented, set(names))
if __name__ == "__main__":
unittest.main()
Shown as text, exactly as the agents wrote it. Nothing here is run.