Unit testing

The first strategy that we will consider is unit testing. The term indicates a method that tests for individual units of the program under consideration, where a unit is the smallest testable part of the program. For this reason, unit testing is not meant for testing a complete concurrent system. Specifically, it is recommended that you do not test a concurrent program as a whole, but that you break the program down into smaller components and test them separately.

As usual, Python provides libraries that offer intuitive APIs to solve most common problems in programming; in this case, it is the unittest module. The module was originally inspired by the unit testing framework for the Java programming language JUnit; it also provides common unit testing functionalities in other languages. Let's consider a quick example of how we can use unittest to test a Python function in the Chapter19/example5.py file:

# Chapter19/example5.py

import unittest

def fib(i):
if i in [0, 1]:
return i

return fib(i - 1) + fib(i - 2)

class FibTest(unittest.TestCase):
def test_start_values(self):
self.assertEqual(fib(0), 0)
self.assertEqual(fib(1), 1)

def test_other_values(self):
self.assertEqual(fib(10), 55)

if __name__ == '__main__':
unittest.main()

In this example, we would like to test the fib() function that generates specific elements in the Fibonacci sequence (where an element is the sum of its two previous elements), whose starting values are 0 and 1, respectively.

Now, let's focus our attention on the FibTest class, which extends the TestCase class from the unittest module. This class contains different methods that test for specific cases of the results returned by the fib() function. Specifically, we have a method that looks at edge cases for this function, which are the first two elements of the sequence, and another method that tests for an arbitrary value in the sequence.

After running the preceding script, your output should be similar to the following:

> python3 unit_test.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

The output indicates that our tests passed without any errors. Additionally, as suggested by the class name, this class is an individual test case, which is a unit of testing. You can expand different test cases into a test suite, which is defined as a collection of test cases, test suites, or both. Test suites are generally used to combine tests that you would like to run together.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.188.138