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

我们可以简单的把Fixture理解为准备测试数据和初始化测试对象的阶段。

一般我们对测试数据和测试对象的管理有这样的一些场景

  • 所有用例开始之前初始化测试数据或对象
  • 所有用例结束之后销毁测试数据或对象
  • 每个用例开始之前初始化测试数据或对象
  • 每个用例结束之后销毁测试数据或对象
  • 在每个/所有module的用例开始之前初始化数据或对象
  • 在每个/所有module的用例开始之后销毁数据或对象
  • ……
  • ……

pytest的fixture特性可以满足上面的需求。

简单的例子

考虑这种场景,我们需要判断用户的密码中包含简单密码,规则是这样的,密码必须至少6位,满足6位的话判断用户的密码不是password123或者password之类的弱密码。

我们将用户的信息导出成名为users.dev.json的文件,该文件如下所示

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

新建名为test_user_password.py的文件,键入以下内容,一定要保证users.dev.json文件与该文件在同一路径下

import pytest
import json class TestUserPassword(object):
@pytest.fixture
def users(self):
return json.loads(open('./users.dev.json', 'r').read()) # 读取当前路径下的users.dev.json文件,返回的结果是dict def test_user_password(self, users):
# 遍历每条user数据
for user in users:
passwd = user['password']
assert len(passwd) >= 6
msg = "user %s has a weak password" %(user['name'])
assert passwd != 'password', msg
assert passwd != 'password123', msg

运行

pytest可以通过指定文件名的方式运行单个用例文件,这里我们只运行test_user_password.py文件

pytest test_user_password.py

运行结果

$ pytest test_user_password.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 1 item test_user_password.py F ============================================================================== FAILURES ===============================================================================
_________________________________________________________________ TestUserPassword.test_user_password _________________________________________________________________ self = <test_user_password.TestUserPassword object at 0x1046e3290>
users = [{'name': 'jack', 'password': 'Iloverose'}, {'name': 'rose', 'password': 'Ilovejack'}, {'name': 'tom', 'password': 'password123'}] def test_user_password(self, users):
for user in users:
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.py:14: AssertionError
====================================================================== 1 failed in 0.03 seconds =======================================================================

分析

  • 使用@pytest.fixture装饰器可以定义feature
  • 在用例的参数中传递fixture的名称以便直接调用fixture,拿到fixture的返回值
  • 3个assert是递进关系,前1个assert断言失败后,后面的assert是不会运行的,因此重要的assert放到前面
  • E AssertionError: user tom has a weak password可以很容易的判断出是哪条数据出了问题,所以定制可读性好的错误信息是很必要的
  • 任何1个断言失败以后,for循环就会退出,所以上面的用例1次只能发现1条错误数据,换句话说任何1个assert失败后,用例就终止运行了

执行顺序

pytest是这样运行上面的用例的

  1. pytest找到以test_开头的方法,也就是test_user_password方法,执行该方法时发现传入的参数里有跟fixture users名称相同的参数
  2. pytest认定users是fixture,执行该fixture,读取json文件解析成dict实例
  3. test_user_password方法真正被执行,users fixture被传入到该方法

注意 我们可以使用下面的命令来查看用例中可用的fixtures

pytest --fixtures test_user_password.py

数据清理

有时候我们需要在用例结束的时候去清理一些测试数据,或清除测试过程中创建的对象,我们可以使用下面的方式

import smtplib
import pytest @pytest.fixture(scope="module")
def smtp():
smtp = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
yield smtp # provide the fixture value
print("teardown smtp")
smtp.close()
  • yield 关键字返回了fixture中实例化的对象smtp
  • module中的用例执行完成后smtp.close()方法会执行,无论用例的运行状态是怎么样的,都会执行

更多的数据清理方式

