CLI Interface

Introduction to Testing in Python

Alexander Levin

Data Scientist

Example: code

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.

Introduction to Testing in Python

Example: output

The command: python3 -m unittest test_sqneg.py

The test output: output of unittest test_sqneg.py

Introduction to Testing in Python

Keyword argument -k

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: output with a keyword

1 https://docs.python.org/3/library/unittest.html
Introduction to Testing in Python

Fail fast flag -f

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.

failed test example

1 https://docs.python.org/3/library/unittest.html
Introduction to Testing in Python

Catch flag -c

Catch flag unittest -c - lets to interrupt the test by pushing "Ctrl - C".

  • If "Ctrl - C"
    • is pushed once, unittest waits for the current test to end and reports all the results so far.
    • is pushed twice, unittest raises the KeyboardInterrupt exception.

Command: python3 -m unittest -c test_script.py

Use case example: when debugging a big test suite

1 https://docs.python.org/3/library/unittest.html
Introduction to Testing in Python

Verbose flag -v

unittest -v - run tests with more detail

Command: python3 -m unittest -v test_script.py.

Use case example: debugging purposes

Output example: output unittest with a verbose flag

1 https://docs.python.org/3/library/unittest.html
Introduction to Testing in Python

Summary

  • 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

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...