Pytest高级进阶之Fixture

From: https://www.jianshu.com/p/54b0f4016300

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

下面会反复提高Python的Module概念,Python中的一个Module对应的就是一个.py文件。其中定义的所有函数或者是变量都属于这个Module。这个Module 对于所有函数而言就相当于一个全局的命名空间,而每个函数又都有自己局部的命名空间。

二. 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\yatyang\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 ======================

如果你的程序出现了下面的错误,就是开始忘记添加‘import pytest',所以不要忘记罗。

=================================== ERRORS ====================================
_________________ ERROR collecting test_fixture_decorator.py __________________
test_fixture_decorator.py:2: in <module>
    @pytest.fixture()
E   NameError: name 'pytest' is not defined
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.36 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()')

运行结果如下,和上面的基础实例的运行效果一样。

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_decorator.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\yatyang\PycharmProjects\pytest_example, inifile:
plugins: metadata-1.3.0, html-1.14.2
collected 6 items 

test_fixture_decorator.py::test_1
before each test
test_1()
PASSED
test_fixture_decorator.py::test_2
before each test
test_2()
PASSED
test_fixture_decorator.py::Test1::test_3
before each test
test_1()
PASSED
test_fixture_decorator.py::Test1::test_4
before each test
test_2()
PASSED
test_fixture_decorator.py::Test2::test_5
before each test
test_1()
PASSED
test_fixture_decorator.py::Test2::test_6
before each test
test_2()
PASSED

========================== 6 passed in 0.10 seconds ===========================

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

从下面的运行结果,可以看到mod_header在该module内运行了一次,而func_header对于每个test都运行了一次,总共两次。该方式如果用得好,还是可以使代码更为简洁。
但是对于不熟悉自己组的测试框架的人来说,在pytest里面去新写测试用例,需要去了解是否已有一些fixture是module或者class级别的需要注意。

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_auto.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\yatyang\PycharmProjects\pytest_example, inifile:
plugins: metadata-1.3.0, html-1.14.2
collected 2 items 

test_fixture_auto.py::test_one
-----------------
module      : test_fixture_auto
-----------------

-----------------
function    : test_one
time        : Sat Mar 18 06:56:54 2017
-----------------
in test_one()
PASSED
test_fixture_auto.py::test_two
-----------------
function    : test_two
time        : Sat Mar 18 06:56:54 2017
-----------------
in test_two()
PASSED

========================== 2 passed in 0.03 seconds ===========================

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

可以看到test_not_2里面把用test_data里面定义的3个参数运行里三次。

C:\Users\yatyang\PycharmProjects\pytest_example>pytest -v -s test_fixture_param.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\yatyang\PycharmProjects\pytest_example, inifile:
plugins: metadata-1.3.0, html-1.14.2
collected 3 items 

test_fixture_param.py::test_not_2[1] test_data: 1
PASSED
test_fixture_param.py::test_not_2[2] test_data: 2
FAILED
test_fixture_param.py::test_not_2[3] test_data: 3
PASSED

================================== FAILURES ===================================
________________________________ test_not_2[2] ________________________________

test_data = 2

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

test_fixture_param.py:9: AssertionError
===================== 1 failed, 2 passed in 0.24 seconds ======================

原文地址:https://www.cnblogs.com/Raul2018/p/10340452.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


