首页 > 编程语言 > 详细

Python unittest测试框架1(单线程顺序执行)

时间:2016-06-28 12:22:01      阅读:240      评论:0      收藏:0      [点我收藏+]

为了解决之前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

测试报告如下:

技术分享

 

多线程执行用例的框架待续...

Python unittest测试框架1(单线程顺序执行)

原文:http://www.cnblogs.com/newvoyage/p/5622854.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!