100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogTesting Python Code with pytest: A Beginner's Guide
Programming

Testing Python Code with pytest: A Beginner's Guide

SV

SkillVeris Team

Engineering Team

May 22, 2026 10 min read
Share:
Testing Python Code with pytest: A Beginner's Guide
Key Takeaway

A pytest test is any function whose name starts with test_, using plain assert statements to verify outcomes.

In this guide, you'll learn:

  • Use fixtures for shared setup, parametrize to test many inputs with one function, and mock to replace external dependencies.
  • Run pytest --cov to see exactly which lines of your code are untested.
  • Test exceptions with pytest.raises to assert that the expected error is raised.
  • Fixtures are injected by name and can include teardown logic via yield.

1Why Testing Matters

Without tests, every code change is a risk. Tests let you refactor confidently, catch regressions before they reach users, document expected behaviour, and ship faster because you spend less time debugging in production. The investment pays back within the first bug a test catches.

Python has two testing frameworks: the built-in unittest (verbose, class-based) and pytest (concise, function-based, much more popular). This guide covers pytest — it's what most Python projects use in 2026.

2Installing pytest

Install pytest into your virtual environment and verify the version. For any non-trivial project, add a few common plugins that extend its capabilities.

  • pytest-cov — Coverage reporting
  • pytest-mock — Convenient mocking via the mocker fixture
  • pytest-asyncio — Test async functions
  • pytest-httpx — Mock httpx requests in tests
  • freezegun — Freeze time.time() in tests

Install and Verify

Install pytest with coverage support and confirm it works.

code
# In your virtual environment
pip install pytest pytest-cov
# Verify
pytest --version

3Your First Test

Write the code you want to test, then create a matching test file. Key conventions: test files must be named test_*.py or *_test.py; test functions must start with test_; and assertions use plain assert. pytest introspects the assertion to show you exactly what values failed.

The four pytest features that make it the preferred testing framework in Python: plain assert, fixtures, parametrize, and plugins.
The four pytest features that make it the preferred testing framework in Python: plain assert, fixtures, parametrize, and plugins.

calculator.py

A small module with one normal path and one that raises.

code
def add(a: float, b: float) -> float:
    return a + b
def divide(a: float, b: float) -> float:
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b

test_calculator.py

Each test function starts with test_ and uses a plain assert.

code
from calculator import add, divide
import pytest
def test_add_two_positives():
    assert add(2, 3) == 5
def test_add_negative_numbers():
    assert add(-1, -2) == -3
def test_add_floats():
    assert add(0.1, 0.2) == pytest.approx(0.3)  # floating point!

4Running Tests

pytest discovers and runs your tests with a single command, and a range of flags let you narrow or expand a run. A passing test shows as ., a failure as F, and a skipped test as s; pytest prints a detailed failure message showing the exact line, the values on both sides of the assertion, and the diff.

Common Commands

From running everything to targeting a single test function.

code
# Run all tests in current directory and subdirectories
pytest
# Verbose output (shows each test name)
pytest -v
# Run a specific file
pytest test_calculator.py
# Run a specific test function
pytest test_calculator.py::test_add_two_positives
# Stop at first failure
pytest -x
# Show print statements during tests
pytest -s
# Run tests matching a keyword
pytest -k "add"

5Testing Edge Cases and Exceptions

pytest.raises(ExceptionClass) asserts that the code inside the with block raises that specific exception. The match parameter checks that the error message matches a pattern. If the exception is NOT raised, the test fails.

Asserting Exceptions

Verify that error conditions raise the right exception.

code
def test_divide_normal():
    assert divide(10, 2) == 5.0
def test_divide_by_zero():
    # Test that the expected exception is raised
    with pytest.raises(ZeroDivisionError, match="Cannot divide by zero"):
        divide(10, 0)
def test_add_strings_raises_type_error():
    with pytest.raises(TypeError):
        add("a", 1)

6Fixtures: Shared Setup

Fixtures are functions that set up shared test data or state. They're injected into test functions simply by naming them as parameters, and they run before each test that requests them.

Fixtures can set up databases, create test files, or initialise FastAPI test clients. Add teardown code using yield — anything after the yield runs once the test finishes.

A Simple Fixture

pytest injects the fixture's return value by parameter name.

code
import pytest
from calculator import add
@pytest.fixture
def sample_numbers():
    return [1, 2, 3, 4, 5]
def test_sum_of_samples(sample_numbers):
    # pytest injects sample_numbers automatically
    total = sum(sample_numbers)
    assert total == 15
def test_max_of_samples(sample_numbers):
    assert max(sample_numbers) == 5

Fixtures with Teardown

yield separates setup from teardown; tmp_path is a built-in fixture.

code
@pytest.fixture
def tmp_file(tmp_path):
    f = tmp_path / "test.txt"
    f.write_text("hello")
    yield f
    # teardown: file is automatically deleted (tmp_path is a pytest built-in)

7Parametrize: Testing Many Inputs

Instead of writing a separate test function for each input combination, use @pytest.mark.parametrize. This creates several separate tests from one function, and pytest names them automatically (test_add_parametrized[2-3-5], and so on) so each runs and reports independently.

💡Pro Tip

Write parametrized tests for edge cases: empty string, zero, negative numbers, very large values, None, and Unicode input. The parametrize decorator makes it trivial to add new cases as you discover them.

One Function, Many Cases

