Introduction to Testing in Python
Alexander Levin
Data Scientist
Test of the exponentiation operator:
# test_sqneg.py
import unittest
# Declaring the TestCase class
class TestSquared(unittest.TestCase):
# Defining the test
def test_negative(self):
self.assertEqual((-3) ** 2, 9)
CLI command:
python3 -m unittest test_sqneg.py
Run Python script test_sqneg.py
using module unittest
.
The command:
python3 -m unittest test_sqneg.py
The test output:
unittest -k
- run test methods and classes that match the pattern or substring
Command:
python3 -m unittest -k "SomeStringOrPattern" test_script.py
Example:
python3 -m unittest -k "Squared" test_sqneg.py
Output:
unittest -f
- stop the test run on the first error or failure.
Command: python3 -m unittest -f test_script.py
Use case example: when all of tests are crucial, like testing the airplane before a flight.
Catch flag unittest -c
- lets to interrupt the test by pushing "Ctrl - C".
unittest
waits for the current test to end and reports all the results so far. unittest
raises the KeyboardInterrupt
exception.Command: python3 -m unittest -c test_script.py
Use case example: when debugging a big test suite
unittest -v
- run tests with more detail
Command: python3 -m unittest -v test_script.py
.
Use case example: debugging purposes
Output example:
Basic command without arguments python3 -m unittest test_script.py
Output in unittest
Keyword argument: python3 -m unittest -k "SomeStringOrPattern" test_script.py
Fail fast flag: python3 -m unittest -f test_script.py
Catch flag: python3 -m unittest -c test_script.py
Verbose flag: python3 -m unittest -v test_script.py
Introduction to Testing in Python