Unit Testing with Python
A software testing technique known as unit testing involves examining individual pieces of source code, sets of one or more computer programme modules, together with the control data, usage procedures, and operating procedures that go along with them, to see if they are ready for use.
In Python, the unittest module is a built-in library that you can use to write unit tests for your Python code. The unittest module provides a number of assert methods that you can use to check the output of your code and see whether it’s what you expected.
Here’s an example of a simple unit test in Python using the unittest module:
import unittest
def reverse_string(s):
return s[::-1]
class TestReverseString(unittest.TestCase):
def test_reverse_string(self):
self.assertEqual(reverse_string('abc'), 'cba')
self.assertEqual(reverse_string('hello'), 'olleh')
self.assertEqual(reverse_string('12345'), '54321')
if __name__ == '__main__':
unittest.main()
In this example, we have a function reverse_string which takes a string as input and returns the reverse of the string. We then have a test case TestReverseString that tests the reverse_string function using the assertEqual method from the unittest module. This method checks if the output of the reverse_string function is equal to the expected output.
To run the unit tests, you can simply run the Python script. If all the tests pass, you should see an output like this:
———————————————————————-
Ran 1 test in 0.000s
OK
If one of the tests fails, you should see an output like this:
======================================================================
FAIL: test_reverse_string (__main__.TestReverseString)
———————————————————————-
Traceback (most recent call last):
File “test_reverse_string.py”, line 14, in test_reverse_string
self.assertEqual(reverse_string(‘abc’), ‘def’)
AssertionError: ‘cba’ != ‘def’
———————————————————————-
Ran 1 test in 0.000s
FAILED (failures=1)
This output tells you which test failed and why it failed. You can then go back and debug your code to fix the error.
There are many other assert methods available in the unittest module that you can use to test different aspects of your code. You can read more about the unittest module and how to use it in the Python documentation.