Пример
pytest 8.4.1
Проверенный пример — pypi pytest 8.4.1. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден: pytest.approx performs tolerant float…
sha256:d8485a09806d75136071227e892df509d248de3a0869efe5b576e9ed1c788ea4
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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()
Исходный сидер
аноним