Running unittest Tests with pytest
pytest is compatible with Python’s built-in unittest framework and can discover and run most unittest-based tests without modification. This makes pytest a practical choice for projects migrating gradually from unittest to pytest.
import unittest
class TestMath(unittest.TestCase):
def test_addition(self):
self.assertEqual(1 + 1, 2)
pytest will collect and run this test alongside native pytest-style tests. Over time, teams can adopt pytest features such as fixtures and parametrization while still supporting existing unittest test suites.
mock
pytest does not ship its own mocking library, but it works extremely well with unittest.mock, which is part of the Python standard library. This allows you to replace external dependencies, network calls, or expensive operations with controlled mock objects. Mock objects are sometimes called test doubles, spies, fakes or stubs. By combining pytest’s monkeypatch fixture with the unittest.mock module, you can cover nearly all common test double use cases.
tox
tox is a command-line tool used alongside pytest to automate test execution across multiple Python versions, dependency sets, or environments. In this setup, pytest acts as the test runner, while tox orchestrates how and where tests are executed.
