@pytest.fixture用法

1.导入pytest模块:import pytest

2.调用装饰器函数:@pytest.fixture(callable_or_scope=None,*args,scope='function',params=None,autouse=False,ids=None,name=None)

scope=function(默认值),表示作用于每一个测试用例

scope=class,表示每一个类调用一次,一个类中可以有多个方法

scope=moudle,表示每一个.py文件调用一次

scope=session,表示多个文件调用一次

autouse=True,表示每个测试用例都会执行初始化清除操作

  1. import pytest
  2.  
  3. @pytest.fixture(autouse=True)
  4. def before():
  5. print("this is setup")
  6. yield
  7. after()
  8.  
  9. '''以下是初始化配套清除操作的第二种写法,代替yield'''
  10. @pytest.fixture(autouse=True)
  11. def before(request):
  12. print("this is setup")
  13. request.addfinalizer(after())
  14.  
  15. def after():
  16. print("this is teardown")
  17.  
  18. def test_001():
  19. print("this is test_001()")
  20.  
  21. def test_002():
  22. print("this is test_002()")

C:\Users\cale\checkapi\test>pytest -s test_gy.py
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 2 items

test_gy.py this is setup
this is test_001()
.this is teardown
this is setup
this is test_002()
.this is teardown

  1.  

 autouse=False(默认值),不会作用于每个测试用例,哪些测试用例要执行初始化清除操作需在测试用例里面传入对应的参数

  1. from api.compare_result import CompareResult
  2. from api.gy import gy_v4
  3. import pytest
  4. class TestSuite():
  5. def test_gy1(self,start):
  6. '''start:调用start()方法作为该测试用例的初始化清除方法'''
  7. inputxml1 = 'C:/Users/cale/checkapi/data/input/gyopt.xml'
  8. outputxml1 = 'C:/Users/cale/checkapi/data/output/gyopt.xml'
  9. cmpr=CompareResult()
  10. cmpr.compareXML(gy_v4,inputxml1,outputxml1)
  11. @pytest.fixture(autouse=False)
  12. def start(self):
  13. '''调用fixture()装饰器,将此方法装饰成初始化清除方法'''
  14. print("执行测试套件前会先执行此方法")
  15. yield
  16. self.end()
  17. def end(self):
  18. print('执行完测试套件后会执行此方法')
  19. 执行结果:
  20. test_gy.py 执行测试套件前会先执行此方法
  21. .<?xml version="1.0" encoding="UTF-8"?>
  22. <root><result><base><hospital_code>H0003</hospital_code><event_no></event_no><patient_id>004026990100aa</patient_id><source>门诊</source></base><btnStatus></btnStatus><invoke_result><invoke_status>0</invoke_status><invoke_message>调用失败</invoke_message></invoke_result><message><recipe_id></recipe_id><infos><info><info_id>1585813554277</info_id><recipe_item_id></recipe_item_id><group_no></group_no><drug_id></drug_id><drug_name></drug_name><error_info>干预异常!</error_info><advice></advice><source></source><rt></rt><source_id></source_id><severity></severity><message_id></message_id><type></type><analysis_type></analysis_type><analysis_result_type></analysis_result_type><info_type>0</info_type></info></infos></message></result></root>
  23. 比标准出参多出来的节点如下>>>>>>>>>>>>>>>>>
  24. 没有多余的节点
  25. 比标准出参少的节点如下>>>>>>>>>>>>>>>>>
  26. 没有缺少的节点
  27. 与标准出参类型不一致的节点如下>>>>>>>>>>>>>>>>>
  28. 节点名称:event_no ,标准出参类型:str ,实际出参类型:<class 'NoneType'>
  29. 节点名称:source ,标准出参类型:str ,实际出参类型:<class 'NoneType'>
  30. 执行完测试套件后会执行此方法
  31. [100%]
  32. ============================== 1 passed in 1.71s ==============================

用fixture decorator调用fixture(autouse=False的情况下)

  1. import pytest
  2.  
  3. @pytest.fixture(autouse=True)
  4. def before():
  5. print("this is setup")
  6. yield
  7. after()
  8.  
  9. def after():
  10. print("this is teardown")
  11.  
  12. class TestSuite():
  13. @pytest.mark.usefixtures("before")
  14. def test_003(self):
  15. print("test_003()")
  16.  
  17. @pytest.mark.usefixtures("before")
  18. def test_004(self):
  19. print("test_004()")
  20.  
  21. @pytest.mark.usefixtures("before")
  22. class TestSuite2():
  23. def test_004(self):
  24. print("test_004()")
  25.  
  26. def test_005(self):
  27. print("test_005()")

C:\Users\cale\checkapi\test>pytest -s test_gy.py
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 4 items

test_gy.py this is setup
test_003()
.this is teardown
this is setup
test_004()
.this is teardown
this is setup
test_004()
.this is teardown
this is setup
test_005()
.this is teardown

用autos调用fixture (autouse=True的情况下)

  1. import pytest
  2.  
  3. @pytest.fixture(scope='module',autouse=True)
  4. def mod_header(request):
  5. print("module:%s"%(request.module.__name__))
  6.  
  7. @pytest.fixture(scope='function',autouse=True)
  8. def func_header(request):
  9. print("function:%s"%(request.function.__name__))
  10.  
  11. def test_006():
  12. print("test_006")
  13.  
  14. def test_007():
  15. print("test_007")

    运行结果:

C:\Users\cale\checkapi\test>pytest test_gy.py -s
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 2 items

test_gy.py module:test_gy
function:test_006
test_006
.function:test_007
test_007
.

================================================== 2 passed in 0.12s ==================================================

 以上mod_header()函数运行了一次,在所有测试用例执行前运行了一次;func_header()运行了两次,每个测试用例执行前都会运行一次

