unittest
calculation.py
class Cal(object):
def add_num_and_double(self, x, y):
if type(x) is not int or type(y) is not int:
raise ValueError
result = x + y
result *= 2
return result
Test calculation.py with unittest
test_calculation.py
import unittest
import calculation
release_name = 'lesson2'
class CalTest(unittest.TestCase):
#Called before the test runs
def setUp(self):
print('set up')
self.cal = calculation.Cal()
#Called after the test
def tearDown(self):
print('clean up')
del self.cal
#@unittest.skip('skip')You can skip the test with, but this time we will not skip it
@unittest.skipIf(release_name == 'lesson', 'skip!')
def test_add_num_and_double(self):#test_Make it in the form of a method name
#cal = calculation.Cal()
self.assertEqual(self.cal.add_num_and_double(1, 1), 4)
#Exception test
def test_add_num_and_double_raise(self):
#cal = calculation.Cal()
with self.assertRaises(ValueError):
self.cal.add_num_and_double('1', '1')
#Not required for pycharm
#if __name__ == '__main__':
# unittest.main()
You can see that setup and teardown are called twice each.
output
PASSED [ 50%]set up
clean up
PASSED [100%]set up
clean up