Thực hành Kiểm thử API với Python: Phương pháp Định cấu hình Tham số, Dữ liệu Động và Xác thực

Trong quy trình kiểm thử API bằng Python, các kỹ thuật định cấu hình tham số, kiểm thử dữ liệu động và xác thực kết quả đóng vai trò then chốt để tối ưu hóa hiệu quả kiểm thử.

Định cấu hình tham số

Phương pháp này cho phép truyền tham số vào hàm kiểm thử để tái sử dụng logic và giảm lặp mã. Dưới đây là ví dụ sử dụng thư viện unittest:

import unittest
import requests

class APITestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.api_endpoint = "https://api.example.com/v1"
    
    def test_retrieve_profile(self, account_id):
        url = f"{self.api_endpoint}/profiles/{account_id}"
        response = requests.get(url)
        self.assertEqual(response.status_code, 200)
    
if __name__ == "__main__":
    test_suite = unittest.TestSuite()
    for account in [101, 205, 307]:
        test_suite.addTest(APITestCase("test_retrieve_profile", account_id=account))
    unittest.TextTestRunner().run(test_suite)

Xử lý sao chép đối tượng trong kiểm thử

Trong kiểm thử API, việc sao chép dữ liệu cần được xử lý cẩn trọng để tránh xung đột dữ liệu. Phân biệt giữa sao chép sâu và sao chép nông:

  • Sao chép nông: Chỉ sao chép tham chiếu cấp đầu, không sao chép cấu trúc lồng nhau
  • Sao chép sâu: Sao chép toàn bộ cấu trúc dữ liệu, bao gồm cả đối tượng lồng nhau

Ví dụ minh họa:

import copy

original_data = {
    "profile": {"id": 101, "name": "Alex"},
    "items": [{"item_id": 1001, "quantity": 5}]
}

shallow_copy = copy.copy(original_data)
deep_copy = copy.deepcopy(original_data)

shallow_copy["profile"]["name"] = "Taylor"
deep_copy["items"][0]["quantity"] = 10

print(original_data["profile"]["name"])  # Output: Taylor
print(original_data["items"][0]["quantity"])  # Output: 5

Kiểm thử dữ liệu động

Phương pháp này lấy dữ liệu kiểm thử từ nguồn bên ngoài thay vì hardcode. Sử dụng thư viện ddt để triển khai:

from ddt import ddt, data
import unittest

@ddt
class ProfileAPITest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.base_url = "https://api.example.com/v1"
    
    @data(
        (101, "John", 200),
        (205, "Jane", 404),
        (999, None, 404)
    )
    def test_profile_retrieval(self, account_id, expected_name, status_code):
        url = f"{self.base_url}/profiles/{account_id}"
        response = requests.get(url)
        self.assertEqual(response.status_code, status_code)
        if status_code == 200:
            self.assertEqual(response.json().get("name"), expected_name)

Xác thực nâng cao

Việc đóng gói các phương thức xác thực giúp tăng tính đọc hiểu và tái sử dụng. Ví dụ:

class APIValidation:
    @staticmethod
    def validate_response(response, expected_status):
        assert response.status_code == expected_status, (
            f"Expected status {expected_status}, got {response.status_code}"
        )
    
    @staticmethod
    def check_json_field(response, field, expected_value):
        json_data = response.json()
        assert field in json_data, f"Missing field: {field}"
        assert json_data[field] == expected_value, (
            f"Field {field} mismatch. Expected: {expected_value}, Got: {json_data[field]}"
        )

# Sử dụng trong kiểm thử
def test_user_data(self):
    response = requests.get("https://api.example.com/v1/users/101")
    APIValidation.validate_response(response, 200)
    APIValidation.check_json_field(response, "email", "user101@example.com")

Thẻ: python unittest ddt api-testing data-driven

Đăng vào ngày 1 tháng 7 lúc 02:29