Connect with us

Hi, what are you looking for?

Introduction - Unit Testing With Python

Introduction – Unit Testing With Python

You’re working on a large software project, and you’ve finally finished that unsolvable task, but you want to check if it’s giving the right results.

You have 2 ways to check you can send it to your teammates and tell them to have a look at the code and do a few tries or you can do it yourself with a unit test.

The logic of unit tests is simple, your code is put to a test, if it passes, it means that it works fine, if it fails, you will get an error message.

Creating Sample Code For Unit Testing

I mentioned that we need an application to implement Unit Test, in this section, we will create a simple function.

``````# Even Number Function
def isEvenNumber(num):
nums = []
for i in range(num):
if i % 2 == 0:
nums.append(i)
else:
continue

return nums
``````

This function finds even numbers in the given range of numbers. It will be an easy function for example tests.

Now let’s add the function to a panel that users can use so that the users can manage the function as they want.

``````from EvenNumberFounder import isEvenNumber

print("Enter Number Range or Enter 0 For Exit!")

while True:
numberRange = int(input("Range: "))
if numberRange == 0:
break
print(isEvenNumber(numberRange))``````

You can add the two codes in the same file, since it is separated here, I import them into the second file. Using separate files for Unit Testing works better in most cases.

Creating First Test in Python

Python offers you a ready-made library for unit testing. You can import unittest without any installation.

The unit test first scans your code for errors, then prompts you to fix your logical errors, simply by letting you know that the test failed.

1 – Creating Test Class

Step by Step: Create a separate file and put the unit test library in it, then create a test function in the test class for the function you are going to test.

``````import unittest
from EvenNumberFounder import isEvenNumber

class EvenNumberTestCase(unittest.TestCase):

def test1(self):
result = isEvenNumber(10)
self.assertEqual(result, [0,2,4,6,8])

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

Here we are checking whether the variable that isEvenNumber function will provide us is equal to the variable that should be.

assertEqual is used to compare the result of the function with the expected result. Returns two results, OK or FAILED.

2 – Start Test & Passing Test

To run the test, simply type the classic python file open command into your console. You can find it below.

``python TestName.py``

After running it, you may get two results, either your code is working fine or it has failed. If the expected value is the same as the result, OK will be displayed.

``````
Ran 1 test in 0.000s

--------------------
OK``````

3 – Failed in Test so How to Fix Problems

Your codes can’t always pass the tests, In this section, we will look at how to fix the errors in unsuccessful codes.

``````# Change This Block
self.assertEqual(result, [2,4,6,8,10])``````

When this test is run, the expected result and the result will not be the same and an error message will be given to us. Let’s examine that message now.

As you can see, your mistakes are written one by one, the mistake we made was to delete 0 and add 10.

4 – Adding New Tests & New TestCases

You can create different tests with different values, or you can test other functions you created in different Test Cases.

``````import unittest
from EvenNumberFounder import isEvenNumber

class EvenNumberTestCase(unittest.TestCase):

def test1(self):
result = isEvenNumber(10)
self.assertEqual(result, [0,2,4,6,8])

def test2(self):
result = isEvenNumber(5)
self.assertEqual(result , [0,2,4])

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

# Ran 2 tests in 0.000s
# OK``````

You can check how your function works with other values by creating different tests and you can get the results of both tests.

Now let’s create different Test Cases for different functions in the same Test file. So you can test a large project piecemeal.

``````import unittest
from unittest import result
from NumberFounder import isEvenNumber, isOddNumber

class EvenNumberTestCase(unittest.TestCase):

def test1(self):
result = isEvenNumber(10)
self.assertEqual(result, [0,2,4,6,8])

class OddNumberTestCase(unittest.TestCase):

def test1(self):
result = isOddNumber(10)
self.assertEqual(result, [1,3,5,7,9])

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

First I changed the name of the file containing the functions and then added the second function there (the function that finds odd numbers).

Then I created a second Test Case and added a few tests so that 2 different functions will be subjected to 2 different tests and a single report will be obtained.

Click to comment

Daily News

The Tokyo Institute of Technology and other organizations have announced the start of development of highly performing generative artificial intelligence using the Fugaku supercomputer,...

Daily News

Japanese researchers announced that AI ChatGPT technology has succeeded in the annual national doctor’s exam. The AI chatbot, which has advanced speech features that...

Programming

clean code is essential for updating scripts, adding new features to code, etc. So every developer, must learn how to clean the code. With...

Daily News

Cloud computing is a system that is often heard today and that most developers use at least once. In this article, we’ll look at...