Data-Driven API Testing with Pytest Parametrize
Environment Setup
Ensure the Pytest framework is installed in your Python environment. Execute the following command via terminal to add the library:
pip install pytest
For handling HTTP requests, the requests module is also required:
pip install requests
Basic API Validation
Construct a test module, for instance validate_endpoints.py, and import the necessary dependencies:
import pytest
import requests
Create a foundational test function to verify an endpoint's response status and payload integrity:
def test_fetch_inventory_item():
api_url = "https://api.mockstore.io/v1/inventory/42"
result = requests.get(api_url)
assert result.status_code == 200
payload = result.json()
assert payload["sku"] == "ITM-42"
Applying Parametrize for Data-Driven Execution
To validate an endpoint across multiple input combinations without duplicating test logic, apply the @pytest.mark.parametrize decorator. This approach injects distinct data sets into the test function parameters iteratively.
@pytest.mark.parametrize("email, secret, expected_status", [
("admin@shop.io", "supersecret", 200),
("guest@shop.io", "wrongpass", 401),
("new_user@shop.io", "newpass123", 201)
])
def test_authenticate_credentials(email, secret, expected_status):
auth_endpoint = "https://api.mockstore.io/v1/auth"
payload = {"user_email": email, "password": secret}
result = requests.post(auth_endpoint, json=payload)
assert result.status_code == expected_status
In the snippet above, the decorator’s initial argument defines the parameter names mapped to the test function signature. The subsequent list of tuples supplies the actual values. Each tuple constitutes a unique test case execution.
Test Execution
Invoke the test runner from the directory containing the test module:
pytest validate_endpoints.py
Pytest identifies the decorated function as three independent test cases, reflecting the data variations in the execution report.