Python Unittest Tutorial

Unit testing is a testing method used in software engineering for individual units of any code. Users can put the individual tests to determine the status of the source and how much the code is suitable to be used. This way users can test the code quality.

Testing is done once the process of development is complete. Users can also begin testing when the test script is to be verified based on  the criteria of the testing. Developers are expected to write the manual types of the source code. Generally, manually writing unit testing codes is a hectic task but in Python, it is done using an in-built function called unittest.

Unittest

The testing in Python is done by unittest framework. Unit testing makes the code secure and easy to use in the future as well. Users usually cannot predict these cases but can easily address them. Unittest can either be the whole module, a particular function, and a whole interface (class/module).

How to write unit tests for your code?

To write the unit tests for your code, always begin with the smallest unit that can be tested from your whole code then move further to other units. This way you will check how the smallest chosen unit interacts to build a whole unit test.

The unit testing framework of Python was formed by taking into account the java’s Junit. It has same to same features like unit testing is done in other different kind of languages. The framework of unit testing in Python helps in automation testing, set up sharing, aggregation of many tests into one big set, and independent tests

Examples:

Now, in the example, we are checking the code to find out the sum in Python code using the sum() function. The answer to this summation must be 12, which is correct.

>>> assert sum([2, 4, 6]) == 12, "Should be equal to 12"

On the other hand, if we try to write a wrong output value, which the sum() is incorrect, the results will fail. It will return an AssertionError. The output stated by us is wrong that is 12, and the actual output must be 6 therefore, it returned this error.

>>> assert sum([2, 2, 2]) == 12, "Should be equal to 12"

Now, instead of testing on the REPL, we will put in a new Python file and name it test_sum.py

>> def testValue_sum():

    assert sum([2, 4, 6]) == 12, "Should be equal to 12"

if __name__ == "__main__":

    testValue_sum()

    print("Everything has been passed correctly")

After writing the test case, you can access the directory that has the test_sum.py file, and then type:

$ python test_sum.py

Output:

The output value, when it is similar to the one displayed, will approve the correct value.

Let us create another file for .py to test the sum. The example as displayed in the code and can be used as a sample by copying:

def testValue_sum():

    assert sum([2, 4, 6]) == 12, "Should be equal to 12"

def testValue_sum_tuple():

    assert sum((1, 1, 1)) == 6, "Should be equal to 6"

if __name__ == "__main__":

    testValue_sum()

    testValue_sum_tuple()

    print("Everything has been passed correctly")

This time we will again name the file test_sum.py 

First code block is correct, whereas the second code block is wrong and has an error, so our output will return the same.

Now, we will go back to the directory of the project, where we saved the .py file, and then test the file using the following command:

$ python test_sum.py

Output:

This time since the input code had an error,  it is expected to return the Assertion error in response.

Example of using unittest:

Unittest requirements are that users can put their tests into classes as different methods, users can use a series of assertion methods, and TestCase class can be used in place of the assert statement.

Users can convert the example discussed in the previous half to a unittest test case.

First, import unitest library. Next, you need to create a TestSum from different classes.

Create a new file for the code discussed below:

import unittest

class TestSum(unittest.TestCase):

    def testValue_sum(self):

        self.assertEqual(sum([2, 4, 6]), 12, "Should be equal to 12")

    def testValue_sum_tuple(self):

        self.assertEqual(sum((1, 1, 1)), 6, "Should be equal to 6")

if __name__ == '__main__':

    unittest.main()

Once you have executed this command, the output has a dot. This means success and an F means a failure.

So, we have success and another one is a failure.

Output:

Writing the First Test:

Create a new project folder and then create a new folder, we will call it sum_file. Inside it, create a file and name it, __init__.py.  Make the project folder like this one:

project/



└── sum_file/

    └── __init__.py

Then you need to open up my_sum/__init__.py and create a new function sum(). It will be iterable (a list, tuple, or set) to add many values:

def sum(arg):

    total_ValueCalculated = 0

    for val in arg:

        total_ValueCalculated += val

    return total_ValueCalculated

Next, you need to create a test file. Start by writing tests, and create a test file called testFile.py. To import the application, and it must be tested, place the file testFile.py above your folder of the package. The following will be overall look of your directory:

project/



├── sum_file/

│   └── __init__.py

|

└── testFile.py

As discussed earlier to test out the code, you can use the following command in the terminal window/ command line:

$ python -m unittest test

Conclusion

The article discusses the process of unit testing in Python. Testing is one of the useful feature of software engineering that is capable to divide the codes into smaller chunks, and then try them out one by one. Users can also compile the entire test samples/ unit codes into one big collection. Unittest is one function used in Python for making an easy use of testing.



from Linux Hint https://ift.tt/3caVqfe

Post a Comment

0 Comments