1. 单个测试集
# coding:utf-8
import json, os, sys, unittest,HTMLTestRunner,requests
reload(sys)
sys.setdefaultencoding('utf8')
class ServiceTest(unittest.TestCase):
def setUp(self):
self.url ='www.baidu.com'
def test_get_service_list(self):
data={}
r=requests.get('http://www.cnblogs.com/xiyozhang136/p/7427730.html')
def tearDown(self):
pass
if __name__ =='__main__':
testsuite = unittest.TestSuite()
testsuite.addTest(ServiceTest("test_get_service_list"))
runner = unittest.TextTestRunner()
fp = file('ttt.html', 'wb')
#可以用print
runner.run = unittest.TextTestRunner(verbosity=2).run(testsuite)
#输出测试报告
# runner = HTMLTestRunner.HTMLTestRunner(
# stream=fp,
# title=u'接口测试报告',
# description=u'用例执行情况:')
# fp = open('res.html','wb')#打开一个保存结果的html文件
# runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title='api测试报告',description='测试情况')
# runner.run(testsuite)
这里选择unittest.TextTestRunner(verbosity=2).run(testsuite)则控制台可以显示print出来的内容,如果选择HTMLTestRunner则控制台不输出,在测试报告中输出内容
-
运行多个测试集
目录结构如下:
test1内容如下
#coding:utf-8
import unittest
import time
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("开始测试1")
@classmethod
def tearDownClass(cls):
print("结束测试")
def setUp(self):
print("开始单个测试用例")
def tearDown(self):
print("结束单个测试用例")
def test01(self):
'''测试0201'''
print("执行测试用例1")
def test02(self):
'''测试0202'''
print("执行测试用例01")
if __name__=="__main__":
unittest.main()
test2内容如下
#coding:utf-8
import unittest
import time
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("开始测试2")
def tearDown(self):
print("测试结束2")
def test01(self):
'''测试0201'''
print("执行测试用例2")
def test02(self):
'''测试0202'''
print("执行测试用例02")
if __name__=="__main__":
unittest.main()
- setUpClass一个测试集的开始运行
- tearDownClass一个测试集的结束运行
- setUp开始单个测试用例运行
- tearDown结束单个测试用例运行
运行all_test如下
#coding:utf-8
import unittest
import os,sys
import HTMLTestRunner
#from send_email import main2
#待执行用例的目录
reload(sys)
sys.setdefaultencoding('utf8')
def allcase():
#写路径即可
case_dir="/test"
#case_path=os.path.join(os.getcwd(),"case")
testcase=unittest.TestSuite()
discover=unittest.defaultTestLoader.discover(case_dir,
pattern='test*.py',
top_level_dir=None)
#discover方法筛选出来的用例,循环添加到测试套件中
#print(discover)
for test_suite in discover:
for test_case in test_suite:
#添加用例到testcase
print(test_case)
testcase.addTest(test_case)
return testcase
if __name__=="__main__":
runner=unittest.TextTestRunner()
runner.run(allcase())
report_path="test.html"
fp=open(report_path,"wb")
runner=HTMLTestRunner.HTMLTestRunner(stream=fp,
title="自动化测试unittest测试框架报告",
description="用例执行情况:")
runner.run(allcase())
fp.close()
版权声明:本文为qq_23114525原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。