From c93c6b508d4b254506107f258b932b224da71d89 Mon Sep 17 00:00:00 2001 From: Vikram Date: Sun, 22 Nov 2026 16:02:03 +0530 Subject: [PATCH] veyra-snap: a Python library that writes pytest tests from real runs `pip install veyra-snap`, then `veyra-snap run app.py` and `veyra-snap write`: it records what the functions in your project are given and what they return or raise, and writes those real calls as readable pytest tests. - No code changes: sys.monitoring on Python 3.12+ (code outside your project is never watched; a function with 25 cases stops being watched), and sys.settrace on 3.9-3.11. Or `recording()` / `@snap` in code. - Every value is rebuilt from its source and compared, type for type, before it goes in a test; values that can't be (files, connections, NaN, ...) are left out with the reason shown. - Functions that change between calls, or only return None, get no tests. - No dependencies. 71 tests, including an end-to-end run whose generated tests pass and then catch a changed rounding rule. - .github/workflows/veyra-snap.yml: tests on Linux, Windows and macOS with Python 3.9-3.14, and publishing to PyPI with Trusted Publishing. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/veyra-snap.yml | 89 +++ python/veyra-snap/.gitignore | 7 + python/veyra-snap/CHANGELOG.md | 16 + python/veyra-snap/LICENSE | 21 + python/veyra-snap/README.md | 135 +++++ python/veyra-snap/examples/shop/app.py | 39 ++ .../veyra-snap/examples/shop/shop/__init__.py | 0 python/veyra-snap/examples/shop/shop/cart.py | 35 ++ .../veyra-snap/examples/shop/shop/models.py | 17 + python/veyra-snap/examples/shop/shop/text.py | 23 + python/veyra-snap/pyproject.toml | 54 ++ python/veyra-snap/src/veyra_snap/__init__.py | 26 + python/veyra-snap/src/veyra_snap/__main__.py | 3 + python/veyra-snap/src/veyra_snap/_encode.py | 142 +++++ python/veyra-snap/src/veyra_snap/_record.py | 511 ++++++++++++++++++ python/veyra-snap/src/veyra_snap/_store.py | 103 ++++ python/veyra-snap/src/veyra_snap/_write.py | 150 +++++ python/veyra-snap/src/veyra_snap/cli.py | 222 ++++++++ python/veyra-snap/src/veyra_snap/py.typed | 0 python/veyra-snap/tests/__init__.py | 0 python/veyra-snap/tests/conftest.py | 45 ++ python/veyra-snap/tests/helpers.py | 25 + python/veyra-snap/tests/test_cli.py | 114 ++++ python/veyra-snap/tests/test_encode.py | 67 +++ python/veyra-snap/tests/test_record.py | 233 ++++++++ 25 files changed, 2077 insertions(+) create mode 100644 .github/workflows/veyra-snap.yml create mode 100644 python/veyra-snap/.gitignore create mode 100644 python/veyra-snap/CHANGELOG.md create mode 100644 python/veyra-snap/LICENSE create mode 100644 python/veyra-snap/README.md create mode 100644 python/veyra-snap/examples/shop/app.py create mode 100644 python/veyra-snap/examples/shop/shop/__init__.py create mode 100644 python/veyra-snap/examples/shop/shop/cart.py create mode 100644 python/veyra-snap/examples/shop/shop/models.py create mode 100644 python/veyra-snap/examples/shop/shop/text.py create mode 100644 python/veyra-snap/pyproject.toml create mode 100644 python/veyra-snap/src/veyra_snap/__init__.py create mode 100644 python/veyra-snap/src/veyra_snap/__main__.py create mode 100644 python/veyra-snap/src/veyra_snap/_encode.py create mode 100644 python/veyra-snap/src/veyra_snap/_record.py create mode 100644 python/veyra-snap/src/veyra_snap/_store.py create mode 100644 python/veyra-snap/src/veyra_snap/_write.py create mode 100644 python/veyra-snap/src/veyra_snap/cli.py create mode 100644 python/veyra-snap/src/veyra_snap/py.typed create mode 100644 python/veyra-snap/tests/__init__.py create mode 100644 python/veyra-snap/tests/conftest.py create mode 100644 python/veyra-snap/tests/helpers.py create mode 100644 python/veyra-snap/tests/test_cli.py create mode 100644 python/veyra-snap/tests/test_encode.py create mode 100644 python/veyra-snap/tests/test_record.py diff --git a/.github/workflows/veyra-snap.yml b/.github/workflows/veyra-snap.yml new file mode 100644 index 0000000..40b14d1 --- /dev/null +++ b/.github/workflows/veyra-snap.yml @@ -0,0 +1,89 @@ +# veyra-snap, the Python library in python/veyra-snap: tests on every change, and publishing to PyPI by hand. +# +# Publishing uses PyPI Trusted Publishing, so no password or token is stored anywhere. One-time setup on +# https://pypi.org/manage/account/publishing/ ("Add a new pending publisher"): +# PyPI project name: veyra-snap Owner: fcopensource Repository: veyraeditor +# Workflow name: veyra-snap.yml Environment name: pypi +# Then: Actions -> "veyra-snap (Python)" -> Run workflow -> publish: pypi. +# (For a trial run first, add the same pending publisher on https://test.pypi.org with environment "testpypi".) +name: veyra-snap (Python) + +on: + push: + branches: [main] + paths: ["python/veyra-snap/**", ".github/workflows/veyra-snap.yml"] + pull_request: + paths: ["python/veyra-snap/**", ".github/workflows/veyra-snap.yml"] + workflow_dispatch: + inputs: + publish: + description: Publish this version + type: choice + options: [none, testpypi, pypi] + default: none + +permissions: + contents: read + +defaults: + run: + working-directory: python/veyra-snap + +jobs: + test: + name: Python ${{ matrix.python }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, windows-latest, macos-latest] + python: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + allow-prereleases: true + - run: python -m pip install --upgrade pip + - run: python -m pip install . pytest + - run: python -m pytest -q -p no:cacheprovider + + build: + name: Build + needs: test + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: python -m pip install build twine + - run: python -m build + - run: python -m twine check --strict dist/* + - uses: actions/upload-artifact@v4 + with: + name: dist + path: python/veyra-snap/dist/ + + publish: + name: Publish to ${{ inputs.publish }} + needs: build + if: github.event_name == 'workflow_dispatch' && inputs.publish != 'none' + runs-on: ubuntu-22.04 + environment: + name: ${{ inputs.publish }} + url: ${{ inputs.publish == 'pypi' && 'https://pypi.org/project/veyra-snap/' || 'https://test.pypi.org/project/veyra-snap/' }} + permissions: + id-token: write # Trusted Publishing + defaults: + run: + working-directory: . + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: ${{ inputs.publish == 'testpypi' && 'https://test.pypi.org/legacy/' || 'https://upload.pypi.org/legacy/' }} + packages-dir: dist/ diff --git a/python/veyra-snap/.gitignore b/python/veyra-snap/.gitignore new file mode 100644 index 0000000..bea9775 --- /dev/null +++ b/python/veyra-snap/.gitignore @@ -0,0 +1,7 @@ +__pycache__/ +*.egg-info/ +dist/ +build/ +.pytest_cache/ +.veyra-snap/ +examples/shop/tests/ diff --git a/python/veyra-snap/CHANGELOG.md b/python/veyra-snap/CHANGELOG.md new file mode 100644 index 0000000..e3413b7 --- /dev/null +++ b/python/veyra-snap/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +## 1.0.0 + +First release. + +- `veyra-snap run app.py` / `run -m pkg`: run a program and record calls to the functions in your project, with no + code changes (`sys.monitoring` on Python 3.12+, `sys.settrace` on 3.9 to 3.11). +- `veyra-snap write`: turn the recordings into readable pytest files, one parametrized test per function, plus a + test for each recorded error with its exact message. +- Every value is checked to rebuild exactly from its source before it goes in a test; calls with values that can't + be (open files, connections, NaN, ...) are left out, with the reason shown. +- Functions that give different results for the same arguments, or only ever return `None`, get no tests. +- `recording()` to record a block in code, and `@snap` to record chosen functions (`VEYRA_SNAP=1`). +- Libraries, virtual environments and test files are never recorded; once a function has 25 cases it is no longer + watched, so hot loops stay fast. diff --git a/python/veyra-snap/LICENSE b/python/veyra-snap/LICENSE new file mode 100644 index 0000000..dc4f037 --- /dev/null +++ b/python/veyra-snap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 FlightCoders + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/veyra-snap/README.md b/python/veyra-snap/README.md new file mode 100644 index 0000000..d291fb3 --- /dev/null +++ b/python/veyra-snap/README.md @@ -0,0 +1,135 @@ +# veyra-snap + +**Run your code. Get pytest tests.** + +veyra-snap watches your program run, records what each of your functions was given and what it returned or raised, +and writes those real calls as ready-to-run pytest tests. Legacy code without tests, a refactor you're nervous about, +a library you want locked down: run it once, and you have a safety net. + +```console +$ pip install veyra-snap + +$ veyra-snap run app.py # use your program exactly as usual +◆ veyra-snap recorded 38 calls in 8 functions, 27 new cases + app.main 1 case + shop.cart.discount 5 cases (1 raise) + shop.cart.line_total 3 cases + shop.cart.price 6 cases (2 raises) + shop.cart.subtotal 4 cases + shop.text.new_order_id 1 case changes between calls: no tests + shop.text.order_number 4 cases + shop.text.slugify 3 cases + ! shop.text.write_receipt: 4 calls left out (an argument: StringIO values can't be written as source) + +$ veyra-snap write + ! app.main: only ever returned None: no tests + ✓ tests/test_snap_shop_cart.py 18 cases in 6 tests + ✓ tests/test_snap_shop_text.py 7 cases in 2 tests + ! shop.text.new_order_id: gave different results for the same arguments: no tests +◆ veyra-snap wrote 25 test cases. Run them: pytest + +$ pytest +25 passed in 0.05s +``` + +No changes to your code. No dependencies. Python 3.9 and newer. + +## What the tests look like + +Plain pytest you can read, review and commit: + +```python +@pytest.mark.parametrize( + "args, kwargs, expected", + [ + pytest.param(([shop.models.Item(name='Veyra mug', price=decimal.Decimal('12.00'), qty=2, size=shop.models.Size.MEDIUM)], None), {'shipping': decimal.Decimal('4.99')}, {'subtotal': decimal.Decimal('24.00'), 'discount': decimal.Decimal('0'), 'shipping': decimal.Decimal('4.99'), 'total': decimal.Decimal('28.99')}, id="price([shop.models.Item(name='Veyra mug', price=decimal.D..."), + ], +) +def test_price(args, kwargs, expected): + assert shop.cart.price(*args, **kwargs) == expected + + +@pytest.mark.parametrize( + "args, kwargs, error, message", + [ + pytest.param(([], None), {'shipping': decimal.Decimal('4.99')}, ValueError, 'the cart is empty', id="price([], None, **{'shipping': decimal.Decimal('4.99')})"), + ], +) +def test_price_raises(args, kwargs, error, message): + with pytest.raises(error) as caught: + shop.cart.price(*args, **kwargs) + assert str(caught.value) == message +``` + +Change `price()` so it gives a different answer, and these tests tell you. + +## How it works + +1. **Record.** `veyra-snap run` runs your script or module and watches the functions in *your* project: not the + standard library, not your installed packages, not your tests. On Python 3.12+ it uses `sys.monitoring`, so code + outside your project costs almost nothing. +2. **Check.** Every argument and result is turned into Python source and rebuilt to make sure it comes back the same, + type for type. Values that can't be (open files, connections, NaN, objects without a usable constructor) are left + out, and veyra-snap tells you which calls and why. +3. **Spot the flaky ones.** If the same arguments ever give a different result (time, randomness, files, a database), + the function is marked as changing between calls and gets no tests, so you never get flaky ones. +4. **Write.** `veyra-snap write` turns the recordings in `.veyra-snap/` into `tests/test_snap_.py`. Record more + runs any time; new cases are added (up to 25 per function), and files are regenerated. + +Values it can write: `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, lists, tuples, dicts, sets, +frozensets, `Decimal`, `Fraction`, `datetime`/`date`/`time`/`timedelta`/`timezone`, `UUID`, enums, dataclasses and +named tuples, nested any way you like. + +## Commands + +| Command | What it does | +|---|---| +| `veyra-snap run app.py [args]` | Run a script and record calls | +| `veyra-snap run -m mypkg [args]` | The same for `python -m mypkg` | +| `veyra-snap run --write ...` | Record and write the tests in one go | +| `veyra-snap write` | Write `tests/test_snap_*.py` from the recordings | +| `veyra-snap show [--cases]` | List what's been recorded | +| `veyra-snap clear` | Forget all recordings | + +Options for `run`: `-i/--include DIR` to watch only some folders, `-x/--exclude PATTERN` to skip modules or functions +(`-x 'shop.db*'`), `--limit N` cases per function. For `write`: `--out DIR` (default `tests`), `--only MODULE`, +`--force` to replace a test file veyra-snap didn't write (it never does otherwise). + +## In code + +Record a block, for example a notebook cell or a test of a bigger flow: + +```python +from veyra_snap import recording + +with recording(exclude=["shop.db*"]): + run_checkout_flow() +``` + +Or mark just the functions you care about: + +```python +from veyra_snap import snap + +@snap +def price(items, coupon=None): ... +``` + +`@snap` costs nothing in normal runs. It records when you run under `veyra-snap run`, inside `recording()`, or with +the environment variable `VEYRA_SNAP=1`. + +## Good to know + +- **Script functions:** functions defined in the script you run are recorded when the script has an + `if __name__ == "__main__":` guard, so tests can import it without running your program. +- **Methods** are recorded too, when the instance can be written as source (for example a dataclass). Class methods + work; nested functions and lambdas are skipped. +- **Python 3.9 to 3.11:** recording returned values works everywhere; recording *raised errors* automatically needs + 3.12+. With `@snap`, errors are recorded on every version. +- **What to commit:** the generated tests. `.veyra-snap/` holds working data and ignores itself in git. +- The tests check behaviour as it is today, bugs included. They're a safety net for changes, not a proof of + correctness: read them, and fix what looks wrong. + +## License + +MIT. Made by [FlightCoders](https://flightcoders.com), the team behind the [Veyra](https://veyraeditor.com) editor. diff --git a/python/veyra-snap/examples/shop/app.py b/python/veyra-snap/examples/shop/app.py new file mode 100644 index 0000000..005fabd --- /dev/null +++ b/python/veyra-snap/examples/shop/app.py @@ -0,0 +1,39 @@ +"""A tiny shop to try veyra-snap on: + + veyra-snap run app.py + veyra-snap write + pytest +""" + +import io +from decimal import Decimal + +from shop.cart import price +from shop.models import Item, Size +from shop.text import new_order_id, order_number, slugify, write_receipt + + +def main() -> None: + mug = Item("Veyra mug", Decimal("12.00"), qty=2) + hoodie = Item("FlightCoders hoodie", Decimal("39.00"), size=Size.LARGE) + stickers = Item("Sticker pack", Decimal("3.50"), qty=4) + + carts = [([mug], None), ([mug, stickers], "welcome10"), ([hoodie, mug], "VIP25"), ([stickers], None)] + for n, (items, coupon) in enumerate(carts, start=1): + bill = price(items, coupon) + receipt = [f"Order {order_number(42, n)}", *(f"{i.qty} x {i.name}" for i in items), f"Total {bill['total']}"] + write_receipt(receipt, io.StringIO()) + print(f"{order_number(42, n)} {slugify(items[0].name)} {bill['total']}") + + for bad in ([], [mug]): + try: + price(bad, "FREEBIE" if bad else None) + except ValueError as error: + print("refused:", error) + + print("internal id", new_order_id()) + print("internal id", new_order_id()) + + +if __name__ == "__main__": + main() diff --git a/python/veyra-snap/examples/shop/shop/__init__.py b/python/veyra-snap/examples/shop/shop/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/python/veyra-snap/examples/shop/shop/cart.py b/python/veyra-snap/examples/shop/shop/cart.py new file mode 100644 index 0000000..db36fc8 --- /dev/null +++ b/python/veyra-snap/examples/shop/shop/cart.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from decimal import ROUND_HALF_UP, Decimal + +from .models import Item, Size + +COUPONS = {"WELCOME10": Decimal("0.10"), "VIP25": Decimal("0.25")} +LARGE_SURCHARGE = Decimal("1.50") + + +def line_total(item: Item) -> Decimal: + extra = LARGE_SURCHARGE if item.size is Size.LARGE else Decimal(0) + return (item.price + extra) * item.qty + + +def subtotal(items: list[Item]) -> Decimal: + return sum((line_total(i) for i in items), Decimal(0)) + + +def discount(amount: Decimal, coupon: str | None) -> Decimal: + if coupon is None: + return Decimal(0) + rate = COUPONS.get(coupon.upper()) + if rate is None: + raise ValueError(f"unknown coupon {coupon!r}") + return (amount * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + +def price(items: list[Item], coupon: str | None = None, *, shipping: Decimal = Decimal("4.99")) -> dict[str, Decimal]: + if not items: + raise ValueError("the cart is empty") + sub = subtotal(items) + off = discount(sub, coupon) + ship = Decimal(0) if sub >= 50 else shipping + return {"subtotal": sub, "discount": off, "shipping": ship, "total": sub - off + ship} diff --git a/python/veyra-snap/examples/shop/shop/models.py b/python/veyra-snap/examples/shop/shop/models.py new file mode 100644 index 0000000..2f418f8 --- /dev/null +++ b/python/veyra-snap/examples/shop/shop/models.py @@ -0,0 +1,17 @@ +from dataclasses import dataclass +from decimal import Decimal +from enum import Enum + + +class Size(Enum): + SMALL = "S" + MEDIUM = "M" + LARGE = "L" + + +@dataclass +class Item: + name: str + price: Decimal + qty: int = 1 + size: Size = Size.MEDIUM diff --git a/python/veyra-snap/examples/shop/shop/text.py b/python/veyra-snap/examples/shop/shop/text.py new file mode 100644 index 0000000..829e3ea --- /dev/null +++ b/python/veyra-snap/examples/shop/shop/text.py @@ -0,0 +1,23 @@ +import re +import unicodedata +import uuid + + +def slugify(title: str, max_length: int = 40) -> str: + text = unicodedata.normalize("NFKD", title).encode("ascii", "ignore").decode() + text = re.sub(r"[^a-zA-Z0-9]+", "-", text).strip("-").lower() + return text[:max_length].rstrip("-") + + +def order_number(customer_id: int, sequence: int) -> str: + return f"FC-{customer_id:05d}-{sequence:04d}" + + +def new_order_id() -> str: + """Changes every call: veyra-snap notices and writes no test for it.""" + return uuid.uuid4().hex[:12] + + +def write_receipt(lines: list, out) -> int: + """Takes an open file: that argument can't be written in a test, so these calls are left out.""" + return out.write("\n".join(lines)) diff --git a/python/veyra-snap/pyproject.toml b/python/veyra-snap/pyproject.toml new file mode 100644 index 0000000..49ecfde --- /dev/null +++ b/python/veyra-snap/pyproject.toml @@ -0,0 +1,54 @@ +[build-system] +requires = ["hatchling>=1.21"] +build-backend = "hatchling.build" + +[project] +name = "veyra-snap" +dynamic = ["version"] +description = "Run your code, get pytest tests: records real function calls and writes them as regression tests." +readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] +requires-python = ">=3.9" +authors = [{ name = "FlightCoders", email = "hire@flightcoders.com" }] +keywords = ["pytest", "testing", "snapshot", "regression", "test generation", "golden master", "characterization tests", "veyra"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Environment :: Console", + "Framework :: Pytest", + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Software Development :: Testing", + "Topic :: Software Development :: Code Generators", + "Typing :: Typed", +] +dependencies = [] + +[project.urls] +Homepage = "https://github.com/fcopensource/veyraeditor/tree/main/python/veyra-snap" +Source = "https://github.com/fcopensource/veyraeditor/tree/main/python/veyra-snap" +Issues = "https://github.com/fcopensource/veyraeditor/issues" +Changelog = "https://github.com/fcopensource/veyraeditor/blob/main/python/veyra-snap/CHANGELOG.md" + +[project.scripts] +veyra-snap = "veyra_snap.cli:main" + +[tool.hatch.version] +path = "src/veyra_snap/__init__.py" + +[tool.hatch.build.targets.wheel] +packages = ["src/veyra_snap"] + +[tool.hatch.build.targets.sdist] +include = ["src", "tests", "examples", "README.md", "CHANGELOG.md", "LICENSE", "pyproject.toml"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/python/veyra-snap/src/veyra_snap/__init__.py b/python/veyra-snap/src/veyra_snap/__init__.py new file mode 100644 index 0000000..03a1aac --- /dev/null +++ b/python/veyra-snap/src/veyra_snap/__init__.py @@ -0,0 +1,26 @@ +"""veyra-snap: run your code, get pytest tests. + +veyra-snap records what your functions are given and what they return or raise, then writes those real calls as +pytest regression tests. + + $ veyra-snap run app.py # use your program as usual + $ veyra-snap write # tests/test_snap_*.py + $ pytest + +Or in code:: + + from veyra_snap import recording, snap + + with recording(): # every function in your project + main() + + @snap # or just the ones you mark (recorded when VEYRA_SNAP=1) + def price(cart, coupon=None): ... +""" + +from ._encode import Unsupported, encode +from ._record import Recorder, recording, snap +from ._write import write + +__version__ = "1.0.0" +__all__ = ["Recorder", "Unsupported", "__version__", "encode", "recording", "snap", "write"] diff --git a/python/veyra-snap/src/veyra_snap/__main__.py b/python/veyra-snap/src/veyra_snap/__main__.py new file mode 100644 index 0000000..eb53e2f --- /dev/null +++ b/python/veyra-snap/src/veyra_snap/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +raise SystemExit(main()) diff --git a/python/veyra-snap/src/veyra_snap/_encode.py b/python/veyra-snap/src/veyra_snap/_encode.py new file mode 100644 index 0000000..45ba99d --- /dev/null +++ b/python/veyra-snap/src/veyra_snap/_encode.py @@ -0,0 +1,142 @@ +"""Turn Python values into source code that rebuilds them exactly. + +``encode(value)`` returns the source and the imports it needs. Every result is checked by evaluating it again and +comparing, type for type, so a generated test never contains a value that doesn't round-trip. Values that can't be +written as plain source (open files, sockets, objects without a usable constructor, NaN, ...) raise ``Unsupported``. +""" + +from __future__ import annotations + +import dataclasses +import datetime +import decimal +import enum +import fractions +import math +import sys +import uuid +from typing import Any + +MAX_SOURCE = 4000 # longer values make unreadable tests, so they're skipped +MAX_DEPTH = 12 + + +class Unsupported(Exception): + """The value can't be written as source code that rebuilds it.""" + + +def encode(value: Any) -> tuple[str, frozenset[str]]: + """Source code for ``value`` and the ``import`` lines it needs. Raises ``Unsupported``.""" + imports: set[str] = set() + try: + source = _enc(value, imports, 0) + except RecursionError: # a self-referencing structure + raise Unsupported("the value refers to itself") from None + if len(source) > MAX_SOURCE: + raise Unsupported(f"too large to read in a test ({len(source)} characters)") + namespace: dict[str, Any] = {} + try: + for line in sorted(imports): + exec(line, namespace) + rebuilt = eval(source, namespace) + except Exception as error: + raise Unsupported(f"its source doesn't rebuild it ({type(error).__name__})") from None + if not same(rebuilt, value): + raise Unsupported("its source rebuilds a different value") + return source, frozenset(imports) + + +def same(a: Any, b: Any) -> bool: + """Equal, and of the same types all the way down (so 1, 1.0 and True stay different).""" + if type(a) is not type(b): + return False + if isinstance(a, (list, tuple)): + return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b)) + if isinstance(a, dict): + return list(a) == list(b) and all(same(a[k], b[k]) for k in a) + try: + return bool(a == b) + except Exception: + return False + + +def _ref(obj: Any) -> tuple[str, str]: + """``(import line, dotted path)`` for a module-level class, or Unsupported.""" + module = getattr(obj, "__module__", None) + qualname = getattr(obj, "__qualname__", None) + if not module or not qualname or module == "__main__" or "<" in qualname: + raise Unsupported(f"{getattr(obj, '__name__', obj)!s} can't be imported by a test") + mod = sys.modules.get(module) + found: Any = mod + for part in qualname.split("."): + found = getattr(found, part, None) + if found is not obj: + raise Unsupported(f"{module}.{qualname} can't be found by importing it") + if module == "builtins": + return "", qualname + return f"import {module}", f"{module}.{qualname}" + + +def _enc(v: Any, imports: set[str], depth: int) -> str: + if depth > MAX_DEPTH: + raise Unsupported("nested too deeply") + t = type(v) + if v is None or t is bool or t is int or t is str or t is bytes: + return repr(v) + if t is float: + if math.isnan(v): + raise Unsupported("NaN never equals itself") + if math.isinf(v): + return "float('inf')" if v > 0 else "float('-inf')" + return repr(v) + if t is complex: + if math.isnan(v.real) or math.isnan(v.imag) or math.isinf(v.real) or math.isinf(v.imag): + raise Unsupported("complex value with NaN or infinity") + return repr(v) + nxt = depth + 1 + if t is list: + return "[" + ", ".join(_enc(x, imports, nxt) for x in v) + "]" + if t is tuple: + items = [_enc(x, imports, nxt) for x in v] + return "(" + items[0] + ",)" if len(items) == 1 else "(" + ", ".join(items) + ")" + if t is dict: + return "{" + ", ".join(f"{_enc(k, imports, nxt)}: {_enc(x, imports, nxt)}" for k, x in v.items()) + "}" + if t is set or t is frozenset: + items = sorted(_enc(x, imports, nxt) for x in v) # sorted, so files don't change between runs + if t is set: + return "{" + ", ".join(items) + "}" if items else "set()" + return "frozenset({" + ", ".join(items) + "})" if items else "frozenset()" + if t is decimal.Decimal: + imports.add("import decimal") + return f"decimal.Decimal({str(v)!r})" + if t is fractions.Fraction: + imports.add("import fractions") + return f"fractions.Fraction({v.numerator}, {v.denominator})" + if t in (datetime.date, datetime.datetime, datetime.time, datetime.timedelta, datetime.timezone): + imports.add("import datetime") + source = repr(v) + if "zoneinfo." in source: + imports.add("import zoneinfo") + return source + if t is uuid.UUID: + imports.add("import uuid") + return f"uuid.UUID({str(v)!r})" + if isinstance(v, enum.Enum): + line, path = _ref(t) + if line: + imports.add(line) + return f"{path}.{v.name}" + if dataclasses.is_dataclass(v) and not isinstance(v, type): + fields = dataclasses.fields(v) + if any(not f.init for f in fields): + raise Unsupported(f"{t.__name__} has fields its constructor doesn't take") + line, path = _ref(t) + if line: + imports.add(line) + return f"{path}(" + ", ".join(f"{f.name}={_enc(getattr(v, f.name), imports, nxt)}" for f in fields) + ")" + if isinstance(v, tuple) and hasattr(t, "_fields"): # a namedtuple + line, path = _ref(t) + if line: + imports.add(line) + return f"{path}(" + ", ".join(f"{name}={_enc(x, imports, nxt)}" for name, x in zip(t._fields, v)) + ")" + raise Unsupported(f"{t.__name__} values can't be written as source") diff --git a/python/veyra-snap/src/veyra_snap/_record.py b/python/veyra-snap/src/veyra_snap/_record.py new file mode 100644 index 0000000..4f25b2f --- /dev/null +++ b/python/veyra-snap/src/veyra_snap/_record.py @@ -0,0 +1,511 @@ +"""Recording real calls: what each function was given, and what it returned or raised. + +Two ways in: + +* automatic: ``veyra-snap run app.py`` or ``with veyra_snap.recording():`` watches every function in your project + (``sys.monitoring`` on Python 3.12+, ``sys.settrace`` before that) without changing your code; +* by hand: ``@snap`` on the functions you choose, recorded when ``VEYRA_SNAP=1`` or inside ``recording()``. +""" + +from __future__ import annotations + +import atexit +import contextlib +import fnmatch +import functools +import inspect +import os +import sys +import threading +from collections import Counter +from pathlib import Path +from typing import Any, Callable, Iterator, TypeVar + +from . import _store +from ._encode import Unsupported, _ref, encode + +F = TypeVar("F", bound=Callable[..., Any]) + +CO_VARARGS, CO_VARKEYWORDS = 0x04, 0x08 +CO_NOT_PLAIN = 0x20 | 0x80 | 0x100 | 0x200 # generator, coroutine, iterable coroutine, async generator +SKIP_DIRS = {"site-packages", "dist-packages", ".venv", "venv", "env", ".env", ".tox", ".nox", "node_modules", + "__pycache__", ".git", "tests", "test", "testing"} +HERE = Path(__file__).resolve().parent + +_local = threading.local() + + +def _busy() -> bool: + return getattr(_local, "busy", False) + + +@contextlib.contextmanager +def _quiet() -> Iterator[None]: + """Our own work (encoding calls __eq__, constructors, ...) mustn't be recorded.""" + before = _busy() + _local.busy = True + try: + yield + finally: + _local.busy = before + + +def _stack() -> list[Any]: + stack = getattr(_local, "stack", None) + if stack is None: + stack = _local.stack = [] + return stack + + +def _is_code(obj: Any, code: Any) -> bool: + for _ in range(20): # through decorators + if obj is None: + return False + if getattr(getattr(obj, "__func__", obj), "__code__", None) is code: + return True + obj = getattr(obj, "__wrapped__", None) + return False + + +def _guess_qualname(code: Any, f_globals: dict[str, Any]) -> str: + """Python 3.9 and 3.10 have no co_qualname: find the function, or the class holding it, in its module.""" + name = code.co_name + if _is_code(f_globals.get(name), code): + return name + module = f_globals.get("__name__") + for key, value in list(f_globals.items()): + if isinstance(value, type) and value.__module__ == module and _is_code(value.__dict__.get(name), code): + return f"{key}.{name}" + return name + + +def _import_root(module: str, file: str | None) -> str | None: + """The folder that must be on sys.path to ``import module`` (``src`` for ``src/shop/cart.py``).""" + if not file: + return None + path = Path(file).resolve() + levels = len(module.split(".")) - (0 if path.name == "__init__.py" else 1) + root = path.parent + for _ in range(levels): + root = root.parent + return str(root) + + +class Target: + """How a test imports and calls a recorded function.""" + + __slots__ = ("module", "qualname", "drop_first", "root", "skip") + + def __init__(self, module: str, qualname: str, drop_first: bool, root: str | None, skip: str | None = None): + self.module, self.qualname, self.drop_first, self.root, self.skip = module, qualname, drop_first, root, skip + + +class Recorder: + """Collects calls in memory; ``save()`` merges them into ``.veyra-snap/``.""" + + def __init__(self, project: str | os.PathLike[str] = ".", limit: int = _store.DEFAULT_LIMIT, + include: list[str] | None = None, exclude: list[str] | None = None): + self.project = Path(project).resolve() + self.limit = limit + self.include = [Path(p).resolve() for p in (include or [self.project])] + self.exclude = list(exclude or []) + self.modules: dict[str, dict[str, Any]] = {} + self.outcomes: dict[tuple[str, str], dict[str, str]] = {} + self.calls = 0 + self.skipped: dict[str, Counter[str]] = {} + self._lock = threading.Lock() + self._scope: dict[str, bool] = {} + self._targets: dict[Any, Target] = {} + self._main_ok: bool | None = None + self.saved: dict[str, int] = {} + + # ------------------------------------------------------------------ what to record + + def in_scope(self, filename: str) -> bool: + cached = self._scope.get(filename) + if cached is not None: + return cached + ok = False + if filename and not filename.startswith("<"): + path = Path(filename).resolve() + name = path.name + root = next((r for r in self.include if r in path.parents), None) + # Only folders inside the project count: a project kept under C:\work\test\ is still recorded. + inside = path.relative_to(root).parts[:-1] if root else () + ok = (root is not None + and HERE not in path.parents + and not any(part in SKIP_DIRS for part in inside) + and not (name.startswith("test_") or name.endswith("_test.py") or name == "conftest.py")) + self._scope[filename] = ok + return ok + + def _excluded(self, module: str, qualname: str) -> bool: + full = f"{module}.{qualname}" + return any(fnmatch.fnmatchcase(full, p) or fnmatch.fnmatchcase(module, p) for p in self.exclude) + + def target_for_code(self, code: Any, f_globals: dict[str, Any]) -> Target | None: + """Where a code object lives, if a test can import and call it; None for code we never record.""" + if code in self._targets: + return self._targets[code] + target = None + qualname = getattr(code, "co_qualname", None) or _guess_qualname(code, f_globals) + # CO_OPTIMIZED: real functions only, not a module or a class body running its definitions + if not (not code.co_flags & 0x01 or code.co_flags & CO_NOT_PLAIN or code.co_name.startswith("<") or "" in qualname + or (code.co_name.startswith("__") and code.co_name.endswith("__"))): + module = f_globals.get("__name__") or "" + target = self._resolve(module, qualname, code, f_globals.get("__file__")) + self._targets[code] = target + return target + + def target_for_function(self, fn: Callable[..., Any]) -> Target | None: + code = getattr(fn, "__code__", None) + if code is None: + return None + if code in self._targets: + return self._targets[code] + target = self._resolve(fn.__module__, fn.__qualname__, code, getattr(sys.modules.get(fn.__module__), "__file__", None)) + self._targets[code] = target + return target + + def _resolve(self, module: str, qualname: str, code: Any, file: str | None) -> Target | None: + if not module or "<" in qualname: + return None + import_as = module + if module == "__main__": + # A script's functions are importable by file name, if importing it doesn't run the program. + if not file or not self._main_guarded(file): + return Target(module, qualname, False, None, "it's in a script without `if __name__ == \"__main__\":`") + path = Path(file).resolve() + try: + import_as = ".".join(path.relative_to(self.project).with_suffix("").parts) + except ValueError: + import_as = path.stem + if self._excluded(import_as, qualname): + return None + found: Any = sys.modules.get(module) + owner: Any = None + for part in qualname.split("."): + owner, found = found, getattr(found, part, None) + drop_first = inspect.ismethod(found) and isinstance(getattr(found, "__self__", None), type) # classmethod + chain, seen = found, 0 + while chain is not None and seen < 20: # the function may be wrapped by decorators + if getattr(getattr(chain, "__func__", chain), "__code__", None) is code: + return Target(import_as, qualname, drop_first, _import_root(import_as, file)) + chain, seen = getattr(chain, "__wrapped__", None), seen + 1 + return Target(import_as, qualname, False, None, "a test can't import it by name") + + def _main_guarded(self, file: str) -> bool: + if self._main_ok is None: + try: + text = Path(file).read_text(encoding="utf-8", errors="replace") + except OSError: + text = "" + self._main_ok = "__name__" in text and "__main__" in text + return self._main_ok + + # ------------------------------------------------------------------ recording + + def full(self, target: Target) -> bool: + return len(self.outcomes.get((target.module, target.qualname), ())) >= self.limit + + def skip(self, target: Target, reason: str) -> None: + with self._lock: + self.skipped.setdefault(f"{target.module}.{target.qualname}", Counter())[reason] += 1 + + def begin(self, target: Target, args: tuple[Any, ...], kwargs: dict[str, Any]) -> dict[str, Any] | None: + """Encodes the arguments before the call (the function may change them). None when it can't be.""" + if target.skip: + self.skip(target, target.skip) + return None + if len(self.outcomes.get((target.module, target.qualname), ())) >= self.limit: + return None # it has enough cases; skip the encoding cost on hot functions + if target.drop_first: + args = args[1:] + with _quiet(): + try: + a, ai = encode(tuple(args)) + k, ki = encode(dict(kwargs)) + except Unsupported as why: + self.skip(target, f"an argument: {why}") + return None + return {"args": a, "kwargs": k, "imports": set(ai) | set(ki)} + + def returned(self, target: Target, call: dict[str, Any], value: Any) -> None: + with _quiet(): + try: + source, imports = encode(value) + except Unsupported as why: + self.skip(target, f"the result: {why}") + return + call["returns"] = source + call["imports"] |= imports + self._add(target, call) + + def raised(self, target: Target, call: dict[str, Any], error: BaseException) -> None: + if not isinstance(error, Exception): + return # KeyboardInterrupt, SystemExit, ... + with _quiet(): + try: + line, path = _ref(type(error)) + message = str(error) + except Exception as why: + self.skip(target, f"the error: {why}") + return + call["raises"] = {"type": path, "import": line, "message": message} + self._add(target, call) + + def _add(self, target: Target, call: dict[str, Any]) -> None: + case = {"args": call["args"], "kwargs": call["kwargs"]} + if "raises" in call: + case["raises"] = call["raises"] + else: + case["returns"] = call["returns"] + case["imports"] = sorted(i for i in call["imports"] if i) + key = (target.module, target.qualname) + with self._lock: + self.calls += 1 + seen = self.outcomes.setdefault(key, {}) + module = self.modules.setdefault(target.module, {"module": target.module, "root": None, "functions": {}}) + if target.root and module["root"] is None: + module["root"] = target.root + fn = module["functions"].setdefault(target.qualname, {"nondeterministic": False, "cases": []}) + ck, oc = _store.case_key(case), _store.outcome(case) + if ck in seen: + if seen[ck] != oc: + fn["nondeterministic"] = True + return + if len(seen) >= self.limit: + return + seen[ck] = oc + fn["cases"].append(case) + + # ------------------------------------------------------------------ saving + + def save(self) -> dict[str, int]: + """Merges what was recorded into ``.veyra-snap/``. Returns new cases per module.""" + recorded = {} + for name, data in self.modules.items(): + root = data["root"] + rel = os.path.relpath(root, self.project) if root else "" + recorded[name] = {"module": name, "root": "" if rel == "." else rel.replace(os.sep, "/"), "functions": data["functions"]} + return _store.merge(_store.store_dir(self.project), recorded, self.limit) + + +# ---------------------------------------------------------------------- automatic recording + +def _frame_call(code: Any, f_locals: dict[str, Any]) -> tuple[tuple[Any, ...], dict[str, Any]]: + names = code.co_varnames + n, k = code.co_argcount, code.co_kwonlyargcount + args = [f_locals[x] for x in names[:n]] + kwargs = {x: f_locals[x] for x in names[n:n + k]} + i = n + k + if code.co_flags & CO_VARARGS: + args.extend(f_locals[names[i]]) + i += 1 + if code.co_flags & CO_VARKEYWORDS: + kwargs.update(f_locals[names[i]]) + return tuple(args), kwargs + + +class _Monitor: + """Python 3.12+: ``sys.monitoring``, which costs almost nothing for code outside your project.""" + + def __init__(self, recorder: Recorder): + self.r = recorder + mon = sys.monitoring # type: ignore[attr-defined] + self.tool = next((i for i in (5, 4, 3, 2) if mon.get_tool(i) is None), None) + if self.tool is None: + raise RuntimeError("every sys.monitoring slot is taken (by a debugger or coverage tool?)") + self.mon = mon + + def start(self) -> None: + mon, ev = self.mon, self.mon.events + mon.use_tool_id(self.tool, "veyra-snap") + mon.restart_events() + mon.register_callback(self.tool, ev.PY_START, self.on_start) + mon.register_callback(self.tool, ev.PY_RETURN, self.on_return) + mon.register_callback(self.tool, ev.PY_UNWIND, self.on_unwind) + mon.set_events(self.tool, ev.PY_START | ev.PY_RETURN | ev.PY_UNWIND) + + def stop(self) -> None: + mon, ev = self.mon, self.mon.events + mon.set_events(self.tool, 0) + for event in (ev.PY_START, ev.PY_RETURN, ev.PY_UNWIND): + mon.register_callback(self.tool, event, None) + mon.free_tool_id(self.tool) + + def _target(self, code: Any) -> Target | None: + if not self.r.in_scope(code.co_filename): + return None + frame = sys._getframe(2) + return self.r.target_for_code(code, frame.f_globals) + + def on_start(self, code: Any, offset: int) -> Any: + if _busy(): + return None + target = self._target(code) + if target is None or self.r.full(target): + return self.mon.DISABLE # never watched again: no cost for libraries, or for functions with enough cases + frame = sys._getframe(1) + try: + args, kwargs = _frame_call(code, frame.f_locals) + except Exception: + call = None + else: + call = self.r.begin(target, args, kwargs) + _stack().append((id(frame), target, call)) + return None + + def _pop(self, code: Any) -> tuple[Target, dict[str, Any] | None] | None: + """The entry for the frame that's ending. Entries above it (frames whose end we didn't see) are dropped.""" + stack = _stack() + frame_id = id(sys._getframe(2)) + for i in range(len(stack) - 1, -1, -1): + if stack[i][0] == frame_id: + _, target, call = stack[i] + del stack[i:] + return target, call + return None + + def on_return(self, code: Any, offset: int, value: Any) -> Any: + if _busy(): + return None + if not self.r.in_scope(code.co_filename) or self._targets_none(code): + return self.mon.DISABLE + popped = self._pop(code) + if popped is None: + target = self.r._targets.get(code) + return self.mon.DISABLE if target is not None and self.r.full(target) else None + if popped[1] is not None: + self.r.returned(popped[0], popped[1], value) + return None + + def on_unwind(self, code: Any, offset: int, error: BaseException) -> None: + if _busy() or not self.r.in_scope(code.co_filename) or self._targets_none(code): + return + popped = self._pop(code) + if popped and popped[1] is not None: + self.r.raised(popped[0], popped[1], error) + + def _targets_none(self, code: Any) -> bool: + return code in self.r._targets and self.r._targets[code] is None + + +class _Tracer: + """Python 3.9-3.11: ``sys.settrace``, on your project's functions only. Errors are recorded with ``@snap``.""" + + def __init__(self, recorder: Recorder): + self.r = recorder + self.previous: Any = None + + def start(self) -> None: + self.previous = sys.gettrace() + sys.settrace(self.on_call) + threading.settrace(self.on_call) + + def stop(self) -> None: + sys.settrace(self.previous) + threading.settrace(self.previous) # type: ignore[arg-type] + + def on_call(self, frame: Any, event: str, arg: Any) -> Any: + if event != "call" or _busy() or not self.r.in_scope(frame.f_code.co_filename): + return None + target = self.r.target_for_code(frame.f_code, frame.f_globals) + if target is None: + return None + try: + args, kwargs = _frame_call(frame.f_code, frame.f_locals) + except Exception: + return None + call = self.r.begin(target, args, kwargs) + if call is None: + return None + frame.f_trace_lines = False + state = {"error": False} + + def local(frame: Any, event: str, arg: Any) -> Any: + if event == "exception": + state["error"] = True + elif event == "return" and not _busy(): + if arg is None and state["error"]: + return None # returned None or raised: can't tell apart here, so leave it out + self.r.returned(target, call, arg) + return local + + return local + + +# ---------------------------------------------------------------------- public API + +_active: Recorder | None = None +_env_recorder: Recorder | None = None + + +def active() -> Recorder | None: + """The recorder @snap should use: inside recording(), or with VEYRA_SNAP=1 set.""" + global _env_recorder + if _active is not None: + return _active + if os.environ.get("VEYRA_SNAP", "").strip().lower() in ("1", "true", "yes", "on"): + if _env_recorder is None: + _env_recorder = Recorder(os.environ.get("VEYRA_SNAP_PROJECT", ".")) + atexit.register(_env_recorder.save) + return _env_recorder + return None + + +@contextlib.contextmanager +def recording(*, include: list[str] | None = None, exclude: list[str] | None = None, + limit: int = _store.DEFAULT_LIMIT, project: str = ".", auto: bool = True) -> Iterator[Recorder]: + """Record calls made inside the block, and save them to ``.veyra-snap/`` when it ends. + + ``include``: folders to watch (default: the project). ``exclude``: module or ``module.function`` patterns to + skip, like ``"shop.db*"``. ``auto=False`` records only functions marked with ``@snap``. + """ + global _active + if _active is not None: + raise RuntimeError("veyra-snap is already recording") + recorder = Recorder(project, limit, include, exclude) + watcher: Any = None + if auto: + watcher = _Monitor(recorder) if hasattr(sys, "monitoring") else _Tracer(recorder) + _active = recorder + if watcher: + watcher.start() + try: + yield recorder + finally: + if watcher: + watcher.stop() + _active = None + recorder.saved = recorder.save() + + +def snap(fn: F | None = None) -> Any: + """Mark a function to record. Free when not recording: it just calls the function.""" + + def decorate(f: F) -> F: + if inspect.isgeneratorfunction(f) or inspect.iscoroutinefunction(f) or inspect.isasyncgenfunction(f): + return f # generators and coroutines can't be snapshotted as a single return value + + @functools.wraps(f) + def wrapper(*args: Any, **kwargs: Any) -> Any: + recorder = active() + if recorder is None or _busy(): + return f(*args, **kwargs) + target = recorder.target_for_function(f) + call = recorder.begin(target, args, kwargs) if target is not None else None + if call is None: + return f(*args, **kwargs) + try: + result = f(*args, **kwargs) # automatic recording may see it too: same case, stored once + except BaseException as error: + recorder.raised(target, call, error) + raise + recorder.returned(target, call, result) + return result + + wrapper.__veyra_snap__ = True # type: ignore[attr-defined] + return wrapper # type: ignore[return-value] + + return decorate(fn) if fn is not None else decorate diff --git a/python/veyra-snap/src/veyra_snap/_store.py b/python/veyra-snap/src/veyra_snap/_store.py new file mode 100644 index 0000000..9da8cc2 --- /dev/null +++ b/python/veyra-snap/src/veyra_snap/_store.py @@ -0,0 +1,103 @@ +"""The recordings on disk: one JSON file per module in ``.veyra-snap/``, merged across runs. + +A module file looks like:: + + {"module": "shop.cart", "root": "src", "functions": { + "price": {"nondeterministic": false, "cases": [ + {"args": "([1, 2],)", "kwargs": "{}", "returns": "3", "imports": []}, + {"args": "([],)", "kwargs": "{}", "raises": {"type": "ValueError", "import": "", + "message": "empty cart"}, "imports": []}]}}} + +``root`` is the folder (relative to the project) that has to be on ``sys.path`` to import the module. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any + +STORE_DIR = ".veyra-snap" +DEFAULT_LIMIT = 25 + + +def store_dir(project: str | os.PathLike[str] = ".") -> Path: + return Path(project) / STORE_DIR + + +def _file(store: Path, module: str) -> Path: + return store / f"{module}.json" + + +def load(store: Path) -> dict[str, dict[str, Any]]: + """Every recorded module, by name.""" + modules: dict[str, dict[str, Any]] = {} + if not store.is_dir(): + return modules + for path in sorted(store.glob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if isinstance(data, dict) and isinstance(data.get("functions"), dict) and data.get("module"): + modules[data["module"]] = data + return modules + + +def case_key(case: dict[str, Any]) -> str: + return case["args"] + "\x00" + case["kwargs"] + + +def outcome(case: dict[str, Any]) -> str: + if "raises" in case: + r = case["raises"] + return f"raises {r['import']} {r['type']} {r['message']}" + return "returns " + case["returns"] + + +def merge(store: Path, recorded: dict[str, dict[str, Any]], limit: int = DEFAULT_LIMIT) -> dict[str, int]: + """Adds new recordings to the store. Returns how many new cases each module got. + + The same arguments with a different outcome mark the function nondeterministic (it depends on time, randomness, + files, ...), and it gets no tests. + """ + store.mkdir(parents=True, exist_ok=True) + ignore = store / ".gitignore" + if not ignore.exists(): # recordings are working data; the generated tests are what you commit + ignore.write_text("*\n", encoding="utf-8") + existing = load(store) + added: dict[str, int] = {} + for module, new in recorded.items(): + data = existing.get(module) or {"module": module, "root": new.get("root", ""), "functions": {}} + if new.get("root") is not None: + data["root"] = new["root"] + count = 0 + for qualname, fn in new["functions"].items(): + target = data["functions"].setdefault(qualname, {"nondeterministic": False, "cases": []}) + if fn.get("nondeterministic"): + target["nondeterministic"] = True + by_key = {case_key(c): c for c in target["cases"]} + for case in fn["cases"]: + old = by_key.get(case_key(case)) + if old is not None: + if outcome(old) != outcome(case): + target["nondeterministic"] = True + continue + if len(target["cases"]) >= limit: + continue + target["cases"].append(case) + by_key[case_key(case)] = case + count += 1 + added[module] = count + _file(store, module).write_text(json.dumps(data, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") + return added + + +def clear(store: Path) -> int: + removed = 0 + if store.is_dir(): + for path in store.glob("*.json"): + path.unlink() + removed += 1 + return removed diff --git a/python/veyra-snap/src/veyra_snap/_write.py b/python/veyra-snap/src/veyra_snap/_write.py new file mode 100644 index 0000000..8683e72 --- /dev/null +++ b/python/veyra-snap/src/veyra_snap/_write.py @@ -0,0 +1,150 @@ +"""Write the recordings in ``.veyra-snap/`` as pytest files.""" + +from __future__ import annotations + +import keyword +import os +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from . import _store + +HEADER = "# Generated by veyra-snap from real calls: https://pypi.org/project/veyra-snap/" + + +@dataclass +class Written: + path: Path + module: str + tests: int = 0 + cases: int = 0 + skipped: list[str] = field(default_factory=list) # functions left out, and why + kept: bool = False # an existing file that isn't ours, left alone + + +def _ident(text: str) -> str: + name = re.sub(r"\W+", "_", text).strip("_") or "fn" + return name + "_" if keyword.iskeyword(name) else name + + +def _call_id(name: str, case: dict[str, Any]) -> str: + inner = case["args"][1:-1].rstrip(",") + if case["kwargs"] != "{}": + inner = (inner + ", " if inner else "") + "**" + case["kwargs"] + text = f"{name}({inner})" + return text if len(text) <= 60 else text[:57] + "..." + + +def _lines(prefix: str, rows: list[str]) -> list[str]: + return [f"{prefix}{row}," for row in rows] + + +def render(data: dict[str, Any], out_dir: Path, project: Path) -> tuple[str, int, int, list[str]]: + """The test file for one recorded module: (source, tests, cases, functions left out).""" + module = data["module"] + imports = {f"import {module}"} + blocks: list[str] = [] + tests = cases = 0 + skipped = [] + for qualname, fn in sorted(data["functions"].items()): + if fn.get("nondeterministic"): + skipped.append(f"{module}.{qualname}: gave different results for the same arguments") + continue + if not fn["cases"]: + continue + if all(c.get("returns") == "None" for c in fn["cases"]): + # Nothing to check, and calling it again in a test would only repeat its side effects. + skipped.append(f"{module}.{qualname}: only ever returned None") + continue + call = f"{module}.{qualname}" + name = _ident(qualname) + short = qualname.rsplit(".", 1)[-1] + returns = [c for c in fn["cases"] if "raises" not in c] + raises = [c for c in fn["cases"] if "raises" in c] + for c in fn["cases"]: + imports.update(c.get("imports", [])) + if "raises" in c and c["raises"]["import"]: + imports.add(c["raises"]["import"]) + if returns: + rows = [f"pytest.param({c['args']}, {c['kwargs']}, {c['returns']}, id={_call_id(short, c)!r})" for c in returns] + blocks.append("\n".join([ + "@pytest.mark.parametrize(", + ' "args, kwargs, expected",', + " [", + *_lines(" ", rows), + " ],", + ")", + f"def test_{name}(args, kwargs, expected):", + f" assert {call}(*args, **kwargs) == expected", + ])) + tests += 1 + if raises: + rows = [f"pytest.param({c['args']}, {c['kwargs']}, {c['raises']['type']}, {c['raises']['message']!r}, " + f"id={_call_id(short, c)!r})" for c in raises] + blocks.append("\n".join([ + "@pytest.mark.parametrize(", + ' "args, kwargs, error, message",', + " [", + *_lines(" ", rows), + " ],", + ")", + f"def test_{name}_raises(args, kwargs, error, message):", + " with pytest.raises(error) as caught:", + f" {call}(*args, **kwargs)", + " assert str(caught.value) == message", + ])) + tests += 1 + cases += len(fn["cases"]) + if not blocks: + return "", 0, 0, skipped + + root = project / data.get("root", "") if data.get("root") else project + rel = os.path.relpath(root, out_dir).replace(os.sep, "/") + path_parts = ", ".join(repr(p) for p in rel.split("/")) if rel != "." else "" + head = [ + HEADER, + "# Re-create it with `veyra-snap write`; changes made here are overwritten.", + "import os", + "import sys", + "", + "import pytest", + "", + "sys.path.insert(0, os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__))" + + (f", {path_parts}" if path_parts else "") + ")))", + "", + *[f"{line} # noqa: E402" for line in sorted(imports)], + ] + return "\n".join(head) + "\n\n\n" + "\n\n\n".join(blocks) + "\n", tests, cases, skipped + + +def write(project: str | os.PathLike[str] = ".", out: str = "tests", force: bool = False, + only: list[str] | None = None) -> list[Written]: + """Writes ``/test_snap_.py`` for every recorded module. Never overwrites a file it didn't write, + unless ``force``.""" + project_path = Path(project).resolve() + out_dir = (project_path / out).resolve() + results = [] + for module, data in sorted(_store.load(_store.store_dir(project_path)).items()): + if only and not any(module == m or module.startswith(m + ".") for m in only): + continue + path = out_dir / f"test_snap_{_ident(module)}.py" + source, tests, cases, skipped = render(data, out_dir, project_path) + result = Written(path, module, tests, cases, skipped) + if not source: + results.append(result) + continue + if path.exists() and not force: + try: + first = path.read_text(encoding="utf-8").split("\n", 1)[0] + except OSError: + first = "" + if first != HEADER: + result.kept = True + results.append(result) + continue + out_dir.mkdir(parents=True, exist_ok=True) + path.write_text(source, encoding="utf-8") + results.append(result) + return results diff --git a/python/veyra-snap/src/veyra_snap/cli.py b/python/veyra-snap/src/veyra_snap/cli.py new file mode 100644 index 0000000..1155dbc --- /dev/null +++ b/python/veyra-snap/src/veyra_snap/cli.py @@ -0,0 +1,222 @@ +"""The ``veyra-snap`` command. + + veyra-snap run app.py [args] run your program and record its function calls + veyra-snap run -m mypkg [args] the same, for ``python -m mypkg`` + veyra-snap write turn the recordings into pytest files in tests/ + veyra-snap show what's been recorded so far + veyra-snap clear forget all recordings +""" + +from __future__ import annotations + +import argparse +import os +import runpy +import sys +import traceback +from pathlib import Path + +from . import __version__, _store +from ._record import recording +from ._write import write + +# ---------------------------------------------------------------------- output + + +def _colour() -> bool: + if os.environ.get("NO_COLOR") or not sys.stderr.isatty(): + return False + if os.name == "nt": + os.system("") # turns on ANSI colours in the Windows console + return True + + +C = _colour() + + +def _symbols() -> bool: + try: + "◆✓→".encode(sys.stderr.encoding or "ascii") + return True + except (UnicodeEncodeError, LookupError): + return False + + +U = _symbols() +DIAMOND, TICK, ARROW = ("◆", "✓", "→") if U else ("*", "+", "->") + + +def paint(text: str, code: str) -> str: + return f"\033[{code}m{text}\033[0m" if C else text + + +def bold(t: str) -> str: return paint(t, "1") +def dim(t: str) -> str: return paint(t, "2") +def green(t: str) -> str: return paint(t, "32") +def yellow(t: str) -> str: return paint(t, "33") +def cyan(t: str) -> str: return paint(t, "36") +def mint(t: str) -> str: return paint(t, "38;5;86") + + +BRAND = mint(f"{DIAMOND} veyra-snap") + + +def say(text: str = "") -> None: + print(text, file=sys.stderr) + + +# ---------------------------------------------------------------------- commands + + +def cmd_run(ns: argparse.Namespace) -> int: + if not ns.module and not ns.target: + say("Tell me what to run: veyra-snap run app.py or veyra-snap run -m mypackage") + return 2 + argv = ns.target + project = Path(ns.project).resolve() + if str(project) not in sys.path: + sys.path.insert(0, str(project)) + exit_code = 0 + with recording(include=ns.include or None, exclude=ns.exclude, limit=ns.limit, project=str(project)) as rec: + old_argv = sys.argv[:] + try: + if ns.module: + sys.argv = [ns.module, *argv] + runpy.run_module(ns.module, run_name="__main__", alter_sys=True) + else: + script = Path(argv[0]).resolve() + sys.argv = [str(script), *argv[1:]] + sys.path.insert(0, str(script.parent)) + runpy.run_path(str(script), run_name="__main__") + except SystemExit as stop: + exit_code = stop.code if isinstance(stop.code, int) else (0 if stop.code is None else 1) + except BaseException: + traceback.print_exc() + exit_code = 1 + finally: + sys.argv = old_argv + report_run(rec) + if ns.write: + say() + report_write(write(project, ns.out)) + else: + say(f"\n{dim('Next:')} {bold('veyra-snap write')} {dim('turns these into pytest tests in tests/')}") + return exit_code + + +def report_run(rec: object) -> None: + from ._record import Recorder + assert isinstance(rec, Recorder) + functions = sum(len(m["functions"]) for m in rec.modules.values()) + new = sum(rec.saved.values()) + say(f"\n{BRAND} recorded {bold(str(rec.calls))} call{'s' * (rec.calls != 1)} " + f"in {bold(str(functions))} function{'s' * (functions != 1)}, {green(str(new) + ' new case' + 's' * (new != 1))}") + rows = [] + for module, data in sorted(rec.modules.items()): + for qualname, fn in sorted(data["functions"].items()): + raises = sum(1 for c in fn["cases"] if "raises" in c) + note = yellow(" changes between calls: no tests") if fn["nondeterministic"] else ( + dim(f" ({raises} raise{'s' * (raises != 1)})") if raises else "") + rows.append((f"{module}.{qualname}", f"{len(fn['cases'])} case{'s' * (len(fn['cases']) != 1)}", note)) + width = max((len(r[0]) for r in rows), default=0) + for name, count, note in rows: + say(f" {name.ljust(width)} {cyan(count)}{note}") + for name, reasons in sorted(rec.skipped.items()): + why, n = reasons.most_common(1)[0] + total = sum(reasons.values()) + say(yellow(f" ! {name}: {total} call{'s' * (total != 1)} left out") + dim(f" ({why})")) + + +def report_write(results: list) -> None: + total_tests = sum(r.tests for r in results if not r.kept) + total_cases = sum(r.cases for r in results if not r.kept) + if not results: + say(f"{BRAND} nothing recorded yet. Start with: {bold('veyra-snap run app.py')}") + return + for r in results: + rel = os.path.relpath(r.path) + if r.kept: + say(yellow(f" ! {rel} exists and wasn't written by veyra-snap, so it was left alone") + dim(" (--force replaces it)")) + elif r.tests: + say(f" {green(TICK)} {rel} {cyan(str(r.cases) + ' case' + 's' * (r.cases != 1))} {dim('in ' + str(r.tests) + ' test' + 's' * (r.tests != 1))}") + for s in r.skipped: + say(yellow(f" ! {s}") + dim(": no tests")) + say(f"{BRAND} wrote {bold(str(total_cases))} test case{'s' * (total_cases != 1)}. Run them: {bold('pytest')}") + + +def cmd_write(ns: argparse.Namespace) -> int: + report_write(write(ns.project, ns.out, ns.force, ns.only or None)) + return 0 + + +def cmd_show(ns: argparse.Namespace) -> int: + modules = _store.load(_store.store_dir(ns.project)) + if not modules: + say(f"{BRAND} nothing recorded yet. Start with: {bold('veyra-snap run app.py')}") + return 0 + say(f"{BRAND} recordings in {_store.STORE_DIR}/") + for module, data in sorted(modules.items()): + say(bold(module)) + for qualname, fn in sorted(data["functions"].items()): + flag = yellow(" changes between calls") if fn.get("nondeterministic") else "" + say(f" {qualname} {cyan(str(len(fn['cases'])))}{flag}") + if ns.cases: + for c in fn["cases"]: + end = f"raises {c['raises']['type']}({c['raises']['message']!r})" if "raises" in c else f"{ARROW} {c['returns']}" + args = c["args"][1:-1].rstrip(",") + say(dim(f" {qualname.rsplit('.', 1)[-1]}({args}{', **' + c['kwargs'] if c['kwargs'] != '{}' else ''}) {end}")) + return 0 + + +def cmd_clear(ns: argparse.Namespace) -> int: + n = _store.clear(_store.store_dir(ns.project)) + say(f"{BRAND} forgot {n} recorded module{'s' * (n != 1)}") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="veyra-snap", + description="Run your code; get pytest tests. veyra-snap records what your functions are given and what " + "they return or raise, and writes it as regression tests.") + parser.add_argument("--version", action="version", version=f"veyra-snap {__version__}") + parser.add_argument("--project", default=".", help="the project folder (default: here)") + sub = parser.add_subparsers(dest="command", metavar="command") + + run = sub.add_parser("run", help="run a script or module and record calls", + description="Run a script or module and record calls to functions in your project.") + run.add_argument("-m", dest="module", metavar="MODULE", help="run a module, like python -m") + run.add_argument("-i", "--include", action="append", metavar="DIR", + help="only record code in this folder (repeatable; default: the project)") + run.add_argument("-x", "--exclude", action="append", default=[], metavar="PATTERN", + help="skip modules or functions matching this, like 'shop.db*' (repeatable)") + run.add_argument("--limit", type=int, default=_store.DEFAULT_LIMIT, help="cases kept per function (default 25)") + run.add_argument("--write", action="store_true", help="write the tests straight away") + run.add_argument("--out", default="tests", help="folder for the tests (default: tests)") + run.add_argument("target", nargs=argparse.REMAINDER, help="script.py and its arguments") + run.set_defaults(func=cmd_run) + + w = sub.add_parser("write", help="write pytest files from the recordings") + w.add_argument("--out", default="tests", help="folder for the tests (default: tests)") + w.add_argument("--force", action="store_true", help="replace test files veyra-snap didn't write") + w.add_argument("--only", action="append", metavar="MODULE", help="only these modules (repeatable)") + w.set_defaults(func=cmd_write) + + s = sub.add_parser("show", help="list what's been recorded") + s.add_argument("--cases", action="store_true", help="show every recorded call") + s.set_defaults(func=cmd_show) + + c = sub.add_parser("clear", help="forget all recordings") + c.set_defaults(func=cmd_clear) + + ns = parser.parse_args(argv) + if not getattr(ns, "func", None): + parser.print_help() + return 0 + if ns.command == "run": + ns.project = os.path.abspath(ns.project) + return int(ns.func(ns) or 0) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/python/veyra-snap/src/veyra_snap/py.typed b/python/veyra-snap/src/veyra_snap/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/python/veyra-snap/tests/__init__.py b/python/veyra-snap/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/python/veyra-snap/tests/conftest.py b/python/veyra-snap/tests/conftest.py new file mode 100644 index 0000000..128e963 --- /dev/null +++ b/python/veyra-snap/tests/conftest.py @@ -0,0 +1,45 @@ +import importlib +import json +import sys +import textwrap +from pathlib import Path + +import pytest + + +class Project: + """A throwaway project: write modules into it, import them, read what veyra-snap stored.""" + + def __init__(self, root: Path): + self.root = root + self.modules: list[str] = [] + + def write(self, rel: str, source: str) -> Path: + path = self.root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(source), encoding="utf-8") + return path + + def load(self, name: str): + importlib.invalidate_caches() + self.modules.append(name.split(".")[0]) + return importlib.import_module(name) + + def stored(self, module: str) -> dict: + return json.loads((self.root / ".veyra-snap" / f"{module}.json").read_text(encoding="utf-8")) + + def cases(self, module: str, qualname: str) -> list: + return self.stored(module)["functions"][qualname]["cases"] + + +@pytest.fixture +def project(tmp_path, monkeypatch): + root = tmp_path / "proj" + root.mkdir() + monkeypatch.syspath_prepend(str(root)) + monkeypatch.chdir(root) + p = Project(root) + yield p + for name in list(sys.modules): + if any(name == m or name.startswith(m + ".") for m in p.modules): + del sys.modules[name] diff --git a/python/veyra-snap/tests/helpers.py b/python/veyra-snap/tests/helpers.py new file mode 100644 index 0000000..51997c4 --- /dev/null +++ b/python/veyra-snap/tests/helpers.py @@ -0,0 +1,25 @@ +from dataclasses import dataclass, field +from enum import Enum +from typing import NamedTuple + + +class Colour(Enum): + RED = 1 + BLUE = 2 + + +@dataclass +class Point: + x: float + y: float + + +class Pair(NamedTuple): + left: str + right: Colour + + +@dataclass +class Locked: + value: int + secret: int = field(default=0, init=False) diff --git a/python/veyra-snap/tests/test_cli.py b/python/veyra-snap/tests/test_cli.py new file mode 100644 index 0000000..ab47ca8 --- /dev/null +++ b/python/veyra-snap/tests/test_cli.py @@ -0,0 +1,114 @@ +"""End to end: run a real program under ``veyra-snap run``, write the tests, run them with pytest, and check they +catch a change in behaviour.""" + +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from veyra_snap import _store +from veyra_snap._write import HEADER +from veyra_snap.cli import main + +EXAMPLE = Path(__file__).resolve().parents[1] / "examples" / "shop" +AUTO_ERRORS = sys.version_info >= (3, 12) + + +def run(*args, cwd): + env = {**os.environ, "NO_COLOR": "1", "PYTHONIOENCODING": "utf-8"} + return subprocess.run([sys.executable, "-m", "veyra_snap", *args], cwd=cwd, env=env, + capture_output=True, text=True, encoding="utf-8", timeout=120) + + +def pytest_in(folder): + return subprocess.run([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "tests"], cwd=folder, + capture_output=True, text=True, timeout=120) + + +@pytest.fixture +def shop(tmp_path): + dest = tmp_path / "shop" + shutil.copytree(EXAMPLE, dest, ignore=shutil.ignore_patterns(".veyra-snap", "tests", "__pycache__")) + return dest + + +def test_record_write_and_catch_a_regression(shop): + rec = run("run", "app.py", cwd=shop) + assert rec.returncode == 0, rec.stderr + assert "FC-00042-0001" in rec.stdout # the program ran normally + assert "recorded" in rec.stderr and "shop.cart.price" in rec.stderr + assert "changes between calls" in rec.stderr # new_order_id is random + assert "write_receipt" in rec.stderr and "StringIO" in rec.stderr + + out = run("write", cwd=shop) + assert out.returncode == 0, out.stderr + cart_tests = (shop / "tests" / "test_snap_shop_cart.py").read_text(encoding="utf-8") + assert cart_tests.startswith(HEADER) + assert "def test_price(" in cart_tests and "shop.models.Size.LARGE" in cart_tests + if AUTO_ERRORS: + assert "def test_price_raises(" in cart_tests and "the cart is empty" in cart_tests + text_tests = (shop / "tests" / "test_snap_shop_text.py").read_text(encoding="utf-8") + assert "new_order_id" not in text_tests and "write_receipt" not in text_tests + assert not (shop / "tests" / "test_snap_app.py").exists() # main() only returned None + + passed = pytest_in(shop) + assert passed.returncode == 0, passed.stdout + passed.stderr + assert " passed" in passed.stdout + + # A "harmless" change to the discount rounding: the generated tests notice. + cart = shop / "shop" / "cart.py" + cart.write_text(cart.read_text(encoding="utf-8").replace("ROUND_HALF_UP", "ROUND_DOWN"), encoding="utf-8") + failed = pytest_in(shop) + assert failed.returncode == 1 + assert "test_discount" in failed.stdout + + +def test_run_module_and_write_in_one_go(shop): + rec = run("run", "--write", "-m", "app", cwd=shop) + assert rec.returncode == 0, rec.stderr + assert (shop / "tests" / "test_snap_shop_cart.py").exists() + + +def test_write_never_replaces_a_file_it_did_not_write(shop): + run("run", "app.py", cwd=shop) + mine = shop / "tests" / "test_snap_shop_cart.py" + mine.parent.mkdir() + mine.write_text("# my own tests\n", encoding="utf-8") + out = run("write", cwd=shop) + assert "left alone" in out.stderr + assert mine.read_text(encoding="utf-8") == "# my own tests\n" + run("write", "--force", cwd=shop) + assert mine.read_text(encoding="utf-8").startswith(HEADER) + + +def test_exit_code_and_arguments_pass_through(tmp_path): + (tmp_path / "tool.py").write_text( + "import sys\n\ndef double(n):\n return n * 2\n\n" + "if __name__ == '__main__':\n print(double(int(sys.argv[1])))\n sys.exit(3)\n", encoding="utf-8") + rec = run("run", "tool.py", "21", cwd=tmp_path) + assert rec.returncode == 3 and rec.stdout.strip() == "42" + cases = _store.load(tmp_path / ".veyra-snap")["tool"]["functions"]["double"]["cases"] + assert cases[0]["returns"] == "42" + + +def test_script_without_main_guard_is_not_importable(tmp_path): + (tmp_path / "loose.py").write_text("def double(n):\n return n * 2\n\nprint(double(2))\n", encoding="utf-8") + rec = run("run", "loose.py", cwd=tmp_path) + assert rec.returncode == 0 + assert '__name__ == "__main__"' in rec.stderr + + +def test_show_and_clear(shop, capsys): + run("run", "app.py", cwd=shop) + assert main(["--project", str(shop), "show", "--cases"]) == 0 + shown = capsys.readouterr().err + assert "shop.cart" in shown and "discount" in shown + assert main(["--project", str(shop), "clear"]) == 0 + assert not list((shop / ".veyra-snap").glob("*.json")) + + +def test_nothing_to_run(capsys): + assert main(["run"]) == 2 diff --git a/python/veyra-snap/tests/test_encode.py b/python/veyra-snap/tests/test_encode.py new file mode 100644 index 0000000..6c6883a --- /dev/null +++ b/python/veyra-snap/tests/test_encode.py @@ -0,0 +1,67 @@ +import datetime +import decimal +import fractions +import io +import uuid + +import pytest + +from veyra_snap import Unsupported, encode +from veyra_snap._encode import same + +from .helpers import Colour, Point, Pair, Locked + + +ROUND_TRIPS = [ + None, True, False, 0, -7, 10**30, 1.5, -0.0, float("inf"), float("-inf"), 3 + 4j, "", "naïve ✓ \n'\"", b"\x00\xff", + [], [1, [2, [3]]], (), (1,), (1, "a", None), {}, {"a": 1, "b": [1, 2]}, {1: "x", (2, 3): {4}}, + set(), {3, 1, 2}, frozenset(), frozenset({"b", "a"}), + decimal.Decimal("12.50"), decimal.Decimal("-0.001"), fractions.Fraction(1, 3), + datetime.date(2026, 11, 22), datetime.datetime(2026, 11, 22, 9, 30, 1, 5), + datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc), datetime.time(23, 59), datetime.timedelta(days=2, seconds=3), + uuid.UUID("12345678-1234-5678-1234-567812345678"), + Colour.RED, Point(1, 2.5), [Point(0, 0), Point(-1, 3)], Pair(left="a", right=Colour.BLUE), +] + + +@pytest.mark.parametrize("value", ROUND_TRIPS, ids=repr) +def test_round_trips(value): + source, imports = encode(value) + namespace = {} + for line in imports: + exec(line, namespace) + assert same(eval(source, namespace), value) + + +def test_types_stay_apart(): + assert not same(1, 1.0) and not same(1, True) and not same([1], (1,)) + assert encode(1)[0] == "1" and encode(1.0)[0] == "1.0" and encode(True)[0] == "True" + + +def test_sets_are_written_in_a_stable_order(): + assert encode({"b", "c", "a"})[0] == "{'a', 'b', 'c'}" + + +def test_imports_are_reported(): + assert encode(decimal.Decimal("1"))[1] == {"import decimal"} + assert encode(Point(1, 2))[1] == {"import tests.helpers"} + + +@pytest.mark.parametrize("value, why", [ + (float("nan"), "NaN"), + (io.StringIO(), "StringIO"), + (object(), "object"), + (lambda: 1, "function"), + (Locked(1), "constructor"), + ("x" * 5000, "too large"), +]) +def test_unsupported(value, why): + with pytest.raises(Unsupported, match=why): + encode(value) + + +def test_self_reference_is_refused(): + loop = [] + loop.append(loop) + with pytest.raises(Unsupported): + encode(loop) diff --git a/python/veyra-snap/tests/test_record.py b/python/veyra-snap/tests/test_record.py new file mode 100644 index 0000000..1db2f03 --- /dev/null +++ b/python/veyra-snap/tests/test_record.py @@ -0,0 +1,233 @@ +import sys + +import pytest + +from veyra_snap import recording, snap + +AUTO_ERRORS = sys.version_info >= (3, 12) # before 3.12, errors are recorded with @snap only + +MATHS = """ + def add(a, b=0, *rest, scale=1, **extra): + return (a + b + sum(rest)) * scale + len(extra) + + def ratio(a, b): + if b == 0: + raise ZeroDivisionError("b can't be zero") + return a / b + + def shout(words): + words.append("!") # changes its argument: the test must use the value from before the call + return " ".join(words).upper() + + def _helper(x): + return x * 2 + + def uses_helper(x): + return _helper(x) + 1 + + def counter(): + counter.n = getattr(counter, "n", 0) + 1 + return counter.n + + def gen(): + yield 1 + + def nested(): + def inner(): + return 1 + return inner() + + class Box: + def __init__(self, size): + self.size = size + + @classmethod + def make(cls, size): + return size * 10 + + @staticmethod + def double(n): + return n * 2 +""" + + +def test_records_returns_with_every_kind_of_argument(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.add(1, 2, 3, 4, scale=2, flag=True) + m.add(5) + cases = project.cases("maths", "add") + assert {(c["args"], c["kwargs"], c["returns"]) for c in cases} == { + ("(1, 2, 3, 4)", "{'scale': 2, 'flag': True}", "21"), + ("(5, 0)", "{'scale': 1}", "5"), + } + + +def test_arguments_are_captured_before_the_call(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.shout(["hi", "there"]) + [case] = project.cases("maths", "shout") + assert case["args"] == "(['hi', 'there'],)" and case["returns"] == "'HI THERE !'" + + +@pytest.mark.skipif(not AUTO_ERRORS, reason="automatic error recording needs Python 3.12+") +def test_records_errors(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.ratio(1, 4) + with pytest.raises(ZeroDivisionError): + m.ratio(1, 0) + cases = {c["args"]: c for c in project.cases("maths", "ratio")} + assert cases["(1, 4)"]["returns"] == "0.25" + assert cases["(1, 0)"]["raises"] == {"type": "ZeroDivisionError", "import": "", "message": "b can't be zero"} + + +def test_private_helpers_and_callers_both_recorded_but_not_generators_or_nested(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.uses_helper(3) + list(m.gen()) + m.nested() + functions = project.stored("maths")["functions"] + assert set(functions) == {"uses_helper", "_helper", "nested"} + + +def test_flaky_functions_are_marked(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.counter() + m.counter() + assert project.stored("maths")["functions"]["counter"]["nondeterministic"] is True + + +def test_class_and_static_methods(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.Box.make(3) + m.Box.double(4) + m.Box(2) + functions = project.stored("maths")["functions"] + assert functions["Box.make"]["cases"][0]["args"] == "(3,)" # cls is dropped: tests call maths.Box.make(3) + assert functions["Box.double"]["cases"][0]["returns"] == "8" + assert "Box.__init__" not in functions + + +def test_limit_and_exclude(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(limit=3, exclude=["maths.ratio"]): + for i in range(10): + m.add(i) + m.ratio(4, 2) + assert len(project.cases("maths", "add")) == 3 + assert "ratio" not in project.stored("maths")["functions"] + + +def test_libraries_and_tests_are_not_recorded(project): + project.write("maths.py", MATHS) + project.write("tests/test_maths.py", "def test_x():\n return 1\n") + project.write(".venv/lib/site-packages/lib.py", "def f():\n return 1\n") + m = project.load("maths") + with recording(): + m.add(1) + import json + json.dumps({"a": 1}) + stored = sorted(p.name for p in (project.root / ".veyra-snap").glob("*.json")) + assert stored == ["maths.json"] + + +def test_unsupported_values_are_skipped_with_a_reason(project): + project.write("io_things.py", "def size(f):\n return len(f.getvalue())\n") + m = project.load("io_things") + import io + with recording() as rec: + m.size(io.StringIO("abc")) + assert "io_things.size" in rec.skipped + assert "StringIO" in next(iter(rec.skipped["io_things.size"])) + + +def test_recordings_merge_across_runs(project): + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.add(1) + with recording(): + m.add(1) + m.add(2) + assert len(project.cases("maths", "add")) == 2 + + +def test_snap_decorator_records_only_when_recording(project, monkeypatch): + project.write("marked.py", """ + from veyra_snap import snap + + @snap + def area(w, h): + if w < 0: + raise ValueError("negative width") + return w * h + """) + m = project.load("marked") + monkeypatch.delenv("VEYRA_SNAP", raising=False) + assert m.area(2, 3) == 6 # not recording: just calls it + assert not (project.root / ".veyra-snap").exists() + with recording(auto=False): + m.area(2, 3) + with pytest.raises(ValueError): + m.area(-1, 3) + cases = {c["args"]: c for c in project.cases("marked", "area")} + assert cases["(2, 3)"]["returns"] == "6" + assert cases["(-1, 3)"]["raises"]["message"] == "negative width" + + +def test_snap_leaves_generators_alone(): + @snap + def g(): + yield 1 + assert list(g()) == [1] + + +def test_nested_recording_is_refused(project): + with recording(): + with pytest.raises(RuntimeError): + with recording(): + pass + + +def test_fallback_tracer_for_older_pythons(project, monkeypatch): + """Python 3.9-3.11 record with sys.settrace; try that path on any version.""" + from veyra_snap import _record + monkeypatch.setattr(_record, "_Monitor", _record._Tracer) + project.write("maths.py", MATHS) + m = project.load("maths") + with recording(): + m.add(1, 2) + m.shout(["a"]) + m.ratio(1, 4) + with pytest.raises(ZeroDivisionError): + m.ratio(1, 0) + m.Box.make(2) + functions = project.stored("maths")["functions"] + assert functions["add"]["cases"][0]["returns"] == "3" + assert functions["shout"]["cases"][0]["args"] == "(['a'],)" + assert [c["args"] for c in functions["ratio"]["cases"]] == ["(1, 4)"] # the raise is left out, not mis-recorded + assert functions["Box.make"]["cases"][0]["returns"] == "20" + assert sys.gettrace() is None # the tracer is removed afterwards + + +def test_qualname_without_co_qualname(project): + """Python 3.9 and 3.10 code objects have no co_qualname; methods must still be found.""" + from veyra_snap._record import _guess_qualname + project.write("maths.py", MATHS) + m = project.load("maths") + g = vars(m) + assert _guess_qualname(m.add.__code__, g) == "add" + assert _guess_qualname(m.Box.make.__func__.__code__, g) == "Box.make" + assert _guess_qualname(m.Box.double.__code__, g) == "Box.double"