目录1、前言2、mark的使用(一)注册自定义标记(二)在测试用例上标记(三)执行3、扩展(一)在同一个测试用例上使用多个标记(二)在测试类上使用标记1、前言在自动化测试工作中我们有时候并不需要测试所有的测试用例,比如在冒烟测试阶段,我们只需要测试基本功能是否正常就可以了。在pytest中提供
用例执行状态用例执行完成后,每条用例都有自己的状态,常见的状态有passed:测试通过failed:断言失败error:用例本身写的质量不行,本身代码报错(譬如:fixture不存在,fixture里面有报错)xfail:预期失败,加了 @pytest.mark.xfail()  error的栗子一:参数不存在 defpwd():prin
什么是conftest.py可以理解成一个专门存放fixture的配置文件 实际开发场景多个测试用例文件(test_*.py)的所有用例都需要用登录功能来作为前置操作,那就不能把登录功能写到某个用例文件中去了 如何解决上述场景问题?conftest.py的出现,就是为了解决上述问题,单独管理一些全局的
前言pytest默认执行用例是根据项目下的文件名称按ascii码去收集运行的;文件中的用例是从上往下按顺序执行的。pytest_collection_modifyitems这个函数顾名思义就是收集测试用例、改变用例的执行顺序的。【严格意义上来说,我们在用例设计原则上用例就不要有依赖顺序,这样才能更好
当我们对测试用例进行参数化时,使用@pytest.mark.parametrize的ids参数自定义测试用例的标题,当标题中有中文时,控制台和测试报告中会出现Unicode编码问题,这看起来特别像乱码,我们想让中文正常展示出来,需要用到pytest框架的钩子函数pytest_collection_modifyitems。先看问题:#file_n
前言:什么是元数据?元数据是关于数据的描述,存储着关于数据的信息,为人们更方便地检索信息提供了帮助。pytest框架里面的元数据可以使用pytest-metadata插件实现。文档地址https://pypi.org/project/pytest-metadata/未安装插件pytest-metadata之前执行:环境搭建:使用
前言前面一篇讲了setup、teardown可以实现在执行用例前或结束后加入一些操作,但这种都是针对整个脚本全局生效的如果有以下场景:用例1需要先登录,用例2不需要登录,用例3需要先登录。很显然无法用setup和teardown来实现了fixture可以让我们自定义测试用例的前置条件 
前言:写完一个项目的自动化用例之后,发现有些用例运行较慢,影响整体的用例运行速度,于是领导说找出运行慢的那几个用例优化下。--durations参数可以统计出每个用例运行的时间,对用例的时间做个排序。pytest-h查看命令行参数,关于--durations=N参数的使用方式--durations=N
钩子函数之pytest_addoption介绍:①pytest_addoption钩子函数可以让用户注册一个自定义的命令行参数,以便于用户在测试开始前将数据从外部(如:控制台)传递给程序;【程序根据获取的用户传递的自定义的参数值来做一些事情】②pytest_addoption钩子函数一般和内置fixturepytestcon
[pytest]#命令行参数----空格分隔,可添加多个命令行参数-所有参数均为插件包的参数addopts=-s-reruns1--html=..eporteport.html#测试路径----当前目录下的scripts文件夹-可自定义testpaths=../scripts#搜索文件名----当前目录下的scripts文件夹下,以test_开头,以.py
python通用测试框架大多数人用的是unittest+HTMLTestRunner,这段时间看到了pytest文档,发现这个框架和丰富的plugins很好用,所以来学习下pytest. image.pngpytest是一个非常成熟的全功能的Python测试框架,主要有以下几个特点:简单灵活,容易上手支持参数化能够支持简单的单
1、装饰器,放在函数前面,跳过用例 @pytest.mark.skip(reason="nowayofcurrentlytestingthis")importpytestdeftest1():print('操作1')print("-----------------------------------------------")@pytest.mark.skip(reason="nowayofcur
本文实例为大家分享了python下载微信公众号相关文章的具体代码,供大家参考,具体内容如下目的:从零开始学自动化测试公众号中下载“pytest"一系列文档1、搜索微信号文章关键字搜索2、对搜索结果前N页进行解析,获取文章标题和对应URL主要使用的是requests和bs4中的Beautifulsoup
From:https://www.jianshu.com/p/54b0f4016300一.fixture介绍fixture是pytest的一个闪光点,pytest要精通怎么能不学习fixture呢?跟着我一起深入学习fixture吧。其实unittest和nose都支持fixture,但是pytest做得更炫。fixture是pytest特有的功能,它用pytest.fixture标识,定义在函
参数化有两种方式:1、@pytest.mark.parametrize2、利用conftest.py里的pytest_generate_tests 1中的例子如下:@pytest.mark.parametrize("test_input,expected",[("3+5",8),("2+4",6),("6*9",42)])deftest_eval(test_input,expected):
pytest优于其他测试框架的地方:1、简单的测试可以简单的写2、复杂的测试也可以简单的写3、测试的可读性强4、易于上手5、断言失败仅使用原生assert关键字,而不是self.assertEqual()或者self.assertLessThan()6、pytest可以运行有unitest和nose编写的测试用例pytest不依赖pyth
学习python的pytest框架需要的基础知识和学习准备测试从业者学习python应该掌握的内容:首先是变量和数据类型,其次列表、字典以及Json的一些处理,再者就是循环判断以及函数或类这些内容。其中的重点:1.循环判断以及字典这块是重点2.函数和类,类的学习这块要花较多时间去学
前言pytest可以支持自定义标记,自定义标记可以把一个web项目划分多个模块,然后指定模块名称执行。app自动化的时候,如果想android和ios公用一套代码时,也可以使用标记功能,标明哪些是ios用例,哪些是android的,运行代码时候指定mark名称运行就可以mark标记1.以下用例,标记test_send_http(
unittest参考文档: https://docs.python.org/3/library/unittest.htmlunittest笔记TheunittestunittestingframeworkwasoriginallyinspiredbyJUnitandhasasimilarflavorasmajorunittestingframeworksinotherlanguages.Itsupportstestautomation,shar
fixture场景一:参数传入代码如下:运行结果: