# Chapter 8 unittest framework import unittest # standard module # Tests at the class level # requires a class to be defined class MathFunctionsTestCase(unittest.TestCase): #Define test method starting with word "test" def test_addition(self): result = 2 + 3 # 5 self.assertEqual(result, 5) def test_subtraction(self): result = 2 - 3 # -1 self.assertEqual(result, -1) def test_multiplication(self): result = 2 * 3 # 6 self.assertEqual(result, 6) def test_division(self): result = 2 / 3 # .6666666in self.assertAlmostEqual(result, .6666) # run the tests if __name__ == "__main__": class CustomTestResult(unittest.TextTestResult): # On init function to create 3 params for log file def __init__(self, stream, descriptions, verbosity): super().__init__(stream, descriptions, verbosity) self.logfile = open("test_log.txt", "w") # Create all the result fixtures success, fail, error def addSuccess(self, test): super().addSuccess(test) self.logfile.write(f"SUCCESS: {test}\n") # string stream self.logfile.write(f" ---- \n") def addFailure(self, test, err): super().addFailure(test,err) self.logfile.write(f"FAILURE: {test} \n") # string stream self.logfile.write(f"FAILURE ERROR: {err} \n") self.logfile.write(f" ---- \n") def addError(self, test, err): super().addError(test,err) self.logfile.write(f"EXCEPTION ERROR: {test} \n") # string stream self.logfile.write(f"ERROR CODE: {err} \n") self.logfile.write(f" ---- \n") def stopTestRun(self): super().stopTestRun() self.logfile.close() # close the log file manually # execute the tests and log ALL results suite = unittest.TestLoader().loadTestsFromTestCase(MathFunctionsTestCase) # capture the execute to the custom class runner = unittest.TextTestRunner(resultclass=CustomTestResult) runner.run(suite)