Practical Test Examples
Testing Simple Functions
Basic Arithmetic Function
def calculate_area(length, width):
return length * width
def test_calculate_area():
assert calculate_area(4, 5) == 20
assert calculate_area(0, 10) == 0
assert calculate_area(-2, 3) == -6
Testing String Manipulation
def reverse_string(text):
return text[::-1]
def test_reverse_string():
assert reverse_string("hello") == "olleh"
assert reverse_string("") == ""
assert reverse_string("12345") == "54321"
Exception Handling Tests
def divide_numbers(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
def test_divide_numbers():
assert divide_numbers(10, 2) == 5
import pytest
with pytest.raises(ValueError):
divide_numbers(10, 0)
Testing Complex Data Structures
def filter_even_numbers(numbers):
return [num for num in numbers if num % 2 == 0]
def test_filter_even_numbers():
assert filter_even_numbers([1, 2, 3, 4, 5, 6]) == [2, 4, 6]
assert filter_even_numbers([]) == []
assert filter_even_numbers([1, 3, 5]) == []
Testing Class Methods
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def test_calculator():
calc = Calculator()
assert calc.add(3, 4) == 7
assert calc.subtract(10, 5) == 5
Parametrized Testing
import pytest
@pytest.mark.parametrize("input_list,expected", [
([1, 2, 3], 6),
([], 0),
([-1, 1, 0], 0)
])
def test_sum_list(input_list, expected):
assert sum(input_list) == expected
Test Coverage Analysis
graph TD
A[Test Coverage] --> B[Statement Coverage]
A --> C[Branch Coverage]
A --> D[Function Coverage]
A --> E[Line Coverage]
Practical Testing Strategies
Strategy |
Description |
Example |
Boundary Testing |
Test edge cases |
Test with min/max values |
Equivalence Partitioning |
Divide input into valid/invalid groups |
Test representative values |
Error Guessing |
Anticipate potential errors |
Test error handling |
LabEx Tip
LabEx provides interactive environments that help you practice writing comprehensive and effective unit tests.
Best Practices
- Test both positive and negative scenarios
- Use meaningful test names
- Keep tests independent
- Test edge cases
- Aim for high test coverage