fixture的作用:作用类似unittest中setup/teardown,它的优势是可以跨文件共享

fixture的格式:在普通函数上加上装饰器@pytest.fixture(),且函数名不能以test_开头,目的是与测试用例做区分

一 fixture的三种调用方式

1.在测试用例中  直接把fixture的函数名称作为参数传入  进行调用

fixture如何使用?fixture可以有返回值,如果没有return默认但会None;用例调用fixture的返回值,就是直接把fixture的函数名称作为参数传入。

特别说明:用例断言失败是failed,fixture断言失败是error

fixture的作用范围

demo1:fixture可以返回一个元组、列表或字典

  1. # test_01.py
  2. import pytest
  3.  
  4. @pytest.fixture()
  5. def user():
  6. print("用户名")
  7. name = 'wangmm'
  8. password = ''
  9. return name,password
  10.  
  11. def test_a(user):
  12. u = user[0]
  13. p = user[1]
  14. assert u == 'wangmm'
  15.  
  16. 执行结果:
  17. D:\myproject\pytest_demo\testcases>pytest -vs test_01.py
  18. =================================================================================== test session starts ====================================================================================
  19. platform win32 -- Python 3.6.5, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- d:\soft\python36\python.exe
  20. cachedir: .pytest_cache
  21. rootdir: D:\myproject\pytest_demo\testcases
  22. collected 1 item
  23.  
  24. test_01.py::test_a 用户名
  25. PASSED
  26.  
  27. ================================================================================= 1 passed in 0.03 seconds =================================================================================

demo2:test_用例传多个fixture参数

  1. # test_02.py
  2. import pytest
  3.  
  4. @pytest.fixture()
  5. def username():
  6. name = 'wangmm'
  7. return name
  8.  
  9. @pytest.fixture()
  10. def pw():
  11. password = ''
  12. return password
  13.  
  14. def test_user(username, pw):
  15. assert username == 'wangmm'
  16. assert pw == ''
  17.  
  18. 执行结果:
  19. D:\myproject\pytest_demo\testcases>pytest -vs test_02.py
  20. =================================================================================== test session starts ====================================================================================
  21. platform win32 -- Python 3.6.5, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- d:\soft\python36\python.exe
  22. cachedir: .pytest_cache
  23. rootdir: D:\myproject\pytest_demo\testcases
  24. collected 1 item
  25.  
  26. test_02.py::test_user PASSED
  27.  
  28. ================================================================================= 1 passed in 0.03 seconds =============================================    ====================================

demo3:fixture与fixture间相互调用

  1. # test_03.py
  2. import pytest
  3.  
  4. @pytest.fixture()
  5. def first():
  6. a = "wangmm"
  7. return a
  8.  
  9. @pytest.fixture()
  10. def sencond(first):
  11. '''psw调用user fixture'''
  12. a = first
  13. b = ""
  14. return (a, b)
  15.  
  16. def test_1(sencond):
  17. '''用例传fixture'''
  18. assert sencond[0] == "wangmm"
  19. assert sencond[1] == ""
  20.  
  21. 输出结果:
  22. D:\myproject\pytest_demo\testcases>pytest -vs test_03.py
  23. =================================================================================== test session starts ====================================================================================
  24. platform win32 -- Python 3.6.5, pytest-5.0.1, py-1.8.0, pluggy-0.12.0 -- d:\soft\python36\python.exe
  25. cachedir: .pytest_cache
  26. rootdir: D:\myproject\pytest_demo\testcases
  27. collected 1 item             
  28.  
  29. test_03.py::test_1 PASSED

2.使用usefixtures    但是需要注意如果fixture有返回值则不能使用usefixtures,usefixtures是获取不到返回值的

  1. @pytest.mark.usefixtures("user")
  2. def test_b():
  3. # u = user[0]
  4. # assert u == 'wangmm'
  5. assert 1 == 1

3.使用autos自动调用fixture    注意:如果不传autouse,默认scope=False

  1. @pytest.fixture(scope='function',autouse=True)
  2. def login_test():
  3. print("登录")
  4.  
  1. def test_s7(): # 该测试用例不需要传login_test,会自动调用的
    print("用例1:登录之后其它动作111")

二 使用conftest.py实现多文件共享fixture

一个测试工程下是可以有多个conftest.py的文件,一般在工程根目录放一个conftest.py起到全局作用。
在不同的测试子目录也可以放conftest.py,作用范围只在该层级以及以下目录生效。

特别地:conftest.py不需要显示导入,pytest会自动读取该文件

session > module > class > function

@pytest.fixture(scope="session"):多个文件调用一次,可以跨.py,每个.py就是module

@pytest.fixture(scope="module"):module级别的fixture在当前.py模块里,只会在用例第一次调用前执行一次

@pytest.fixture(scope="class"):class级别的fixture,在每个类里,只会在第一次调用前执行一次

