pytest学习和使用-fixture如何使用?

news2024/7/4 4:48:52

1 引入

  • 和setup、teardown的区别是:fixture可自定义测试用例的前置条件;

  • setup、teardown针对整个脚本全局生效,可实现在执行用例前后加入一些操作;

  • setup、teardown不能做到灵活使用,比如用例A先登陆,用例B不需要登陆,用例C需要登陆,这样使用fixture更容易实现功能。

2 fixture参数说明

2.1 fixture源码

  • 部分源码如下:

def fixture(
    fixture_function: Optional[_FixtureFunction] = None,
    *,
    scope: "Union[_Scope, Callable[[str, Config], _Scope]]" = "function",
    params: Optional[Iterable[object]] = None,
    autouse: bool = False,
    ids: Optional[
        Union[
            Iterable[Union[None, str, float, int, bool]],
            Callable[[Any], Optional[object]],
        ]
    ] = None,
    name: Optional[str] = None,
) -> Union[FixtureFunctionMarker, _FixtureFunction]:
  • 我们可看到有五个参数scopeparamsautouseidsname,源码中也对着几个参数进行了说明,如下:

"""Decorator to mark a fixture factory function.

    This decorator can be used, with or without parameters, to define a
    fixture function.

    The name of the fixture function can later be referenced to cause its
    invocation ahead of running tests: test modules or classes can use the
    ``pytest.mark.usefixtures(fixturename)`` marker.

    Test functions can directly use fixture names as input arguments in which
    case the fixture instance returned from the fixture function will be
    injected.

    Fixtures can provide their values to test functions using ``return`` or
    ``yield`` statements. When using ``yield`` the code block after the
    ``yield`` statement is executed as teardown code regardless of the test
    outcome, and must yield exactly once.

    :param scope:
        The scope for which this fixture is shared; one of ``"function"``
        (default), ``"class"``, ``"module"``, ``"package"`` or ``"session"``.

        This parameter may also be a callable which receives ``(fixture_name, config)``
        as parameters, and must return a ``str`` with one of the values mentioned above.

        See :ref:`dynamic scope` in the docs for more information.

    :param params:
        An optional list of parameters which will cause multiple invocations
        of the fixture function and all of the tests using it. The current
        parameter is available in ``request.param``.

    :param autouse:
        If True, the fixture func is activated for all tests that can see it.
        If False (the default), an explicit reference is needed to activate
        the fixture.

    :param ids:
        List of string ids each corresponding to the params so that they are
        part of the test id. If no ids are provided they will be generated
        automatically from the params.

    :param name:
        The name of the fixture. This defaults to the name of the decorated
        function. If a fixture is used in the same module in which it is
        defined, the function name of the fixture will be shadowed by the
        function arg that requests the fixture; one way to resolve this is to
        name the decorated function ``fixture_<fixturename>`` and then use
        ``@pytest.fixture(name='<fixturename>')``.
    """

2.2 参数说明

  • 从以上部分源码以及说明我们可以看到:

fixture(scope="function", params=None, autouse=False, ids=None, name=None):
参数说明
scope默认:function,还有class、module、package、session
autouse默认:False,手动调用该fixture;为True,所有作用域内的测试用例都会自动调用该fixture
params一个可选的参数列表
ids每个字符串id的列表
namefixture的名称, 默认为装饰函数的名称,同一模块的fixture相互调用建议写个不同的name

3 fixture的特点

  • 命名方式灵活,不局限于 setup 和teardown 这几个命名

  • conftest.py 配置里可以实现数据共享,不需要 import 就能自动找到fixture

  • scope="module" 可以实现多个.py 跨文件共享前置

  • scope="session" 以实现多个.py 跨文件使用一个 session 来完成多个用例

4 fixture如何使用?

4.1 调用方式

4.1.1 方式一:直接传参

# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2022/11/17 
# 文件名称:test_mfixture.py
# 作用:fixture的使用
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

import pytest

# 不带参数时默认scope="function"
@pytest.fixture
def case():
    print("这个是登陆功能!")

def test_one(case):
    print("用例1需要登陆,然后进行操作one")

def test_two():
    print("用例2不需要登陆,直接操作two")

def test_three(case):
    print("用例3需要登陆,然后操作three")

if __name__ == "__main__":
    pytest.main(["-s", "test_mfixture.py"])

