Decorator @pytest.mark.parametrize cho phép thực thi cùng một hàm kiểm thử với nhiều bộ dữ liệu đầu vào khác nhau, hỗ trợ hiệu quả cho mô hình kiểm thử dựa trên dữ liệu (data-driven testing).
1. Sử dụng tệp JSON làm nguồn dữ liệu
Dữ liệu kiểm thử có thể được lưu trữ dưới dạng JSON để dễ dàng quản lý và tách biệt khỏi mã nguồn. Cấu trúc dữ liệu mẫu như sau:
{
"cases": [
[
{
"author": "user01",
"allow_comment": false,
"body": "Nội dung bài viết",
"format": "markdown",
"is_private": false,
"is_promoted": false,
"is_spam": false,
"title": "Tiêu đề mẫu",
"category_id": ""
},
null
],
[
{
"author": "user01",
"allow_comment": false,
"body": "Nội dung bài viết",
"format": "markdown",
"is_private": false,
"is_promoted": false,
"is_spam": false,
"title": "Tiêu đề mẫu",
"category_id": "INVALID_ID"
},
"java.sql.SQLException: Incorrect integer value"
]
]
}
Đoạn mã dưới đây sẽ tải dữ liệu từ tệp và cấu hình cho hàm test:
import json
import requests
import pytest
# Đường dẫn tệp dữ liệu
DATA_PATH = './data/test_cases.json'
with open(DATA_PATH, 'r', encoding='utf-8') as f:
config = json.load(f)
test_scenarios = config['cases']
@pytest.mark.parametrize('payload,expected_error', test_scenarios)
def test_submit_article(payload, expected_error):
api_url = "https://api.example.com/articles"
req_headers = {"Content-Type": "application/json"}
response = requests.post(api_url, json=payload, headers=req_headers)
response_data = response.json()
# Kiểm tra thông báo lỗi trả về
assert str(response_data.get('message')) == str(expected_error)
2. Sử dụng tệp Excel làm nguồn dữ liệu
Đối với các trường hợp cần nhiều cột dữ liệu phức tạp, tệp Excel là lựa chọn phù hợp. Thư viện openpyxl thường được sử dụng để đọc các tệp này.
from openpyxl import load_workbook
workbook = load_workbook("./data/scenarios.xlsx")
sheet = workbook['article_tests']
excel_cases = []
# Duyệt qua các dòng bắt đầu từ dòng thứ 2 (bỏ qua header)
for row in sheet.iter_rows(min_row=2, values_only=True):
# Giả sử các cột lần lượt là: URL, Method, Body, Status Code, Message
if row[0] is not None:
excel_cases.append(list(row))
Hàm kiểm thử sẽ nhận nhiều tham số tương ứng với các cột trong Excel:
@pytest.mark.parametrize('endpoint,http_method,body,status_code,error_msg', excel_cases)
def test_article_workflow(endpoint, http_method, body, status_code, error_msg):
headers = {"Authorization": "Bearer token"}
if http_method.lower() == 'post':
resp = requests.post(endpoint, json=body, headers=headers)
# Xác thực mã trạng thái và nội dung phản hồi
assert resp.status_code == status_code
assert resp.json().get('message') == error_msg