Labs ICT
โญ Pro Login

What is pytest?

An introduction to the pytest framework and why it is popular.

What is pytest?

pytest is a full-featured Python testing framework that helps you write and run tests with minimal effort. Unlike the built-in unittest module, pytest uses simple assert statements instead of verbose test classes, making your tests clean and readable.

pytest has become the most popular testing framework in the Python ecosystem. It is used by companies like Instagram, Dropbox, and Mozilla to test their codebases. Its power comes from a rich plugin ecosystem, automatic test discovery, and detailed failure reports.

Why pytest?

There are several reasons developers prefer pytest over other testing tools:

  • Simplicity - Write tests with plain assert statements, no boilerplate required.
  • Auto-discovery - pytest finds your tests automatically based on naming conventions.
  • Fixtures - Powerful setup/teardown mechanism that is modular and reusable.
  • Plugins - Over 1,000+ plugins for coverage, mocking, reporting, and more.
  • Detailed tracebacks - When a test fails, pytest shows you exactly what went wrong.

A Quick Example

Here is what a typical pytest test looks like:

# test_example.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

That is it. No classes, no setup methods, no imports. Just functions that start with test_ and plain assert statements.

pytest vs unittest

Python ships with unittest, which is modeled after JUnit. While unittest is capable, it requires more boilerplate code. Here is a comparison:

# unittest style
import unittest

class TestAdd(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

# pytest style
def test_add():
    assert add(2, 3) == 5

pytest achieves the same result with less code and better error messages.

๐Ÿงช Quick Quiz

What is pytest?