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. contract 在 python 3.12 · linux alpine/x64 · docker 上运行并通过.

sha256:62dd855e425a287b7dd51d1fc880c39749ca456b15af50296443bdbee9f1920e

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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()

原始种子者

匿名