Pytest - 进阶功能fixture

1. 概述

Pytest的fixture功能灵活好用,支持参数设置,便于进行多用例测试,简单便捷,很有pythonic。
若是要深刻学习pytest,必学fixture。html

fixture函数的做用:python

  • 完成setup和teardown操做,处理数据库、文件等资源的打开和关闭
  • 完成大部分测试用例须要完成的通用操做,例如login、设置config参数、环境变量等
  • 准备测试数据,将数据提早写入到数据库,或者经过params返回给test用例,等

2. 使用介绍

2.1. 简介

  • 把一个函数定义为Fixture很简单,只能在函数声明以前加上“@pytest.fixture”。其余函数要来调用这个Fixture,只用把它当作一个输入的参数便可
  • 多个fixture方法,能够互相调用,最好不要递归哈(没试过,有兴趣的童鞋能够试试)
  • 一个test函数能够包含多个fixture参数
  • fixture做用域:fixture能够修饰单个函数,单个或多个类的成员函数,单个类

2.2. 三种使用方式

方式1,将fixture函数,做为test函数的参数

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 

方式2,@pytest.mark.usefixtures("before")

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,使用时须要谨慎

@pytest.fixture(scope="function", autouse=True)数据库

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()') 
  • fixture scope
  • function:每一个test都运行,默认是function的scope
  • class:每一个class的全部test只运行一次
  • module:每一个module的全部test只运行一次
  • session:每一个session只运行一次

2.3. fixture返回参数

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 

3. 参考

  • pytest fixtures: explicit, modular, scalablehttps://docs.pytest.org/en/latest/fixture.html
相关文章
相关标签/搜索