From: https://www.cnblogs.com/feiyi211/p/6626314.html

一. 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就可以只做一次,否则每个测试用例都要做这两步也是冗余。

二. Fixture基础实例入门

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

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.py

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()')

四. fixture scope

function:每个test都运行,默认是function的scope class:每个class的所有test只运行一次 module:每个module的所有test只运行一次 session:每个session只运行一次

比如你的所有test都需要连接同一个数据库,那可以设置为module,只需要连接一次数据库,对于module内的所有test,这样可以极大的提高运行效率。

五. 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

Pytest高级进阶之Fixture的更多相关文章

  1. pytest进阶之fixture

    前言 学pytest就不得不说fixture,fixture是pytest的精髓所在,就像unittest中的setup和teardown一样,如果不学fixture那么使用pytest和使用unit ...

  2. Pytest - 进阶功能fixture

    1. 概述 Pytest的fixture功能灵活好用,支持参数设置,便于进行多用例测试,简单便捷,颇有pythonic.如果要深入学习pytest,必学fixture. fixture函数的作用: 完 ...

  3. 一凡老师亲录视频,Python从零基础到高级进阶带你飞

    如需Q群交流 群:893694563 不定时更新2-3节视频 零基础学生请点击 Python基础入门视频 如果你刚初入测试行业 如果你刚转入到测试行业 如果你想学习Python,学习自动化,搭建自动化 ...

  4. 潭州学院-JavaVIP的Javascript的高级进阶-KeKe老师

    潭州学院-JavaVIP的Javascript的高级进阶-KeKe老师 讲的不错,可以学习 下面是教程的目录截图: 下载地址:http://www.fu83.cn/thread-283-1-1.htm ...

  5. C#可扩展编程之MEF学习笔记(五):MEF高级进阶

    好久没有写博客了,今天抽空继续写MEF系列的文章.有园友提出这种系列的文章要做个目录,看起来方便,所以就抽空做了一个,放到每篇文章的最后. 前面四篇讲了MEF的基础知识,学完了前四篇,MEF中比较常用 ...

  6. 高级进阶DB2(第2版)——内部结构、高级管理与问题诊断

    <高级进阶DB2(第2版)——内部结构.高级管理与问题诊断> 基本信息 作者: 牛新庄    出版社:清华大学出版社 ISBN:9787302323839 上架时间:2013-7-3 出版 ...

  7. MEF高级进阶

    MEF高级进阶   好久没有写博客了,今天抽空继续写MEF系列的文章.有园友提出这种系列的文章要做个目录,看起来方便,所以就抽空做了一个,放到每篇文章的最后. 前面四篇讲了MEF的基础知识,学完了前四 ...

  8. .Net高级进阶,在复杂的业务逻辑下,如何以最简练的代码,最直观的编写事务代码?

    本文将通过场景例子演示,来通俗易懂的讲解在复杂的业务逻辑下,如何以最简练的代码,最直观的编写事务代码. 通过一系列优化最终达到两个效果,1.通过代码块来控制事务(分布式事务),2.通过委托优化Tran ...

  9. 《Android高级进阶》读书笔记

    <Android高级进阶>是据我所知的市面上唯一一本技术工具书,比较的高大全,作者的目的是为了对全领域有个初步的概念 No1: 在Android系统中,拥有事件传递处理能力的类有以下三种 ...

随机推荐

  1. python调用c++ DLL

    python DLL = ctypes.cdll.LoadLibrary("./dll_file.so") #引入dllDLL.func(mat.ctypes.data // (1 ...

  2. Oracle CONNECT by 简单用法

    Oracle查询层级的  一个表里 通过一个parentid连接 select * FROM A_MERIATILA start with id=520 CONNECT by prior id=PAR ...

  3. 面向对象text 01 盖伦vs瑞文vs提莫

    ''' Text For Class: League of Legends Garen vs Riven vs Teemo ''' import random # 全局随机 import time c ...

  4. TP5 数据库迁移工具 migrate 教程

    第一步: 安装compose,不赘述,安装详情可百度或查看https://pkg.phpcomposer.com/#how-to-install-composer 第二步: 通过 composer   ...

  5. org.springframework.beans.factory.BeanCreationException 解决异常错误

    一月 18, 2017 10:18:51 上午 org.apache.coyote.http11.Http11Protocol initINFO: Initializing Coyote HTTP/1 ...

  6. Vue小技巧-懒加载

    Vue懒加载包括图片懒加载与路由懒加载 1.图片懒加载: 首先安装 vue-lazyload包 然后导入并加载事先下载好的加载图片 import VueLazyLoad from 'vue-lazyl ...

  7. knockout checkbox 全选

    knockout checkbox 全选 <input type=checkbox data-bind="checked:IsAll"/>全选 <ul data- ...

  8. myEclipse出现cannot paste the clipboard contents into the selected elements报错

    导入jar包报错,cannot paste the clipboard contents into the selected elements,查阅资料让重新打开工程,但依然报错. 最后在本地路径复制 ...

  9. python-selctors实现文件上传

    服务端代码:程序目录server/server.py   上传文件目录:server/upload import os import time import socket import selecto ...

  10. 关于PHP 缓冲区: ob_star , ob_get_contents

    PHP ob_star ob_get_contents 细说   作者:田园花香  关于PHP 缓冲区 ob_start: 打开输出缓冲区,当缓冲区激活时,所有来自PHP程序的非头文件信息均不会发送, ...