CodeSampleX

샘플

referencing 0.37.0: Registry

검증된 샘플 — pypi referencing 0.37.0: Registry. python 3.12 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: referencing.Registry creates an immutable schema…

sha256:3b3ec7a4421a3ef461bdaf10d6d8c8b88da8916d19246872b32af367679d11da

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

케이스

HOW
목표
verify referencing.Registry in pkg:pypi/referencing@0.37.0
패키지
심벌
  • referencing.Registry
생성일
2026-09-02T13:25:31Z

컨트랙트

  1. referencing.Registry creates an immutable schema registry and registers resources with with_resource and with_resources
  2. referencing.Registry.resolver creates a resolver that looks up registered schemas and nested JSON pointer fragments
  3. referencing.Registry.crawl recursively indexes internal schema anchors and enables anchor URI resolution
  4. referencing.Registry.combine merges multiple schema registries into a unified registry mapping
  5. referencing.Registry raises NoSuchResource when querying contents of an unregistered URI
  6. referencing.Registry.resolver raises Unresolvable when looking up an unregistered URI

파일

  • 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 referencing.Registry in pkg:pypi/referencing@0.37.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/referencing@0.37.0
Demonstrate these symbols/APIs:
  - referencing.Registry

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:20d25b522804eed1d6cf04465b134c65287fd4a3376c0b27f6b9d48c3389f6ba","contract":["referencing.Registry creates an immutable schema registry and registers resources with with_resource and with_resources","referencing.Registry.resolver creates a resolver that looks up registered schemas and nested JSON pointer fragments","referencing.Registry.crawl recursively indexes internal schema anchors and enables anchor URI resolution","referencing.Registry.combine merges multiple schema registries into a unified registry mapping","referencing.Registry raises NoSuchResource when querying contents of an unregistered URI","referencing.Registry.resolver raises Unresolvable when looking up an unregistered URI"],"goal":"verify referencing.Registry in pkg:pypi/referencing@0.37.0","kind":"HOW","packages":["pkg:pypi/referencing@0.37.0"],"schemaVersion":1,"symbols":["referencing.Registry"]},"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/referencing@0.37.0"],"schemaVersion":1,"subject":"pkg:pypi/referencing@0.37.0","symbols":["referencing.Registry"],"verifierAdapter":"python@1"}
requirements.txt
referencing==0.37.0
sample.py
"""Sample demonstrating referencing.Registry usage for JSON Schema and resource management."""

from typing import Any, Dict, Iterable, Tuple
import referencing
from referencing import Registry, Resource
from referencing.exceptions import NoSuchResource, Unresolvable


def create_registry_with_resource(uri: str, contents: Dict[str, Any]) -> Registry:
    """Create a new Registry populated with a single JSON schema resource."""
    resource = Resource.from_contents(contents)
    return Registry().with_resource(uri, resource)


def create_registry_with_resources(items: Iterable[Tuple[str, Dict[str, Any]]]) -> Registry:
    """Create a new Registry populated with multiple JSON schema resources."""
    pairs = [(uri, Resource.from_contents(contents)) for uri, contents in items]
    return Registry().with_resources(pairs)


def resolve_uri(registry: Registry, uri: str) -> Dict[str, Any]:
    """Resolve a URI or URI fragment against a Registry and return its contents."""
    resolver = registry.resolver()
    resolved = resolver.lookup(uri)
    return resolved.contents


def crawl_registry_anchors(registry: Registry) -> Registry:
    """Crawl a Registry to discover and index internal anchors and IDs."""
    return registry.crawl()


def merge_registries(registry_a: Registry, registry_b: Registry) -> Registry:
    """Combine two schema registries into a single unified registry."""
    return registry_a.combine(registry_b)
spec.json
{
  "schemaVersion": 1,
  "goal": "verify referencing.Registry in pkg:pypi/referencing@0.37.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/referencing@0.37.0"
  ],
  "symbols": [
    "referencing.Registry"
  ]
}
test/contract.py
"""Contract verification test for referencing.Registry."""

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__))))

from referencing import Registry, Resource
from referencing.exceptions import NoSuchResource, Unresolvable
from sample import (
    crawl_registry_anchors,
    create_registry_with_resource,
    create_registry_with_resources,
    merge_registries,
    resolve_uri,
)