Testing started at 10:33 ...
F:\pytest_study\venv\Scripts\python.exe "D:\JetBrains\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pycharm\_jb_pytest_runner.py" --path F:/pytest_study/test_case/test_d/test_mfixture.py
Launching pytest with arguments F:/pytest_study/test_case/test_d/test_mfixture.py in F:\pytest_study\test_case\test_d

============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 -- F:\pytest_study\venv\Scripts\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.7.0', 'Platform': 'Windows-10-10.0.19041-SP0', 'Packages': {'pytest': '6.2.4', 'py': '1.10.0', 'pluggy': '0.13.1'}, 'Plugins': {'reportlog': '0.1.2', 'allure-pytest': '2.8.12', 'cov': '2.8.1', 'forked': '1.1.3', 'html': '2.0.1', 'metadata': '1.8.0', 'ordering': '0.6', 'xdist': '1.31.0'}, 'JAVA_HOME': 'D:\\jdk-11.0.8'}
rootdir: F:\pytest_study\test_case\test_d
plugins: reportlog-0.1.2, allure-pytest-2.8.12, cov-2.8.1, forked-1.1.3, html-2.0.1, metadata-1.8.0, ordering-0.6, xdist-1.31.0
collecting ... collected 3 items

test_mfixture.py::test_one              这个是登陆功能!
PASSED                                  [ 33%]用例1需要登陆,然后进行操作one

test_mfixture.py::test_two PASSED       [ 66%]用例2不需要登陆,直接操作two

test_mfixture.py::test_three            这个是登陆功能!
PASSED                                  [100%]用例3需要登陆,然后操作three


============================== 3 passed in0.02s ==============================

进程已结束,退出代码 0

4.1.2 方式二:使用mark.usefixtures

# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2022/11/17 
# 文件名称:test_mfixture.py
# 作用:fixture的使用
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson


import pytest

# 不带参数时默认scope="function"
@pytest.fixture
def case():
    print("这个是登陆功能!")

def test_one(case):
    print("用例1需要登陆,然后进行操作one")

def test_two():
    print("用例2不需要登陆,直接操作two")

@pytest.fixture
def case1():
    print("输入验证码")

def test_three(case):
    print("用例3需要登陆,然后操作three")

@pytest.mark.usefixtures("case", "case1")
def test_four(case1):
    print("先登录,再输入验证码,最后操作four")

if __name__ == "__main__":
    pytest.main(["-s", "test_mfixture.py"])

test_mfixture.py::test_one                    这个是登陆功能!
PASSED                                        [ 25%]用例1需要登陆,然后进行操作one

test_mfixture.py::test_two PASSED             [ 50%]用例2不需要登陆,直接操作two

test_mfixture.py::test_three                  这个是登陆功能!
PASSED                                        [ 75%]用例3需要登陆,然后操作three

test_mfixture.py::test_four                   这个是登陆功能!
                                              输入验证码
PASSED                                       [100%]先登录,再输入验证码,最后操作four


============================== 4 passed in0.03s ==============================

进程已结束,退出代码 0

4.1.3 方式三:使用autouse=True

# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2022/11/17 
# 文件名称:test_mfixture.py
# 作用:fixture的使用
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson


import pytest

# 不带参数时默认scope="function"
@pytest.fixture
def case():
    print("这个是登陆功能!")

def test_one(case):
    print("用例1需要登陆,然后进行操作one")

def test_two():
    print("用例2不需要登陆,直接操作two")

@pytest.fixture
def case1():
    print("输入验证码")

def test_three(case):
    print("用例3需要登陆,然后操作three")

@pytest.mark.usefixtures("case", "case1")
def test_four(case1):
    print("先登录,再输入验证码,最后操作four")

@pytest.fixture(autouse=True)
def case2():
    print("所有用例都会调用case2")

if __name__ == "__main__":
    pytest.main(["-s", "test_mfixture.py"])

test_mfixture.py::test_one                    所有用例都会调用case2
                                              这个是登陆功能!
PASSED                                        [ 25%]用例1需要登陆,然后进行操作one

test_mfixture.py::test_two                    所有用例都会调用case2
PASSED                                        [ 50%]用例2不需要登陆,直接操作two

test_mfixture.py::test_three                  所有用例都会调用case2
                                              这个是登陆功能!
PASSED                                        [ 75%]用例3需要登陆,然后操作three

test_mfixture.py::test_four                   所有用例都会调用case2
                                              这个是登陆功能!
                                              输入验证码
PASSED                                       [100%]先登录,再输入验证码,最后操作four


============================== 4 passed in0.03s ==============================

进程已结束,退出代码 0

