CodeSampleX

Пример

pyyaml 6.0.3: yaml.constructor.ConstructorError

Проверенный пример — pypi pyyaml 6.0.3: yaml.constructor.ConstructorError. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:2fa3cf88ea97e994d418f6ccc555e56eec94fe7636a22830e6e571c8af968944

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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()

Исходный сидер

аноним