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. Gym101482 NWERC 2014(队内训练第4场)

    -----------------------前面的两场感觉质量不高,就没写题解----------------------------- A .Around the Track pro:给定内多边形 ...

  2. Thread_run()方法

    cas 1: package threadTest; public class ThreadTest { public static void main(String[] args) { Thread ...

  3. hdu4549 M斐波那契数列 矩阵快速幂+快速幂

    M斐波那契数列F[n]是一种整数数列,它的定义如下: F[0] = aF[1] = bF[n] = F[n-1] * F[n-2] ( n > 1 ) 现在给出a, b, n,你能求出F[n]的 ...

  4. 进程的环境变量environ

    编程之路刚刚开始,错误难免,希望大家能够指出. 每个进程都有自己的环境变量,在C语言程序中可使用外部变量(char **environ)来访问环境,而库函数可允许进程去获取或修改自己环境的值. 两种方 ...

  5. UVA10341 Solve It

    题意 PDF 分析 在\(0\le x\le 1\)时,\(f(x)=pe^{-x}+q\sin x+r\cos x+s\tan x+tx^2+u\)是减函数,所以当\(f(0)\ge 0 \wedg ...

  6. shell批量创建随机文件名格式文件

    //随机生成文件 //文件名会带数字的...注意echo后面的是反引号,不是单引号 #!/bin/bash dir=/root/bp for i in 'seq 10' touch $dir`echo ...

  7. kubebapps 添加私有harbor 中的helm repo

    kubebapps 支持添加私有的helm repo,基于http basic auth ,我们通过添加header 就可以了 备注 harbor helm 以及kubebapps 的搭建可以参考 h ...

  8. Announcing HashiCorp Consul + Kubernetes

    转自:https://www.hashicorp.com/blog/consul-plus-kubernetes We're excited to announce multiple features ...

  9. Laya IDE 快捷键

    Laya IDE 快捷键: ctrl+p 快速打开文件,fb中对应的是ctrl+shift+G ctrl+d 删除一行 ctrl+shift+o打开符号 alt+shift+下箭头 复制一行 alt+ ...

  10. 编写一个函数实现n^k,使用递归实现

    思路:例如2的3次方.可以分解为2乘2的2次方,而2的2次方又可以分解为2乘2的以此方法,以此类推. #include<stdio.h> int Find_num(int n,int k) ...