From: http://www.testclass.net/pytest/parametrize_fixture/

背景

继续上一节的测试需求,在上一节里,任何1条测试数据导致断言不通过后测试用例就会停止运行,这样每次只能检查出1条不符合规范的数据,有没有什么办法可以一次性把所有的不符合结果都测出来呢?

这时候我们就需要用到参数化的fixture特性了

更新数据文件

新建users.test.json文件,内容如下

[
{"name":"jack","password":"Iloverose"},
{"name":"rose","password":"Ilovejack"}
{"name":"tom","password":"password123"},
{"name":"mike","password":"password"},
{"name":"james","password":"AGoodPasswordWordShouldBeLongEnough"}
]

我们增加了2条用户信息,其中mike的密码是弱密码。

参数化fixture

参数化fixture允许我们向fixture提供参数,参数可以是list,该list中有几条数据,fixture就会运行几次,相应的测试用例也会运行几次。

参数化fixture的语法是

@pytest.fixture(params=["smtp.gmail.com", "mail.python.org"])

其中len(params)的值就是用例执行的次数

在fixture的定义中,可以使用request.param来获取每次传入的参数,如下:

@pytest.fixture(scope="module",
params=["smtp.gmail.com", "mail.python.org"])
def smtp(request):
smtp = smtplib.SMTP(request.param, 587, timeout=5)
yield smtp
print ("finalizing %s" % smtp)
smtp.close()
  • 上面的代码smtp fixture会执行2次
  • 第1次request.param == 'smtp.gmail.com'
  • 第2次request.param == 'mail.python.org'

实现用例

我们现在使用参数化fixtures来实现一次性检查出弱密码的用例。

新建文件test_user_password_with_params.py,内容如下:


import pytest
import json
users = json.loads(open('./users.test.json', 'r').read()) class TestUserPasswordWithParam(object):
@pytest.fixture(params=users)
def user(self, request):
return request.param def test_user_password(self, user):
passwd = user['password']
assert len(passwd) >= 6
msg = "user %s has a weak password" %(user['name'])
assert passwd != 'password', msg
assert passwd != 'password123', msg

上面的例子里,我们先把所有用户信息读到users变量里,注意users这时候是list类型,可以直接传入到fixture的params

运行及结果

运行

pytest test_user_password_with_params.py

结果

$ pytest test_user_password_with_params.py
========================================================================= test session starts =========================================================================
platform darwin -- Python 2.7.12, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /Users/easonhan/code/testclass.net/src/pytest, inifile:
collected 5 items test_user_password_with_params.py ..FF. ============================================================================== FAILURES ===============================================================================
_________________________________________________________ TestUserPasswordWithParam.test_user_password[user2] _________________________________________________________ self = <test_user_password_with_params.TestUserPasswordWithParam object at 0x10de1d790>, user = {'name': 'tom', 'password': 'password123'} def test_user_password(self, user):
passwd = user['password']
assert len(passwd) >= 6
msg = "user %s has a weak password" %(user['name'])
assert passwd != 'password', msg
> assert passwd != 'password123', msg
E AssertionError: user tom has a weak password
E assert 'password123' != 'password123' test_user_password_with_params.py:15: AssertionError
_________________________________________________________ TestUserPasswordWithParam.test_user_password[user3] _________________________________________________________ self = <test_user_password_with_params.TestUserPasswordWithParam object at 0x10de1df50>, user = {'name': 'mike', 'password': 'password'} def test_user_password(self, user):
passwd = user['password']
assert len(passwd) >= 6
msg = "user %s has a weak password" %(user['name'])
> assert passwd != 'password', msg
E AssertionError: user mike has a weak password
E assert 'password' != 'password' test_user_password_with_params.py:14: AssertionError
================================================================= 2 failed, 3 passed in 0.05 seconds ==================================================================

稍微留意一下, 可以看出tom和mike使用了弱密码。总共运行了5个用例,3个成功,2个失败。

fixture的更多特性

fixture还有很多更加灵活和深入的用法,具体见这里

pytest.5.参数化的Fixture的更多相关文章

  1. Pytest(3)fixture的使用

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

  2. Pytest高级进阶之Fixture

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

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

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

  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 8 参数化parametrize

    pytest.mark.parametrize装饰器可以实现用例参数化 1.以下是一个实现检查一定的输入和期望输出测试功能的典型例子 import pytest @pytest.mark.parame ...

  7. pytest的参数化测试

    感觉在单元测试当中可能有用, 但在django这种框架中,用途另一说. import pytest import tasks from tasks import Task def test_add_1 ...

  8. pytest的参数化

    参数化有两种方式: 1. @pytest.mark.parametrize 2.利用conftest.py里的 pytest_generate_tests 1中的例子如下: @pytest.mark. ...

  9. pytest初始化与清除fixture(二)

    @pytest.fixture用法 1.导入pytest模块:import pytest 2.调用装饰器函数:@pytest.fixture(callable_or_scope=None,*args, ...

随机推荐

  1. 【c++基础】c++提升速度的方法总结

    参考 1. C++程序提高运行速度的方法; 2. 提高C++程序运行效率的10个简单方法; 3. C++编程中提高程序运行效率的方式(不断更新); 完

  2. MySQL篇,第四章:数据库知识4

    MySQL 数据库 4 数据备份(在Linux终端操作) 1.命令格式 mysqldump -u用户名 -p 源库名 > 路径/XXX.sql 2.源库名的表示方式 --all-database ...

  3. nmon使用命令

    nmon使用命令   启动nmon后, c       查看CPU监控的窗口 mV     查看内存和虚拟内存            V是大写 ndt     查看网络.磁盘和虚拟进程 q      ...

  4. 初识Odoo的辅助核算

    Odoo财务里类似辅助核算功能的叫做:Analytic Accouting,翻译为,分析会计. 再说说辅助核算是个什么东东. 财务辅助核算就是基于会计科目和会计理论分析财务数据的辅助工具. 简单的说就 ...

  5. HDU1272小希的迷宫–并查集

    上次Gardon的迷宫城堡小希玩了很久(见Problem B),现在她也想设计一个迷宫让Gardon来走.但是她设计迷宫的思路不一样,首先她认为所有的通道都应该是双向连通的,就是说如果有一个通道连通了 ...

  6. php基础-2

    php的逻辑运算 &&符号 <?php function tarcrnum() { for ($i = 0; $i <= 100; $i++) { if ($i % 2 = ...

  7. 【BZOJ4554】【TJOI2016】【HEOI2016】游戏

    我好弱啊quq 原题: 在2016年,佳缘姐姐喜欢上了一款游戏,叫做泡泡堂.简单的说,这个游戏就是在一张地图上放上若干个炸弹,看 是否能炸到对手,或者躲开对手的炸弹.在玩游戏的过程中,小H想到了这样一 ...

  8. openresty 集成lua-resty-mail +smtp2http 扩展灵活的mail 服务

    lua-resty-mail 是一个不错的openresty mail 扩展,我们可以用来进行邮件发送,支持附件功能 smtp2http 是一个smtp 服务,可以将smtp 请求数据转换为http ...

  9. 计算元素个数(count和count_if)

    count 计算first和last之间与value相等于元素个数 template <class InputIterator,class EqualityComparable> type ...

  10. 不用修改 hosts 本地开发(续篇)

    上一篇说过不修改 hosts 在 Chrome 中可以使用 *.localhost 进行绑定域名开发. 但只能用于 Chrome 中,今天找了一个还有一些好心人提供了域名指向 127.0.0.1 . ...