📡 You're offline — showing cached content
New version available!
Quick Access
Python Intermediate

Python Testing with pytest: Fixtures, Mocking and Coverage

Master pytest — writing tests, fixtures for setup, parametrize for data-driven tests, patch for mocking dependencies, and coverage reporting.

EzyCoders Admin December 11, 2025 11 min read 1 views
Python Testing pytest Fixtures Mocking Guide
Share: Twitter LinkedIn WhatsApp

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.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment