Skip to main content

pytest-txtar

Contract testing for command-line tools, driven by txtar archives: one file per case carrying the fixture tree, the invocation, and everything asserted about the result — stdout, stderr, exit code, and files left behind.

Each case runs in a fresh sandbox; paths that vary per run are normalized to tokens before comparison, and a golden-update flow rewrites assertions from the actual run.

The package is layered: pytest_txtar.txtar parses the archive format, the pytest-free core (case, sandbox, compare, update) executes and compares cases parameterized by a TxtarSpec, and a pytest plugin collects *.txtar files as test items.

Status: pre-release, under construction.

Configuration

A consumer states what to run and where by implementing the pytest_txtar_spec hook in a conftest.py beside its cases:

from pathlib import Path

import pytest
from pytest_txtar.case import TxtarSpec

ROOT = Path(__file__).resolve().parents[1]


def pytest_txtar_spec(config: pytest.Config) -> TxtarSpec:
    return TxtarSpec(
        commands={"mytool": ROOT / "bin" / "mytool"},
        roots=("home", "xdg", "cwd"),
        cwd_root="cwd",
        env={"HOME": "home", "XDG_CONFIG_HOME": "xdg"},
    )
Field Meaning
commands Command word → binary it resolves to, for the first word of a cmd line.
roots Sandbox subdirectories a case may address under fixtures/ and expected/.
cwd_root The root the commands run in.
env Environment variable → the root it is pointed at, on top of the ambient environment.
tokens Root → normalization token; defaults to the upper-cased root in braces.

The home/xdg/cwd roots above are one configuration, not a fixed set: a spec may name any roots and bind any variables to them.

Case format

This section defines the behavior; the package implements it. A runner in another language is conformant when it agrees with everything below.

Container — txtar

An archive is a leading comment followed by file sections. A section starts with a marker line -- name --; everything up to the next marker line is its content.

  • The marker line is exactly --, a space, the name, a space, --. Surrounding whitespace in the name is stripped; a name may contain /.
  • A line whose name would be empty (-- --) is content, not a marker.
  • Content that does not end in a newline is treated as if it did. A well-formed archive therefore round-trips byte-exactly through parse and serialize.
  • A section name may appear only once per case; a repeat is a malformed case.
  • There are no other syntax errors: any byte sequence parses.

Sections

Section Required Meaning
cmd yes One command per line, run in order in the sandbox.
exit no (default 0) Expected exit code of the last cmd line, as a decimal integer.
stdout no Expected stdout, normalized.
stderr no Expected stderr, normalized.
stdin no Input written to the stdin of the last cmd line, with root tokens expanded.
fixtures/<root>/<path> no File written under that sandbox root before the run.
expected/<root>/<path> no Expected content of that file after the run, normalized.

<root> is one of the spec's roots, and <path> must stay inside it — an absent root, a bare root with no path, or a path escaping through .. is a malformed case.

Any other section name is a hard error — the case is malformed and collection fails. Unknown sections are never ignored, so a typo (stdOut, expect/cwd/x) fails loudly instead of silently asserting nothing.

Parent directories of a fixtures/ path are created; an empty section creates an empty file.

Sandbox

Each case runs in a fresh temporary directory holding one subdirectory per root in the spec. The spec's env mapping points the named environment variables at those directories, and the commands run in cwd_root.

Fixtures are materialized into the roots, then the cmd lines run. Nothing outside the sandbox is read or written, and the sandbox is discarded after the case.

Commands

Each cmd line is split with shell-like quoting and executed directly — there is no shell, so no pipes, redirection, globbing or variable expansion. A first word listed in the spec's commands mapping resolves to its configured binary path; any other first word is executed as given.

With more than one line:

  • every line but the last must exit 0; if one does not, the case fails;
  • the last line's exit code is compared against exit;
  • stdout and stderr are asserted against the concatenation of all lines' output, in order.

All lines share one sandbox, so a case can chain commands that build on each other's writes.

Standard input

Without a shell there is no < or |, so input reaches a command through the stdin section.

  • The stdin content is written to the standard input of the last cmd line — the one whose exit code is asserted — and the stream is then closed.
  • Every earlier line, and the last line of a case without a stdin section, gets an empty standard input: reading it yields end-of-file at once. Standard input is never inherited from the runner, so a case cannot block on a terminal.
  • The content is passed as parsed, byte for byte, including blank and trailing-space lines. The txtar rule applies: content that does not end in a newline is treated as if it did, so input always ends in a newline.
  • Root tokens are expanded: every occurrence of a root's token ({CWD}, {HOME}, …, per the spec's tokens) is replaced by the absolute path of that root in the sandbox — the same path the spec's env bindings and the working directory point at. This is the inverse of normalization, and the only way a case can hand a command an absolute path inside its sandbox. There is no escape for a literal token. Nothing else is rewritten: [..] has no meaning in stdin.

Normalization

Before comparison, both sides are rewritten so that volatile values do not leak into the expected text. Expected sections are written in normalized form.

Absolute sandbox paths in captured output are replaced by each root's token — {HOME} for the home root by default, and whatever the spec's tokens mapping says otherwise.

