CodeSampleX

サンプル

pytest 8.4.1

検証済みサンプル — pypi pytest 8.4.1. python 3.12 · linux debian/x64 · docker で contract を実行し、成功しました: pytest.approx performs tolerant float comparisons for scalars…

sha256:d8485a09806d75136071227e892df509d248de3a0869efe5b576e9ed1c788ea4

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 pip

検証実行環境

環境 コントラクト ステージ 実行日
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

ケース

HOW
ゴール
verify pkg:pypi/pytest@8.4.1
パッケージ
作成日
2026-09-10T16:06:37Z

コントラクト

  1. pytest.approx performs tolerant float comparisons for scalars, sequences, and mappings with relative and absolute tolerances
  2. pytest.raises captures expected exception types, validates error message regex, and exposes ExceptionInfo
  3. pytest.warns captures expected warnings and verifies warning categories and message patterns
  4. pytest.MonkeyPatch safely modifies environment variables and restores them on exit
  5. pytest.main executes test targets 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 pkg:pypi/pytest@8.4.1
Kind: HOW

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

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:da10932a5197d00b91c3ac4f6a2f2338855f3b1ac00b6b231bde3c86e6d16e89","contract":["pytest.approx performs tolerant float comparisons for scalars, sequences, and mappings with relative and absolute tolerances","pytest.raises captures expected exception types, validates error message regex, and exposes ExceptionInfo","pytest.warns captures expected warnings and verifies warning categories and message patterns","pytest.MonkeyPatch safely modifies environment variables and restores them on exit","pytest.main executes test targets programmatically and returns ExitCode enum values"],"goal":"verify pkg:pypi/pytest@8.4.1","kind":"HOW","packages":["pkg:pypi/pytest@8.4.1"],"schemaVersion":1},"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","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 module demonstrating pytest 8.4.1 usage and helpers."""

import os
from typing import Dict
import pytest


def compare_tolerances(val: float, target: float, rel: float = 1e-6, abs_tol: float = 1e-12) -> bool:
    """Compare two floats within given relative or absolute tolerance."""
    return val == pytest.approx(target, rel=rel, abs=abs_tol)


def compare_mappings(actual: Dict[str, float], expected: Dict[str, float]) -> bool:
    """Compare dictionaries containing float values within default tolerance."""
    return actual == pytest.approx(expected)


def divide_positive(a: float, b: float) -> float:
    """Divide a by b with input validation."""
    if b == 0:
        raise ZeroDivisionError("division by zero is undefined")
    if a < 0 or b < 0:
        raise ValueError("operands must be non-negative")
    return a / b


def read_config_variable(name: str, fallback: str = "") -> str:
    """Read an environment variable with a default fallback."""
    return os.environ.get(name, fallback)


def run_inline_test(test_file_path: str) -> pytest.ExitCode:
    """Run an isolated test module programmatically."""
    return pytest.main(["-q", "--no-header", test_file_path])
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/pytest@8.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pytest@8.4.1"
  ]
}
test/contract.py
import os
import sys
import tempfile
import warnings

# Add project root to sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pytest
from sample import (
    compare_mappings,
    compare_tolerances,
    divide_positive,
    read_config_variable,
    run_inline_test,
)


def test_approx_comparisons():
    # Assertion: pytest.approx performs tolerant float comparisons for scalars, sequences, and mappings with relative and absolute tolerances
    assert compare_tolerances(0.1 + 0.2, 0.3, rel=1e-6)
    assert [10.001, 20.002] == pytest.approx([10.0, 20.0], abs=1e-2)
    assert compare_mappings({"rate": 0.1 + 0.2}, {"rate": 0.3})


def test_raises_validation():
    # Assertion: pytest.raises captures expected exception types, validates error message regex, and exposes ExceptionInfo
    with pytest.raises(ZeroDivisionError, match=r"^division by zero is undefined$") as exc_info:
        divide_positive(10.0, 0.0)

    assert exc_info.type is ZeroDivisionError
    assert "division by zero" in str(exc_info.value)

    with pytest.raises(ValueError, match=r"operands must be non-negative"):
        divide_positive(-1.0, 2.0)


def test_warns_validation():
    # Assertion: pytest.warns captures expected warnings and verifies warning categories and message patterns
    with pytest.warns(UserWarning, match=r"sample warning message") as warn_records:
        warnings.warn("sample warning message", UserWarning)

    assert len(warn_records) == 1
    assert warn_records[0].category is UserWarning
    assert "sample warning message" in str(warn_records[0].message)


def test_monkeypatch_environment():
    # Assertion: pytest.MonkeyPatch safely modifies environment variables and restores them on exit
    test_var = "TEST_SAMPLE_CONFIG_KEY"
    assert read_config_variable(test_var, "default") == "default"

    with pytest.MonkeyPatch.context() as mp:
        mp.setenv(test_var, "configured_value")
        assert read_config_variable(test_var, "default") == "configured_value"

    assert read_config_variable(test_var, "default") == "default"


def test_main_execution():
    # Assertion: pytest.main executes test targets programmatically and returns ExitCode enum values
    with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as temp_script:
        temp_script.write("def test_dummy_ok():\n    assert 42 == 42\n")
        temp_path = temp_script.name

    try:
        code = run_inline_test(temp_path)
        assert code == pytest.ExitCode.OK
        assert isinstance(code, pytest.ExitCode)
    finally:
        if os.path.exists(temp_path):
            os.remove(temp_path)


def main():
    test_approx_comparisons()
    test_raises_validation()
    test_warns_validation()
    test_monkeypatch_environment()
    test_main_execution()
    print("Contract verification passed.")


if __name__ == "__main__":
    main()

オリジンシーダー

匿名