Python Testing with Pytest
Write tests for Python code using pytest.
Test your code properly.
Install Pytest
```bash pip install pytest ```
Basic Test
```python # test_math.py def add(a, b): return a + b
def test_add(): assert add(2, 3) == 5 assert add(0, 0) == 0 assert add(-1, 1) == 0
Run: pytest test_math.py ```
Test Class
```python # test_calculator.py class Calculator: def add(self, a, b): return a + b def multiply(self, a, b): return a * b
def test_calculator(): calc = Calculator() assert calc.add(2, 3) == 5 assert calc.multiply(2, 3) == 6 ```
Fixtures
```python import pytest
@pytest.fixture def sample_data(): return [1, 2, 3, 4, 5]
def test_sum(sample_data): assert sum(sample_data) == 15
def test_length(sample_data): assert len(sample_data) == 5 ```
Parametrize Tests
```python import pytest
def is_even(n): return n % 2 == 0
@pytest.mark.parametrize("number,expected", [ (2, True), (3, False), (4, True), (5, False) ]) def test_is_even(number, expected): assert is_even(number) == expected ```
Test Exceptions
```python import pytest
def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b
def test_divide_by_zero(): with pytest.raises(ValueError): divide(10, 0) ```
Mock Objects
```python from unittest.mock import Mock
def get_user_data(api): return api.fetch_user(123)
def test_get_user_data(): mock_api = Mock() mock_api.fetch_user.return_value = {"name": "Tom"} result = get_user_data(mock_api) assert result["name"] == "Tom" ```
Remember
- Write tests for all functions - Use fixtures for setup - Test edge cases - Run tests often