關鍵字驅動小例子 ...
compute.py #該文件用來存被測函數 #encoding=UTF-8 import random import re def add(a,b): c=int(a) d=int(b) print c+d return c+d def sub(a,b): c=int(a) d=int(b) print c-d return c-d def mul(a,b,c): d=int(a) e=int(b) f=int(c) return d*e*f def abs_value(a): return abs(int(a)) def random_value(): return random.randint(1,1000) def assert_value(actual_value,expected_value): expected_value = str(expected_value).strip() actual_value = str(actual_value) if re.search(r"\\|\*|\.|\?",expected_value):#看預期結果是否是個正則表達式,看裡面是否含有.*?斜杠中的任意一個 #.匹配除換行符之外的任意1個字元 .不能匹配回車; #\d 匹配中任意一個數字,範圍為[0-9] #*(星號) 匹配前一個字元0次1次或多次 #?匹配前一個字元0次或1次 #豎線表示或,都表示第1個位置 if re.match(expected_value,actual_value): return True else: return False if actual_value==expected_value: return True else: return False #------------------------------------------------------------------------------------------------- data.txt #將該txt文件存於電腦E盤根目錄下 add,1,2,3 sub,2,1,1 mul,1,2,3,6 abs_value,-1,1 random_value,\d+ #-------------------------------------------------------------------------------------------------- test.py #要運行的程式 #encoding=UTF-8 from compute import * test_case_num = 0 success_test_case =0 faile_test_case = 0 with open("e:\\data2.txt") as f: for line in f: test_case_num+=1 func_name = line.split(",")[0] value = ",".join(line.split(",")[1:-1]) expect_value = line.split(",")[-1] s= func_name+"("+value+")" actual_result=eval(s) if assert_value(actual_result,expect_value): success_test_case+=1 else: faile_test_case +=1 print "total %s test cases runned" % test_case_num print "total %s succeeded test cases runned" % success_test_case print "total %s failed test cases runned" % faile_test_case