This article is contributed by Aditi Gupta. Unittest.main() provides a command-line interface to the test script.On running the above script from the command line, following output is produced : The assertEqual() statement returns true in this case if the result matches the given output. This test is used to check the split function of the string which splits the string through the argument passed in the function and returns the result as list. The assertEqual() statement returns true if the string is stripped and matches the given output. This test is used to check if all chars passed in the function have been stripped from the string. The assertTrue() / assertFalse() statement is used for this verification. This test is used to test the property of string which returns TRUE if the string is in uppercase else returns False. The assertEqual() statement returns true if the string returned is in uppercase. This test is used to check if the given string is converted to uppercase or not. This test is used to test the property of string in which a character say ‘a’ multiplied by a number say ‘x’ gives the output as x times ‘a’. assertRaises() – This statement is used to raise a specific exception.assertTrue() / assertFalse() – This statement is used to verify if a given statement is true or false.assertEqual() – This statement is used to check if the result obtained is equal to the expected result.
The last block of the code at the bottom allows us to run all the tests just by running the file. unittest.TestCase is used to create test cases by subclassing it. The above code is a short script to test 5 string methods. Let’s walk through an example to understand the implementation of unittest framework. ERROR – This means that the test raises an exception other than AssertionError.FAIL – This means that the test did not pass and an AssertionError exception is raised.OK – This means that all the tests are passed.There are three types of possible test outcomes : “-v” option is added in the command line while running the tests to obtain more detailed test results. Here, in the output the “.” on the first line of output means that a test passed. The last block helps to run the test by running the file through the command line.
This test() method will fail if TRUE is ever FALSE. This is the basic test code using unittest framework, which is having a single test.