| name | pytest-generator |
| description | Generate pytest-based unit tests for Python code. Creates test files Use when this capability is needed. |
| metadata | {"author":"ForceInjection"} |
Pytest Generator Skill
Purpose
This skill generates pytest-based unit tests for Python code, following pytest conventions, best practices, and project standards. It creates comprehensive test suites with proper fixtures, mocking, parametrization, and coverage.
When to Use
- Generate pytest tests for Python modules
- Create test files for new Python features
- Add missing test coverage to existing Python code
- Need pytest-specific patterns (fixtures, markers, parametrize)
Test File Naming Convention
Source to Test Mapping:
- Source:
src/tools/feature/core.py
- Test:
tests/test_core.py
- Pattern:
test_<source_filename>.py
Examples:
src/utils/validator.py → tests/test_validator.py
src/models/user.py → tests/test_user.py
src/services/auth.py → tests/test_auth.py
Pytest Test Generation Workflow
1. Analyze Python Source Code
Read the source file:
cat src/tools/feature/core.py
Identify test targets:
- Public functions to test
- Classes and methods
- Error conditions
- Edge cases
- Dependencies (imports, external calls)
Output: List of functions/classes requiring tests
2. Generate Test File Structure
Create test file with proper naming:
"""
Unit tests for [module name].
This module tests:
- [Functionality 1]
- [Functionality 2]
- Error handling and edge cases
"""
import pytest
from unittest.mock import Mock, MagicMock, patch, call
from typing import Any, Dict, List, Optional
from pathlib import Path
from src.tools.feature.core import (
function_to_test,
ClassToTest,
CustomException,
)
@pytest.fixture
def sample_data() -> Dict[str, Any]:
"""
Sample data for testing.
Returns:
Dictionary with test data
"""
return {
"id": 1,
"name": "test",
"value": 123,
}
@pytest.fixture
def mock_dependency() -> Mock:
"""
Mock external dependency.
Returns:
Configured mock object
"""
mock = Mock()
mock.method.return_value = {"status": "success"}
mock.validate.return_value = True
return mock
@pytest.fixture
def temp_directory() -> Path:
test_dir = tmp_path /
test_dir.mkdir()
test_dir
:
():
instance = ClassToTest(param=)
instance.param ==
instance.initialized
():
instance = ClassToTest()
result = instance.method(sample_data)
result[]
result[] == sample_data[]
():
instance = ClassToTest()
invalid_data =
pytest.raises(ValueError, =):
instance.method(invalid_data)
():
expected =
result = function_to_test(sample_data)
result == expected
():
empty_input = {}
result = function_to_test(empty_input)
result == {}
():
invalid_input =
pytest.raises(ValueError, =):
function_to_test(invalid_input)
():
input_data = {: }
result = function_using_dependency(input_data, mock_dependency)
result[] ==
mock_dependency.method.assert_called_once_with(input_data)
():
mock_api.return_value = {: }
input_data = {: }
result = function_with_api(input_data)
result[] ==
mock_api.assert_called_once()
():
result = validate_input(input_value)
result == expected
():
user = {: user_type}
result = get_permissions(user)
result == permission
():
input_data = {: }
result = async_function(input_data)
result.success
result.data == input_data
():
mock_service = Mock()
mock_service.fetch = AsyncMock(return_value={: })
input_data = {: }
result = async_function_with_service(input_data, mock_service)
result[] ==
mock_service.fetch.assert_awaited_once()
():
invalid_input =
pytest.raises(CustomException):
function_that_raises(invalid_input)
():
invalid_input =
pytest.raises(CustomException, =):
function_that_raises(invalid_input)
():
invalid_input =
pytest.raises(CustomException) exc_info:
function_that_raises(invalid_input)
exc_info.value.code ==
exc_info.value.details
():
file_path = temp_directory /
content =
save_file(file_path, content)
file_path.exists()
file_path.read_text() == content
():
file_path = temp_directory /
expected_content =
file_path.write_text(expected_content)
content = read_file(file_path)
content == expected_content
():
missing_file = temp_directory /
pytest.raises(FileNotFoundError):
read_file(missing_file)
():
():
():
():
result = perform_expensive_setup()
result
cleanup(result)
():
result = setup()
result
teardown(result)
Deliverable: Complete pytest test file
Pytest-Specific Patterns
1. Fixtures
Basic fixture:
@pytest.fixture
def sample_user():
"""Create sample user for testing."""
return User(name="Test User", email="test@example.com")
Fixture with setup and teardown:
@pytest.fixture
def database_connection():
"""Database connection with cleanup."""
conn = connect_to_database()
yield conn
conn.close()
Fixture with parameters:
@pytest.fixture(params=["sqlite", "postgres", "mysql"])
def database_type(request):
"""Parametrized database fixture."""
return request.param
def test_with_all_databases(database_type):
"""Test runs 3 times, once per database."""
db = connect(database_type)
assert db.connected
Fixture scopes:
@pytest.fixture(scope="function")
def per_test():
pass
@pytest.fixture(scope="class")
def per_class():
pass
@pytest.fixture(scope="module")
def per_module():
pass
@pytest.fixture(scope="session")
def per_session():
pass
2. Parametrize
Basic parametrization:
@pytest.mark.parametrize("input,expected", [
(2, 4),
(3, 9),
(4, 16),
])
def test_square(input, expected):
assert square(input) == expected
Multiple parameters:
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(2, 3, 5),
(10, 20, 30),
])
def test_add(a, b, expected):
assert add(a, b) == expected
Named parameters:
@pytest.mark.parametrize("test_input,expected", [
pytest.param("valid", True, id="valid_input"),
pytest.param("invalid", False, id="invalid_input"),
pytest.param("", False, id="empty_input"),
])
def test_validation(test_input, expected):
assert validate(test_input) == expected
3. Markers
Built-in markers:
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
pass
@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_feature():
pass
@pytest.mark.xfail(reason="Known bug #123")
def test_buggy_feature():
pass
@pytest.mark.slow
def test_slow_operation():
pass
Custom markers (in pytest.ini):
[pytest]
markers =
slow: marks tests as slow
integration: marks tests as integration tests
unit: marks tests as unit tests
smoke: marks tests as smoke tests
4. Mocking with pytest
Mock with pytest-mock:
def test_with_mocker(mocker):
"""Test using pytest-mock plugin."""
mock_api = mocker.patch('module.api_call')
mock_api.return_value = {"status": "success"}
result = function_using_api()
assert result["status"] == "success"
mock_api.assert_called_once()
Mock attributes:
def test_mock_attributes(mocker):
"""Test with mocked object attributes."""
mock_obj = mocker.Mock()
mock_obj.property = "value"
mock_obj.method.return_value = 42
assert mock_obj.property == "value"
assert mock_obj.method() == 42
5. Async Testing
Async test:
@pytest.mark.asyncio
async def test_async_function():
"""Test async function."""
result = await async_function()
assert result.success
@pytest.mark.asyncio
async def test_async_with_mock(mocker):
"""Test async with mocked async call."""
mock_service = mocker.Mock()
mock_service.fetch = AsyncMock(return_value="data")
result = await function_with_async_call(mock_service)
assert result == "data"
mock_service.fetch.assert_awaited_once()
Test Generation Strategy
For Functions
- Happy path test: Normal successful execution
- Edge case tests: Empty input, max values, min values
- Error tests: Invalid input, None values
- Dependency tests: Mock external dependencies
For Classes
- Initialization tests: Valid params, invalid params
- Method tests: Each public method
- State tests: Verify state changes
- Property tests: Getters and setters
- Error tests: Exception handling
For Modules
- Import tests: Module can be imported
- Public API tests: All public functions/classes
- Integration tests: Module interactions
- Configuration tests: Config loading and validation
Running Pytest
Basic commands:
pytest
pytest tests/test_module.py
pytest tests/test_module.py::test_function
pytest -v
pytest --cov=src --cov-report=html --cov-report=term-missing
pytest -m "not slow"
pytest -m integration
pytest -n auto
pytest -s
pytest -v -s
Coverage commands:
pytest --cov=src --cov-report=html
open htmlcov/index.html
pytest --cov=src --cov-fail-under=80
pytest --cov=src --cov-report=term-missing
Best Practices
- Use descriptive test names:
test_function_condition_expected_result
- Follow AAA pattern: Arrange, Act, Assert
- One assertion per test (generally)
- Use fixtures for setup: Reusable test setup
- Mock external dependencies: Isolate unit under test
- Parametrize similar tests: Reduce code duplication
- Use markers for organization: Group related tests
- Keep tests independent: No test depends on another
- Test edge cases: Empty, None, max values
- Test error conditions: Exceptions and failures
Quality Checklist
Before marking tests complete:
Integration with Testing Workflow
Input: Python source file to test
Process: Analyze → Generate structure → Write tests → Run & verify
Output: pytest test file with ≥ 80% coverage
Next Step: Integration testing or code review
Remember
- Follow naming convention:
test_<source_file>.py
- Use pytest fixtures for reusable setup
- Parametrize to reduce duplication
- Mock external calls to isolate tests
- Test behavior, not implementation
- Aim for 80%+ coverage
- Keep tests fast and independent
Source: ForceInjection/domain-driven-design-skills — distributed by TomeVault.