Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions .github/workflows/veyra-snap.yml
Original file line number Diff line number Diff line change
@@ -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/
7 changes: 7 additions & 0 deletions python/veyra-snap/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
__pycache__/
*.egg-info/
dist/
build/
.pytest_cache/
.veyra-snap/
examples/shop/tests/
16 changes: 16 additions & 0 deletions python/veyra-snap/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
21 changes: 21 additions & 0 deletions python/veyra-snap/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
135 changes: 135 additions & 0 deletions python/veyra-snap/README.md
Original file line number Diff line number Diff line change
@@ -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_<module>.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.
39 changes: 39 additions & 0 deletions python/veyra-snap/examples/shop/app.py
Original file line number Diff line number Diff line change
@@ -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()
Empty file.
35 changes: 35 additions & 0 deletions python/veyra-snap/examples/shop/shop/cart.py
Original file line number Diff line number Diff line change
@@ -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}
17 changes: 17 additions & 0 deletions python/veyra-snap/examples/shop/shop/models.py
Original file line number Diff line number Diff line change
@@ -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
23 changes: 23 additions & 0 deletions python/veyra-snap/examples/shop/shop/text.py
Original file line number Diff line number Diff line change
@@ -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))
Loading
Loading