Python unittest module, pythonunittest
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 = num113 self. operate_num2 = num214 15 def get_result (self): 16 pass17 18 19 class AddOp (Operation): 20 21 def get_result (self): 22 return self. operate_num1 + self. operate_num223 24 25 class MinusOp (Operation): 26 27 def get_result (self): 28 return self. operate_num1-self. operate_num229 30 31 class MultiOp (Operation): 32 33 def get_result (self): 34 return self. operate_num1 * self. operate_num235 36 37 class DivideOp (Operation): 38 39 def get_result (self): 40 return self. operate_num1/self. operate_num241 42 43 class OperationFactory (object): 44 45 @ staticmethod46 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 pass59 60 61 class NotIntegerError (ValueError): 62 pass63 64 65 class KnownValues (unittest. testCase): 66 67 def test_add_op (self): 68 "test whether the addition operation is correct" 69 ope_obj = OperationFactory. choose_operation ('+') 70 for I in range (0, 11): 71 ope_obj.operate_num1 = i72 ope_obj.operate_num2 = random. randint (1, 10) 73 sum1 = ope_obj.operate_num1 + ope_obj.operate_num274 sum2 = ope_obj.get_result () 75 self. assertEqual (sum1, sum2) 76 77 def test_out_of_range (self): 78 "test" "79 for I in [-1, 11]: 80 operate_num1 = i81 self. assertRaises (OutOfRangeError, Operation, operate_num1) 82 83 def test_integer (self): 84 "test floating point number" "85 operate_num1 = 0.586 self. assertRaises (NotIntegerError, Operation, operate_num1) 87 88 89 if _ name _ = '_ main _': 90 unittest. main ()