Skip to main content

👍 Validate return values against a schema-like object in testing

Project description

pytest-schema

👍 Validate return values against a schema-like object in testing

schema v0.7 is a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types.

Example

Here is a quick example to get a feeling of schema, validating a list of entries with personal information:

from pytest_schema import schema, And, Enum, Optional, Or, Regex

# single user schema
user = {
    # name must be type str
    "name": str,
    # email must be type str or nullable
    "description": Or(None, str),
    # email valid str format
    "email": Regex(r".*?@.*?\.[A-Za-z]{2,6}"),
    # age converted to int then validated gt 18 lt 99 and must be type str
    "age": And(str, lambda n: 18 <= int(n) <= 99),
    # gender key is optional but must be str
    Optional("gender"): str,
    # role of enum values
    "role": Enum(["user", "super-user", "admin"]),
}

# multiple users schema
users = [ user ]

def test_users_endpoint():
    """
    Test calling a users endpoint and its response of users info.
    """
    response = [
        {
            "name": "Sue",
            "age": "28",
            "email": "sue@gmail.com",
            "gender": "female",
            "role": "admin",
        },
        {
            "name": "Sam",
            "age": "42",
            "email": "sam@aol.com",
            "role": "user",
        },
    ]

    assert schema(users) == response

If data is valid, it will return the True. If data is invalid, it will raise SchemaError exception.

Installation

Use pip:

pip install pytest-schema

Supported validations

The resulting JSON schema is not guaranteed to accept the same objects as the library would accept, since some validations are not implemented or have no JSON schema equivalent. This is the case of the Use and Hook objects for example.

Object properties

Use a dict literal. The dict keys are the JSON schema properties.

Python:

{ "test": str }

Json Schema:

{
    "type": "object",
    "properties": {
        "test": {"type": "string"}
    },
    "required": ["test"],
    "additionalProperties": false,
}

Please note that attributes are required by default. To create optional attributes use Optional, like so:

Python:

{ Optional("test"): str }

Json Schema:

{
    "type": "object", 
    "properties": {
        "test": { "type": "string" }
    },
    "required": [],
    "additionalProperties": false
}

Types

Use the Python type name directly. It will be converted to the JSON name:

Python Json Json Schema
str string { "type": "string" }
int integer { "type": "integer" }
float number { "type": "number" }
bool boolean { "type": "boolean" }
list array { "type": "array" }
dict object { "type": "object" }

Array items

Surround a schema with [].

Python:

[str] # means an array of string and becomes

Json Schema:

{
    "type": "array",
    "items": { "type": "string" }
}

Enumerated values

Use Enum or Or.

Python:

Enum([1, 2, 3])
# or
Or(1, 2, 3)

Json Schema:

{ "enum": [1, 2, 3] }

Constant values

Use the value itself or Const.

Python:

"name"
# or
Const("name")
{ "const": "name" }

Regular expressions

Use Regex.

Python:

Regex(r"^v\d+")

Json Schema:

{
    "type": "string",
    "pattern": "^v\\d+"
}

Combining schemas with allOf

Use And.

Python:

And(str, "value")

Json Schema:

{
    "allOf": [
        { "type": "string" },
        { "const": "value" }
    ]
}

Note that this example is not really useful in the real world, since const already implies the type.

Combining schemas with anyOf

Use Or.

Python:

Or(str, int)

Json Schema:

{
    "anyOf": [
        { "type": "string" },
        { "type": "integer" }
    ]
}

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

pytest-schema-0.1.0rc2.tar.gz (10.3 kB view hashes)

Uploaded Source

Built Distribution

pytest_schema-0.1.0rc2-py3-none-any.whl (7.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page