标签:
为了解决之前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的导入,该文件为动态生成,遍历当前文件夹下所有的文件夹,获取测试用例的文件名
# -*- coding: utf-8 -*-
import sys,os,time
import unittest
def getdir(currentpath,allpath):
result = []
for f in allpath:
tmp = currentpath+‘\\‘+f
if(os.path.isdir(tmp)):
result.append(f)
return result
def getfilename(dirpath):
file=os.listdir(dirpath)
filename=[]
for f in file:
if(f[0:4]==‘test‘ and f[-3:]==‘.py‘):
filename.append(f[0:(len(f)-3)])
return filename
def genemptyinit(dirpath):
fp=open(dirpath+‘\\__init__.py‘,"w")
fp.flush()
fp.close()
def genallinit():
fp=open("__init__.py","w")
fp.write("# -*- coding: utf-8 -*-\n")
fp.write("import sys\n")
fp.write("from time import sleep\n")
currentpath=os.getcwd()
allfile=os.listdir(currentpath)
dir=getdir(currentpath,allfile)
testcase=[]
for d in dir:
genemptyinit(d)
filenames = getfilename(d)
for f in filenames:
fp.write(‘from ‘+d+‘ import ‘+ f + ‘\n‘)
testcase.append(d+‘.‘+f+‘.‘+‘test‘)
fp.write(‘import unittest\n‘)
fp.flush()
fp.close()
return testcase
testcases = genallinit()
sys.path.append("..")
from fortest import *
from public import HTMLTestRunner
suit=unittest.TestSuite()
for test in testcases:
suit.addTest(unittest.defaultTestLoader.loadTestsFromName(test))
filename = ‘E:\\python\\selenium\\fortest\\result\\result‘+ time.strftime("_%Y%m%d_%H%M%S",time.localtime(time.time())) +‘.html‘
fp=open(filename,"wb")
runner=HTMLTestRunner.HTMLTestRunner(
stream = fp,
title = u‘测试报告‘,
description = u‘用例执行结果‘)
runner.run(suit)
测试用例的写法
# -*- coding: utf-8 -*-
import unittest
class test(unittest.TestCase):
def setUp(self):
pass
def test_login(self):
u"""test_1 test1登录用例login"""
pass
def test_quit(self):
u"""test_1 test1登录用例quit"""
pass
def tearDown(self):
pass
测试报告如下:
多线程执行用例的框架待续...
标签:
原文地址:http://www.cnblogs.com/newvoyage/p/5622854.html