The first thing we need to do within our test program is to import the unittest module. This will contain everything we need in order to test our simple function.
Below this import, we define our simpleFunction, which takes in a single argument and increments it by one. Nothing overly complex, I'm sure you'll agree, but the key point here is that if other parts of our codebase start to rely on the output of this function, then we need to have some form of a checking mechanism to ensure we don't break everything if we make some changes.
In the function code given next, we define our SimpleFunctionTest class which inherits from unittest.TestCase. Within this, we define our setUp and tearDown functions. These will run before and after all of the tests in our test suite.
Finally, we kick off this newly defined, but somewhat barebones, test suite by calling unittest.main().
import unittest
def simpleFunction(x):
return x + 1
class SimpleFunctionTest(unittest.TestCase):
def setUp(self):
print("This is run before all of our tests have a chance to execute")
def tearDown(self):
print("This is executed after all of our tests have completed")
def test_simple_function(self):
print("Testing that our function works with positive tests")
self.assertEqual(simpleFunction(2), 3)
self.assertEqual(simpleFunction(234135145145432143214321432), 234135145145432143214321433)
self.assertEqual(simpleFunction(0), 1)
if __name__ == '__main__':
unittest.main()