addfinalizer 也可以完成数据清理的工作,具体见(这里)[https://docs.pytest.org/en/latest/fixture.html#fixture-finalization-executing-teardown-code]

pytest.4.Fixture的更多相关文章

  1. pytest(6)-Fixture(固件)

    什么是固件 Fixture 翻译成中文即是固件的意思.它其实就是一些函数,会在执行测试方法/测试函数之前(或之后)加载运行它们,常见的如接口用例在请求接口前数据库的初始连接,和请求之后关闭数据库的操作 ...

  2. 『德不孤』Pytest框架 — 12、Pytest中Fixture装饰器(二)

    目录 5.addfinalizer关键字 6.带返回值的Fixture 7.Fixture实现参数化 (1)params参数的使用 (2)进阶使用 8.@pytest.mark.usefixtures ...

  3. pytest 15 fixture之autouse=True

    前言 平常写自动化用例会写一些前置的fixture操作,用例需要用到就直接传该函数的参数名称就行了.当用例很多的时候,每次都传这个参数,会比较麻烦.fixture里面有个参数autouse,默认是Fa ...

  4. pytest 5. fixture之yield实现teardown

    前言: 1.前面讲的是在用例前加前置条件,相当于setup,既然有setup那就有teardown,fixture里面的teardown用yield来唤醒teardown的执行 看以下的代码: #!/ ...

  5. pytest 3.fixture介绍一 conftest.py

    前言: 前面一篇pytest2 讲到用例加setup和teardown可以实现在测试用例之前或之后加入一些操作,但这种是整个脚本全局生效的,如果我想实现以下场景: 用例1需要先登录,用例2不需要登录, ...

  6. pytest的fixture和conftest

    解决问题:用例1需要先登录,用例2不需要登录,用例3需要先登录.很显然这就无法用setup和teardown来实现了,这个时候就可以自定义测试用例的预置条件,比setup灵活很多. 1.fixture ...

  7. 【Pytest04】全网最全最新的Pytest框架fixture应用篇(2)

    一.Fixture参数之params参数可实现参数化:(可以为list和tuple,或者字典列表,字典元祖等) 实例如下: import pytest def read_yaml(): '] @pyt ...

  8. 【Pytest03】全网最全最新的Pytest框架fixture应用篇(1)

    fixtrue修饰器标记的方法通常用于在其他函数.模块.类或者整个工程调用时会优先执行,通常会被用于完成预置处理和重复操作.例如:登录,执行SQL等操作. 完整方法如下:fixture(scope=' ...

  9. pytest之fixture使用详解

    简介: fixture区别于unnitest的传统单元测试(setup/teardown)有显著改进: 1.有独立的命名,并通过声明它们从测试函数.模块.类或整个项目中的使用来激活. 2.按模块化的方 ...

随机推荐

  1. Python之路,第一篇:Python入门与基础

    第一篇:Python入门与基础 1,什么是python? Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. 2,python的特征: (1)易于学习,易于利用: (2)开 ...

  2. [LeetCode&Python] Problem 551. Student Attendance Record I

    You are given a string representing an attendance record for a student. The record only contains the ...

  3. Gym -102007 :Benelux Algorithm Programming Contest (BAPC 18) (寒假自训第5场)

    A .A Prize No One Can Win 题意:给定N,S,你要从N个数中选最多是数,使得任意两个之和不大于S. 思路:排序,然后贪心的选即可. #include<bits/stdc+ ...

  4. js知识点: 数组

    1.行内元素  margin  padding 左右值都有效,上下值都无效 2.var ev = ev || window.event document.documentElement.clientW ...

  5. Tree Recovery

    #include<stdio.h> #include<string.h> void build(int n,char*s1,char*s2) { )return ; ])-s2 ...

  6. .Net Core开发环境迁移到Linux

    .Net开发环境迁移到Linux上去 .Net Core发布之前,多年来,.Net程序员的开发环境都在Windows上. 三街第一帅的我,虽然上班的8小时一直在windows上撸C#,但是下班时间一般 ...

  7. Blender简单动画:一个小球从一座山上滚下.

    简单动画:一个小球从一座山上滚下.注:[key]方括号内是快捷键; {大括号}内是模式,页签名称或选项等. ==== 1. 建模:    == 1.1 山[shift A] 建立平面plane,可以大 ...

  8. wireshark显示过滤器的几种用法(转自他人博客)

    本文章转自:http://blog.51cto.com/houm01/1872652 几种条件操作符 ==   eq    等于    ip.addr == 192.168.0.1   ip.addr ...

  9. Python基础线程和协程

    线程: 优点:共享内存,IO操作时,创造并发操作 缺点:枪战资源 线程不是越多越好,具体案例具体分析,请求上下文切换耗时 IO密集型适用于线程,IO操作打开文件网络通讯类,不需要占用CPU,只是由CP ...

  10. hdu3642 Get The Treasury 线段树--扫描线

    Jack knows that there is a great underground treasury in a secret region. And he has a special devic ...