Backend Development 5 min read

Encapsulating Assertion Logic in Pytest for API Automation Testing

This article explains how to encapsulate common assertion logic—such as status‑code, JSON data, and database assertions—within the Pytest framework, providing reusable functions and a generic assertion class to improve readability, maintainability, and efficiency of backend API tests.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Encapsulating Assertion Logic in Pytest for API Automation Testing

In API automation testing, assertions verify that the response meets expectations; encapsulating these assertions enhances code readability and maintainability while reducing duplication.

1. Basic concept – Python’s assert statement can be used directly, for example:

response = requests.get("https://api.example.com")
assert response.status_code == 200, "接口请求失败"

2. Encapsulated status‑code assertion

def assert_status_code(response, expected_status_code=200):
    """Validate that the HTTP status code matches the expected value."""
    assert response.status_code == expected_status_code, f"状态码不匹配。预期:{expected_status_code},实际:{response.status_code}"

3. Encapsulated JSON data assertion

import jsonpath

def assert_json(response, jsonpath_expr, expected_value):
    """Validate that a JSON field extracted by a JSONPath expression matches the expected value."""
    actual_value = jsonpath.jsonpath(response.json(), jsonpath_expr)
    assert actual_value[0] == expected_value, f"JSON 数据不匹配。预期:{expected_value},实际:{actual_value[0]}"

4. Encapsulated database assertion

import pymysql

def assert_db(query, expected_result):
    """Validate that the result of a SQL query matches the expected result."""
    conn = pymysql.connect(host='localhost', user='root', password='password', db='testdb')
    cursor = conn.cursor()
    cursor.execute(query)
    result = cursor.fetchone()
    cursor.close()
    conn.close()
    assert result == expected_result, f"数据库查询结果不匹配。预期:{expected_result},实际:{result}"

5. Generic assertion class

class ApiAssert:
    @staticmethod
    def assert_status_code(response, expected_status_code=200):
        assert response.status_code == expected_status_code, f"状态码不匹配。预期:{expected_status_code},实际:{response.status_code}"

    @staticmethod
    def assert_json(response, jsonpath_expr, expected_value):
        actual_value = jsonpath.jsonpath(response.json(), jsonpath_expr)
        assert actual_value[0] == expected_value, f"JSON 数据不匹配。预期:{expected_value},实际:{actual_value[0]}"

    @staticmethod
    def assert_db(query, expected_result):
        conn = pymysql.connect(host='localhost', user='root', password='password', db='testdb')
        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchone()
        cursor.close()
        conn.close()
        assert result == expected_result, f"数据库查询结果不匹配。预期:{expected_result},实际:{result}"

6. Using the encapsulated assertion class in a test case

def test_api():
    response = requests.get("https://api.example.com")
    ApiAssert.assert_status_code(response, 200)
    ApiAssert.assert_json(response, "$.status", "success")
    ApiAssert.assert_db("SELECT * FROM users WHERE id=1", (1, "John Doe"))

By wrapping assertion logic into reusable functions and a class, developers can write cleaner, more maintainable API tests, improving overall testing efficiency.

backendPythonAutomationAPI testingpytestassertion
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.