This project demonstrates how to use pytest hooks to create custom reports while testing the Petstore Swagger API. The goal is to provide an example of combining pytest hooks and Redis-based tracing to track the execution of test cases and generate detailed insights into API interactions.
This project leverages publicly available APIs from the Petstore Swagger API, which is designed as an example for practicing API interactions. The test suite uses pytest for:
- Parametrized API testing.
- Tracing test execution line-by-line with custom tracking (Redis-based).
- Hooking into pytest events to generate a tailored testing report.
- Base URL:
https://petstore.swagger.io/v2 - Endpoints Covered:
/pet(Pet-related operations)/store/order(Order-related operations)/user(User-related operations)
- Documentation: Petstore API Docs
- Utilizes the
pytest_runtest_callhook to track test execution dynamically. - Logs the following details into a Redis database:
- Test case name.
- Execution line number and content.
- Test steps with associated Redis keys for easy retrieval.
- Custom tracing ensures detailed insights into what happens during each test execution.
- Logs each line executed during a test case to a Redis database for real-time tracking and reporting.
- Stores information in the format:
execution_id:test_case_id:step_number(for line content).
- Uses
@pytest.mark.parametrizeto dynamically test various attributes of a pet, such asname,category,photo_urls, andstatus. - Example parameterized test:
@pytest.mark.parametrize( "attribute, updated_value", [ pytest.param("name", random_string(), marks=pytest.mark.sanity), ("category", Category(id=random_id(), name=random_string())), ("photo_urls", [f"https://example.com/{random_string()}.jpg"]), ("tags", [Tag(id=random_id(), name=random_string())]), ("status", "sold"), ], ids=[ "Update name", "Update category", "Update photo URLs", "Update tags", "Update status", ], ) def test_update_pet(attribute, updated_value): # Implementation of the test pass
- Hooks into Python’s tracing mechanism using:
sys.settrace(lambda f, e, a: trace_lines(redis_client, f, e, a))
- Tracks and logs each line executed during a test case using the
trace_linesfunction.
- The
pytest_runtest_callhook initializes Redis, sets up tracing, and attaches the Redis client to each test item. - Example:
def pytest_runtest_call(item: Item) -> None: global current_test_case_id current_test_case_id = item.name print(f"\n[pytest] Starting test case: {current_test_case_id}") redis_client = RedisClient() redis_client.__enter__() sys.settrace(lambda f, e, a: trace_lines(redis_client, f, e, a)) setattr(item, "_redis_client", redis_client)
git clone https://github.com/your-repo/pytest_hooks
cd pytest_hooks- Python 3.11 or higher.
- Install required dependencies:
pip install -r requirements.txt
- Ensure Redis is running locally or provide a connection to a Redis instance.
- Set up the required API credentials (if any).
Run the tests with:
pytestRun only sanity-marked tests:
pytest -m sanitypytest -vThis project includes CI/CD workflows to automate code quality checks, testing, and deployment using GitHub Actions. Below is a description of the workflows:
-
Static Code Analysis:
- Ensures the codebase adheres to quality standards by running tools like
black,isort,pycodestyle,flake8,mypy, andyamllint. - This helps catch formatting issues, syntax errors, and type inconsistencies before code is merged.
- Ensures the codebase adheres to quality standards by running tools like
-
Continuous Integration (CI):
- Runs the static code analysis workflow automatically on every push or manual trigger.
- Ensures that the codebase remains clean and compliant with coding standards.
-
Test Workflow:
- Executes all test cases in the repository using pytest.
- Uses Docker Compose to set up any required dependencies (e.g., Redis).
- Logs the execution results and generates reports for debugging.
- Initialization:
- Redis is initialized and connected before each test case using the
pytest_runtest_callhook.
- Redis is initialized and connected before each test case using the
- Test Execution:
- Each line executed in the test case is traced using
trace_linesand logged to Redis.
- Each line executed in the test case is traced using
- Custom Report:
- Test steps are logged with Redis keys for debugging or custom reporting purposes.
Feel free to fork the repository and contribute with pull requests. Suggestions and feedback are always welcome!
This project is licensed under the MIT License. See the LICENSE file for details.
- Swagger Petstore API for providing the example API.
- pytest for the powerful testing framework.
- Redis for enabling real-time tracing and logging.