How do I test a Python program or component?


To test a Python program, use the unittest module in Pygthon. The doctest and unittest modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module.

The doctest module

The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.

The unittest module

The unittest module supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.

Before moving further, let us understand some key concepts about Testing in Python −

  • A test fixture − It represents the preparation needed to perform one or more tests, and any associated cleanup actions.

  • A test case − A test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. The unittest provides a base class, TestCase, which may be used to create new test cases.

  • A test suite − A test suite is a collection of test cases, test suites, or both. It aggregates tests tobe executed together.

  • test runner − A test runner is a component which orchestrates the execution of tests and provides the outcome to the user.

Let us now create a test −

Create a Test

Example

In this example, we will test some methods in Python

import unittest class TestMethods(unittest.TestCase): def test_lower(self): self.assertEqual('AMIT'.lower(), 'amit') def test_islower(self): self.assertTrue('amit'.islower()) self.assertFalse('Amit'.isupper()) def test_split(self): s = 'Demo Text' self.assertEqual(s.split(), ['Demo', 'Text']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): s.split(2) if __name__ == '__main__': unittest.main()

Output

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

In the above example, we ran the test successfully. The root of each test is a call to assertEqual() to check for an expected result −

  • assertTrue() or assertFalse() to verify a condition; or
  • assertRaises() to verify that a specific exception gets raised

Updated on: 20-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements