Encapsulating Data Type Handling in API Automation Testing with Python
This article explains how to encapsulate data type processing in an API automation framework by creating a Python utility class that provides conversion, validation, and assertion methods, defines JSON Schemas, and demonstrates writing and executing Pytest test cases to ensure correct data types and values.
In API automation testing, handling various data types such as strings, numbers, booleans, lists, and dictionaries is essential for ensuring response correctness and robustness.
1. Data type handling goals include conversion of response data to the required format, validation that the data types match expectations, and assertions that enforce correctness within test cases.
2. Encapsulating a data type handling tool – first install the jsonschema library:
pip install jsonschemaThen create a data_handler.py file that defines a DataHandler class with static methods for conversion, validation, and assertions:
import json
import jsonschema
from jsonschema import validate
class DataHandler:
@staticmethod
def convert_to_json(data):
"""
将数据转换为 JSON 格式。
:param data: 要转换的数据
:return: JSON 格式的数据
"""
try:
return json.loads(data)
except json.JSONDecodeError as e:
raise ValueError(f"数据转换为 JSON 格式失败:{e}")
@staticmethod
def validate_json(data, schema):
"""
验证 JSON 数据是否符合指定的 schema。
:param data: 要验证的 JSON 数据
:param schema: JSON Schema
:raises: jsonschema.exceptions.ValidationError
"""
validate(instance=data, schema=schema)
@staticmethod
def assert_data_type(data, expected_type):
"""
验证数据类型是否符合预期。
:param data: 要验证的数据
:param expected_type: 预期的数据类型
:raises: AssertionError
"""
assert isinstance(data, expected_type), f"数据类型不匹配。预期:{expected_type},实际:{type(data)}"
@staticmethod
def assert_data_value(data, expected_value):
"""
验证数据值是否符合预期。
:param data: 要验证的数据
:param expected_value: 预期的数据值
:raises: AssertionError
"""
assert data == expected_value, f"数据值不匹配。预期:{expected_value},实际:{data}"3. Defining a JSON Schema to describe the expected structure of a user information object:
{
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"},
"email": {"type": "string"},
"is_active": {"type": "boolean"}
},
"required": ["id", "name", "email", "is_active"]
}4. Writing test cases using Pytest and the encapsulated tool. Create test_user_info.py :
import pytest
import requests
from data_handler import DataHandler
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 = DataHandler.convert_to_json(response.text)
DataHandler.validate_json(data, user_info_schema)
DataHandler.assert_data_type(data["id"], int)
DataHandler.assert_data_type(data["name"], str)
DataHandler.assert_data_type(data["email"], str)
DataHandler.assert_data_type(data["is_active"], bool)
DataHandler.assert_data_value(data["name"], "John Doe")
DataHandler.assert_data_value(data["email"], "[email protected]")5. Executing the tests – run the following command in the terminal:
pytest test_user_info.pyThe test output will indicate whether all assertions passed; any failure points to mismatched data types or values that need debugging.
6. Summary – By encapsulating data type handling logic in a reusable utility class and defining JSON Schemas, developers can write clear, maintainable API tests with Pytest, improving test accuracy and code robustness.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.