CodeSampleX

샘플

pytest 9.1.1: pytest

검증된 샘플 — pypi pytest 9.1.1: pytest. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: pytest.approx performs tolerant float comparisons for…

sha256:6e0fa108cad419e46493b64950e03b6aeb126636eb859f7b5c0740c7585838e4

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 pip

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify pytest in pkg:pypi/pytest@9.1.1
패키지
심벌
  • pytest
생성일
2026-08-27T18:04:27Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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()

오리진 시더

익명