Testing is a critical part of software development. It ensures your code works as expected and prevents future changes from breaking existing functionality. Python provides built-in tools for testing, as well as highly popular third-party frameworks.
1. unittest module
The unittest module is built into the Python standard library. It is inspired by Java’s JUnit and provides a solid framework for constructing and running tests.
2. Writing test cases & assert methods
To write a test case, you must create a class that inherits from unittest.TestCase.
Inside this class, any method that starts with the word test_ will be automatically run by the test runner.
import unittest
# The function we want to test
def add(a, b):
return a + b
# The test suite
class TestMathOperations(unittest.TestCase):
def test_add_positive_numbers(self):
# We use assert methods to verify expectations
self.assertEqual(add(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add(-1, -1), -2)
if __name__ == '__main__':
unittest.main()
Common Assert Methods
assertEqual(a, b): Checks if a == bassertNotEqual(a, b): Checks if a != bassertTrue(x): Checks if bool(x) is TrueassertFalse(x): Checks if bool(x) is FalseassertIsNone(x): Checks if x is NoneassertIn(a, b): Checks if a is in bassertRaises(exc, fun, *args, **kwds): Checks if calling the function throws the specified exception.
3. Running tests
If you added if __name__ == '__main__': unittest.main() to the bottom of your script, you can run the test file directly from the command line:
python test_math.py
Alternatively, you can use the command-line interface of the unittest module to discover and run all tests in a directory automatically:
python -m unittest discover
4. pytest basics
While unittest is built-in, the most popular testing framework in the Python community is pytest. It requires much less boilerplate code and produces highly readable output.
You must install it first:
pip install pytest
With pytest, you don’t need to create classes or use self.assertEqual. You just write normal functions and use the standard Python assert keyword.
# test_sample.py
def add(a, b):
return a + b
def test_add_positive():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, -1) == -2
To run the tests, simply open the terminal and run:
pytest
pytest will automatically find any files starting with test_ or ending with _test.py, run all functions inside them starting with test_, and report the results.
Discussion
Loading comments...