Creating a robust and extensible API test automation framework in Python involves careful planning of the architecture to ensure scalability, maintainability, and ease of use. Below is a comprehensive guide to designing such a framework based on your requirements:
- Framework Architecture Overview
- Directory Structure
- Core Components
- API Classes
- Test Case Classes
- Test Runner
- Reporter
- Utilities
- Sample Implementation
- Adding New Test Cases
- Extending the Framework
1. Framework Architecture Overview
To meet your requirements, the framework should have the following characteristics:
- Modular Design: Separate concerns into different modules/classes to enhance maintainability.
- Reusability: Utilize base classes and utility functions to reduce code duplication.
- Dependency Management: Handle API dependencies systematically.
- Reporting: Implement a reporting mechanism that logs test results to an Excel sheet.
- Extensibility: Allow easy addition of new APIs and test cases with minimal changes.
2. Directory Structure
Organizing your project with a clear directory structure will aid in scalability and maintainability. Here's a suggested structure:
api_test_framework/
│
├── apis/
│ ├── __init__.py
│ ├── base_api.py
│ ├── api1.py
│ ├── api2.py
│ └── ... (other API modules)
│
├── tests/
│ ├── __init__.py
│ ├── base_test.py
│ ├── test_case1.py
│ ├── test_case2.py
│ └── ... (other test case modules)
│
├── utils/
│ ├── __init__.py
│ ├── http_client.py
│ ├── data_utils.py
│ └── ... (other utility modules)
│
├── reports/
│ └── test_results.xlsx
│
├── requirements.txt
└── run_tests.py
3. Core Components
a. API Classes
Create a base API class that includes common functionalities such as sending HTTP requests, handling authentication, etc. Each specific API will inherit from this base class.
apis/base_api.py
import requests
from utils.data_utils import load_config
class BaseAPI:
def __init__(self):
self.base_url = load_config('base_url')
self.headers = self.get_headers()
def get_headers(self):
# Implement common headers, possibly with authentication tokens
return {
'Content-Type': 'application/json',
'Authorization': f"Bearer {self.get_auth_token()}"
}
def get_auth_token(self):
# Implement authentication logic if needed
return load_config('auth_token')
def send_request(self, method, endpoint, params=None, data=None, headers=None):
url = f"{self.base_url}{endpoint}"
final_headers = self.headers.copy()
if headers:
final_headers.update(headers)
response = requests.request(method, url, params=params, json=data, headers=final_headers)
return response
apis/api1.py
from .base_api import BaseAPI
class API1(BaseAPI):
def get_resource(self, resource_id):
endpoint = f"/resource/{resource_id}"
response = self.send_request('GET', endpoint)
return response
def create_resource(self, payload):
endpoint = "/resource"
response = self.send_request('POST', endpoint, data=payload)
return response
# Add more methods as needed
Repeat the above for other APIs (api2.py, api3.py, etc.), encapsulating each API's specific endpoints and operations.
b. Test Case Classes
Create a base test case class that includes common test functionalities such as setup, teardown, logging results, etc. Each specific test case will inherit from this base class.
tests/base_test.py
from abc import ABC, abstractmethod
from utils.http_client import HttpClient
from utils.data_utils import initialize_report, log_test_result
class BaseTest(ABC):
def __init__(self):
self.client = HttpClient()
self.test_results = initialize_report()
@abstractmethod
def run_test(self):
pass
def execute(self):
try:
self.run_test()
log_test_result(self.test_results, self.get_name(), 'PASS', '')
except AssertionError as e:
log_test_result(self.test_results, self.get_name(), 'FAIL', str(e))
except Exception as e:
log_test_result(self.test_results, self.get_name(), 'ERROR', str(e))
@abstractmethod
def get_name(self):
pass
tests/test_case1.py
from .base_test import BaseTest
from apis.api1 import API1
from apis.api2 import API2
class TestCase1(BaseTest):
def __init__(self):
super().__init__()
self.api1 = API1()
self.api2 = API2()
def get_name(self):
return "Test Case 1: API1 followed by API2"
def run_test(self):
# Step 1: Call API1
response1 = self.api1.create_resource({'name': 'Test Resource'})
assert response1.status_code == 201, "API1 failed to create resource"
resource_id = response1.json().get('id')
assert resource_id is not None, "Resource ID not returned"
# Step 2: Call API2 dependent on API1's outcome
response2 = self.api2.get_resource(resource_id)
assert response2.status_code == 200, "API2 failed to retrieve resource"
assert response2.json().get('name') == 'Test Resource', "Resource name mismatch"
Repeat similar structures for other test cases, encapsulating various API sequences and dependencies.
c. Test Runner
A script to discover and execute all test cases.
run_tests.py
import os
import importlib
from tests.base_test import BaseTest
from utils.data_utils import save_report
def discover_tests(test_directory="tests"):
test_cases = []
for file in os.listdir(test_directory):
if file.startswith("test_case") and file.endswith(".py"):
module_name = file[:-3]
module = importlib.import_module(f"tests.{module_name}")
for attribute in dir(module):
cls = getattr(module, attribute)
if isinstance(cls, type) and issubclass(cls, BaseTest) and cls is not BaseTest:
test_cases.append(cls())
return test_cases
def main():
tests = discover_tests()
for test in tests:
test.execute()
save_report()
if __name__ == "__main__":
main()
d. Reporter
Utility to handle reporting test results to an Excel sheet.
utils/data_utils.py
import pandas as pd
import os
REPORT_PATH = 'reports/test_results.xlsx'
report_data = []
def load_config(key):
# Implement configuration loader, could be from a JSON/YAML file
config = {
'base_url': 'https://api.example.com',
'auth_token': 'your_auth_token_here'
}
return config.get(key)
def initialize_report():
global report_data
if os.path.exists(REPORT_PATH):
df = pd.read_excel(REPORT_PATH)
report_data = df.to_dict('records')
else:
report_data = []
def log_test_result(results, test_name, status, message):
results.append({
'Test Name': test_name,
'Status': status,
'Message': message
})
def save_report():
df = pd.DataFrame(report_data)
df.to_excel(REPORT_PATH, index=False)
e. HTTP Client (Optional)
If you need more control over HTTP requests, you can abstract it further.
utils/http_client.py
import requests
class HttpClient:
def __init__(self, base_url, headers=None):
self.base_url = base_url
self.headers = headers or {}
def get(self, endpoint, params=None):
return requests.get(f"{self.base_url}{endpoint}", headers=self.headers, params=params)
def post(self, endpoint, data=None):
return requests.post(f"{self.base_url}{endpoint}", headers=self.headers, json=data)
def put(self, endpoint, data=None):
return requests.put(f"{self.base_url}{endpoint}", headers=self.headers, json=data)
def delete(self, endpoint, params=None):
return requests.delete(f"{self.base_url}{endpoint}", headers=self.headers, params=params)
4. Sample Implementation
Here's how the components come together in a sample test case.
apis/api2.py
from .base_api import BaseAPI
class API2(BaseAPI):
def get_resource(self, resource_id):
endpoint = f"/resource/{resource_id}"
response = self.send_request('GET', endpoint)
return response
def update_resource(self, resource_id, payload):
endpoint = f"/resource/{resource_id}"
response = self.send_request('PUT', endpoint, data=payload)
return response
# Add more methods as needed
tests/test_case1.py
from .base_test import BaseTest
from apis.api1 import API1
from apis.api2 import API2
class TestCase1(BaseTest):
def __init__(self):
super().__init__()
self.api1 = API1()
self.api2 = API2()
def get_name(self):
return "Test Case 1: Create and Retrieve Resource"
def run_test(self):
# Step 1: Create a resource using API1
create_response = self.api1.create_resource({'name': 'Test Resource'})
assert create_response.status_code == 201, "Failed to create resource"
resource_id = create_response.json().get('id')
assert resource_id is not None, "Resource ID not returned"
# Step 2: Retrieve the resource using API2
get_response = self.api2.get_resource(resource_id)
assert get_response.status_code == 200, "Failed to retrieve resource"
assert get_response.json().get('name') == 'Test Resource', "Resource name mismatch"
run_tests.py
import os
import importlib
from tests.base_test import BaseTest
from utils.data_utils import save_report
def discover_tests(test_directory="tests"):
test_cases = []
for file in os.listdir(test_directory):
if file.startswith("test_case") and file.endswith(".py"):
module_name = file[:-3]
module = importlib.import_module(f"tests.{module_name}")
for attribute in dir(module):
cls = getattr(module, attribute)
if isinstance(cls, type) and issubclass(cls, BaseTest) and cls is not BaseTest:
test_cases.append(cls())
return test_cases
def main():
tests = discover_tests()
for test in tests:
test.execute()
save_report()
print("Test execution completed. Report saved to 'reports/test_results.xlsx'.")
if __name__ == "__main__":
main()
requirements.txt
requests
pandas
openpyxl
Running the Tests
-
Install Dependencies
pip install -r requirements.txt
-
Execute Test Runner
python run_tests.py
After execution, the test results will be available in reports/test_results.xlsx.
5. Adding New Test Cases
To add a new test case with minimal changes:
-
Create a New Test Case File
Add a new Python file in the tests/ directory following the naming convention, e.g., test_case3.py.
-
Define the Test Case Class
from .base_test import BaseTest
from apis.api1 import API1
from apis.api3 import API3 # Example of another API
class TestCase3(BaseTest):
def __init__(self):
super().__init__()
self.api1 = API1()
self.api3 = API3()
def get_name(self):
return "Test Case 3: API1 and API3 Interaction"
def run_test(self):
# Implement test steps
pass
-
No Changes Needed Elsewhere
The run_tests.py script automatically discovers and runs all test cases following the naming convention.
6. Extending the Framework
a. Handling API Dependencies
If certain APIs depend on the outcomes of others, manage dependencies within the test cases as shown in TestCase1. Alternatively, implement a dependency injection mechanism or a context manager to share state across test steps.
b. Enhancing Reporting
For more detailed reports, consider adding timestamps, execution duration, or integrating with existing reporting tools.
Extended log_test_result Example:
from datetime import datetime
def log_test_result(results, test_name, status, message):
results.append({
'Test Name': test_name,
'Status': status,
'Message': message,
'Timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
c. Data-Driven Testing
For scalability, especially with numerous test cases and varying input data, consider implementing data-driven tests where test data is read from external sources like Excel, JSON, or CSV files.
d. Configuration Management
Externalize configurations (like base URLs, auth tokens, etc.) using configuration files (JSON, YAML) or environment variables for flexibility across different environments.
Example config.json:
{
"base_url": "https://api.example.com",
"auth_token": "your_auth_token_here"
}
Updated load_config Function:
import json
def load_config(key):
with open('config.json', 'r') as f:
config = json.load(f)
return config.get(key)
e. Logging
Implement a logging mechanism to capture detailed logs, which is helpful for debugging.
Using Python's logging Module:
utils/logger.py
import logging
def setup_logger():
logger = logging.getLogger("APITestFramework")
logger.setLevel(logging.DEBUG)
# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler('reports/test_execution.log')
c_handler.setLevel(logging.INFO)
f_handler.setLevel(logging.DEBUG)
# Create formatters and add to handlers
c_format = logging.Formatter('%(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)
# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)
return logger
Integrate Logger in base_test.py:
from abc import ABC, abstractmethod
from utils.data_utils import initialize_report, log_test_result
from utils.logger import setup_logger
class BaseTest(ABC):
def __init__(self):
self.logger = setup_logger()
self.test_results = initialize_report()
@abstractmethod
def run_test(self):
pass
def execute(self):
try:
self.logger.info(f"Starting test: {self.get_name()}")
self.run_test()
log_test_result(self.test_results, self.get_name(), 'PASS', '')
self.logger.info(f"Test Passed: {self.get_name()}")
except AssertionError as e:
log_test_result(self.test_results, self.get_name(), 'FAIL', str(e))
self.logger.error(f"Test Failed: {self.get_name()} - {str(e)}")
except Exception as e:
log_test_result(self.test_results, self.get_name(), 'ERROR', str(e))
self.logger.error(f"Test Error: {self.get_name()} - {str(e)}")
Conclusion
By following the architecture and implementation guidelines above, you can build a robust, extensible, and maintainable API test automation framework in Python. This structure promotes reusability, reduces code duplication, and makes it straightforward to add new APIs and test cases. Additionally, integrating comprehensive reporting and logging ensures that test results are well-documented and easily accessible for analysis.
Feel free to share your existing function definitions and test case implementations in subsequent messages, and I can provide more specific guidance or code enhancements tailored to your current setup.