Each tuple becomes its own independently reported test.

code
@pytest.mark.parametrize("a, b, expected", [
    (2, 3, 5),
    (0, 0, 0),
    (-1, 1, 0),
    (100, 200, 300),
    (0.1, 0.2, pytest.approx(0.3)),
])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

8Mocking: Replace External Dependencies

Tests should be fast, isolated, and free of real network requests or database calls. Use unittest.mock (or pytest-mock) to replace external dependencies.

patch temporarily replaces the named object with a mock during the test. The mock records all calls made to it, letting you assert not just the return value but also whether the dependency was called correctly.

Patching a Network Call

Replace requests.get with a mock and assert how it was called.

code
from unittest.mock import patch, MagicMock
import requests
def get_weather(city: str) -> str:
    r = requests.get(f"https://api.weather.com/{city}")
    return r.json()["description"]
def test_get_weather():
    mock_response = MagicMock()
    mock_response.json.return_value = {"description": "Sunny"}
    with patch("requests.get", return_value=mock_response) as mock_get:
        result = get_weather("Chennai")
        assert result == "Sunny"
        mock_get.assert_called_once_with("https://api.weather.com/Chennai")

9Testing Classes

Classes are tested the same way as functions: build the object in a fixture, then exercise its methods and assert on the resulting state, including the error paths.

The testing pyramid guides how much of each test type to write — many fast unit tests, fewer integration tests, fewer still end-to-end tests.
The testing pyramid guides how much of each test type to write — many fast unit tests, fewer integration tests, fewer still end-to-end tests.

Testing a BankAccount

A fixture builds the account; each test checks one behaviour.

code
class BankAccount:
    def __init__(self, balance: float = 0):
        self._balance = balance
    def deposit(self, amount: float): self._balance += amount
    def withdraw(self, amount: float):
        if amount > self._balance: raise ValueError("Insufficient funds")
        self._balance -= amount
    @property
    def balance(self): return self._balance
@pytest.fixture
def account():
    return BankAccount(balance=1000.0)
def test_deposit_increases_balance(account):
    account.deposit(500)
    assert account.balance == 1500.0
def test_withdraw_reduces_balance(account):
    account.withdraw(200)
    assert account.balance == 800.0
def test_overdraft_raises_error(account):
    with pytest.raises(ValueError, match="Insufficient funds"):
        account.withdraw(5000)

10Code Coverage

Coverage shows which lines were executed during your test run. 80% is a common target; 100% is achievable for small modules but often overkill for large ones. Focus on covering edge cases and error paths, not chasing a percentage.

Running Coverage

Report missing lines, generate an HTML view, or enforce a threshold.

code
# Run tests with coverage report
pytest --cov=calculator --cov-report=term-missing
# Output shows which lines are NOT covered:
# Name           Stmts   Miss  Cover   Missing
# calculator.py      8      1    88%   12
# Generate an HTML report
pytest --cov=calculator --cov-report=html
# Opens htmlcov/index.html in browser
# Fail if coverage drops below threshold
pytest --cov=calculator --cov-fail-under=80

11Test Organisation

For larger projects, organise tests to mirror your source structure. conftest.py is pytest's special file for fixtures shared across multiple test files — pytest discovers it automatically, so you don't import it. Put database connections, API clients, and other expensive fixtures there.

Project Layout

Mirror the source tree under a tests/ directory.

code
my_project/
  src/
    calculator.py
    bank_account.py
    api/
      routes.py
  tests/
    test_calculator.py
    test_bank_account.py
    api/
      test_routes.py
    conftest.py  # shared fixtures available to all tests

12Key Takeaways

These conventions cover the vast majority of day-to-day testing in Python.

  • Test files: test_*.py. Test functions: def test_*(). Assertions: plain assert.
  • Test exceptions with: with pytest.raises(ExceptionClass): ...
  • Fixtures (@pytest.fixture) provide shared setup and teardown; they're injected by name.
  • @pytest.mark.parametrize runs one test with many input combinations.
  • Mock external dependencies with unittest.mock.patch; measure coverage with pytest-cov.

13What to Learn Next

Apply testing in real projects and automate it in your pipeline.

  • Build a REST API with FastAPI — FastAPI has a built-in test client that works with pytest.
  • CI/CD Explained — run pytest automatically on every Git push.
  • Python Error Handling — test that your error handling works as expected.

14Frequently Asked Questions

Should I write tests before or after the code? Test-Driven Development (TDD) says write tests first. In practice, many developers write tests after the code, especially when exploring a problem. What matters is that tests exist before you consider a feature "done." Retrofitting tests to existing code is harder but better than no tests.

What is the difference between a unit test and an integration test? Unit tests test a single function or class in isolation, with all external dependencies mocked. Integration tests test how multiple components work together with real dependencies. Unit tests are faster and pinpoint failures precisely; integration tests catch issues that only appear when components interact.

How do I test async functions with pytest? Install pytest-asyncio and mark async tests with @pytest.mark.asyncio (or configure asyncio_mode = "auto" in pytest.ini). The test function uses async def and await normally.

What is a good target for test coverage? 80% is a common baseline; 90%+ is achievable for well-designed modules. 100% coverage doesn't mean all bugs are caught — tests need to verify correct behaviour, not just execute lines. Prioritise coverage of business logic, error paths, and edge cases over getter/setter boilerplate.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Engineering Team

Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse