Covers unit, integration, functional, and performance testing with the AAA pattern (Arrange, Act, Assert) for test structure
Includes 10 fundamental and advanced patterns: basic tests, fixtures with setup/teardown, parameterization, mocking, exception handling, async testing, monkeypatching, temporary files, custom fixtures, and property-based testing
Confirm successful installation by checking the skill directory location:
.cursor/skills/python-testing-patterns
Restart Cursor to activate python-testing-patterns. Access via /python-testing-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.
Comprehensive guide to implementing robust testing strategies in Python using pytest, fixtures, mocking, parameterization, and test-driven development practices.
When to Use This Skill
Writing unit tests for Python code
Setting up test suites and test infrastructure
Implementing test-driven development (TDD)
Creating integration tests for APIs and services
Mocking external dependencies and services
Testing async code and concurrent operations
Setting up continuous testing in CI/CD
Implementing property-based testing
Testing database operations
Debugging failing tests
Core Concepts
1. Test Types
Unit Tests: Test individual functions/classes in isolation
Integration Tests: Test interaction between components
Functional Tests: Test complete features end-to-end
Performance Tests: Measure speed and resource usage
2. Test Structure (AAA Pattern)
Arrange: Set up test data and preconditions
Act: Execute the code under test
Assert: Verify the results
3. Test Coverage
Measure what code is exercised by tests
Identify untested code paths
Aim for meaningful coverage, not just high percentages
4. Test Isolation
Tests should be independent
No shared state between tests
Each test should clean up after itself
Quick Start
# test_example.pydefadd(a, b):return a + b
deftest_add():"""Basic test example.""" result = add(2,3)assert result ==5deftest_add_negative():"""Test with negative numbers."""assert add(-1,1)==0# Run with: pytest test_example.py
Fundamental Patterns
Pattern 1: Basic pytest Tests
# test_calculator.pyimport pytest
classCalculator:"""Simple calculator for testing."""defadd(self, a:float, b:float)->float:return a + b
defsubtract(self, a:float, b:float)->float:return a - b
defmultiply(self, a:float, b:float)->float:return a * b
defdivide(self, a:float, b:float)->float:if b ==0:raise ValueError("Cannot divide by zero")return a / b
deftest_addition():"""Test addition.""" calc = Calculator()assert calc.add(2,3)==5assert calc.add(-1,1)==0assert calc.add(0,0)==0deftest_subtraction():"""Test subtraction.""" calc = Calculator()assert calc.subtract(5,3)==2assert calc.subtract(0,5)==-5deftest_multiplication():"""Test multiplication.""" calc = Calculator()assert calc.multiply(3,4)==12assert calc.multiply(0,5)==0deftest_division():"""Test division.""" calc = Calculator()assert calc.divide(6,3)==2assert calc.divide(5,2)==2.5deftest_division_by_zero():"""Test division by zero raises error.""" calc = Calculator()with pytest.raises(ValueError,match="Cannot divide by zero"): calc.divide(5,0)
Pattern 2: Fixtures for Setup and Teardown
# test_database.pyimport pytest
from typing import Generator
classDatabase:"""Simple database class."""def__init__(self, connection_string:str): self.connection_string = connection_string
self.connected =Falsedefconnect(self):"""Connect to database.""" self.connected =Truedefdisconnect(self):"""Disconnect from database.""" self.connected =Falsedefquery(self, sql:str)->list:"""Execute query."""ifnot self.connected:raise RuntimeError("Not connected")return[{"id":1,"name":"Test"}]@pytest.fixturedefdb()-> Generator[Database,None,None]:"""Fixture that provides connected database."""# Setup database = Database("sqlite:///:memory:") database.connect()# Provide to testyield database
# Teardown database.disconnect()deftest_database_query(db):"""Test database query with fixture.""" results = db.query("SELECT * FROM users")assertlen(results)==1assert results[0]["name"]=="Test"@pytest.fixture(scope="session")defapp_config():"""Session-scoped fixture - created once per test session."""return{"database_url":"postgresql://localhost/test",
Implementation Guide
Prerequisites
โบ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