Sobes.tech
Junior
200

What testing modules do you know in Python?

Answer from AI

sobes.tech AI

  • unittest (or PyUnit) - a standard module for creating and running tests. Supports concepts of test cases (TestCase), test suites (TestSuite), and test runners (TestRunner).
  • pytest - a popular third-party testing framework. Known for its simplicity in writing tests (without inheriting from TestCase), support for fixtures, parameterization, and a flexible plugin system.
  • nose2 - another third-party framework that enhances and extends the capabilities of unittest.
  • doctest - allows executing code examples embedded in docstrings as tests.
  • mock (built into unittest.mock in Python 3.3+) - used for replacing parts of your system with "mock" objects, enabling testing of code independently of its dependencies.
  • coverage.py - measures the test coverage of your code.
  • hypothesis - a property-based testing framework that generates diverse input data to check your code's invariants.

Comparison of unittest and pytest:

Feature unittest pytest
Test description Classes inheriting from TestCase Functions or class methods
Fixtures setUp, tearDown methods @pytest.fixture decorator
Parameterization Requires additional tricks Built-in (@pytest.mark.parametrize)
Reports Basic More detailed
Plugins Limited Extensive plugin ecosystem

Example of a simple test using pytest:

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

# test_my_module.py
def test_add():
    """Test for add function"""
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

Running tests:

pytest