Pins this version in aipm.package.json and aipm-lock.json.
aipm add @affaan-m/python-testing@1.0.0
Without project tracking
Writes the skill files only. Add --no-init to skip aipm.package.json and the lockfile.
aipm add @affaan-m/python-testing@1.0.0 --no-init
How to use
Install the skill above, then run this in your AI tool:
/python-testing <your description>
About
Comprehensive testing strategies for Python applications using pytest, TDD methodology, and best practices.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
Python testing strategies using pytest, TDD methodology, fixtures, mocking, parametrization, and coverage requirements. Use when writing pytest tests — fixtures, mocks, parametrization, or coverage.
Skill instructions
Python Testing Patterns
Comprehensive testing strategies for Python applications using pytest, TDD methodology, and best practices.
When to Activate
Writing new Python code (follow TDD: red, green, refactor)
Designing test suites for Python projects
Reviewing Python test coverage
Setting up testing infrastructure
Core Testing Philosophy
Test-Driven Development (TDD)
Always follow the TDD cycle:
RED: Write a failing test for the desired behavior
GREEN: Write minimal code to make the test pass
REFACTOR: Improve code while keeping tests green
python
# Step 1: Write failing test (RED)deftest_add_numbers():
result = add(2, 3)
assert result == 5# Step 2: Write minimal implementation (GREEN)defadd(a, b):
return a + b
# Step 3: Refactor if needed (REFACTOR)
@pytest.fixturedefdatabase():
"""Fixture with setup and teardown."""# Setup
db = Database(":memory:")
db.create_tables()
db.insert_test_data()
yield db # Provide to test# Teardown
db.close()
deftest_database_query(database):
"""Test database operations."""
result = database.query("SELECT * FROM users")
assertlen(result) > 0
Fixture Scopes
python
# Function scope (default) - runs for each test@pytest.fixturedeftemp_file():
withopen("temp.txt", "w") as f:
yield f
os.remove("temp.txt")
# Module scope - runs once per module@pytest.fixture(scope="module")defmodule_db():
db = Database(":memory:")
db.create_tables()
yield db
db.close()
# Session scope - runs once per test session@pytest.fixture(scope="session")defshared_resource():
resource = ExpensiveResource()
yield resource
resource.cleanup()
Fixture with Parameters
python
@pytest.fixture(params=[1, 2, 3])defnumber(request):
"""Parameterized fixture."""return request.param
deftest_numbers(number):
"""Test runs 3 times, once for each parameter."""assert number > 0
@pytest.mark.parametrize("input,expected", [
("valid@email.com", True),
("invalid", False),
("@no-domain.com", False),
], ids=["valid-email", "missing-at", "missing-domain"])deftest_email_validation(input, expected):
"""Test email validation with readable test IDs."""assert is_valid_email(input) is expected
Parametrized Fixtures
python
@pytest.fixture(params=["sqlite", "postgresql", "mysql"])defdb(request):
"""Test against multiple database backends."""if request.param == "sqlite":
return Database(":memory:")
elif request.param == "postgresql":
return Database("postgresql://localhost/test")
elif request.param == "mysql":
return Database("mysql://localhost/test")
deftest_database_operations(db):
"""Test runs 3 times, once for each database."""
result = db.query("SELECT 1")
assert result isnotNone
Markers and Test Selection
Custom Markers
python
# Mark slow tests@pytest.mark.slowdeftest_slow_operation():
time.sleep(5)
# Mark integration tests@pytest.mark.integrationdeftest_api_integration():
response = requests.get("https://api.example.com")
assert response.status_code == 200# Mark unit tests@pytest.mark.unitdeftest_unit_logic():
assert calculate(2, 3) == 5
Run Specific Tests
bash
# Run only fast tests
pytest -m "not slow"# Run only integration tests
pytest -m integration
# Run integration or slow tests
pytest -m "integration or slow"# Run tests marked as unit but not slow
pytest -m "unit and not slow"
Configure Markers in pytest.ini
ini
[pytest]markers =
slow: marks tests as slow
integration: marks tests as integration tests
unit: marks tests as unit tests
django: marks tests as requiring Django
Mocking and Patching
Mocking Functions
python
from unittest.mock import patch, Mock
@patch("mypackage.external_api_call")deftest_with_mock(api_call_mock):
"""Test with mocked external API."""
api_call_mock.return_value = {"status": "success"}
result = my_function()
api_call_mock.assert_called_once()
assert result["status"] == "success"
Mocking Return Values
python
@patch("mypackage.Database.connect")deftest_database_connection(connect_mock):
"""Test with mocked database connection."""
connect_mock.return_value = MockConnection()
db = Database()
db.connect()
connect_mock.assert_called_once_with("localhost")
Mocking Exceptions
python
@patch("mypackage.api_call")deftest_api_error_handling(api_call_mock):
"""Test error handling with mocked exception."""
api_call_mock.side_effect = ConnectionError("Network error")
with pytest.raises(ConnectionError):
api_call()
api_call_mock.assert_called_once()
Mocking Context Managers
python
@patch("builtins.open", new_callable=mock_open)deftest_file_reading(mock_file):
"""Test file reading with mocked open."""
mock_file.return_value.read.return_value = "file content"
result = read_file("test.txt")
mock_file.assert_called_once_with("test.txt", "r")
assert result == "file content"
Using Autospec
python
@patch("mypackage.DBConnection", autospec=True)deftest_autospec(db_mock):
"""Test with autospec to catch API misuse."""
db = db_mock.return_value
db.query("SELECT * FROM users")
# This would fail if DBConnection doesn't have query method
db_mock.assert_called_once()
Mock Class Instances
python
classTestUserService:
@patch("mypackage.UserRepository")deftest_create_user(self, repo_mock):
"""Test user creation with mocked repository."""
repo_mock.return_value.save.return_value = User(id=1, name="Alice")
service = UserService(repo_mock.return_value)
user = service.create_user(name="Alice")
assert user.name == "Alice"
repo_mock.return_value.save.assert_called_once()
Mock Property
python
@pytest.fixturedefmock_config():
"""Create a mock with a property."""
config = Mock()
type(config).debug = PropertyMock(return_value=True)
type(config).api_key = PropertyMock(return_value="test-key")
return config
deftest_with_mock_config(mock_config):
"""Test with mocked config properties."""assert mock_config.debug isTrueassert mock_config.api_key == "test-key"
Testing Async Code
Async Tests with pytest-asyncio
python
import pytest
@pytest.mark.asyncioasyncdeftest_async_function():
"""Test async function."""
result = await async_add(2, 3)
assert result == 5@pytest.mark.asyncioasyncdeftest_async_with_fixture(async_client):
"""Test async with async fixture."""
response = await async_client.get("/api/users")
assert response.status_code == 200
Async Fixture (FastAPI)
ASGITransport does not run lifespan events. Install asgi-lifespan and wrap the client in LifespanManager when the app uses startup or shutdown handlers. See FastAPI's async testing guidance.
python
import pytest
import pytest_asyncio
from asgi_lifespan import LifespanManager
from httpx import ASGITransport, AsyncClient
@pytest_asyncio.fixtureasyncdefasync_client():
"""Async fixture providing async test client with lifespan events."""
app = create_app() # Returns a FastAPI applicationasyncwith LifespanManager(app) as manager:
asyncwith AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://test") as client:
yield client
@pytest.mark.asyncioasyncdeftest_api_endpoint(async_client):
"""Test using async fixture."""
response = await async_client.get("/api/data")
assert response.status_code == 200
Mocking Async Functions
python
@pytest.mark.asyncio@patch("mypackage.async_api_call")asyncdeftest_async_mock(api_call_mock):
"""Test async function with mock."""
api_call_mock.return_value = {"status": "ok"}
result = await my_async_function()
api_call_mock.assert_awaited_once()
assert result["status"] == "ok"
Testing Exceptions
Testing Expected Exceptions
python
deftest_divide_by_zero():
"""Test that dividing by zero raises ZeroDivisionError."""with pytest.raises(ZeroDivisionError):
divide(10, 0)
deftest_custom_exception():
"""Test custom exception with message."""with pytest.raises(ValueError, match="invalid input"):
validate_input("invalid")
Testing Exception Attributes
python
deftest_exception_with_details():
"""Test exception with custom attributes."""with pytest.raises(CustomError) as exc_info:
raise CustomError("error", code=400)
assert exc_info.value.code == 400assert"error"instr(exc_info.value)
Testing Side Effects
Testing File Operations
python
import tempfile
import os
deftest_file_processing():
"""Test file processing with temp file."""with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
f.write("test content")
temp_path = f.name
try:
result = process_file(temp_path)
assert result == "processed: test content"finally:
os.unlink(temp_path)
Testing with pytest's tmp_path Fixture
python
deftest_with_tmp_path(tmp_path):
"""Test using pytest's built-in temp path fixture."""
test_file = tmp_path / "test.txt"
test_file.write_text("hello world")
result = process_file(str(test_file))
assert result == "hello world"# tmp_path automatically cleaned up
Testing with tmpdir Fixture
python
deftest_with_tmpdir(tmpdir):
"""Test using pytest's tmpdir fixture."""
test_file = tmpdir.join("test.txt")
test_file.write("data")
result = process_file(str(test_file))
assert result == "data"
classTestUserService:
"""Group related tests in a class.""" @pytest.fixture(autouse=True)defsetup(self):
"""Setup runs before each test in this class."""self.service = UserService()
deftest_create_user(self):
"""Test user creation."""
user = self.service.create_user("Alice")
assert user.name == "Alice"deftest_delete_user(self):
"""Test user deletion."""
user = User(id=1, name="Bob")
self.service.delete_user(user)
assertnotself.service.user_exists(1)
Best Practices
DO
Follow TDD: Write tests before code (red-green-refactor)
Test one thing: Each test should verify a single behavior
Use descriptive names: test_user_login_with_invalid_credentials_fails
Use fixtures: Eliminate duplication with fixtures
Mock external dependencies: Don't depend on external services
Test edge cases: Empty inputs, None values, boundary conditions
Aim for 80%+ coverage: Focus on critical paths
Keep tests fast: Use marks to separate slow tests
DON'T
Don't test implementation: Test behavior, not internals
Don't use complex conditionals in tests: Keep tests simple
Don't ignore test failures: All tests must pass
Don't test third-party code: Trust libraries to work
Don't share state between tests: Tests should be independent
Don't catch exceptions in tests: Use pytest.raises
Don't use print statements: Use assertions and pytest output
Don't write tests that are too brittle: Avoid over-specific mocks
[pytest]testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts =
--strict-markers
--disable-warnings
--cov=mypackage
--cov-report=term-missing
--cov-report=html
markers =
slow: marks tests as slow
integration: marks tests as integration tests
unit: marks tests as unit tests
pyproject.toml
toml
[tool.pytest.ini_options]testpaths = ["tests"]
python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
addopts = [
"--strict-markers",
"--cov=mypackage",
"--cov-report=term-missing",
"--cov-report=html",
]
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration tests",
"unit: marks tests as unit tests",
]
Running Tests
bash
# Run all tests
pytest
# Run specific file
pytest tests/test_utils.py
# Run specific test
pytest tests/test_utils.py::test_function
# Run with verbose output
pytest -v
# Run with coverage
pytest --cov=mypackage --cov-report=html
# Run only fast tests
pytest -m "not slow"# Run until first failure
pytest -x
# Run and stop on N failures
pytest --maxfail=3
# Run last failed tests
pytest --lf
# Run tests with pattern
pytest -k "test_user"# Run with debugger on failure
pytest --pdb
Quick Reference
Pattern
Usage
pytest.raises()
Test expected exceptions
@pytest.fixture()
Create reusable test fixtures
@pytest.mark.parametrize()
Run tests with multiple inputs
@pytest.mark.slow
Mark slow tests
pytest -m "not slow"
Skip slow tests
@patch()
Mock functions and classes
tmp_path fixture
Automatic temp directory
pytest --cov
Generate coverage report
assert
Simple and readable assertions
Remember: Tests are code too. Keep them clean, readable, and maintainable. Good tests catch bugs; great tests prevent them.
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/affaan-m/python-testing/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@affaan-m/python-testing@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: Python testing strategies using pytest, TDD methodology, fixtures, mocking, parametrization, and coverage requirements. Use when writing pytest tests — fixtures, mocks, parametrization, or coverage.
Preview a UI component mockup in a local browser canvas where the human directly edits it (move, resize, edit text, delete, restyle), switches mobile/desktop/custom viewports, tests it, chats with you, and clicks Save and Finish. You the...
Run aipm add @affaan-m/python-testing@1.0.0 in a project that has AIPM initialized.
Supported tools
@affaan-m/python-testing@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.