CodeSampleX

Sample

pytest 8.4.1: pytest

Verified sample for pypi pytest 8.4.1: pytest. The contract ran on python 3.12 · linux debian/x64 · docker and passed: pytest.approx performs tolerant float…

sha256:a4d76bdab682fbe8960e4be862eb9c76ee45ead82c5d9a4d11525b7fd1044b8e

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 pip

Verification-run environments

Environment Contract Stages Run
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-10

Case

HOW
Goal
verify pytest in pkg:pypi/pytest@8.4.1
Packages
Symbols
  • pytest
Created
2026-09-10T16:41:24Z

Contract

  1. pytest.approx performs tolerant float comparisons for scalar, sequence, and dictionary structures with custom abs and rel tolerances
  2. pytest.approx supports nan comparison when nan_ok is explicitly enabled
  3. pytest.raises verifies expected exception types, matches error messages with regex, and yields ExceptionInfo
  4. pytest.raises accepts multiple expected exceptions as a tuple and fails when no exception is raised
  5. pytest.MonkeyPatch context manager safely modifies environment variables and restores them on exit
  6. pytest.main executes test sessions programmatically and returns ExitCode enum values

Files

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Download the source artifact (tar.gz)

Source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pytest in pkg:pypi/pytest@8.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pytest@8.4.1
Demonstrate these symbols/APIs:
  - pytest

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:2aa505ac7e38c845d791efef35b5a81a0484dd5408449b423ecf9b454366d026","contract":["pytest.approx performs tolerant float comparisons for scalar, sequence, and dictionary structures with custom abs and rel tolerances","pytest.approx supports nan comparison when nan_ok is explicitly enabled","pytest.raises verifies expected exception types, matches error messages with regex, and yields ExceptionInfo","pytest.raises accepts multiple expected exceptions as a tuple and fails when no exception is raised","pytest.MonkeyPatch context manager safely modifies environment variables and restores them on exit","pytest.main executes test sessions programmatically and returns ExitCode enum values"],"goal":"verify pytest in pkg:pypi/pytest@8.4.1","kind":"HOW","packages":["pkg:pypi/pytest@8.4.1"],"schemaVersion":1,"symbols":["pytest"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pytest@8.4.1"],"schemaVersion":1,"subject":"pkg:pypi/pytest@8.4.1","symbols":["pytest"],"verifierAdapter":"python@1"}
requirements.txt
iniconfig==2.3.0
packaging==26.3
pluggy==1.6.0
pygments==2.21.0
pytest==8.4.1
sample.py
"""Sample demonstrating core pytest APIs including approx, raises, MonkeyPatch, and main."""

import os
from typing import Any, Dict, List
import pytest


def calculate_metrics(values: List[float]) -> Dict[str, float]:
    """Calculate mean and variance for a list of numbers."""
    if not values:
        raise ValueError("cannot calculate metrics for an empty list")
    mean = sum(values) / len(values)
    variance = sum((x - mean) ** 2 for x in values) / len(values)
    return {"mean": mean, "variance": variance}


def compare_floats(a: float, b: float, rel: float = 1e-6, abs_tol: float = 1e-12) -> bool:
    """Compare two floating point numbers using pytest.approx."""
    return a == pytest.approx(b, rel=rel, abs=abs_tol)


def compare_dict_metrics(actual: Dict[str, float], expected: Dict[str, float]) -> bool:
    """Compare dictionary of float metrics using pytest.approx."""
    return actual == pytest.approx(expected)


def read_env_setting(key: str, default: str = "") -> str:
    """Retrieve environment configuration value."""
    return os.environ.get(key, default)


def execute_test_target(test_target: str) -> pytest.ExitCode:
    """Run a test file programmatically using pytest.main."""
    return pytest.main(["-q", "--no-header", test_target])
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pytest in pkg:pypi/pytest@8.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pytest@8.4.1"
  ],
  "symbols": [
    "pytest"
  ]
}
test/contract.py
import os
import sys
import tempfile

# Ensure project root is on sys.path for local imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pytest
from sample import (
    calculate_metrics,
    compare_dict_metrics,
    compare_floats,
    execute_test_target,
    read_env_setting,
)


def test_approx_scalar_sequence_dict():
    # Assertion 1: pytest.approx performs tolerant float comparisons for scalar, sequence, and dictionary structures with custom abs and rel tolerances
    assert compare_floats(0.1 + 0.2, 0.3, rel=1e-6)
    assert [1.0001, 2.0002] == pytest.approx([1.0, 2.0], abs=1e-3)

    metrics = calculate_metrics([1.0, 2.0, 3.0, 4.0, 5.0])
    assert compare_dict_metrics(metrics, {"mean": 3.0, "variance": 2.0})


def test_approx_nan_support():
    # Assertion 2: pytest.approx supports nan comparison when nan_ok is explicitly enabled
    nan_val = float("nan")
    assert nan_val != pytest.approx(nan_val)
    assert nan_val == pytest.approx(nan_val, nan_ok=True)


def test_raises_and_exception_info():
    # Assertion 3: pytest.raises verifies expected exception types, matches error messages with regex, and yields ExceptionInfo
    with pytest.raises(ValueError, match=r"^cannot calculate metrics for an empty list$") as exc_info:
        calculate_metrics([])

    assert exc_info.type is ValueError
    assert exc_info.errisinstance(ValueError)
    assert "empty list" in str(exc_info.value)


def test_raises_multiple_exceptions_and_no_raise_failure():
    # Assertion 4: pytest.raises accepts multiple expected exceptions as a tuple and fails when no exception is raised
    with pytest.raises((KeyError, ValueError)):
        calculate_metrics([])

    with pytest.raises(pytest.fail.Exception, match=r"DID NOT RAISE"):
        with pytest.raises(ValueError):
            pass


def test_monkeypatch_context():
    # Assertion 5: pytest.MonkeyPatch context manager safely modifies environment variables and restores them on exit
    test_key = "CSX_TEST_CONFIG_ENV"
    assert read_env_setting(test_key, "default") == "default"

    with pytest.MonkeyPatch.context() as mp:
        mp.setenv(test_key, "active_value")
        assert read_env_setting(test_key, "default") == "active_value"

    assert read_env_setting(test_key, "default") == "default"


def test_main_exit_code():
    # Assertion 6: pytest.main executes test sessions programmatically and returns ExitCode enum values
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
        f.write("def test_ok(): assert 1 + 1 == 2\n")
        temp_file = f.name

    try:
        exit_code = execute_test_target(temp_file)
        assert exit_code == pytest.ExitCode.OK
        assert isinstance(exit_code, pytest.ExitCode)
    finally:
        if os.path.exists(temp_file):
            os.remove(temp_file)


def main():
    test_approx_scalar_sequence_dict()
    test_approx_nan_support()
    test_raises_and_exception_info()
    test_raises_multiple_exceptions_and_no_raise_failure()
    test_monkeypatch_context()
    test_main_exit_code()
    print("Contract verification passed.")


if __name__ == "__main__":
    main()

Origin Seeder

anonymous