Creating unit tests

In this section, we are going to create unit tests. To do this, we will create two scripts. One will be your normal script and the other will contain the code for testing.

First, create a script named arithmetic.py and write the following code in it:

# In this script, we are going to create a 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)

In the preceding script, we created four functions: add_numbers, sub_numbers, mul_numbers, and div_numbers. Now, we are going to write test cases for these functions. First, we will learn how we can write test cases for the add_numbers function. Create a test_addition.py script and write the following code in it:

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):
sum = arithmetic.add_numbers(50.55, 78)
self.assertEqual(sum, 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()

In the preceding script, we have written the three test cases for the add_numbers function. The first is for testing integer numbers, the second is for testing float numbers, and the third is for testing strings. In strings, adding means concatenating two strings. Similarly, you can write the test cases for subtraction, multiplication, and division.

Now, we will run our test_addition.py test script and we will see what result we get after running this script.

Run the script as follows and you will get the following output:

student@ubuntu:~$ python3 test_addition.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

Here, we get OK , which means our testing was successful.

Whenever you run your test script, you have three possible test results:

Result

Description

OK

Successful

FAIL

Test failed– raises an AssertionError exception

ERROR

Raises an exception other than AssertionError

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

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