API Association Wrapping with Pytest: A Complete Step‑by‑Step Guide
This article explains how to implement API association wrapping in Pytest, covering environment setup, test file creation, dependency imports, detailed test case definitions with sample code for login, user creation, retrieval and update, execution of the suite, result verification, and advanced project structuring for complex scenarios.
In API automated testing, interface association encapsulation is a crucial step that extracts key data from one API response and uses it as input for subsequent APIs, enabling data linkage and workflow chaining.
1. Build the test environment – ensure Python and Pytest are installed and install required libraries:
pip install pytest requests2. Create the test case file – name it test_api.py .
3. Import dependencies :
import pytest
import requests4. Define test cases – examples include a login API that returns a token, a user‑creation API that uses the token, a user‑retrieval API, and a user‑update API. Sample code snippets:
def test_login():
url = "https://api.example.com/login"
data = {"username": "testuser", "password": "testpass"}
response = requests.post(url, json=data)
assert response.status_code == 200
token = response.json()["token"]
return token def test_create_user():
token = test_login()
url = "https://api.example.com/users"
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
data = {"name": "John Doe", "email": "[email protected]"}
response = requests.post(url, headers=headers, json=data)
assert response.status_code == 201
user_id = response.json()["id"]
return user_id def test_get_user():
user_id = test_create_user()
token = test_login()
url = f"https://api.example.com/users/{user_id}"
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
response = requests.get(url, headers=headers)
assert response.status_code == 200
user_info = response.json()
assert user_info["name"] == "John Doe"
assert user_info["email"] == "[email protected]" def test_update_user():
user_id = test_create_user()
token = test_login()
url = f"https://api.example.com/users/{user_id}"
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
data = {"name": "John Doe Updated", "email": "[email protected]"}
response = requests.put(url, headers=headers, json=data)
assert response.status_code == 200
updated_user_info = response.json()
assert updated_user_info["name"] == "John Doe Updated"
assert updated_user_info["email"] == "[email protected]"5. Execute the test cases with:
pytest test_api.py6. Verify results – all assertions must pass; any failure indicates an issue with the API association logic.
7. More complex association wrapping – a sample project structure is presented, along with utility modules ( common/utils.py ) for request handling and assertions, configuration ( conf/config.py ), and organized test modules ( test_case/test_login.py , etc.). Example utility functions:
def send_request(method, url, headers=None, params=None, data=None):
response = requests.request(method, url, headers=headers, params=params, data=data)
response.raise_for_status()
return response.json()
def assert_response(response_data, expected_key, expected_value):
assert expected_key in response_data, f"Expected key '{expected_key}' not found in response."
assert response_data[expected_key] == expected_value, (
f"Expected value for '{expected_key}' is '{expected_value}', but got '{response_data[expected_key]}'"
)The configuration file defines the test environment and base URL:
TEST_ENVIRONMENT = "development"
BASE_URL = "http://localhost:8000/api/"Test cases use these utilities to send requests and validate responses, and a test suite ( testsuite.py ) loads and runs modules, asserting overall success.
8. Summary – By following these steps, you can plan and write API association wrappers in Pytest from scratch, enabling robust automated integration testing.
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.