pytest-schema

raw JSON →
0.1.2 verified Mon Apr 27 auth: no python

A pytest plugin that allows you to validate return values against a schema-like object, built on top of the `schema` library. Current version 0.1.2, released June 2024. Low release cadence.

pip install pytest-schema
error ModuleNotFoundError: No module named 'pytest_schema'
cause pytest-schema is not installed or installed in a different environment.
fix
Run pip install pytest-schema in your virtual environment.
error TypeError: 'Schema' object is not callable
cause Using the `schema` object from `schema` library directly instead of pytest_schema's wrapper.
fix
Import schema from pytest_schema instead: from pytest_schema import schema.
error AssertionError: assert <pytest_schema...> == ...
cause The schema comparison failed because the actual data does not match the schema.
fix
Check the types and structure of your actual data against the schema definition.
gotcha The `schema` callable returns a validator that must be compared with `==` (or `!=`) to actually validate. Simply calling `schema(...)` without comparison does nothing.
fix Always use `assert actual == schema(expected)` or `assert actual != schema(expected)`.
gotcha `like_schema` (or `like`) allows extra keys in the actual dict, while `exact_schema` (or `exact`) does not. Using the wrong one can cause false passes or failures.
fix Use `like_schema` when extra keys are acceptable; use `exact_schema` when the dict must match exactly.
deprecated The methods `like` and `exact` are deprecated in favor of `like_schema` and `exact_schema`. The old names may be removed in future versions.
fix Use `like_schema` and `exact_schema` instead.

Basic usage of schema, like_schema, and exact_schema in pytest tests.

from pytest_schema import schema

def test_validate_schema():
    expected = {"name": str, "age": int}
    actual = {"name": "Alice", "age": 30}
    assert actual == schema(expected)

def test_like_schema():
    from pytest_schema import like_schema
    expected = {"id": int, "value": str}
    actual = {"id": 1, "value": "foo", "extra": True}
    assert actual == like_schema(expected)

def test_exact_schema():
    from pytest_schema import exact_schema
    expected = {"key": str}
    actual = {"key": "val"}
    assert actual == exact_schema(expected)