Backend Development 6 min read

Encapsulating JSON Data Format Validation Test Cases with Pytest

This article explains how to encapsulate JSON data format validation in Pytest by creating a reusable JSONValidator utility, defining JSON Schemas, writing test cases that check structure, field types, and values, and executing them to ensure efficient and maintainable API testing.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Encapsulating JSON Data Format Validation Test Cases with Pytest

In API automated testing, verifying that the returned JSON data conforms to the expected format is a key step for ensuring interface correctness. This guide demonstrates how to encapsulate JSON data format validation in Pytest to improve efficiency, accuracy, and maintainability.

Why encapsulate JSON data format test cases? By wrapping validation logic in a reusable utility you can avoid duplicated code, reduce the amount of test code, ensure each field’s structure, type, and value are checked, and make the tests easier to maintain and extend.

Encapsulating a JSON validation tool

import jsonschema
from jsonschema import validate

class JSONValidator:
    @staticmethod
    def validate_json(data, schema):
        """
        Validate JSON data against a given schema.

        :param data: JSON data to validate.
        :param schema: JSON Schema.
        :raises: jsonschema.exceptions.ValidationError
        """
        validate(instance=data, schema=schema)

    @staticmethod
    def validate_field_type(data, field, expected_type):
        """
        Validate that a field's type matches the expected type.

        :param data: JSON data.
        :param field: Field name.
        :param expected_type: Expected Python type.
        :raises: AssertionError
        """
        assert isinstance(data.get(field), expected_type), f"字段 '{field}' 的类型不匹配,预期类型为 {expected_type}"

    @staticmethod
    def validate_field_value(data, field, expected_value):
        """
        Validate that a field's value matches the expected value.

        :param data: JSON data.
        :param field: Field name.
        :param expected_value: Expected value.
        :raises: AssertionError
        """
        assert data.get(field) == expected_value, f"字段 '{field}' 的值不匹配,预期值为 {expected_value}"

Defining a JSON Schema

{
    "type": "object",
    "properties": {
        "id": {"type": "integer"},
        "name": {"type": "string"},
        "email": {"type": "string"},
        "is_active": {"type": "boolean"}
    },
    "required": ["id", "name", "email", "is_active"]
}

Writing test cases

import pytest
import requests
from project.common.json_validator import JSONValidator

user_info_schema = {
    "type": "object",
    "properties": {
        "id": {"type": "integer"},
        "name": {"type": "string"},
        "email": {"type": "string"},
        "is_active": {"type": "boolean"}
    },
    "required": ["id", "name", "email", "is_active"]
}

def test_get_user_info():
    url = "https://api.example.com/users/123"
    response = requests.get(url)
    assert response.status_code == 200
    data = response.json()
    JSONValidator.validate_json(data, user_info_schema)
    JSONValidator.validate_field_type(data, "id", int)
    JSONValidator.validate_field_type(data, "name", str)
    JSONValidator.validate_field_type(data, "email", str)
    JSONValidator.validate_field_type(data, "is_active", bool)
    JSONValidator.validate_field_value(data, "name", "John Doe")
    JSONValidator.validate_field_value(data, "email", "[email protected]")

Executing the tests

pytest test_user_info.py

Run the above command in the terminal from the directory containing the test file. If all assertions pass, the JSON data format validation succeeds; any failure indicates a problem with the JSON structure, types, or values that needs debugging.

Conclusion

By encapsulating JSON format validation logic in a reusable utility and defining clear JSON Schemas, you can achieve efficient and accurate validation in Pytest. The resulting test cases are well‑structured, easy to maintain, and help ensure reliable API responses.

PythonJSONAPI testingpytestSchema Validation
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.