Best Practices
Assertion Strategy Overview
graph TD
A[Assertion Best Practices] --> B[Clear Messages]
A --> C[Specific Checks]
A --> D[Performance]
A --> E[Error Handling]
A --> F[Test Coverage]
Writing Effective Assertions
1. Provide Meaningful Error Messages
def calculate_percentage(value, total):
assert total > 0, f"Total must be positive, got {total}"
assert 0 <= value <= total, f"Invalid value: {value} outside range 0-{total}"
return (value / total) * 100
2. Be Specific in Assertions
Bad Practice |
Good Practice |
assert result |
assert result is not None, "Result cannot be None" |
assert len(data) |
assert len(data) > 0, "Data list must contain elements" |
3. Use Appropriate Assertion Methods
import math
def test_mathematical_operations():
## Prefer specific assertions
assert math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9), "Floating point comparison"
## Type-specific checks
assert isinstance(result, list), "Result must be a list"
Assertion Overhead
def optimize_assertions():
## Use assertions for development, not production
## Python -O flag can disable assertions
assert critical_condition(), "Critical check during development"
Error Handling Strategies
def robust_function(data):
try:
## Validate input
assert data is not None, "Input data cannot be None"
assert isinstance(data, list), "Input must be a list"
## Process data
return process_data(data)
except AssertionError as e:
## Log and handle specific assertion errors
log_error(str(e))
raise
LabEx Testing Recommendations
When practicing assertion techniques, LabEx suggests:
- Write assertions before implementation
- Cover edge cases
- Use parameterized testing
- Maintain clear, concise test cases
Advanced Assertion Techniques
Custom Assertion Functions
def assert_between(value, lower, upper, message=None):
"""Custom assertion to check value range"""
default_msg = f"{value} not between {lower} and {upper}"
assert lower <= value <= upper, message or default_msg
## Usage
assert_between(5, 1, 10) ## Passes
assert_between(15, 1, 10) ## Raises AssertionError
Common Pitfalls to Avoid
- Don't use assertions for runtime error checking
- Avoid complex logic within assertions
- Keep assertions simple and focused
- Use appropriate testing frameworks
Assertion Configuration
## Python assertion configuration
import sys
## Disable assertions in optimized mode
if not sys.flags.optimize:
## Assertions are active
assert critical_condition(), "Development-time check"
By following these best practices, developers can create more robust, maintainable, and effective test suites in Python.