4.2 总结

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/87009.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【毕业设计】微信失物招领小程序 失物招领微信小程序

一、前言 生活中&#xff0c;很多人都有丢失物品的经历&#xff0c;随着互联网的快速发展&#xff0c;你可以在各种地方信息平台来发布丢失说明。但是这些信息往往会随着平台的发布量被刷掉&#xff0c;想要找回丢失的东西还是很困难的。只需要打开微信即可使用失物招领小程序…

软件测试丨基于Junit4,利用xUnit框架让你的测试用例可维护性大幅提升

xUnit是一系列测试框架的统称&#xff0c;最开始来源于一个叫做Smalltalk的SUnit框架。 现在各种面向对象的语言&#xff0c;如Java、Python的鼻祖就是Smalltalk&#xff0c;后来这些语言都借助了Sunit框架的理念&#xff0c;有很多通用的规范和特征&#xff0c;也就统称为xUn…

C. Hossam and Trainees(欧拉筛 + 分解质因数)

Problem - C - Codeforces 胡萨姆有n名学员。他给第i个学员分配了一个号码。 如果存在一个整数x (x≥2)&#xff0c;使得x能整除ai, x能整除aj&#xff0c;则第i个和第j个(i≠j)练习者被称为成功练习者。 胡萨姆想知道是否有一对成功的学员。 胡萨姆现在很累了&#xff0c;所以…

推荐一个平台,JNPF开发平台3.4.5版本更新升级,企业级的低代码开发平台

JNPF快速开发框架是一个可复用的设计构件&#xff0c;使用JNPF的编程人员可以在一个通用功能已经实现的基础上开始具体的系统开发&#xff1b; 简单来讲&#xff0c;软件开发框架可以理解为我们盖楼房时&#xff0c;用梁柱子承重墙做起来的钢筋混凝土结构框架。而实现的软件功…

R语言基于协方差的结构方程拟合的卡方检验

在评估结构方程模型的拟合&#xff0c;很常见的应用是研究χ2进行测试&#xff0c;因为在给定足够大的样本量的情况下&#xff0c;它几乎总会检测出模型与数据之间的统计上的显着差异。因为&#xff0c;我们的模型几乎总是数据的近似值。如果我们的模型的协方差矩阵实际上匹配抽…

【云计算与大数据技术】分布式数据库NoSQL中KV、列式、图、文档数据库的讲解(图文解释 超详细)

一、NoSQL数据库概述 NoSQL泛指非关系型数据库&#xff0c;相对于传统关系型数据库&#xff0c;NoSQL有着更复杂的分类&#xff0c;包括KV数据库&#xff0c;文档数据库&#xff0c;列式数据库以及图数据库等等&#xff0c;这些类型的数据库能够更好的适应复杂类型的海量数据存…

QT点云显示--基于QOpenGLWidget和QOpenGLFunctions实现

一、实现功能 1、网格显示 2、坐标轴显示 3、鼠标操作旋转、平移、缩放 4、点云显示 之前写了一篇基于QGLWidget实现&#xff0c;此版本的功能接口基本保持一致&#xff0c;方便对比 QT点云显示--基于QGLWidget实现_Jason~shen的博客-CSDN博客1、网格显示2、坐标轴显示3、…

操作系统学习笔记_2 中断和系统调用;进程和线程

中断 一开始的计算机只是简单的串行执行程序。 现在的操作系统不仅可以并发执行程序&#xff0c;而且收到中断指令时&#xff0c;CPU 会切换到内核模式&#xff0c;中断当前程序的执行&#xff0c;按中断指令调整程序执行顺序&#xff0c;然后恢复到用户态继续执行。 中断分…

docker容器安装与使用

目录 1. 什么是docker 2. docker的核心组件 3. docker的安装 3.1 安装的先决条件 3.2.1 ubuntu安装docker 3.2.2 CentOS安装docker 3.3 配置镜像加速器 4. 镜像常用操作 4.1 搜索镜像 4.3 查看宿主机中的镜像 4.3 删除镜像 5. 容器常用命令 5.1 运行容器 5.2 使用…

【算法】斐波那契数列通项公式

特征方程和通项公式 如果数列ana_nan​的递推公式&#xff1a;anc1an−1c2an−2a_nc_1a_{n-1}c_2a_{n-2}an​c1​an−1​c2​an−2​------(1) 根据待定系数法&#xff0c;假设an−xan−1y(an−1−xan−2)a_n-xa_{n-1}y(a_{n-1}-xa_{n-2})an​−xan−1​y(an−1​−xan−2​)…

