use the unittest module for testing in python

The unittest module in Python provides a framework for automated testing. Here is an example of how to use it:

main.py
import unittest

# Define the class that contains the unit tests
class TestStringMethods(unittest.TestCase):

    # Define a test method
    def test_upper(self):
        self.assertEqual('hello'.upper(), 'HELLO')

    # Define another test method
    def test_isupper(self):
        self.assertTrue('HELLO'.isupper())
        self.assertFalse('Hello'.isupper())

    # Define another test method
    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

# Define the main function to run the tests
if __name__ == '__main__':
    unittest.main()
733 chars
26 lines

In this example, we define a class TestStringMethods that inherits from unittest.TestCase. This class contains several test methods, each of which tests a specific aspect of the code under test. In this case, we test the upper(), isupper(), and split() string methods.

To run the tests, we define a main function that calls unittest.main(). This function automatically finds and runs all the test methods in the TestStringMethods class.

When the tests run, the assertEqual() and assertTrue() methods check that the values being tested are what we expect them to be. If a test fails, an exception is raised and the test is marked as a failure.

By using the unittest module, you can easily write and run automated tests for your Python code.

gistlibby LogSnag