7 min read
ā¢Question 38 of 41hardTesting in Python
Unit testing and mocking patterns.
Testing in Python
Pytest Basics
code.pyPython
# test_calculator.py
import pytest
from calculator import add, divide
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_divide():
assert divide(10, 2) == 5
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(10, 0)Fixtures
code.pyPython
import pytest
@pytest.fixture
def sample_user():
return {"name": "Alice", "age": 30}
@pytest.fixture
def db_connection():
conn = create_connection()
yield conn # Provide to test
conn.close() # Cleanup after test
def test_user_name(sample_user):
assert sample_user["name"] == "Alice"
def test_database(db_connection):
result = db_connection.query("SELECT 1")
assert result is not NoneMocking
code.pyPython
from unittest.mock import Mock, patch, MagicMock
# Basic mock
mock = Mock()
mock.method.return_value = 42
assert mock.method() == 42
# Patch decorator
@patch('module.external_api')
def test_api_call(mock_api):
mock_api.return_value = {"status": "ok"}
result = call_api()
assert result["status"] == "ok"
mock_api.assert_called_once()
# Context manager
def test_file_read():
with patch('builtins.open', mock_open(read_data='hello')):
with open('test.txt') as f:
assert f.read() == 'hello'Parametrized Tests
code.pyPython
import pytest
@pytest.mark.parametrize("input,expected", [
(2, 4),
(3, 9),
(4, 16),
(-2, 4),
])
def test_square(input, expected):
assert input ** 2 == expected
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(0, 0, 0),
(-1, 1, 0),
])
def test_add(a, b, expected):
assert add(a, b) == expectedAsync Testing
code.pyPython
import pytest
import asyncio
@pytest.mark.asyncio
async def test_async_function():
result = await async_operation()
assert result == "expected"