fixture返回值的使用

  1. import pytest
  2.  
  3. @pytest.fixture(params=[1,2])
  4. def test_data(request):
  5. return request.param
  6.  
  7. def test_not_2(test_data):
  8. print("test_data:%s"%(test_data))
  9. assert test_data!=2

    运行结果:

C:\Users\cale\checkapi\test>pytest test_gy.py -s
================================================= test session starts =================================================
platform win32 -- Python 3.7.3, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: C:\Users\cale\checkapi\test
plugins: html-2.0.0, metadata-1.8.0, rerunfailures-7.0
collected 2 items

test_gy.py test_data:1
.test_data:2
F

====================================================== 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_gy.py:49: AssertionError
============================================= 1 failed, 1 passed in 0.47s =============================================

可以看到test_not_2这个测试用例执行了两次,test_data函数中params这个变量传了几个参数,测试用例就会运行几次

链接:https://www.jianshu.com/p/54b0f4016300

目录下的初始化(session):https://blog.csdn.net/qq_36502272/article/details/100776789

pytest初始化与清除fixture(二)的更多相关文章

  1. pytest初始化与清除(一)

    一.初始化函数 1.测试用例级别:def setup() 2.套件级别(在模块文件中定义):def setup_module() 3.套件级别(在类中定义): @classmethod def set ...

  2. Pytest(3)fixture的使用

    fixture的优势 Pytest的fixture相对于传统的xUnit的setup/teardown函数做了显著的改进: 命名方式灵活,不局限于 setup 和teardown 这几个命名 conf ...

  3. 《C++编程思想》第四章 初始化与清除(原书代码+习题+解答)

    相关代码: 1. #include <stdio.h> class tree { int height; public: tree(int initialHeight); ~tree(); ...

  4. pytest进阶之xunit fixture

    前言 今天我们再说一下pytest框架和unittest框架相同的fixture的使用, 了解unittest的同学应该知道我们在初始化环境和销毁工作时,unittest使用的是setUp,tearD ...

  5. pytest自动化3:fixture之conftest.py实现setup

    出处:https://www.cnblogs.com/yoyoketang/p/9390073.html 前言: 前面一篇讲到用例加setup和teardown可以实现在测试用例之前或之后加入一些操作 ...

  6. Pytest高级进阶之Fixture

    From: https://www.cnblogs.com/feiyi211/p/6626314.html 一. fixture介绍 fixture是pytest的一个闪光点,pytest要精通怎么能 ...

  7. Pytest单元测试框架之FixTure基本使用

    前言: 在单元测试框架中,主要分为:测试固件,测试用例,测试套件,测试执行及测试报告: 测试固件不难理解,也就是我们在执行测试用例前需要做的动作和测试执行后的需要做的事情: 比如在UI自动化测试中,我 ...

  8. bss段为什么要初始化,清除

    我们都知道bss段需要初始化,但是这是为什么呢? 通过浏览资料,我们都会发现,bss段是不会出现在程序下载文件(*.bin *.hex)中的,因为全都是0.如果把它们出现在程序下载文件中,会增加程序下 ...

  9. pytest.5.参数化的Fixture

    From: http://www.testclass.net/pytest/parametrize_fixture/ 背景 继续上一节的测试需求,在上一节里,任何1条测试数据导致断言不通过后测试用例就 ...

随机推荐

  1. Win64 驱动内核编程-2.基本框架(安装.通讯.HelloWorld)

    驱动安装,通讯,Hello World 开发驱动的简单流程是这样,开发驱动安装程序,开发驱动程序,然后安装程序(或者其他程序)通过通讯给驱动传命令,驱动接到之后进行解析并且执行,然后把执行结果返回. ...

  2. Oauth2.0认证

    目录 Oauth Oauth2.0 客户端应用注册 授权码模式(authorization code)流程

  3. Intel汇编程序设计-高级过程(上)

    第八章 高级过程 8.1 简介 本章主要讲: 堆栈框架 变量作用域和生存期 对战参数的类型 通过传递值或者传递引用来传递参数 在堆栈上创建和初始化局部变量 递归 编写多模块程序 内存模型和语言关键字 ...

  4. 使用乌龟Git连接github

    之前自己是在Gitee+乌龟Git来进行管理项目,因为特殊的需求,需要再Github+乌龟Git来进行管理项目,这盘博客主要讲解的就是这个. 安装环境 Git 安装参考链接:https://www.c ...

  5. Java学习之jackson篇

    Java学习之jackson篇 0x00 前言 本篇内容比较简单,简单记录. 0x01 Json 概述 概述:JSON(JavaScript Object Notation, JS 对象简谱) 是一种 ...

  6. 33.2.NIO

    4.1概述[理解] BIO Blocking IO,阻塞型IO NIO No Blocking IO,非阻塞型IO 阻塞IO的弊端 在等待的过程中,什么事也做不了 非阻塞IO的好处 不需要一直等待,当 ...

  7. [tools] 工具

    代码编辑 notepad++ 文档对比 Beyond Compare 代码阅读 source insight 代码分析 Scitools 下载 http://www.cr173.com/soft/29 ...

  8. google 谷歌Python语言规范

    Python语言规范 https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_lan ...

  9. Web网站实现用户认证访问(加密访问)

    Web网站实现用户认证访问,有效减少流量的访问,具体的实现步骤如下: 我们使用httpd作为测试对象,体现安装好httpd服务,并且可以在浏览器访问测试首页(可以关闭防火墙:如果不关闭防火墙,则需要开 ...

  10. 运维常用shell脚本二(压缩文件、过滤不需要的文件、检测进程)

    一.压缩指定目录下的文件并删除原文件 #!/bin/bashZIP_DAY=7 function zip { local dir=$1 if [ -d $dir ];then local file_n ...