Pytest plugin for automatic JSON Schema generation and validation from examples
This project has been archived.
The maintainers of this project have marked this project as archived. No new releases are expected.
Project description
pytest: Typed Schema Shot
Plugin for pytest that automatically generates JSON Schemas based on data examples and validates data against saved schemas.
Плагин для pytest, который автоматически генерирует JSON Schema на основе примеров данных и проверяет данные по сохраненным схемам.
Features
-
Automatic JSON Schema generation from data examples (using the
gensonlibrary).Автоматическая генерация JSON Schema по примерам данных (на основе библиотеки
genson). -
Format detection: Automatic detection and validation of string formats (email, UUID, date, date-time, URI, IPv4).
Обнаружение форматов: Автоматическое обнаружение и валидация форматов строк (email, UUID, date, date-time, URI, IPv4).
-
Schema storage and management.
Хранение и управление схемами.
-
Validation of data against saved schemas.
Валидация данных по сохраненным схемам.
-
Schema update via
--schema-update(create new schemas, remove unused ones, update existing).Обновление схем через
--schema-update(создание новых, удаление неиспользуемых, обновление существующих). -
Support for both
asyncand synchronous functions.Поддержка асинхронных (
async) и синхронных функций. -
Support for
Uniontypes and optional fields.Поддержка
Unionтипов и опциональных полей. -
Built-in diff comparison of changes
Встроенный diff сравнения изменений:
- ["complex_structure"]["mail"].format: "email" r ["complex_structure"]["age"].type: - [ - "integer", - "number" - ] + "number" - ["multitype_array"]: {"key": {"type": "string"}} - ["multitype_array"].type: "object" - ["multitype_array"].required: - "ключ" + ["multitype_array"].anyOf: + {"type": ["null", "string"]}, + {"type": "object", "properties": {"key": {"type": "string"}}, "required": ["key"]}
Installation
pip install pytest-typed-schema-shot
Usage
-
Use the
schemashotfixture in your testsВ тестах используйте фикстуру
schemashot:from typed_schema_shot import SchemaShot @pytest.mark.asyncio async def test_something(schemashot: SchemaShot): data = await API.data() schemashot.assert_match(data, "data")
-
On first run, generate schemas with the
--schema-updateflagПри первом запуске создайте схемы
--schema-update:pytest --schema-update -
On subsequent runs, tests will validate data against saved schemas
В последующих запусках тесты будут проверять данные по сохраненным схемам:
pytest
Key Capabilities
-
Union Types: support multiple possible types for fields
Поддержка множественных типов полей.
-
Optional Fields: automatic detection of required and optional fields
Автоматическое определение обязательных и необязательных полей.
-
Format Detection: automatic detection of string formats including:
-
Email:
user@example.com→{"type": "string", "format": "email"} -
UUID:
550e8400-e29b-41d4-a716-446655440000→{"type": "string", "format": "uuid"} -
Date:
2023-01-15→{"type": "string", "format": "date"} -
Date-Time:
2023-01-01T12:00:00Z→{"type": "string", "format": "date-time"} -
URI:
https://example.com→{"type": "string", "format": "uri"} -
IPv4:
192.168.1.1→{"type": "string", "format": "ipv4"}Обнаружение форматов: автоматическое определение форматов строк с поддержкой валидации.
-
-
Cleanup: automatic removal of unused schemas when running in update mode
Автоматическое удаление неиспользуемых схем в режиме обновления.
-
Schema Summary: colored terminal output showing created, updated, deleted and unused schemas
Цветной вывод в терминале с информацией о созданных, обновленных, удаленных и неиспользуемых схемах.
Advanced Usage
Configuration Options
The plugin supports the following pytest options:
--schema-update: Enable schema update mode (create new, update existing, delete unused schemas)
You can also configure the plugin via pytest.ini:
[tool:pytest]
# Custom directory for storing schemas (default: __snapshots__)
schema_shot_dir = schema_files
Or in pyproject.toml:
[tool.pytest.ini_options]
schema_shot_dir = "schema_files"
Schema Summary
The plugin automatically shows a summary at the end of test execution:
======== Schema Summary ========
Created schemas (1):
- new_api_schema.schema.json
Updated schemas (1):
- user_profile.schema.json
Unused schemas (2):
- old_feature.schema.json
- deprecated_api.schema.json
Use --schema-update to delete unused schemas
Best Practices
- Commit schemas to version control: Schemas should be part of your repository
- Review schema changes: When schemas change, review the diffs carefully
- Clean up regularly: Use
--schema-updateperiodically to remove unused schemas - Descriptive names: Use clear, descriptive names for your schemas
Troubleshooting
Schema not found error: Run tests with --schema-update to create missing schemas
Validation errors: Check if your data structure has changed and update schemas accordingly
Permission errors: Ensure your test directory is writable
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pytest_typed_schema_shot-0.1.9.tar.gz.
File metadata
- Download URL: pytest_typed_schema_shot-0.1.9.tar.gz
- Upload date:
- Size: 19.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d91d117cc527e7265730687ab2070471d53152b65ed0bea5d90576d774c105d5
|
|
| MD5 |
2c47f3cd994a21edd7f097a91346fb92
|
|
| BLAKE2b-256 |
a61e9475c48c94cdf2e074d514fc9341a09f9a381dae07c6f3360848496cf56b
|
Provenance
The following attestation bundles were made for pytest_typed_schema_shot-0.1.9.tar.gz:
Publisher:
python-publish.yml on Open-Inflation/pytest-typed-schema-shot
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pytest_typed_schema_shot-0.1.9.tar.gz -
Subject digest:
d91d117cc527e7265730687ab2070471d53152b65ed0bea5d90576d774c105d5 - Sigstore transparency entry: 238307961
- Sigstore integration time:
-
Permalink:
Open-Inflation/pytest-typed-schema-shot@a4138417d9367ee6c0b7269c59f4d72b6f9b92d1 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/Open-Inflation
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@a4138417d9367ee6c0b7269c59f4d72b6f9b92d1 -
Trigger Event:
push
-
Statement type:
File details
Details for the file pytest_typed_schema_shot-0.1.9-py3-none-any.whl.
File metadata
- Download URL: pytest_typed_schema_shot-0.1.9-py3-none-any.whl
- Upload date:
- Size: 17.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
fd66fa6b320889d6e3ec3c83b50972c8e9ade128d8a4a79e928d8d7265a9314a
|
|
| MD5 |
2690b3e1629bdfafc31d2266fbdbe036
|
|
| BLAKE2b-256 |
95f532238dd50e3c94f8d6f87cac107a0ddea38cfd9db9b55726a34e2817d1d5
|
Provenance
The following attestation bundles were made for pytest_typed_schema_shot-0.1.9-py3-none-any.whl:
Publisher:
python-publish.yml on Open-Inflation/pytest-typed-schema-shot
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pytest_typed_schema_shot-0.1.9-py3-none-any.whl -
Subject digest:
fd66fa6b320889d6e3ec3c83b50972c8e9ade128d8a4a79e928d8d7265a9314a - Sigstore transparency entry: 238307966
- Sigstore integration time:
-
Permalink:
Open-Inflation/pytest-typed-schema-shot@a4138417d9367ee6c0b7269c59f4d72b6f9b92d1 -
Branch / Tag:
refs/heads/main - Owner: https://github.com/Open-Inflation
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
python-publish.yml@a4138417d9367ee6c0b7269c59f4d72b6f9b92d1 -
Trigger Event:
push
-
Statement type: