Skip to main content

pytest

You can use d42 as a validation tool for your pytest tests.

Installation

To install the package, use the following command:

$ pip3 install d42

Usage

To use d42 with pytest, you need to define a custom assertion message that uses the validate function to validate the test result against the schema. To do this, create a conftest.py file in the root of your project and add the following code:

# ./conftest.py
from d42.declaration import Schema
from d42.validation import format_result, validate


def pytest_assertrepr_compare(op, left, right):
if isinstance(right, Schema):
result = validate(right, left)
return format_result(result)

Next, in your test file, define the test scenario and its steps, as shown in the example below:

from base64 import b64decode
from d42 import schema


def test_b64decode():
encoded = "Y3VjdW1iZXI="

result = {
"result": b64decode(encoded)
}

assert result == schema.dict({
"result": schema.bytes(b"banana")
})

In this example, the test scenario decodes a base64 encoded string and validates that the result matches the expected output defined in the schema.

Run tests

To run the tests, use the following command:

$ pytest tests/

If the tests fail, a ValidationException will be raised, indicating which validation rule was not met. For example:

E    AssertionError: assert d42.ValidationException
E - Value <class 'bytes'> at _['result'] must be equal to b'banana', but b'cucumber' given