Exemple
pytest 9.1.1: verify pytest.raises exception assertion and ExceptionInfo contract
Échantillon vérifié pour pypi pytest 9.1.1: verify pytest.raises exception assertion and ExceptionInfo contract. Le contrat s'est exécuté sur python 3.12 …
sha256:62dd855e425a287b7dd51d1fc880c39749ca456b15af50296443bdbee9f1920e
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.raises exception assertion and ExceptionInfo contract
- Paquets
- Symboles
-
- pytest.raises
- Créé
- 2026-08-27T18:00:53Z
Contrat
- pytest.raises catches expected exception as context manager and yields ExceptionInfo with type and value
- pytest.raises matches exception message using match regex pattern
- pytest.raises accepts multiple expected exceptions as a tuple
- pytest.raises executes callable directly and returns ExceptionInfo
- pytest.raises fails with pytest.fail.Exception when no exception is raised
Fichiers
- PROMPT.md
- csx.json
- requirements.txt
- sample.py
- spec.json
- test/contract.py
Code source
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.raises exception assertion and ExceptionInfo contract
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:pypi/pytest@9.1.1
Demonstrate these symbols/APIs:
- pytest.raises
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:88b15e3c6b88e3e3a4dfda3bc6de80534de6dfd3a41a84aaf533df20730ae29c","contract":["pytest.raises catches expected exception as context manager and yields ExceptionInfo with type and value","pytest.raises matches exception message using match regex pattern","pytest.raises accepts multiple expected exceptions as a tuple","pytest.raises executes callable directly and returns ExceptionInfo","pytest.raises fails with pytest.fail.Exception when no exception is raised"],"goal":"verify pytest.raises exception assertion and ExceptionInfo contract","kind":"HOW","packages":["pkg:pypi/pytest@9.1.1"],"schemaVersion":1,"symbols":["pytest.raises"]},"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.raises"],"verifierAdapter":"python@1"}
iniconfig==2.3.0
packaging==26.3
pluggy==1.6.0
pygments==2.21.0
pytest==9.1.1
"""Sample demonstrating exception assertions and ExceptionInfo with pytest.raises."""
from typing import Any
import pytest
class ValidationError(ValueError):
"""Raised when input validation fails."""
pass
class ResourceNotFoundError(KeyError):
"""Raised when a requested resource is not found."""
pass
def parse_positive_integer(value_str: str) -> int:
"""Parse a string into a strictly positive integer."""
try:
val = int(value_str)
except (ValueError, TypeError) as exc:
raise ValidationError(f"invalid integer format: {value_str!r}") from exc
if val <= 0:
raise ValidationError(f"value must be positive, got: {val}")
return val
def get_item_by_key(store: dict, key: str) -> Any:
"""Retrieve an item from store by key."""
if key not in store:
raise ResourceNotFoundError(f"key {key!r} not found in store")
return store[key]
def divide_elements(numerator: float, denominator: float) -> float:
"""Divide numerator by denominator."""
if denominator == 0:
raise ZeroDivisionError("division by zero is not allowed")
return numerator / denominator
def demonstrate_pytest_raises() -> None:
"""Demonstrate pytest.raises exception assertions."""
# 1. Context manager catching expected exception and inspecting ExceptionInfo
with pytest.raises(ValidationError) as exc_info:
parse_positive_integer("-5")
assert exc_info.type is ValidationError
assert "value must be positive, got: -5" in str(exc_info.value)
assert exc_info.errisinstance(ValueError)
# 2. Regex matching on exception message
with pytest.raises(ValidationError, match=r"^invalid integer format: 'abc'$"):
parse_positive_integer("abc")
# 3. Tuple of expected exceptions
with pytest.raises((ValidationError, ResourceNotFoundError)):
get_item_by_key({}, "missing_item")
# 4. Callable form of pytest.raises
info = pytest.raises(ZeroDivisionError, divide_elements, 10.0, 0.0)
assert info.type is ZeroDivisionError
assert "division by zero is not allowed" in str(info.value)
if __name__ == "__main__":
demonstrate_pytest_raises()
print("pytest.raises demonstrations completed successfully.")
{
"schemaVersion": 1,
"goal": "verify pytest.raises exception assertion and ExceptionInfo contract",
"kind": "HOW",
"packages": [
"pkg:pypi/pytest@9.1.1"
],
"symbols": [
"pytest.raises"
]
}
import os
import sys
# Ensure project root is on sys.path for local module imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pytest
from sample import (
ResourceNotFoundError,
ValidationError,
divide_elements,
get_item_by_key,
parse_positive_integer,
)
def test_raises_context_manager_and_exception_info():
# Assertion 1: pytest.raises catches expected exception as context manager and yields ExceptionInfo with type and value
with pytest.raises(ValidationError) as exc_info:
parse_positive_integer("-10")
assert exc_info.type is ValidationError
assert isinstance(exc_info.value, ValidationError)
assert "value must be positive, got: -10" in str(exc_info.value)
assert exc_info.errisinstance((ValidationError, ValueError))
assert not exc_info.errisinstance(TypeError)
def test_raises_match_regex():
# Assertion 2: pytest.raises matches exception message using match regex pattern
with pytest.raises(ValidationError, match=r"^invalid integer format: 'not_a_number'$"):
parse_positive_integer("not_a_number")
with pytest.raises(ResourceNotFoundError, match=r"key 'secret' not found"):
get_item_by_key({"other": 1}, "secret")
# Verify that mismatching regex fails the assertion with AssertionError
with pytest.raises(AssertionError):
with pytest.raises(ValidationError, match=r"^completely wrong pattern$"):
parse_positive_integer("invalid")
def test_raises_multiple_exceptions_tuple():
# Assertion 3: pytest.raises accepts multiple expected exceptions as a tuple
with pytest.raises((ValidationError, ResourceNotFoundError)) as exc_info1:
parse_positive_integer("bad")
assert exc_info1.type is ValidationError
with pytest.raises((ValidationError, ResourceNotFoundError)) as exc_info2:
get_item_by_key({}, "unknown")
assert exc_info2.type is ResourceNotFoundError
def test_raises_callable_form():
# Assertion 4: pytest.raises executes callable directly and returns ExceptionInfo
exc_info = pytest.raises(ZeroDivisionError, divide_elements, 42.0, 0.0)
assert exc_info.type is ZeroDivisionError
assert "division by zero is not allowed" in str(exc_info.value)
assert exc_info.errisinstance(ZeroDivisionError)
def test_raises_fails_when_no_exception():
# Assertion 5: pytest.raises fails with pytest.fail.Exception when no exception is raised
with pytest.raises(pytest.fail.Exception, match=r"DID NOT RAISE ValueError"):
with pytest.raises(ValueError):
pass
def main():
test_raises_context_manager_and_exception_info()
test_raises_match_regex()
test_raises_multiple_exceptions_tuple()
test_raises_callable_form()
test_raises_fails_when_no_exception()
print("Contract verification passed.")
if __name__ == "__main__":
main()
Seeder d'origine
anonyme