CodeSampleX

Пример

et-xmlfile 2.0.0: et_xmlfile.xmlfile

Проверенный пример — pypi et-xmlfile 2.0.0: et_xmlfile.xmlfile. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:a652e679b9adbcfb7b561b24a4b265a2ca5f585b1b22bc00c787544c84ce30b8

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

Кейс

HOW
Цель
verify pkg:pypi/et-xmlfile@2.0.0
Пакеты
Символы
  • et_xmlfile.xmlfile
Создан
2026-10-14T10:13:16Z

Контракт

  1. et_xmlfile.xmlfile streams nested XML elements, attributes, text strings, and ElementTree.Element instances with automatic CDATA escaping
  2. et_xmlfile.xmlfile serializes default and prefixed XML namespace mappings passed via nsmap when tags are qualified in Clark notation, and raises ValueError for unqualified tags under a default namespace
  3. et_xmlfile.xmlfile respects the close parameter on the underlying stream and raises LxmlSyntaxError when writing plain strings outside an active element

Файлы

  • 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 pkg:pypi/et-xmlfile@2.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/et-xmlfile@2.0.0

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:388d6438550b5e0649bed25a1f0416e847203cb9c6a381332780d2e41e28925d","contract":["et_xmlfile.xmlfile streams nested XML elements, attributes, text strings, and ElementTree.Element instances with automatic CDATA escaping","et_xmlfile.xmlfile serializes default and prefixed XML namespace mappings passed via nsmap when tags are qualified in Clark notation, and raises ValueError for unqualified tags under a default namespace","et_xmlfile.xmlfile respects the close parameter on the underlying stream and raises LxmlSyntaxError when writing plain strings outside an active element"],"goal":"verify pkg:pypi/et-xmlfile@2.0.0","kind":"HOW","packages":["pkg:pypi/et-xmlfile@2.0.0"],"schemaVersion":1,"symbols":["et_xmlfile.xmlfile"]},"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/et-xmlfile@2.0.0"],"schemaVersion":1,"subject":"pkg:pypi/et-xmlfile@2.0.0","symbols":["et_xmlfile.xmlfile"],"verifierAdapter":"python@1"}
requirements.txt
et-xmlfile==2.0.0
sample.py
"""Incremental XML generation using et_xmlfile.xmlfile."""

import io
from typing import Dict, List, Optional
from xml.etree.ElementTree import Element

from et_xmlfile import xmlfile


def _qualify(tag: str, ns_uri: Optional[str]) -> str:
    """Return Clark-notation qualified tag if ns_uri is provided."""
    if ns_uri:
        return f"{{{ns_uri}}}{tag}"
    return tag


def generate_catalog_xml(
    items: List[Dict[str, str]],
    default_ns: Optional[str] = None,
    custom_nsmap: Optional[Dict[Optional[str], str]] = None,
) -> bytes:
    """Stream a structured XML catalog document into a UTF-8 byte buffer using xmlfile."""
    buffer = io.BytesIO()
    nsmap: Optional[Dict[Optional[str], str]] = None
    if default_ns or custom_nsmap:
        nsmap = {}
        if default_ns:
            nsmap[None] = default_ns
        if custom_nsmap:
            nsmap.update(custom_nsmap)

    with xmlfile(buffer, encoding="utf-8") as xf:
        with xf.element(_qualify("catalog", default_ns), attrib={"version": "1.0"}, nsmap=nsmap):
            for entry in items:
                with xf.element(_qualify("item", default_ns), attrib={"id": entry["id"]}):
                    name_el = Element(_qualify("name", default_ns))
                    name_el.text = entry["name"]
                    xf.write(name_el)

                    with xf.element(_qualify("description", default_ns)):
                        xf.write(entry["description"])

    return buffer.getvalue()


def write_xml_and_close(
    stream: io.BytesIO,
    root_tag: str,
    text_content: str,
    close: bool = True,
) -> None:
    """Write a single-element XML payload to a stream and optionally close it on exit."""
    with xmlfile(stream, encoding="utf-8", close=close) as xf:
        with xf.element(root_tag):
            xf.write(text_content)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/et-xmlfile@2.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/et-xmlfile@2.0.0"
  ]
}
test/contract.py
"""Contract verification test for pkg:pypi/et-xmlfile@2.0.0."""

import io
import os
import sys
import xml.etree.ElementTree as ET

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from et_xmlfile import xmlfile
from et_xmlfile.xmlfile import LxmlSyntaxError
import sample


