CodeSampleX

Пример

jsonschema 4.26.0: Draft202012Validator, FormatChecker, validate

Проверенный пример — pypi jsonschema 4.26.0: Draft202012Validator, FormatChecker, validate. Контракт выполнен на python 3.12 · linux alpine/x64 · docker и…

sha256:9fd526ef72524f76856ce3e958e35425538e7ce0f0373627f7d519c302ebd7f1

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-27

Кейс

HOW
Цель
verify pkg:pypi/jsonschema@4.26.0
Пакеты
Символы
  • jsonschema.Draft202012Validator
  • jsonschema.FormatChecker
  • jsonschema.validate
Окружение
python
Создан
2026-08-27T18:27:08Z

Контракт

  1. validate verifies native Python data structures against Draft 2020-12 schemas.
  2. validate raises jsonschema.exceptions.ValidationError on schema constraint violations with accurate path and validator details.
  3. Draft202012Validator provides is_valid for boolean validation and iter_errors for collecting multiple validation errors.
  4. Draft202012Validator correctly evaluates Draft 2020-12 tuple and item validation keywords including prefixItems.
  5. FormatChecker supports registering custom format check functions via the checks decorator.
  6. Draft202012Validator.check_schema validates schema structures and raises SchemaError on invalid schemas.

Файлы

  • NOTES.md
  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • test/contract.py

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# jsonschema validation and Draft 2020-12 APIs

This sample pins `jsonschema` 4.26.0 and verifies JSON Schema validation, Draft 2020-12 validator execution, custom format checking, and schema checking.

The contract verifies:
- `validate` verifies native Python data structures against Draft 2020-12 schemas.
- `validate` raises `jsonschema.exceptions.ValidationError` on schema violation with validator context and error path.
- `Draft202012Validator.is_valid` and `iter_errors` inspect validation validity and collect multiple errors.
- `Draft202012Validator` evaluates Draft 2020-12 specific features including `prefixItems` and `items`.
- `FormatChecker` registers custom format checkers via `@FormatChecker.checks` decorator.
- `Draft202012Validator.check_schema` validates schema structure and raises `jsonschema.exceptions.SchemaError` on malformed schemas.
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/jsonschema@4.26.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/jsonschema@4.26.0
Demonstrate these symbols/APIs:
  - jsonschema.Draft202012Validator
  - jsonschema.FormatChecker
  - jsonschema.validate

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:72a58ad37851c8c314ba33f684c78b33ca361c3c911b899b482a9230857b7cdc","contract":["validate verifies native Python data structures against Draft 2020-12 schemas.","validate raises jsonschema.exceptions.ValidationError on schema constraint violations with accurate path and validator details.","Draft202012Validator provides is_valid for boolean validation and iter_errors for collecting multiple validation errors.","Draft202012Validator correctly evaluates Draft 2020-12 tuple and item validation keywords including prefixItems.","FormatChecker supports registering custom format check functions via the checks decorator.","Draft202012Validator.check_schema validates schema structures and raises SchemaError on invalid schemas."],"goal":"verify pkg:pypi/jsonschema@4.26.0","kind":"HOW","packages":["pkg:pypi/jsonschema@4.26.0"],"schemaVersion":1,"symbols":["jsonschema.Draft202012Validator","jsonschema.FormatChecker","jsonschema.validate"]},"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/jsonschema@4.26.0"],"schemaVersion":1,"subject":"pkg:pypi/jsonschema@4.26.0","symbols":["jsonschema.Draft202012Validator","jsonschema.FormatChecker","jsonschema.validate"],"verifierAdapter":"python@1"}
requirements.txt
jsonschema==4.26.0
attrs==26.1.0
jsonschema-specifications==2025.9.1
referencing==0.37.0
rpds-py==2026.6.3
typing-extensions==4.16.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/jsonschema@4.26.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/jsonschema@4.26.0"
  ],
  "symbols": [
    "jsonschema.Draft202012Validator",
    "jsonschema.FormatChecker",
    "jsonschema.validate"
  ]
}
test/contract.py
import jsonschema
from jsonschema import Draft202012Validator, FormatChecker, validate
from jsonschema.exceptions import SchemaError, ValidationError

# 1. Verify validate validates valid instances against JSON Schema Draft 2020-12
schema = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer", "minimum": 0},
        "tags": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["name", "age"],
    "additionalProperties": False,
}

valid_data = {
    "name": "Alice",
    "age": 30,
    "tags": ["developer", "csx"],
}

validate(instance=valid_data, schema=schema)

# 2. Verify validate raises ValidationError on invalid data
invalid_data = {
    "name": "Bob",
    "age": -5,
}
try:
    validate(instance=invalid_data, schema=schema)
    raise AssertionError("Expected ValidationError for negative age")
except ValidationError as e:
    assert e.validator == "minimum"
    assert e.validator_value == 0
    assert list(e.path) == ["age"]

# 3. Verify Draft202012Validator provides is_valid and iter_errors methods
validator = Draft202012Validator(schema)
assert validator.is_valid(valid_data) is True
assert validator.is_valid(invalid_data) is False

errors = list(validator.iter_errors({"age": "not-an-integer"}))
assert len(errors) == 2
error_fields = {e.validator for e in errors}
assert "required" in error_fields
assert "type" in error_fields

# 4. Verify Draft 2020-12 specific features (prefixItems tuple validation)
tuple_schema = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "array",
    "prefixItems": [
        {"type": "string"},
        {"type": "number"},
    ],
    "items": False,
}
tuple_validator = Draft202012Validator(tuple_schema)
assert tuple_validator.is_valid(["hello", 42]) is True
assert tuple_validator.is_valid(["hello", 42, "extra"]) is False
assert tuple_validator.is_valid([123, "wrong-order"]) is False

# 5. Verify FormatChecker with custom format decorators
checker = FormatChecker()

@checker.checks("even-hex")
def is_even_hex(val):
    if not isinstance(val, str):
        return True
    try:
        num = int(val, 16)
        return num % 2 == 0
    except ValueError:
        return False

format_schema = {
    "type": "string",
    "format": "even-hex",
}

format_validator = Draft202012Validator(format_schema, format_checker=checker)
assert format_validator.is_valid("0x1A") is True
assert format_validator.is_valid("0x1B") is False

# 6. Verify check_schema detects invalid schemas and raises SchemaError
invalid_schema = {
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "invalid_type_name",
}
try:
    Draft202012Validator.check_schema(invalid_schema)
    raise AssertionError("Expected SchemaError on invalid schema definition")
except SchemaError:
    pass

print("CONTRACT PASS: jsonschema 4.26.0 verified offline")

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

аноним