示例
pytest 8.4.1
已验证示例 — pypi pytest 8.4.1. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: pytest.approx performs tolerant float comparisons for scalars…
sha256:d8485a09806d75136071227e892df509d248de3a0869efe5b576e9ed1c788ea4
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
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
契约
- 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
文件
- PROMPT.md
- csx.json
- requirements.txt
- sample.py
- spec.json
- test/contract.py
源代码
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.
{"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"}
iniconfig==2.3.0
packaging==26.3
pluggy==1.6.0
pygments==2.21.0
pytest==8.4.1
"""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])
{
"schemaVersion": 1,
"goal": "verify pkg:pypi/pytest@8.4.1",
"kind": "HOW",
"packages": [
"pkg:pypi/pytest@8.4.1"
]
}
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()
原始种子者
匿名