2 min read

Python Testing with unittest and pytest

Testing is a crucial part of software development. Python provides built-in tools like unittest and supports powerful third-party frameworks like pytest.

unittest

unittest is the unit testing framework included in the Python standard library. It is inspired by JUnit and supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

Basic Example

To create a test case, you subclass unittest.TestCase.

import unittest

def add(x, y):
    return x + y

class TestAddFunction(unittest.TestCase):

    def test_add_integers(self):
        self.assertEqual(add(1, 2), 3)

    def test_add_floats(self):
        self.assertAlmostEqual(add(1.1, 2.2), 3.3, places=1)

    def test_add_strings(self):
        self.assertEqual(add('a', 'b'), 'ab')

if __name__ == '__main__':
    unittest.main()

Common Assertions

  • assertEqual(a, b)
  • assertNotEqual(a, b)
  • assertTrue(x)
  • assertFalse(x)
  • assertIn(item, list)
  • assertRaises(Error, func, args)

pytest

pytest is a mature, full-featured Python testing tool that helps you write better programs. It is often preferred over unittest because of its simpler syntax and powerful features like fixtures.

Installation

pip install pytest

Basic Example

With pytest, you don't need classes. You just write functions that start with test_.

# test_sample.py

def add(x, y):
    return x + y

def test_add_integers():
    assert add(1, 2) == 3

def test_add_strings():
    assert add('a', 'b') == 'ab'

Fixtures

Fixtures are a powerful feature in pytest for setting up the environment for your tests (e.g., database connections, temporary files).

import pytest

@pytest.fixture
def sample_data():
    return {"key": "value"}

def test_data(sample_data):
    assert sample_data["key"] == "value"

programming/python/python