Junior
208
What testing modules do you know in Python?
Answer from AI
sobes.tech AI
unittest(orPyUnit) - 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 fromTestCase), support for fixtures, parameterization, and a flexible plugin system.nose2- another third-party framework that enhances and extends the capabilities ofunittest.doctest- allows executing code examples embedded in docstrings as tests.mock(built intounittest.mockin 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