def test_registry_registration_and_contents() -> None:
    """Assertion 1: referencing.Registry creates an immutable schema registry and registers resources with with_resource and with_resources."""
    schema1 = {
        "$id": "https://example.com/schemas/user",
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "properties": {
            "id": {"type": "integer"},
            "name": {"type": "string"},
        },
    }
    schema2 = {
        "$id": "https://example.com/schemas/product",
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "properties": {
            "sku": {"type": "string"},
            "price": {"type": "number"},
        },
    }

    # Test single resource registration
    reg1 = create_registry_with_resource("https://example.com/schemas/user", schema1)
    assert isinstance(reg1, Registry), "Result must be an instance of Registry"
    assert "https://example.com/schemas/user" in reg1, "Registered URI must be present in registry"
    assert len(reg1) == 1, f"Expected registry length 1, got {len(reg1)}"
    assert reg1.contents("https://example.com/schemas/user") == schema1, "Schema contents mismatch"

    # Test multiple resources registration
    reg2 = create_registry_with_resources([
        ("https://example.com/schemas/user", schema1),
        ("https://example.com/schemas/product", schema2),
    ])
    assert len(reg2) == 2, f"Expected registry length 2, got {len(reg2)}"
    assert "https://example.com/schemas/user" in reg2
    assert "https://example.com/schemas/product" in reg2
    assert reg2.contents("https://example.com/schemas/product") == schema2


def test_resolver_lookup_and_pointer_resolution() -> None:
    """Assertion 2: referencing.Registry.resolver creates a resolver that looks up registered schemas and nested JSON pointer fragments."""
    schema = {
        "$id": "https://example.com/schemas/profile",
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "properties": {
            "email": {"type": "string", "format": "email"},
            "age": {"type": "integer", "minimum": 0},
        },
    }
    reg = create_registry_with_resource("https://example.com/schemas/profile", schema)

    # Direct URI resolution
    root_contents = resolve_uri(reg, "https://example.com/schemas/profile")
    assert root_contents == schema, "Root schema contents mismatch"

    # JSON pointer fragment resolution
    email_contents = resolve_uri(reg, "https://example.com/schemas/profile#/properties/email")
    assert email_contents == {"type": "string", "format": "email"}, "JSON pointer fragment mismatch"

    age_contents = resolve_uri(reg, "https://example.com/schemas/profile#/properties/age")
    assert age_contents == {"type": "integer", "minimum": 0}, "JSON pointer fragment mismatch"


def test_registry_crawl_and_anchor_resolution() -> None:
    """Assertion 3: referencing.Registry.crawl recursively indexes internal schema anchors and enables anchor URI resolution."""
    schema = {
        "$id": "https://example.com/schemas/order",
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "$defs": {
            "orderItem": {
                "$anchor": "itemAnchor",
                "type": "object",
                "properties": {
                    "itemId": {"type": "string"},
                    "quantity": {"type": "integer"},
                },
            },
        },
    }
    reg = create_registry_with_resource("https://example.com/schemas/order", schema)
    crawled_reg = crawl_registry_anchors(reg)

    anchor_uri = "https://example.com/schemas/order#itemAnchor"
    anchor_contents = resolve_uri(crawled_reg, anchor_uri)
    assert anchor_contents["type"] == "object"
    assert "itemId" in anchor_contents["properties"]
    assert "quantity" in anchor_contents["properties"]


def test_registry_combine_merges_registries() -> None:
    """Assertion 4: referencing.Registry.combine merges multiple schema registries into a unified registry mapping."""
    schema_a = {"$id": "https://example.com/schemas/a", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string"}
    schema_b = {"$id": "https://example.com/schemas/b", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "number"}

    reg_a = create_registry_with_resource("https://example.com/schemas/a", schema_a)
    reg_b = create_registry_with_resource("https://example.com/schemas/b", schema_b)

    merged = merge_registries(reg_a, reg_b)
    assert len(merged) == 2, f"Expected merged length 2, got {len(merged)}"
    assert "https://example.com/schemas/a" in merged
    assert "https://example.com/schemas/b" in merged
    assert resolve_uri(merged, "https://example.com/schemas/a") == schema_a
    assert resolve_uri(merged, "https://example.com/schemas/b") == schema_b


def test_registry_raises_no_such_resource() -> None:
    """Assertion 5: referencing.Registry raises NoSuchResource when querying contents of an unregistered URI."""
    reg = Registry()
    unregistered_uri = "https://example.com/schemas/missing"
    try:
        reg.contents(unregistered_uri)
        assert False, "Expected NoSuchResource was not raised"
    except NoSuchResource as exc:
        assert exc.ref == unregistered_uri, f"Expected ref {unregistered_uri}, got {exc.ref}"


def test_resolver_raises_unresolvable() -> None:
    """Assertion 6: referencing.Registry.resolver raises Unresolvable when looking up an unregistered URI."""
    reg = Registry()
    unregistered_uri = "https://example.com/schemas/missing"
    try:
        resolve_uri(reg, unregistered_uri)
        assert False, "Expected Unresolvable was not raised"
    except Unresolvable as exc:
        assert exc.ref == unregistered_uri, f"Expected ref {unregistered_uri}, got {exc.ref}"


def main() -> None:
    test_registry_registration_and_contents()
    test_resolver_lookup_and_pointer_resolution()
    test_registry_crawl_and_anchor_resolution()
    test_registry_combine_merges_registries()
    test_registry_raises_no_such_resource()
    test_resolver_raises_unresolvable()
    print("All referencing.Registry contract assertions passed successfully.")


if __name__ == "__main__":
    main()

오리진 시더

익명