CodeSampleX

示例

pyyaml 6.0.3: yaml.constructor.ConstructorError

已验证示例 — pypi pyyaml 6.0.3: yaml.constructor.ConstructorError. contract 在 python 3.12 · linux debian/x64 · docker 上运行并通过: assert ConstructorError inherits…

sha256:2fa3cf88ea97e994d418f6ccc555e56eec94fe7636a22830e6e571c8af968944

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-05

案例

HOW
目标
verify yaml.constructor.ConstructorError in pkg:pypi/pyyaml@6.0.3
包
符号
  • yaml.constructor.ConstructorError
创建时间
2026-09-05T18:29:48Z

契约

  1. assert ConstructorError inherits from MarkedYAMLError and YAMLError and supports custom instantiation
  2. assert safe loading unhashable mapping keys raises ConstructorError with unhashable key problem message
  3. assert safe loading unknown tag without registered constructor raises ConstructorError
  4. assert safe loading malformed base64 binary scalar raises ConstructorError

文件

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • 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 yaml.constructor.ConstructorError in pkg:pypi/pyyaml@6.0.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pyyaml@6.0.3
Demonstrate these symbols/APIs:
  - yaml.constructor.ConstructorError

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:aef821b22f028152d08f372e2a4ce7efdb166985439c7cae8f4a8b5c28308c0a","contract":["assert ConstructorError inherits from MarkedYAMLError and YAMLError and supports custom instantiation","assert safe loading unhashable mapping keys raises ConstructorError with unhashable key problem message","assert safe loading unknown tag without registered constructor raises ConstructorError","assert safe loading malformed base64 binary scalar raises ConstructorError"],"goal":"verify yaml.constructor.ConstructorError in pkg:pypi/pyyaml@6.0.3","kind":"HOW","packages":["pkg:pypi/pyyaml@6.0.3"],"schemaVersion":1,"symbols":["yaml.constructor.ConstructorError"]},"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/pyyaml@6.0.3"],"schemaVersion":1,"subject":"pkg:pypi/pyyaml@6.0.3","symbols":["yaml.constructor.ConstructorError"],"verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-pyyaml-constructor-error"
version = "0.1.0"
dependencies = [
    "pyyaml==6.0.3",
]
requirements.txt
pyyaml==6.0.3
sample.py
"""Sample demonstrating yaml.constructor.ConstructorError handling and usage in PyYAML."""

from typing import Any, Optional, Tuple
import yaml
from yaml.constructor import ConstructorError
from yaml.error import MarkedYAMLError, YAMLError


def parse_yaml_safely(yaml_str: str) -> Tuple[bool, Any, Optional[ConstructorError]]:
    """Attempt to safely load a YAML string, catching ConstructorError if present."""
    try:
        data = yaml.safe_load(yaml_str)
        return True, data, None
    except ConstructorError as exc:
        return False, None, exc


def expect_unhashable_key_error(yaml_str: str) -> ConstructorError:
    """Load YAML that has an unhashable mapping key, asserting ConstructorError is raised."""
    try:
        yaml.safe_load(yaml_str)
    except ConstructorError as exc:
        return exc
    raise AssertionError("Expected ConstructorError was not raised")


def expect_unknown_tag_error(yaml_str: str) -> ConstructorError:
    """Load YAML with an undefined tag, asserting ConstructorError is raised."""
    try:
        yaml.safe_load(yaml_str)
    except ConstructorError as exc:
        return exc
    raise AssertionError("Expected ConstructorError was not raised")


def expect_invalid_binary_error(yaml_str: str) -> ConstructorError:
    """Load YAML with malformed base64 binary scalar, asserting ConstructorError is raised."""
    try:
        yaml.safe_load(yaml_str)
    except ConstructorError as exc:
        return exc
    raise AssertionError("Expected ConstructorError was not raised")


def build_constructor_error(
    context: Optional[str] = None,
    problem: Optional[str] = None,
    note: Optional[str] = None,
) -> ConstructorError:
    """Construct an explicit ConstructorError instance with contextual information."""
    return ConstructorError(
        context=context,
        context_mark=None,
        problem=problem,
        problem_mark=None,
        note=note,
    )
spec.json
{
  "schemaVersion": 1,
  "goal": "verify yaml.constructor.ConstructorError in pkg:pypi/pyyaml@6.0.3",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pyyaml@6.0.3"
  ],
  "symbols": [
    "yaml.constructor.ConstructorError"
  ]
}
test/contract.py
"""Contract verification test for yaml.constructor.ConstructorError in pkg:pypi/pyyaml@6.0.3."""

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 yaml
from yaml.constructor import ConstructorError
from yaml.error import MarkedYAMLError, YAMLError
from sample import (
    parse_yaml_safely,
    expect_unhashable_key_error,
    expect_unknown_tag_error,
    expect_invalid_binary_error,
    build_constructor_error,
)


def test_constructor_error_hierarchy_and_instantiation() -> None:
    """assert ConstructorError inherits from MarkedYAMLError and YAMLError and supports custom instantiation"""
    assert issubclass(ConstructorError, MarkedYAMLError)
    assert issubclass(ConstructorError, YAMLError)

    err = build_constructor_error(
        context="while constructing custom mapping",
        problem="duplicate key encountered",
        note="keys must be unique in this schema",
    )
    assert isinstance(err, ConstructorError)
    assert isinstance(err, MarkedYAMLError)
    assert isinstance(err, YAMLError)
    assert err.context == "while constructing custom mapping"
    assert err.problem == "duplicate key encountered"
    assert err.note == "keys must be unique in this schema"

    err_str = str(err)
    assert "while constructing custom mapping" in err_str
    assert "duplicate key encountered" in err_str
    assert "keys must be unique in this schema" in err_str


def test_unhashable_key_raises_constructor_error() -> None:
    """assert safe loading unhashable mapping keys raises ConstructorError with unhashable key problem message"""
    unhashable_yaml = "{ [1, 2]: sample_value }"
    success, data, err = parse_yaml_safely(unhashable_yaml)
    assert success is False
    assert data is None
    assert isinstance(err, ConstructorError)

    raised = expect_unhashable_key_error(unhashable_yaml)
    assert raised.problem == "found unhashable key"
    assert raised.context == "while constructing a mapping"
    assert "found unhashable key" in str(raised)


def test_unknown_tag_raises_constructor_error() -> None:
    """assert safe loading unknown tag without registered constructor raises ConstructorError"""
    unknown_tag_yaml = "!customUndefinedTag test_value"
    success, data, err = parse_yaml_safely(unknown_tag_yaml)
    assert success is False
    assert data is None
    assert isinstance(err, ConstructorError)

    raised = expect_unknown_tag_error(unknown_tag_yaml)
    assert "could not determine a constructor for the tag" in str(raised)
    assert "!customUndefinedTag" in str(raised)


def test_invalid_binary_scalar_raises_constructor_error() -> None:
    """assert safe loading malformed base64 binary scalar raises ConstructorError"""
    invalid_binary_yaml = "!!binary 'not_valid_base64!?*#'"
    success, data, err = parse_yaml_safely(invalid_binary_yaml)
    assert success is False
    assert data is None
    assert isinstance(err, ConstructorError)

    raised = expect_invalid_binary_error(invalid_binary_yaml)
    assert "failed to decode base64 data" in str(raised)


def main() -> None:
    test_constructor_error_hierarchy_and_instantiation()
    test_unhashable_key_raises_constructor_error()
    test_unknown_tag_raises_constructor_error()
    test_invalid_binary_scalar_raises_constructor_error()
    print("All contract assertions passed.")


if __name__ == "__main__":
    main()

原始种子者

匿名