为了解决之前unittest测试中文件下的所有的测试用例全部执行并生成测试报告的问题.
方案如下:
目录结构
│ testlibmain.py
│
├─public
│ HTMLTestRunner.py
│
├─result
├─test_1
│ test1.py
│ test2.py
│
├─test_2
│ test1.py
│ test2.py
│
└─test_3
test1.py
test2.py
命名规则,测试用例文件夹和文件以test开头,测试用例class名称统一为test
public中保存共通lib,result中保存测试报告
思路:通过当前目录的__init__.py文件实现所有的文件夹下class的导入,该文件为动态生成,遍历当前文件夹下所有的文件夹,获取测试用例的文件名
1 # -*- coding: utf-8 -*- 2 import sys,os,time 3 import unittest 4 5 def getdir(currentpath,allpath): 6 result = [] 7 for f in allpath: 8 tmp = currentpath+'\'+f 9 if(os.path.isdir(tmp)): 10 result.append(f) 11 return result 12 def getfilename(dirpath): 13 file=os.listdir(dirpath) 14 filename=[] 15 for f in file: 16 if(f[0:4]=='test' and f[-3:]=='.py'): 17 filename.append(f[0:(len(f)-3)]) 18 return filename 19 def genemptyinit(dirpath): 20 fp=open(dirpath+'\__init__.py',"w") 21 fp.flush() 22 fp.close() 23 def genallinit(): 24 fp=open("__init__.py","w") 25 fp.write("# -*- coding: utf-8 -*- ") 26 fp.write("import sys ") 27 fp.write("from time import sleep ") 28 currentpath=os.getcwd() 29 allfile=os.listdir(currentpath) 30 dir=getdir(currentpath,allfile) 31 testcase=[] 32 for d in dir: 33 genemptyinit(d) 34 filenames = getfilename(d) 35 for f in filenames: 36 fp.write('from '+d+' import '+ f + ' ') 37 testcase.append(d+'.'+f+'.'+'test') 38 fp.write('import unittest ') 39 fp.flush() 40 fp.close() 41 return testcase 42 testcases = genallinit() 43 sys.path.append("..") 44 from fortest import * 45 from public import HTMLTestRunner 46 suit=unittest.TestSuite() 47 for test in testcases: 48 suit.addTest(unittest.defaultTestLoader.loadTestsFromName(test)) 49 filename = 'E:\python\selenium\fortest\result\result'+ time.strftime("_%Y%m%d_%H%M%S",time.localtime(time.time())) +'.html' 50 fp=open(filename,"wb") 51 runner=HTMLTestRunner.HTMLTestRunner( 52 stream = fp, 53 title = u'测试报告', 54 description = u'用例执行结果') 55 runner.run(suit)
测试用例的写法
1 # -*- coding: utf-8 -*- 2 import unittest 3 class test(unittest.TestCase): 4 def setUp(self): 5 pass 6 def test_login(self): 7 u"""test_1 test1登录用例login""" 8 pass 9 def test_quit(self): 10 u"""test_1 test1登录用例quit""" 11 pass 12 def tearDown(self): 13 pass
测试报告如下:
多线程执行用例的框架待续...