CodeSampleX

Пример

referencing 0.37.0: Resource

Проверенный пример — pypi referencing 0.37.0: Resource. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден.

sha256:9884ae97b9fd488503701183c15da61afc27ecd16db751875c97e88cac415b0c

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда python linux 24 · ubuntu · glibc 2.39 x64 python python 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.Resource in pkg:pypi/referencing@0.37.0
Пакеты
Символы
  • referencing.Resource
Окружение
python
Создан
2026-09-02T13:29:11Z

Контракт

  1. Resource.from_contents() creates a Resource instance from JSON schema data and auto-detects $schema specification and $id.
  2. Resource.from_contents() accepts default_specification to identify schemas without an explicit $schema keyword.
  3. Resource.from_contents() raises CannotDetermineSpecification when schema dialect cannot be identified and no default is provided.
  4. Resource.opaque() wraps arbitrary mapping or data as an opaque resource without subresources or anchor resolution.
  5. Resource.anchors() retrieves schema anchors ($anchor) with their respective name and Resource references.
  6. Resource.subresources() iterates over all subresources embedded within the document.
  7. Resource.pointer() resolves JSON pointer references using a Resolver and raises PointerToNowhere for invalid paths.
  8. Resource instances support value equality comparison based on contents and specification.

Файлы

  • PROMPT.md
  • csx.json
  • requirements.txt
  • 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.Resource 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.Resource

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:f85f6edbc62fba26aebd3e9dfd79f3c5d6f0e638d330d541829bcf8bb7347e4a","contract":["Resource.from_contents() creates a Resource instance from JSON schema data and auto-detects $schema specification and $id.","Resource.from_contents() accepts default_specification to identify schemas without an explicit $schema keyword.","Resource.from_contents() raises CannotDetermineSpecification when schema dialect cannot be identified and no default is provided.","Resource.opaque() wraps arbitrary mapping or data as an opaque resource without subresources or anchor resolution.","Resource.anchors() retrieves schema anchors ($anchor) with their respective name and Resource references.","Resource.subresources() iterates over all subresources embedded within the document.","Resource.pointer() resolves JSON pointer references using a Resolver and raises PointerToNowhere for invalid paths.","Resource instances support value equality comparison based on contents and specification."],"goal":"verify referencing.Resource in pkg:pypi/referencing@0.37.0","kind":"HOW","packages":["pkg:pypi/referencing@0.37.0"],"schemaVersion":1,"symbols":["referencing.Resource"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/referencing@0.37.0"],"schemaVersion":1,"subject":"pkg:pypi/referencing@0.37.0","symbols":["referencing.Resource"],"verifierAdapter":"python@1"}
requirements.txt
referencing==0.37.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify referencing.Resource in pkg:pypi/referencing@0.37.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/referencing@0.37.0"
  ],
  "symbols": [
    "referencing.Resource"
  ]
}
test/contract.py
from referencing import Registry, Resource
from referencing.exceptions import CannotDetermineSpecification, PointerToNowhere
from referencing.jsonschema import DRAFT7, DRAFT202012


def test_resource_from_contents_with_schema():
    schema = {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "https://example.com/root",
        "$anchor": "root-anchor",
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "nested": {
                "$id": "https://example.com/nested",
                "$anchor": "nested-anchor",
                "type": "boolean",
            },
        },
    }
    res = Resource.from_contents(schema)
    assert res.contents == schema
    assert res.id() == "https://example.com/root"
    assert res._specification == DRAFT202012


def test_resource_from_contents_with_default_specification():
    schema_without_id = {"type": "string", "maxLength": 100}
    res = Resource.from_contents(schema_without_id, default_specification=DRAFT7)
    assert res.contents == schema_without_id
    assert res.id() is None
    assert res._specification == DRAFT7


def test_resource_from_contents_cannot_determine_specification():
    schema_ambiguous = {"type": "integer"}
    try:
        Resource.from_contents(schema_ambiguous)
        raise AssertionError("Resource.from_contents should have raised CannotDetermineSpecification")
    except CannotDetermineSpecification:
        pass


def test_resource_opaque():
    data = {"arbitrary": "data", "count": 42}
    res_opaque = Resource.opaque(data)
    assert res_opaque.contents == data
    assert res_opaque.id() is None
    assert list(res_opaque.anchors()) == []
    assert list(res_opaque.subresources()) == []


def test_resource_anchors():
    schema = {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "https://example.com/anchored",
        "$anchor": "main-anchor",
        "type": "object",
    }
    res = Resource.from_contents(schema)
    anchors = list(res.anchors())
    assert len(anchors) == 1
    assert anchors[0].name == "main-anchor"
    assert anchors[0].resource == res


def test_resource_subresources():
    schema = {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "https://example.com/parent",
        "type": "object",
        "properties": {
            "child": {
                "$id": "https://example.com/child",
                "type": "string",
            },
        },
    }
    res = Resource.from_contents(schema)
    subresources = list(res.subresources())
    assert len(subresources) == 1
    assert subresources[0].id() == "https://example.com/child"
    assert subresources[0].contents == {"$id": "https://example.com/child", "type": "string"}


def test_resource_pointer_and_pointer_to_nowhere():
    schema = {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "https://example.com/document",
        "type": "object",
        "properties": {
            "title": {"type": "string"},
        },
    }
    res = Resource.from_contents(schema)
    registry = Registry().with_resource("https://example.com/document", res)
    resolver = registry.resolver()

    resolved = res.pointer("/properties/title", resolver=resolver)
    assert resolved.contents == {"type": "string"}

    try:
        res.pointer("/properties/nonexistent", resolver=resolver)
        raise AssertionError("res.pointer should have raised PointerToNowhere")
    except PointerToNowhere as exc:
        assert exc.ref == "/properties/nonexistent"


def test_resource_equality():
    schema1 = {"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "number"}
    schema2 = {"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "number"}
    schema3 = {"$schema": "https://json-schema.org/draft/2020-12/schema", "type": "string"}

    res1 = Resource.from_contents(schema1)
    res2 = Resource.from_contents(schema2)
    res3 = Resource.from_contents(schema3)

    assert res1 == res2
    assert res1 != res3


def main():
    test_resource_from_contents_with_schema()
    test_resource_from_contents_with_default_specification()
    test_resource_from_contents_cannot_determine_specification()
    test_resource_opaque()
    test_resource_anchors()
    test_resource_subresources()
    test_resource_pointer_and_pointer_to_nowhere()
    test_resource_equality()
    print("CONTRACT PASS: referencing.Resource verified offline")


if __name__ == "__main__":
    main()

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

аноним