@pytest.fixture(scope="function"):function级别,每个函数都会调用(默认)

  1. # conftest.py
  2. import pytest
  3.  
  4. @pytest.fixture(scope="class")
  5. def login():
  6. print("登录系统")
  7.  
  8. # test_fix.py
  9. import pytest
  10.  
  11. class Test1:
  12. def test_s1(self,login):
  13. print("用例1:登录之后其它动作111")
  14.  
  15. def test_s2(self): # 不传login
  16. print("用例2:不需要登录,操作222")
  17.  
  18. def test_s3(self, login):
  19. print("用例3:登录之后其它动作333")
  20.  
  21. class Test2:
  22. def test_s4(self, login):
  23. print("用例4:登录之后其它动作444")
  24.  
  25. def test_s5(self): # 不传login
  26. print("用例5:不需要登录,操作555")
  27.  
  28. def test_s6(self, login):
  29. print("用例6:登录之后其它动作666")
  30.  
  31. 输出结果:
  32. testcases\test_fix.py 登录系统
  33. 用例1:登录之后其它动作111
  34. .用例2:不需要登录,操作222
  35. .用例3:登录之后其它动作333
  36. .登录系统
  37. 用例4:登录之后其它动作444
  38. .用例5:不需要登录,操作555
  39. .用例6:登录之后其它动作666

三 fixture中yield的作用

Fixture finalization / executing teardown code 
By using a yield statement instead of return, all the code after the yield statement serves as the teardown code.

测试代码的执行顺序: yield前的代码-测试用例中的代码-yield后的代码

demo1:

  1. # conftest.py
  2. import pytest
  3. import smtplib
  4.  
  5. @pytest.fixture(scope='module')
  6. def smtp_connection():
  7. smtp_connection = smtplib.SMTP('smtp.126.com',25)
  8. yield smtp_connection
  9. print("teardown smtp")
  10. smtp_connection.close()
  11.  
  12. # test_module.py
  13. def test_ehlo(smtp_connection):
  14. response, msg = smtp_connection.ehlo()
  15. assert response == 250
  16. # assert 0
  17.  
  18. def test_noop(smtp_connection):
  19. response, msg = smtp_connection.noop()
  20. assert response == 250
  21. # assert 0
  22.  
  23. 输出结果:
  24. D:\myproject\pytest_demo>pytest -qs --tb=no test_module.py # --tb=no,指关闭回溯信息
  25. ..teardown smtp
  26.  
  27. 2 passed in 13.75 seconds

四 多个fixture的执行顺序

举例:

  1. import pytest
  2.  
  3. order = []
  4.  
  5. @pytest.fixture(scope='session')
  6. def s1():
  7. order.append("s1")
  8.  
  9. @pytest.fixture(scope='module')
  10. def m1():
  11. order.append('m1')
  12.  
  13. @pytest.fixture()
  14. def f1(f3):
  15. order.append('f1')
  16.  
  17. @pytest.fixture()
  18. def f3():
  19. order.append('f3')
  20.  
  21. @pytest.fixture(autouse=True)
  22. def a1():
  23. order.append('a1')
  24.  
  25. @pytest.fixture()
  26. def f2():
  27. order.append('f2')
  28.  
  29. def test_order(f1, m1, f2, s1):
  30. assert order == ["s1", "m1", "a1", "f3", "f1", "f2"]
  31.  
  32. 输出结果:1 passed  #即test_doder.py测试用例通过

理论:

session > module > class > function

@pytest.fixture(scope="session"):多个文件调用一次,可以跨.py,每个.py就是module

@pytest.fixture(scope="module"):module级别的fixture在当前.py模块里,只会在用例第一次调用前执行一次

@pytest.fixture(scope="class"):class级别的fixture,在每个类里,只会在第一次调用前执行一次

@pytest.fixture(scope="function"):function级别,每个函数都会调用(默认)

  1. def fixture(scope="function", params=None, autouse=False, ids=None, name=None):
  2.  
  3. :arg scope: the scope for which this fixture is shared, one of
  4. ``"function"`` (default), ``"class"``, ``"module"``,
  5. ``"package"`` or ``"session"``.
  6.  
  7. ``"package"`` is considered **experimental** at this time.

fixture源码

特别地:平常写自动化用例会写一些前置的fixture操作,用例需要用到就直接传该函数的参数名称就行了。当用例很多的时候,每次都传这个参数,会比较麻烦。
fixture里面有个参数autouse,默认是Fasle没开启的,可以设置为True开启自动使用fixture功能,这样用例就不用每次都去传参了

