python unittest模块
1 import unittest 2 import random 3 4 5 class Operation(object): 6 7 def __init__(self, num1=0, num2=0): 8 if not (0 <= num1 <= 10 and 0 <= num2 <= 10): 9 raise OutOfRangeError('number out of range (must be 0~10)') 10 if not isinstance(num1, int) or not isinstance(num2, int): 11 raise NotIntegerError('non‐integers can not be operate') 12 self.operate_num1 = num1 13 self.operate_num2 = num2 14 15 def get_result(self): 16 pass 17 18 19 class AddOp(Operation): 20 21 def get_result(self): 22 return self.operate_num1 + self.operate_num2 23 24 25 class MinusOp(Operation): 26 27 def get_result(self): 28 return self.operate_num1 - self.operate_num2 29 30 31 class MultiOp(Operation): 32 33 def get_result(self): 34 return self.operate_num1 * self.operate_num2 35 36 37 class DivideOp(Operation): 38 39 def get_result(self): 40 return self.operate_num1 / self.operate_num2 41 42 43 class OperationFactory(object): 44 45 @staticmethod 46 def choose_operation(op): 47 if op == '+': 48 return AddOp() 49 elif op == '-': 50 return MinusOp() 51 elif op == '*': 52 return MultiOp() 53 elif op == '/': 54 return DivideOp() 55 56 57 class OutOfRangeError(ValueError): 58 pass 59 60 61 class NotIntegerError(ValueError): 62 pass 63 64 65 class KnownValues(unittest.TestCase): 66 67 def test_add_op(self): 68 """测试加法运算是否正确""" 69 ope_obj = OperationFactory.choose_operation('+') 70 for i in range(0, 11): 71 ope_obj.operate_num1 = i 72 ope_obj.operate_num2 = random.randint(1, 10) 73 sum1 = ope_obj.operate_num1 + ope_obj.operate_num2 74 sum2 = ope_obj.get_result() 75 self.assertEqual(sum1, sum2) 76 77 def test_out_of_range(self): 78 """测试出界""" 79 for i in [-1, 11]: 80 operate_num1 = i 81 self.assertRaises(OutOfRangeError, Operation, operate_num1) 82 83 def test_integer(self): 84 """测试浮点数""" 85 operate_num1 = 0.5 86 self.assertRaises(NotIntegerError, Operation, operate_num1) 87 88 89 if __name__ == '__main__': 90 unittest.main()