CodeSampleX

Exemple

pytest 9.1.1: pytest

Échantillon vérifié pour pypi pytest 9.1.1: pytest. Le contrat s'est exécuté sur python 3.12 · linux alpine/x64 · docker et a réussi.

sha256:6e0fa108cad419e46493b64950e03b6aeb126636eb859f7b5c0740c7585838e4

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 pip

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-27

Cas

HOW
Objectif
verify pytest in pkg:pypi/pytest@9.1.1
Paquets
Symboles
  • pytest
Créé
2026-08-27T18:04:27Z

Contrat

  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

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code 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@9.1.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pytest@9.1.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:b2ef20775aa5cbeefbd156379a85f1c828d3468157abc53469ab6bd361b3dee9","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@9.1.1","kind":"HOW","packages":["pkg:pypi/pytest@9.1.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@9.1.1"],"schemaVersion":1,"subject":"pkg:pypi/pytest@9.1.1","symbols":["pytest"],"verifierAdapter":"python@1"}
requirements.txt
iniconfig==2.3.0
packaging==26.3
pluggy==1.6.0
pygments==2.21.0
pytest==9.1.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_statistics(values: List[float]) -> Dict[str, float]:
    """Calculate mean and variance for a list of numbers."""
    if not values:
        raise ValueError("cannot calculate statistics 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 evaluate_float_comparison(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 evaluate_dict_comparison(actual: Dict[str, float], expected: Dict[str, float]) -> bool:
    """Compare dictionary of floats using pytest.approx."""
    return actual == pytest.approx(expected)


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


def run_minimal_test_suite(test_target: str) -> pytest.ExitCode:
    """Run a test target programmatically using pytest.main."""
    return pytest.main(["-q", "--no-header", test_target])
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pytest in pkg:pypi/pytest@9.1.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pytest@9.1.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_statistics,
    evaluate_dict_comparison,
    evaluate_float_comparison,
    get_environment_config,
    run_minimal_test_suite,
)


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 evaluate_float_comparison(0.1 + 0.2, 0.3, rel=1e-6)
    assert [1.0001, 2.0002] == pytest.approx([1.0, 2.0], abs=1e-3)

    stats = calculate_statistics([1.0, 2.0, 3.0, 4.0, 5.0])
    assert evaluate_dict_comparison(stats, {"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")
    # By default, nan != nan even with approx
    assert nan_val != pytest.approx(nan_val)
    # When nan_ok=True, nan comparisons evaluate to True
    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 statistics for an empty list$") as exc_info:
        calculate_statistics([])

    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_statistics([])

    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 = "SAMPLE_CONFIG_VAR_TEST"
    assert get_environment_config(test_key, "default") == "default"

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

    assert get_environment_config(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_sanity(): assert 1 + 1 == 2\n")
        temp_file = f.name

    try:
        exit_code = run_minimal_test_suite(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()

Seeder d'origine

anonyme