def test_incremental_nested_elements_and_escaping() -> None:
    """Assertion 1: et_xmlfile.xmlfile streams nested XML elements, attributes, text strings, and ElementTree.Element instances with automatic CDATA escaping."""
    items = [
        {
            "id": "A1",
            "name": "Widget & Co",
            "description": "Fast <10ms> & reliable",
        },
        {
            "id": "B2",
            "name": "Standard Bolt",
            "description": "Plain text",
        },
    ]
    raw_xml = sample.generate_catalog_xml(items)
    xml_text = raw_xml.decode("utf-8")

    # Verify escaped entities in raw output
    assert "Widget &amp; Co" in xml_text
    assert "Fast &lt;10ms&gt; &amp; reliable" in xml_text

    # Parse back with ElementTree to verify structure
    root = ET.fromstring(raw_xml)
    assert root.tag == "catalog"
    assert root.attrib == {"version": "1.0"}

    children = list(root)
    assert len(children) == 2
    assert children[0].tag == "item"
    assert children[0].attrib == {"id": "A1"}
    assert children[0].findtext("name") == "Widget & Co"
    assert children[0].findtext("description") == "Fast <10ms> & reliable"

    assert children[1].tag == "item"
    assert children[1].attrib == {"id": "B2"}
    assert children[1].findtext("name") == "Standard Bolt"
    assert children[1].findtext("description") == "Plain text"


def test_namespace_mapping_support() -> None:
    """Assertion 2: et_xmlfile.xmlfile serializes default and prefixed XML namespace mappings passed via nsmap when tags are qualified in Clark notation, and raises ValueError for unqualified tags under a default namespace."""
    items = [
        {
            "id": "N1",
            "name": "Namespaced Item",
            "description": "With nsmap",
        }
    ]
    raw_xml = sample.generate_catalog_xml(
        items,
        default_ns="http://example.com/ns/default",
        custom_nsmap={"ext": "http://example.com/ns/ext"},
    )
    xml_text = raw_xml.decode("utf-8")
    assert 'xmlns="http://example.com/ns/default"' in xml_text
    assert 'xmlns:ext="http://example.com/ns/ext"' in xml_text

    # Verify writing a prefixed element inside nsmap scope
    buf = io.BytesIO()
    with xmlfile(buf, encoding="utf-8") as xf:
        with xf.element(
            "{http://example.com/ns/default}root",
            nsmap={None: "http://example.com/ns/default", "p": "http://example.com/ns/p"},
        ):
            with xf.element("{http://example.com/ns/p}child"):
                xf.write("value")

    out = buf.getvalue().decode("utf-8")
    assert "<root" in out
    assert "<p:child>value</p:child>" in out

    # Verify that non-qualified tag with default namespace raises ValueError
    err_buf = io.BytesIO()
    raised_val_err = False
    try:
        with xmlfile(err_buf, encoding="utf-8") as xf:
            with xf.element("unqualified", nsmap={None: "http://example.com/ns/default"}):
                pass
    except ValueError:
        raised_val_err = True
    assert raised_val_err, "Expected ValueError when using unqualified tag with default namespace"


def test_close_parameter_and_syntax_validation() -> None:
    """Assertion 3: et_xmlfile.xmlfile respects the close parameter on the underlying stream and raises LxmlSyntaxError when writing plain strings outside an active element."""
    # close=False keeps stream open
    open_stream = io.BytesIO()
    sample.write_xml_and_close(open_stream, "note", "keep open", close=False)
    assert not open_stream.closed
    assert open_stream.getvalue() == b"<note>keep open</note>"

    # close=True closes stream upon exit
    closed_stream = io.BytesIO()
    sample.write_xml_and_close(closed_stream, "note", "close me", close=True)
    assert closed_stream.closed

    # Writing plain string outside of any element raises LxmlSyntaxError
    err_stream = io.BytesIO()
    raised = False
    try:
        with xmlfile(err_stream, encoding="utf-8") as xf:
            xf.write("orphan text outside root")
    except LxmlSyntaxError:
        raised = True
    assert raised, "Expected LxmlSyntaxError when writing string outside root element"


def main() -> None:
    test_incremental_nested_elements_and_escaping()
    test_namespace_mapping_support()
    test_close_parameter_and_syntax_validation()
    print("All et-xmlfile contract assertions passed.")


if __name__ == "__main__":
    main()

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

аноним