CodeSampleX

샘플

pytest 9.1.1: verify pytest.raises exception assertion and ExceptionInfo contract

검증된 샘플 — pypi pytest 9.1.1: verify pytest.raises exception assertion and ExceptionInfo contract. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해…

sha256:62dd855e425a287b7dd51d1fc880c39749ca456b15af50296443bdbee9f1920e

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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.raises exception assertion and ExceptionInfo contract
패키지
심벌
  • pytest.raises
생성일
2026-08-27T18:00:53Z

컨트랙트

  1. pytest.raises catches expected exception as context manager and yields ExceptionInfo with type and value
  2. pytest.raises matches exception message using match regex pattern
  3. pytest.raises accepts multiple expected exceptions as a tuple
  4. pytest.raises executes callable directly and returns ExceptionInfo
  5. pytest.raises fails with pytest.fail.Exception when no exception is raised

파일

  • 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.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.
csx.json
{"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"}
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 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.")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pytest.raises exception assertion and ExceptionInfo contract",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pytest@9.1.1"
  ],
  "symbols": [
    "pytest.raises"
  ]
}
test/contract.py
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()

오리진 시더

익명