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…

sha256:3b3ec7a4421a3ef461bdaf10d6d8c8b88da8916d19246872b32af367679d11da

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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()

オリジンシーダー

匿名