A comprehensive skill for mastering Python testing with pytest. This skill covers everything from basic test structure to advanced patterns including fixtures, parametrization, mocking, test organization, coverage analysis, and CI/CD integration.
Confirm successful installation by checking the skill directory location:
.cursor/skills/pytest-patterns
Restart Cursor to activate pytest-patterns. Access via /pytest-patterns in your agent's command palette.
โ
Security Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your environment. Always review source, verify the publisher, and test in isolation before production.
A comprehensive skill for mastering Python testing with pytest. This skill covers everything from basic test structure to advanced patterns including fixtures, parametrization, mocking, test organization, coverage analysis, and CI/CD integration.
Setting up test infrastructure for a new Python project
Refactoring existing tests to be more maintainable and efficient
Implementing test-driven development (TDD) workflows
Creating fixture patterns for database, API, or external service testing
Organizing large test suites with hundreds or thousands of tests
Debugging failing tests or improving test reliability
Setting up continuous integration testing pipelines
Measuring and improving code coverage
Writing integration, unit, or end-to-end tests
Testing async Python code
Mocking external dependencies and services
Core Concepts
What is pytest?
pytest is a mature, full-featured Python testing framework that makes it easy to write simple tests, yet scales to support complex functional testing. It provides:
Simple syntax: Use plain assert statements instead of special assertion methods
Powerful fixtures: Modular, composable test setup and teardown
Parametrization: Run the same test with different inputs
Plugin ecosystem: Hundreds of plugins for extended functionality
Detailed reporting: Clear failure messages and debugging information
Test discovery: Automatic test collection following naming conventions
pytest automatically discovers tests by following these conventions:
Test files: test_*.py or *_test.py
Test functions: Functions prefixed with test_
Test classes: Classes prefixed with Test (no __init__ method)
Test methods: Methods prefixed with test_ inside Test classes
Fixtures - The Heart of pytest
What are Fixtures?
Fixtures provide a fixed baseline for tests to run reliably and repeatably. They handle setup, provide test data, and perform cleanup.
Basic Fixture Pattern
import pytest
@pytest.fixturedefsample_data():"""Provides sample data for testing."""return{"name":"Alice","age":30}deftest_data_access(sample_data):assert sample_data["name"]=="Alice"assert sample_data["age"]==30
Fixture Scopes
Fixtures can have different scopes controlling how often they're created:
function (default): Created for each test function
class: Created once per test class
module: Created once per test module
package: Created once per test package
session: Created once per test session
@pytest.fixture(scope="session")defdatabase_connection():"""Database connection created once for entire test session.""" conn = create_db_connection()yield conn
conn.close()# Cleanup after all tests@pytest.fixture(scope="module")defapi_client():"""API client created once per test module.""" client = APIClient() client.authenticate()yield client
client.logout()@pytest.fixture# scope="function" is defaultdeftemp_file():"""Temporary file created for each test."""import tempfile
f = tempfile.NamedTemporaryFile(mode='w', delete=False)yield f.name
os.unlink(f.name)
Fixture Dependencies
Fixtures can depend on other fixtures, creating a dependency graph:
@pytest.fixturedefdatabase(): db = Database() db.connect()yield db
db.disconnect()@pytest.fixturedefuser_repository(database):"""Depends on database fixture."""return UserRepository(database)@pytest.fixturedefsample_user(user_repository):"""Depends on user_repository, which depends on database.""" user = user_repository.create(name="Test User")yield user
user_repository.delete(user.id)deftest_user_operations(sample_user):"""Uses sample_user fixture (which uses user_repository and database)."""assert sample_user.name =="Test User"
Autouse Fixtures
Fixtures that run automatically without being explicitly requested:
@pytest.fixture(autouse=True)defreset_database():"""Runs before every test automatically.""" clear_database() seed_test_data()@pytest.fixture(autouse=True, scope="session")defconfigure_logging():"""Configure logging once for entire test session."""import logging
logging.basicConfig(level=logging.DEBUG)
Fixture Factories
Fixtures that return functions for creating test data:
@pytest.fixturedefmake_user():"""Factory fixture for creating users.""" users =[]def_make_user(name, email=None): user = User(name=name, email=email orf"{name}@example.com") users.append(user)return user
yield _make_user
# Cleanup all created usersfor user in users: user.delete()deftest_multiple_users(make_user): user1 = make_user("Alice") user2 = make_user("Bob", email="[email protected]")assert user1.name =="Alice"assert user2.email =="[email protected]"
โบClaude Desktop or compatible AI client with skill support
โบClear understanding of task or problem to solve
โบWillingness to iterate and refine outputs
Time Estimate
15-45 minutes depending on use case complexity
Steps
1Install skill using provided installation command
2Test with simple use case relevant to your work
3Evaluate output quality and relevance
4Iterate on prompts to improve results
5Integrate into regular workflow if valuable
Common Pitfalls
โ Expecting perfect results without iteration
โ Not providing enough context in prompts
โ Using skill for tasks outside its intended scope
โ Accepting outputs without review and validation
Best Practices
โ Do
+Start with clear, specific prompts
+Provide relevant context and constraints
+Review and refine all outputs before using
+Iterate to improve output quality
+Document successful prompt patterns
โ Don't
โDon't use without understanding skill limitations
โDon't skip validation of outputs
โDon't share sensitive information in prompts
โDon't expect skill to replace human judgment
๐ก Pro Tips
โ Be specific about desired format and style
โ Ask for multiple options to choose from
โ Request explanations to understand reasoning
โ Combine AI efficiency with human expertise
When to Use This
โ Use when
Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.
โ Avoid when
Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.
Learning Path
1Familiarize yourself with skill capabilities and limitations
2Start with low-risk, non-critical tasks
3Progress to more complex and valuable use cases
4Build expertise through regular use and experimentation