scope参数有四种,分别是
‘function’,‘module’,‘class’,‘session’,默认为function
1,function:每个test都运行,默认是function的scope
2,class:每个class的所有test只运行一次
3,module:每个module的所有test只运行一次
4,session:每个session只运行一次
小编刚开始学习见到这部分知识,很懵!!!只能一边实践,一边学习,似乎懂了一丢丢。。。
主要先讨论function和class,结合例子讨论
fucntion相关代码1:test_demo.py
#! /usr/bin/python
# -*- coding:utf-8 -*-
import pytest
@pytest.fixture()
def before():
print '\n到此一游'
def test_1():
print '\ntest_1()'
def test_2(before):
print '我是test_2()'
assert 1==1
def test_3(before):
print '我是test_3()'
@pytest.fixture() :这个小编就称它为“控制标记”,这儿控制标记括号是空的,默认就是function,也就是一开始提到四种参数时所说,也可以显示写出来:@pytest.fixture(scope=‘function’) ,效果一样
执行:
pytest -s test_demo.py
结果:
这儿before函数被标记为@pytest.fixture(scope=‘function’),function的作用范围指:只要测试函数调用before函数,就可以调用;test_1()函数未调用before(),则未打印输出“到此一游”
值得一说,通俗讲,fixture主要的目的是为了提供一种可靠和可重复性的手段去运行那些最基本的测试内容。比如在测试网站的功能时,每个测试用例都要登录和退出,利用fixture就可以只做一次,否则每个测试用例都要做这两步也是冗余;简单点,就是避免一些代码重复写,写一次,其他函数都可以调用
当然,这儿为了方便理解,before()都是简单写法,pytest是有比较规范的写法,fixture的作用也有专业的讲法,涉及到setup和teardown使用,且用处应该不止上述所说,第3个代码例子会涉及到
class相关代码2:test_demo.py
# -*- coding:utf-8 -*-
import pytest
@pytest.mark.pytestto
class TestPytestDemo(object):
def setup_class(self):
print "到此一游"
pass
@pytest.mark.asserttest
def test_assert(self):
assert 3 < 4, "3期望是小于4"
@pytest.mark.strtest
def test_str(self):
b = "hello"
assert "h" in b, "字符h期望在单词hello中出现"
执行:
#打印每个测试函数print()
pytest -s test_demo.py
结果:
看结果,“到此一游”指打印一次,说明class内所有test只运行一次,通俗点讲,就是即使测试函数test_assert和test_str都传入self这个参数,但是最终class内只执行一次;如果没有测试函数传入self,则不会打印输出“到此一游”
不知道大家对function和class的用法是否有点理解呢?
注意,这儿和代码1中fixture写法不一致,小编试了试,在class中,好像代码1中写法行不通,感兴趣可以自己多试试
代码3:test_demo3.py
# -*- coding:utf-8 -*-
import pytest
@pytest.fixture(scope='function')
def setup_function(request):
def teardown_function():
print("teardown_function called.")
request.addfinalizer(teardown_function) # 此内嵌函数做teardown工作
print('setup_function called.')
@pytest.fixture(scope='module')
def setup_module(request):
def teardown_module():
print("teardown_module called.")
request.addfinalizer(teardown_module)
print('setup_module called.')
@pytest.mark.website
def test_1(setup_function):
print('Test_1 called.')
def test_2(setup_module):
print('Test_2 called.')
def test_3(setup_module):
print('Test_3 called.')
assert 2==1+1 # 通过assert断言确认测试结果是否符合预期
大家有空可以执行这段代码,看看结果,可以进一步理解pytest一些用法
关于setup和teardown,小编觉得下面这个说法似乎更准确一些:
setup,在测试函数或类之前执行,完成准备工作,例如数据库链接、测试数据、打开文件等
在测试函数或类之后执行,完成收尾工作,例如断开数据库链接、回收内存资源等
备注:也可以通过在fixture函数中通过yield实现setup和teardown功能
运行结果以html格式报告输出
Pytest有个用于生成html测试结果报告的插件:pytest-html,可直接使用pip命令安装
pip install pytest-html
在执行用例时,需要加上参数:–html,如:
pytest -s test_demo3.py --html=report.html
指定报告的存放路径,需使用如下格式,比如,指定到一个log的文件夹里
pytest -s test_demo3.py --html=./log/report.html