Computer >> Computer tutorials >  >> Programming >> Python

Unit Testing in Python using Unittest


In this article, we will learn about the fundamentals of software testing with the help of the unit test module available in Python 3.x. Or earlier. It allows automation, sharing of the setup and exit code for tests, and independent tests for every framework.

In the unit tests, we use a wide variety of object-oriented concepts. We will be discussing some majorly used concepts here.

  • Testcase − It is response specific base class in accordance with a given set of inputs. We use base class of unit test i.e. “TestCase” to implement this operation.

  • Testsuite − It is used to club test cases together and execute them simultaneously.

  • Testrunner − It follows an outcome-based execution of tasks. It is involved in displaying the results after executing the tasks.

  • Test fixture − It serves as a baseline for the test cases in the associated environment.

Now lets a basic example to see how unit testing works.

Example

import unittest
class TestStringMethods(unittest.TestCase):
   def test_upper(self):
      self.assertEqual('TUTOR'.lower(), 'tutor')
   def test_islower(self):
      self.assertTrue('tutor'.islower())
      self.assertFalse('Tutor'.islower())
if __name__ == '__main__':
   unittest.main()

Output

...
---------------------------------------------------------------

Ran 2 tests in 0.000s
OK

Unit Testing in Python using Unittest

Here we extend the unit test class in the form of single inheritance. Here we used to built-in methods like assertEqual() , assertTrue() & assertFalse()

assertEqual() is used to validate/compare the output with the result

assertTrue() is used to verify that the given condition is True or not.

assertFalse() is used to verify that the given condition is False or not.

The output of the above code can be in three forms −

OK – This indicates that all tests generated have executed successfully

FAIL – This indicates either test case has failed and an AssertionError exception is raised.

ERROR – This indicates that the test raises an exception/error.

We can use the decorator @unittest.skip(<reason>)

Example

import unittest
class TestString(unittest.TestCase):
   @unittest.skip("check skipped tests")
   def test_upper(self):
      self.assertEqual('TUTOR'.lower(), 'tutor')
   def test_islower(self):
      self.assertTrue('tutor'.islower())
      self.assertFalse('Tutor'.islower())
if __name__ == '__main__':
   unittest.main()

Output

...
---------------------------------------------------------------
-
Ran 2 tests in 0.000s
OK (skipped=2)

Conclusion

In this article, we learned about Unit Testing in Python using the unittest module in Python 3.x. Or earlier.