Testing projects is an essential part of software development. In this chapter, we’ll learn how to do unit testing in Python. Python has a module called UnitTest, which is a unit testing framework. In this chapter we will study the UnitTest framework.

In this chapter we will cover the following topics:

  • Introduction to the unit testing framework
  • Create a unit test task

What are unit tests?

Unittest is a unit testing framework in Python. It supports multiple tasks, such as test fixtures, writing test cases, aggregating test cases into a test suite, and running tests.

Unittest supports the following four main concepts:

  • Test fixture: This includes preparation and cleanup activities for performing one or more tests
  • Test cases: This includes our individual tests. We can create new test cases by using the TestCase base class in UnitTest
  • Test suite: This contains a test case, a test suite, or a combination of both. Used to execute test cases together
  • Test runner: This includes scheduling test execution and giving output to users

Python has a UnitTest module that we can import in scripts. The UnitTest module has TestCase classes for creating test cases.

Individual test cases can be created in method form. These method names begin with the word test. Thus, the test runner can know which methods represent test cases.

Creating unit tests

In this section, we create unit tests. We will create two scripts to implement it. One is a normal script, and the other is code that contains the tests.

First, create a script called arithmetic. Py and write the following code:

# In this script, we will create 4 functions: add_numbers, sub_numbers, mul_numbers, div_numbers def add_numbers(x, y): return x + y def sub_numbers(x, y): return x - y def mul_numbers(x, y): return x * y def div_numbers(x, y): return (x / y)Copy the code

In the script above, we created four functions: add_numbers, sub_numbers, MUL_numbers, and div_numbers. We’ll write test cases for these functions next. First, we’ll learn how to write test cases for the add_numbers function. Create the test_addition.py script and write the following code:

import arithmetic import unittest # Testing add_numbers function from arithmetic. class Test_addition(unittest.TestCase): # Testing Integers def test_add_numbers_int(self): sum = arithmetic.add_numbers(50, 50) self.assertEqual(sum, 100) # Testing Floats def test_add_numbers_float(self): AssertEqual (sum, = arithmetic. Add_numbers (50.55, 78)) 128.55) #Testing Strings def test_add_numbers_strings(self): sum = arithmetic.add_numbers('hello','python') self.assertEqual(sum, 'hellopython') if __name__ == '__main__': unittest.main()Copy the code

In the above script, we wrote three test cases for the add_numbers function. The first tests integer numbers, the second tests floating-point numbers, and the third tests strings. String addition means concatenating strings. Similarly, we can write test cases for subtraction, multiplication, and division.

Now we’ll run the test_addition.py test script, and you’ll see the results when you run the script.

Run the script as follows to get the following output:

vagrant@python-scripting:~$ python3 test_addition.py ... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran three tests in 0.000 s OKCopy the code

Here we get an OK, which means our test was successful.

Whenever we run the test script, there are three possible test results:

The results of describe
OK successful
FAIL Test failed – Throws AssertionError
ERROR Throws exceptions other than AssertionError

Methods used in unit tests

When using UnitTest, there are several methods we can use in our script. These methods are as follows:

  • AssertEqual () and assertNotEqual() : Detects the expected result
  • AssertTrue () and assertFalse() : Validation conditions
  • AssertRaises () : Verifies that the specified exception is thrown
  • SetUp () and tearDown() : Define the instructions before and after each test method executes

We can also use the Unittest module on the command line. So the aforementioned test script could also be run like this:

vagrant@python-scripting:~$ python3 -m unittest test_addition.py ... -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran three tests in 0.001 s OKCopy the code

Let’s look at another example. We create two scripts: if_example.py and test_if.py. If_example.py is our regular script, and test_if.py will contain the test cases. In this test, we check if the number entered is equal to 100. If it is, our test will succeed. Otherwise, a FAILED result should be displayed.

Create an if_example.py script and add the following code:

def check_if():
        a = int(input("Enter a number \n"))
        if(a == 100):
                print("a is equal to 100")
        else:
                print("a is not equal to 100")
        return a
Copy the code

Now create the test_if.py test script and write the following code:

import if_example
import unittest

class Test_if(unittest.TestCase):
        def test_if(self):
                result = if_example.check_if()
                self.assertEqual(result, 100)

if __name__ == '__main__':
        unittest.main()
Copy the code

Run the test script as follows:

vagrant@python-scripting:~/Chapter03$ python3 -m unittest test_if.py Enter a number 100 a is equal to 100 . -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 1 test in 0.984 s OKCopy the code

We ran the script and got a successful test result. If we enter a value other than 100, we will get a FAILED result. Run the following script:

vagrant@python-scripting:~/Chapter03$ python3 -m unittest test_if.py Enter a number 50 a is not equal to 100 F ====================================================================== FAIL: test_if (test_if.Test_if) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/vagrant/Chapter03/test_if.py", line 7, in test_if self.assertEqual(result, 100) AssertionError: 50! = 100 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Ran 1 test in 0.638 s FAILED (failures = 1)Copy the code

conclusion

In this chapter we learned about UnitTest, a unit testing framework in Python. We also learned how to create test cases and methods to use in unit tests.

In the next chapter, we’ll learn how to automate the normal administration activities of a system administrator. We’ll learn to receive input, work with passwords, execute external commands, read configuration files, add warning code to scripts, set CPU limits, start a Web browser, use OS modules, and make backups.

☞ Chapter IV Automating routine O&M Activities

Further reading

  • Unit test document: docs.python.org/3/library/u…
  • In Python PEP8 coding standard: www.python.org/dev/peps/pe…