pytest4-单文件使用fixture(Fixtures as Function arguments)的更多相关文章

  1. tp5 ajax单文件上传

    HTML代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  2. ASP.NET MVC5+EF6+EasyUI 后台管理系统(56)-插件---单文件上传与easyui使用fancybox

    系列目录 https://yunpan.cn/cZVeSJ33XSHKZ  访问密码 0fc2 今天整合lightbox插件Fancybox1.3.4,发现1.3.4版本太老了.而目前easyui 1 ...

  3. 小型单文件NoSQL数据库SharpFileDB初步实现

    小型单文件NoSQL数据库SharpFileDB初步实现 我不是数据库方面的专家,不过还是想做一个小型的数据库,算是一种通过mission impossible进行学习锻炼的方式.我知道这是自不量力, ...

  4. webpack入坑之旅(五)加载vue单文件组件

    这是一系列文章,此系列所有的练习都存在了我的github仓库中vue-webpack,在本人有了新的理解与认识之后,会对文章有不定时的更正与更新.下面是目前完成的列表: webpack入坑之旅(一)不 ...

  5. yii2.0单文件上传和多文件上传

    yii2文件上传使用到yii2自带的文件上传类UploadFIle,以及对应的模型规则,这里分别介绍单文件上传和多文件上传: yii2单个文件上传: 上传步奏,先创建上传表单模型model(包含验证规 ...

  6. Struts1文件上传、单文件、多文件上传【Struts1】

     将struts1文件上传的操作汇总了一下,包括单文件上传和多文件上传,内容如下,留作备忘: Struts2实现文件上传的文章(http://blog.csdn.net/itwit/article/d ...

  7. Vue单文件组件基础模板

    背景 相信大家在使用Vue开发项目时,基本都是以单文件组件的形式开发组件的,这种方式好处多多: 1.代码集中,便于开发.管理和维护 2.可复用性高,直接将vue文件拷贝到新项目中 我暂时就想到这两点, ...

  8. ng-file-upload(在单文件选择,并且通过点击“上传”按钮上传文件的情况下,如何在真正选择文件之前保留上一文件信息?)

    文章前面研究ng-file-upload可能涉及指令: You can use ng-model or ngf-change instead of specifying function for ng ...

  9. Vue 单文件元件 — vTabs

    简书原文 这是我做了第二个单文件元件 第一个在这里vCheckBox 这次这个叫vTabs,用于操作标签页 演示DEMO 演示DEMO2 - 子组件模式及别名 演示DEMO3 - 极简模式 示例: h ...

随机推荐

  1. cocos meta 文件git显示

    是如果提交meta文件后,并且大家是用git来做版本控制的话,CCC可能会在打开时自动修改meta(即使你是刚从最新版本拉下来的),这个问题的原因是git在windows和linux不同系统间换行符不 ...

  2. 年年有余之java求余的技巧集合

    背景 传说里玉皇大帝派龙王马上降雨到共光一带,龙王接到玉皇大帝命令,立马从海上调水,跑去共光施云布雨,但粗心又着急的龙王不小心把海里的鲸鱼随着雨水一起降落在了共光,龙王怕玉皇大帝责怪,灵机一动便声称他 ...

  3. scp建立安全信任关系

    1. 在机器Client上root用户执行ssh-keygen命令,生成建立安全信任关系的证书. [root@Client root]# ssh-keygen -b 1024 -t rsa Gener ...

  4. HTML文档简介

    HTML简介 HTML标签 html文档标签: html源代码就好像word文档,有特殊的语法结构定义自己的功能. html文档标签 html标签,其下由两个主要节点标签head.body. head ...

  5. Hadoop 之 MapReduce原理

    1.什么是MapReduce 答:简而言之,就是将一个大任务分成多个小的子任务(Map),并行执行后,合并结果(Reduce).下面举一个纸牌得栗子  2.MapReduce的运行流程  3.JobT ...

  6. 配置树莓派3的openwrt中的网络

    在上一篇中讲到openwrt的编译安装: http://www.cnblogs.com/yeqluofwupheng/p/7296218.html 但是烧写进去,启动系统后发现它的默认配置是路由器,所 ...

  7. github博客Hexo引流到微信

    相信有不少小伙伴都在github上创建了属于自己的博客,其中用Hexo的Next主题应该不少,那么,我们究竟该如何将博客的流量引流到微信呢?今天就来带你看一看. 如何引流 现在网上有一种套路,当你在看 ...

  8. 数位DP 详解

    序 天堂在左,战士向右 引言 数位DP在竞赛中的出现几率极低,但是如果不会数位DP,一旦考到就只能暴力骗分. 以下是数位DP详解,涉及到的例题有: [HDU2089]不要62 [HDU3652]B-n ...

  9. thymeleaf 语法

    一.语法: 1. 简单表达式 (simple expressions) ${...}  变量表达式 *{...}  选择变量表达式 #{...}  消息表达式 @{...}  链接url表达式 2.字 ...

  10. mysql root密码忘记

    首先停掉mysql服务,在/etc/my.cnf中添加 skip-grant-tables,同时可以添加skip-networking选项来禁用网络功能,防止这时其他人通过网络连接到数据库 [mysq ...