Python Testing with pytest
pytest is the most popular Python testing framework. More concise than unittest, with excellent fixture support and parametrization.
def test_addition():
assert 2 + 2 == 4
def test_raises():
import pytest
with pytest.raises(ValueError, match="invalid"):
validate_email("not-an-email")
Fixtures
import pytest
@pytest.fixture
def sample_user():
return {'id': 1, 'name': 'Rahul', 'email': 'r@e.com', 'active': True}
@pytest.fixture
def db():
connection = create_test_db()
yield connection
connection.close()
def test_user_is_active(sample_user):
assert sample_user['active'] is True
def test_user_in_db(db, sample_user):
db.insert('users', sample_user)
result = db.find('users', id=1)
assert result['name'] == 'Rahul'
Parametrize and Mocks
import pytest
from unittest.mock import patch
@pytest.mark.parametrize("email,valid", [
("rahul@example.com", True),
("bad-email", False),
("@nodomain.com", False),
])
def test_email_validation(email, valid):
assert validate_email(email) == valid
def test_send_email():
with patch('myapp.services.send_email') as mock_send:
mock_send.return_value = True
result = UserService.register({'name': 'Rahul', 'email': 'r@e.com'})
mock_send.assert_called_once_with('r@e.com', subject='Welcome!')
pytest -v # verbose
pytest -k "test_user" # run matching tests
pytest --cov=myapp --cov-report=html # coverage report
Q: Mock vs Stub?
A stub provides hardcoded return values to isolate the system under test. A mock additionally records calls and verifies interactions (assert_called_once). Use stubs when you only care about output; use mocks when you also care about whether and how a function was called.
Comments (0)
No comments yet. Be the first!
Leave a Comment