Pytest高级进阶之Fixture

一. fixture介绍

fixture是pytest的一个闪光点,pytest要精通怎么能不学习fixture呢?跟着我一块儿深刻学习fixture吧。其实unittest和nose都支持fixture,可是pytest作得更炫。 fixture是pytest特有的功能,它用pytest.fixture标识,定义在函数前面。在你编写测试函数的时候,你能够将此函数名称作为传入参数,pytest将会以依赖注入方式,将该函数的返回值做为测试函数的传入参数。 fixture有明确的名字,在其余函数,模块,类或整个工程调用它时会被激活。 fixture是基于模块来执行的,每一个fixture的名字就能够触发一个fixture的函数,它自身也能够调用其余的fixture。 咱们能够把fixture看作是资源,在你的测试用例执行以前须要去配置这些资源,执行完后须要去释放资源。好比module类型的fixture,适合于那些许多测试用例都只须要执行一次的操做。 fixture还提供了参数化功能,根据配置和不一样组件来选择不一样的参数。 fixture主要的目的是为了提供一种可靠和可重复性的手段去运行那些最基本的测试内容。好比在测试网站的功能时,每一个测试用例都要登陆和退出,利用fixture就能够只作一次,不然每一个测试用例都要作这两步也是冗余。html

二. Fixture基础实例入门

把一个函数定义为Fixture很简单,只能在函数声明以前加上“@pytest.fixture”。其余函数要来调用这个Fixture,只用把它当作一个输入的参数便可。 test_fixture_basic.pypython

import pytest

@pytest.fixture()
def before():
    print '\nbefore each test'

def test_1(before):
    print 'test_1()'

def test_2(before):
    print 'test_2()'
    assert 0

下面是运行结果,test_1和test_2运行以前都调用了before,也就是before执行了两次。默认状况下,fixture是每一个测试用例若是调用了该fixture就会执行一次的。数据库

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_basic.py
============================= test session starts =============================
platform win32 -- Python 2.7.13, pytest-3.0.6, py-1.4.32, pluggy-0.4.0 -- C:\Python27\python.exe
cachedir: .cache
metadata: {'Python': '2.7.13', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'py': '1.4.32', 'pytest': '3.0.6', 'pluggy': '0.4.0'}, 'JAVA_HOME': 'C:\\Program Files (x86)\\Java\\jd
k1.7.0_01', 'Plugins': {'html': '1.14.2', 'metadata': '1.3.0'}}
rootdir: C:\Users\PycharmProjects\pytest_example, inifile:
plugins: metadata-1.3.0, html-1.14.2
collected 2 items 

test_fixture_basic.py::test_1
before each test
test_1()
PASSED
test_fixture_basic.py::test_2
before each test
test_2()
FAILED

================================== FAILURES ===================================
___________________________________ test_2 ____________________________________

before = None

    def test_2(before):
        print 'test_2()'
>       assert 0
E       assert 0

test_fixture_basic.py:12: AssertionError
===================== 1 failed, 1 passed in 0.23 seconds ======================

三. 调用fixture的三种方式

1. 在测试用例中直接调用它,例如第二部分的基础实例。

2. 用fixture decorator调用fixture

能够用如下三种不一样的方式来写,我只变化了函数名字和类名字,内容没有变。第一种是每一个函数前声明,第二种是封装在类里,类里的每一个成员函数声明,第三种是封装在类里在前声明。在能够看到3中不一样方式的运行结果都是同样。 test_fixture_decorator.pysession

import pytest

@pytest.fixture()
def before():
    print('\nbefore each test')

@pytest.mark.usefixtures("before")
def test_1():
    print('test_1()')

@pytest.mark.usefixtures("before")
def test_2():
    print('test_2()')

class Test1:
    @pytest.mark.usefixtures("before")
    def test_3(self):
        print('test_1()')

    @pytest.mark.usefixtures("before")
    def test_4(self):
        print('test_2()')

@pytest.mark.usefixtures("before")
class Test2:
    def test_5(self):
        print('test_1()')

    def test_6(self):
        print('test_2()')

3. 用autos调用fixture

fixture decorator一个optional的参数是autouse, 默认设置为False。 当默认为False,就能够选择用上面两种方式来试用fixture。 当设置为True时,在一个session内的全部的test都会自动调用这个fixture。 权限大,责任也大,因此用该功能时也要谨慎当心。函数

import time
import pytest

@pytest.fixture(scope="module", autouse=True)
def mod_header(request):
    print('\n-----------------')
    print('module      : %s' % request.module.__name__)
    print('-----------------')

@pytest.fixture(scope="function", autouse=True)
def func_header(request):
    print('\n-----------------')
    print('function    : %s' % request.function.__name__)
    print('time        : %s' % time.asctime())
    print('-----------------')

def test_one():
    print('in test_one()')

def test_two():
    print('in test_two()')

4、 fixture 返回值学习

在上面的例子中,fixture返回值都是默认None,咱们能够选择让fixture返回咱们须要的东西。若是你的fixture须要配置一些数据,读个文件,或者链接一个数据库,那么你可让fixture返回这些数据或资源。测试

如何带参数 fixture还能够带参数,能够把参数赋值给params,默认是None。对于param里面的每一个值,fixture都会去调用执行一次,就像执行for循环同样把params里的值遍历一次。 test_fixture_param.py网站

import pytest

@pytest.fixture(params=[1, 2, 3])
def test_data(request):
    return request.param

def test_not_2(test_data):
    print('test_data: %s' % test_data)
    assert test_data != 2

相关文章
相关标签/搜索