Mybatis源码解析之执行SQL语句

作者&#xff1a;郑志杰 mybatis 操作数据库的过程 // 第一步&#xff1a;读取mybatis-config.xml配置文件 InputStream inputStream Resources.getResourceAsStream("mybatis-config.xml"); // 第二步&#xff1a;构建SqlSessionFactory(框架初始化) SqlSessionF…

FITC-PEG-Biotin,Biotin-PEG-Fluorescein,荧光素PEG生物素生物标记物用试剂

一&#xff1a;产品描述 1、名称 英文&#xff1a;FITC-PEG-Biotin&#xff0c;Biotin-PEG-Fluorescein 中文&#xff1a;荧光素-聚乙二醇-生物素 2、CAS编号&#xff1a;N/A 3、所属分类&#xff1a;Biotin PEG Fluorescent PEG 4、分子量&#xff1a;可定制&#xff0c…

MyBatis访问Db2和MySQL(Maven)

注&#xff1a;虽然前面写过一些文档&#xff0c;包含MyBatis连接Db2和MySQL的内容&#xff0c;但是貌似没有单独记录用Maven方式连接DB的文档&#xff0c;所以单写了这一篇文档&#xff0c;方便以后需要快速搭建MyBatis环境时参考。 注&#xff1a;有一篇文档“MyBatis访问Db…

基于java+springboot+mybatis+vue+mysql的摄影跟拍预定管理系统

项目介绍 摄影跟拍预定管理方面的任务繁琐,以至于每年都在摄影跟拍预定管理这方面投入较多的精力却效果甚微,摄影跟拍预定管理系统的目标就是为了能够缓解摄影跟拍预定管理工作方面面临的压力,让摄影跟拍预定管理方面的工作变得更加高效准确。 本项目在开发和设计过程中涉及到…

MyBaits入门完结篇

不仅可以判断参数&#xff0c;还可以判断_parameter和_databasedId bind标签 sql标签配合include标签完成对重复sql语句的抽取 要在带注解的映射器接口类中使用动态 SQL&#xff0c;可以使用 script 元素 缓存 一级缓存 一级缓存失效情况 手动清空缓冲的函数&#xff1a…

【众筹】百问网DShanMCU-Mio开源掌机(爻-澪)项目,完美支持运行10多个模拟器!

众筹说明 定金翻倍&#xff0c;即定金19.9元&#xff0c;在付尾款时可抵40元(成品售价不会超过120元)&#xff01;达标当天就开搞&#xff0c;满100人加速搞尽量在年前发货&#xff0c;让大家先玩起来&#xff01;如果不达标则原路退款&#xff0c;项目取消。 众筹时间&#…

ADI Blackfin DSP处理器-BF533的开发详解44:图像处理专题-StenciFilter (图像的平滑处理)(含源码)

硬件准备 ADSP-EDU-BF533&#xff1a;BF533开发板 AD-HP530ICE&#xff1a;ADI DSP仿真器 软件准备 Visual DSP软件 硬件链接 功能介绍 代码实现了图像的平滑处理&#xff08;高斯模板&#xff09;&#xff0c;代码运行时&#xff0c;会通过文件系统打开工程文件根目下&qu…

NetCore基于Roslyn的动态编译实现

目录 一. AvalonEdit文本器 1.功能实现 2. 高亮 3. 代码提示 二. 运行效果展示 三. 源码链接 四. 参考资料 一. AvalonEdit文本器 1.功能实现 直接用Github上的源码进行实现&#xff0c;icsharpcode/AvalonEdit&#xff1a;The WPF-based text editor component used i…

在R语言中使用概率分布:dnorm,pnorm,qnorm和rnorm

在这里&#xff0c;我将讨论哪些函数可用于处理正态分布&#xff1a;dnorm&#xff0c;pnorm&#xff0c;qnorm和rnorm。 R中的分布函数 有四个关联的函数&#xff0c; 四个正态分布函数是&#xff1a; d范数&#xff1a;正态分布的密度函数p范数&#xff1a;正态分布的累积密…

【Spring】SpringBoot 配置 log4j2 日志

1. 概述 Apache Log4j2 是对原先的 Log4j 项目的升级版本&#xff0c;参考了 logback 的一些优秀的设计&#xff0c;并且修复了一些问题&#xff0c;因此带来了一些重大的提升。 2. 案例与解析 2.1 引入依赖 SpringBoot 的 starter 自带的是 logback 日志&#xff0c;若要使…