Create Pytest Fixtures and Parametrized Test Cases for Python Applications
Generate a complete Pytest suite with reusable fixtures, parametrized test cases, mocking patterns, and proper test organization.
๐ The Prompt
Write a comprehensive Pytest test suite for a [MODULE_NAME] module in Python that handles [MODULE_FUNCTIONALITY]. The module contains the following key functions/classes: [FUNCTION_OR_CLASS_LIST].
Generate the following:
1. **Fixtures (conftest.py)**:
- A session-scoped fixture that initializes [SHARED_RESOURCE] (e.g., database connection, API client).
- A function-scoped fixture that provides [TEST_DATA_DESCRIPTION] and handles setup/teardown using `yield`.
- A fixture that mocks [EXTERNAL_DEPENDENCY] using `unittest.mock.patch` or `pytest-mock`.
- A fixture factory pattern for creating [ENTITY_NAME] objects with customizable attributes.
2. **Parametrized Tests**:
- Use `@pytest.mark.parametrize` to test [FUNCTION_NAME] with at least 6 input/output combinations including: valid inputs, edge cases (empty strings, zero values, None), boundary values, and invalid inputs that should raise [EXCEPTION_TYPE].
- Include IDs for each parameter set for readable test output.
- Add a parametrized test that reads test cases from a list of dictionaries for complex scenarios.
3. **Test Organization**:
- Group related tests in classes prefixed with `Test`.
- Use `pytest.raises` for exception testing.
- Include at least one test using `pytest.approx` for floating-point comparisons if applicable.
- Add custom markers for [TEST_CATEGORIES] (e.g., slow, integration, unit).
4. **Assertions**: Use descriptive assertion messages and prefer specific assertions over generic `assert` where possible.
Include a `pytest.ini` or `pyproject.toml` snippet for marker registration and test configuration.
๐ก Tips for Better Results
Paste your actual function signatures into [FUNCTION_OR_CLASS_LIST] so the AI generates tests matching your real code. Always specify the exact exceptions your code raises to get accurate `pytest.raises` blocks. Request fixture dependency chains if your setup is multi-layered.
๐ฏ Use Cases
Python developers use this when building or expanding a test suite and need well-structured fixtures, thorough edge-case coverage, and maintainable parametrized tests.