1.Skip装饰器的使用
'''
Skip装饰器的使用
skip表示无条件直接跳过
skipIf表示表达式成立,则跳过,不成立则继续执行
skipUnless与skipIf相反
expectedFailure 默认用例执行会失败,并将其忽略
Unittest下的杂技套装
'''
import unittest
class Demo(unittest.TestCase):
@unittest.skip('无条件跳过该条用例执行')
def test_01(self):
print(1)
@unittest.skipIf(1 == 2,'这是If的理由')
def test_02(self):
print(2)
def test_03(self):
print(3 / 0)
def test_04(self):
print(4)
self.assertEqual(1,2,msg = '断言失败')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
2.Suite测试套件,
'''
Suite测试套件,专门用于管理所有的测试用例类。可以理解为是用例的List,物理形态下就是一个文件夹的概念
套件的使用,一定是重新建立一个py文件进行调用,如果在UnitTest类下通过main函数调用则不会生效。
unittest.TestSuite类来进行使用
suite的运行一定是基于运行器运行的
套件中运行的测试用例,是基于添加的顺序来进行执行的,与UnitTest的用例排序没有关系
HTMLTestRunner测试报告:本质意义而言,其实就是一个运行器。
环境部署:直接下载py文件,放到python安装路径下的lib文件夹中就可以了。不要通过pip安装
网上下载的默认是只支持2.7版本及以下的。如果要支持到3以上版本,需要修改源码。
修改py文件的源码:
第94行,将import StringIO修改成import io
第539行,将self.outputBuffer = StringIO.StringIO()修改成 self.outputBuffer = io.StringIO()
第642行,将if not rmap.has_key(cls):修改成if not cls in rmap:
第766行,将uo = o.decode('latin-1')修改成uo = e
第772行,将ue = e.decode('latin-1')修改成ue = e
第631行,将print >> sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime)修改成print(sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime))
UnitTest下所有的测试用例用test开头。所有的测试用例文件,也需要以test开头。
'''
import os
import unittest
from HTMLTestReportCN import HTMLTestRunner
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
1.创建测试套件
suite = unittest.TestSuite()
2.在套件中添加测试用例
3.批量添加用例
4.通过添加一个完整的class进入套件
5.基于文件名称来进行添加
6.批量添加测试用例
path = '../class28'
discover = unittest.defaultTestLoader.discover(start_dir=path,pattern='test*.py')
7.通过运行器来运行套件
3.HTMLTestRunner生成测试报告
1.配置测试报告的相关内容
report_dir = './report/'
report_title = '虚竹的测试报告'
report_description = '这是测试报告中的描述部分'
report_file = report_dir + 'report.html'
report_tester = '司小幽'
2.保存报告的路径是否存在,不存在则创建一个
if not os.path.exists(report_dir):
os.mkdir(report_dir)
3.生成测试报告,其实就是写入一个文件内容
with open(report_file,'wb') as file:
runner = HTMLTestRunner(stream = file,title = report_title,description=report_description,verbosity=2,tester = report_tester)
runner.run(discover)