Comparison is line by line. Within a line, the literal [..] matches any run of characters, including none, and never crosses a line boundary — it covers commit hashes, timestamps and durations. A line without [..] must match exactly, whitespace included.

Tokens and [..] apply to stdout, stderr and every expected/ section. They are not expanded in cmd or fixtures/, which are written to the sandbox literally; a fixture's text is matched with them only when it stands in for an absent expected/ section (see below). stdin runs the other way: its tokens expand to sandbox paths, and [..] means nothing there (see Standard input).

Assertions

  • An absent section asserts nothing: a case with no stderr section does not require stderr to be empty.
  • An absent exit asserts exit 0.
  • An expected/ section for a file that does not exist fails the case.
  • Every file seeded by a fixtures/<root>/<path> section with no matching expected/<root>/<path> section must be left unchanged: after the run it must still match the fixture's text, under the same tokens and [..] as an expected/ section, and a deleted or altered one fails the case as expected/<root>/<path> (unchanged fixture). An error path must leave its inputs intact, and asserting that by default keeps the corpus deterministic without the author remembering to.
  • Files created beyond those named by fixtures/ and expected/ are not flagged.
  • A failure that needs an unwritable path or another OS-level fault is not expressible — fixtures carry content, not permissions.

Running

Cases collect as ordinary pytest items, one per *.txtar file, whose nodeid is the case path:

pytest tests/cases
pytest tests/cases -k smoke

Selection, parallelism, reporting and exit codes are pytest's. A failing case reports one labeled unified diff per mismatched section; a malformed case is a collection error.

Authoring a case

Write the comment, cmd and fixtures/ sections by hand, then let the runner fill in the rest:

pytest tests/cases/my-case.txtar --txtar-update

--txtar-update rewrites each selected case whose assertions do not hold — its stdout, stderr, exit and expected/ sections come from the actual normalized run, cmd, stdin and fixtures/ are left untouched as input — and lists the rewritten cases in the terminal summary. A fixture the run altered without an expected/ section gains one holding its new text; one the run deleted gains nothing and the case keeps failing, since txtar cannot assert an absent file. A case that already passes is never rewritten, so a holding [..] is not flattened into the run's literal text. Review the resulting diff as you would any other change — a baseline is only as good as the reading it got. Re-running --txtar-update on an unchanged corpus must produce no diff.

Worked example

Initializes a project from the template named in the user's config.

-- fixtures/xdg/mytool/config.yaml --
template: minimal
-- cmd --
mytool init demo
-- exit --
0
-- stdout --
created demo/ from template minimal (config: {XDG}/mytool/config.yaml)
-- expected/cwd/demo/mytool.yaml --
template: minimal

The fixture lands at <sandbox>/xdg/mytool/config.yaml, which the spec's XDG_CONFIG_HOME binding makes the tool read as the user's config. The absolute path it echoes back is normalized to {XDG}, while demo is relative to the working directory and needs no token. The trailing expected/cwd/ section asserts the file the run left behind.

Changes

0.3.0

  • New optional stdin section: its content, with root tokens expanded to sandbox paths, is the standard input of the last cmd line. Every cmd line now gets an explicitly empty standard input otherwise, where 0.2.0 let it inherit the runner's.
  • stdin is a known section; a case that used it was a malformed case before.

0.2.0

  • A fixture without a matching expected/ section is now asserted unchanged after the run, where 0.1.0 did not check it. A case whose command alters or deletes such a fixture now fails; give it an expected/ section (or run --txtar-update) if the change is intended.

License

MIT. src/pytest_txtar/txtar.py is a port of golang.org/x/tools/txtar and carries the upstream BSD-3-Clause notice — see LICENSE.

Metadata

Release files for pytest-txtar 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-txtar 0.3.0
File Size Uploaded Provenance Actions
pytest_txtar-0.3.0.tar.gz 24.1 kB Without provenance Details for pytest_txtar-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-txtar 0.3.0
File Interpreter ABI Platform Actions
pytest_txtar-0.3.0-py3-none-any.whl Python 3 none any Details for pytest_txtar-0.3.0-py3-none-any.whl

Total release size: 40.5 kB

Release files / pytest_txtar-0.3.0.tar.gz

Download URL pytest_txtar-0.3.0.tar.gz
Size 24.1 kB
Tags Source
SHA-256 checksum
How to use checksums
d31f04a29e41990b21502f757d8adc11ce7c0fff0f26b7b390a63a0855fe778a
BLAKE2b-256 checksum
How to use checksums
59ec9d5934349eead76e8f8723de243612fbfc208fc6795cecb5c5c9735e7bed
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pytest_txtar-0.3.0-py3-none-any.whl

Download URL pytest_txtar-0.3.0-py3-none-any.whl
Size 16.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
56776f97610895b1b4b71a9bd8929e317f2406213e93a8416fe0eab74a5301c4
BLAKE2b-256 checksum
How to use checksums
920896cf3ba4b8fbbacfa374e6fcaae88308e3ddae4775bf0a86b3cc4f84a9c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.0 {"installer":{"name":"uv","version":"0.13.0","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pytest-txtar 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page