Automated software testing with Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about automating testing in Python. After writing code, we have to test them by giving different types of input and check whether the code is working correctly or not.

We can do it manually or automatically. Doing manual testing is very hard. So, we are going to learn about automated testing in Python. Let's start.

We have a module called unittest, which is used to test the code automatically. We are going to work with this module in this tutorial. It's straightforward for a beginner to get started with the unittest module for testing. Let's start the coding with basics.

The method which you have to test must start with the test text.

Example

# importing unittest module
import unittest
class SampleTest(unittest.TestCase):
   # return True or False
   def test(self):
      self.assertTrue(True)
# running the test
unittest.main()

Output

If you run the above program, you will get the following results.

Ran 1 test in 0.001s
OK

Testing String Methods

Now, we are going to test different string methods with sample test cases. Remember that the method name must start with a test.

Example

# importing unittest module
import unittest
class TestingStringMethods(unittest.TestCase):
   # string equal
   def test_string_equality(self):
      # if both arguments are then it's succes
      self.assertEqual('ttp' * 5, 'ttpttpttpttpttp')
   # comparing the two strings
   def test_string_case(self):
      # if both arguments are then it's succes
      self.assertEqual('tutorialspoint'.upper(), 'TUTORIALSPOINT')
   # checking whether a string is upper or not
   def test_is_string_upper(self):
      # used to check whether the statement is True or False
      self.assertTrue('TUTORIALSPOINT'.isupper())
      self.assertFalse('TUTORIALSpoint'.isupper())
# running the tests
unittest.main()

Output

If you run the above program, you will get the following results.

Ran 3 tests in 0.001s
OK

Conclusion

You can use the testing in your programs to save a lot of time. If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 01-Nov-2019 12:21:47
Advertisements