pytest的fixture梳理

这篇具有很好参考价值的文章主要介绍了pytest的fixture梳理。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

fixture特性

夹具是在测试中用于提供共享资源、设置测试环境或模拟行为的工具。

1. 可以重复使用,多个用例可以使用同一个fixture

2. 一个测试用例可以使用多个装置

import pytest
# Arrange
@pytest.fixture
def first_entry():
    return "a"

# Arrange
@pytest.fixture
def second_entry():
    return 2

# Arrange
@pytest.fixture
def order(first_entry, second_entry):
    return [first_entry, second_entry]
2.1 如果多个装置存在yield,则是先进后出
import pytest

@pytest.fixture
def a():
    print("hello")
    yield
    print("this is a")

@pytest.fixture
def b():
    print("world")
    yield
    print("this is b")

def test_demo(a, b):
    print("this is test_demo")

if __name__ == '__main__':
    pytest.main(["-sv", "test1.py"])

pytest的fixture梳理,pytest,python,开发语言

3. fixture的返回值不需要接收

  • 如果一个fixture存在返回值,那么可以通过函数名直接使用其返回值,如下所示:
import pytest
@pytest.fixture
def first_entry():
    return "a"

def test_a(first_entry):
    print(first_entry)

if __name__ == '__main__':
    pytest.main(["-sv","test1.py"])

pytest的fixture梳理,pytest,python,开发语言

4. fixfure多重嵌套

  • 如下append_firsttest_string_only并且此fixture缓存即order
    如果一个 fixture 被请求了多次,但它的作用范围是函数级别(默认),那么这个 fixture 在每次请求时都会重新执行一次,而不会缓存。这会导致每次请求获得的数据都是独立的,不受前一次请求的影响。所以一般不要使用缓存,保证起独立性。

所以一般不要使用缓存,保证起独立性

import pytest

# Arrange
@pytest.fixture
def first_entry():
    return "a"


# Arrange
@pytest.fixture
def order():
    return []
    
# Act
@pytest.fixture
def append_first(order, first_entry):
    order.append(first_entry)
    return order

def test_string_only(append_first, order, first_entry):
    # Assert
    print(append_first) # ['a']
    print(order) # ['a']
    assert order == [first_entry]

pytest.main(["-sv", "test1.py"])

5自动使用fixture,不需要请求

  • 设置和清理环境、全局配置,例如数据库连接、日志设置等可以使用,笔者用的不多
import pytest

@pytest.fixture
def first_entry():
    return "a"
    
@pytest.fixture(autouse=True)
def order():
    return "hello world"

def test_a(order):
    print(order)

pytest.main(["-sv", "test1.py"])

6 动态定义fixture范围

7 安全拆卸的fixture

8fixture的request

9 fixture的参数化

10 向fixture里传参

  • 此fixture带有参数get_time,如何向fixture内传参呢?
@pytest.fixture(scope="function")
def dust_alarm_param_single_more_80(get_time):
    """崇州紫园get_time参数化生成告警"""
    get_time=get_time

目前有两种方法实现

  • 1、通过@pytest.mark.parametrize传参
    @pytest.mark.parametrize("get_time",[(my_time.current_timestamp()[0] + 1 * 3600)])
    函数def test_dust_alarm_001(cls, dust_alarm_init,get_time, dust_alarm_param_single_more_80)直接接受此参数,注意一般将需要传入得参数(get_time)放在那个fixture的前面
    @allure.feature("告警抑制")
    @allure.story("夜间不告警")
    @allure.title("0到08:59:59之间产生告警 如1点崇州紫园省站超标80不告警")
    @pytest.mark.parametrize("get_time",[(my_time.current_timestamp()[0] + 1 * 3600)])
    @pytest.mark.debug
    def test_dust_alarm_001(cls, dust_alarm_init,get_time, dust_alarm_param_single_more_80):
	    pass
  • 例子2
  • @pytest.mark.parametrize多次使用
# conftest.py
@pytest.fixture(scope="function")
def illegal_alarm_init_test_illegal_sale_finished_sand(alarm_type):
    alarm_type=alarm_type
    """违规销售砂石成品料"""
    # 新加的5种类型
    print(alarm_type)
    del_sql1 = f"""delete FROM alarm_dog WHERE type in ({alarm_type});"""
    print(del_sql1)
    try:
        db.delete(del_sql1)
    except Exception as e:
        log.error(e)

  • 可以看到成功打印出fixture的内容
    pytest的fixture梳理,pytest,python,开发语言

  • 2、通过fixture传参,把get_time写成一个fixture也可以实现,这个fixture return一个数据即可

order会接收一个参数

import pytest

# Arrange
@pytest.fixture
def first_entry():
    print("hello")
    return "a"

# Arrange
@pytest.fixture
def order(first_entry):
    print("it's ok")
    yield first_entry
    print("over")


def test_string_only( order ):
    result =order
    print(result)
    assert result == "a"


pytest.main(["-sv", "1test.py"]

pytest的fixture梳理,pytest,python,开发语言

11 多重嵌套fixture时,fixfure的作用域优先于fixture顺序

  • 存在以下fixture,test_demo(d, c, b, a): 如果d,c,b,a都是function级别执行顺序应该是d,c,b,a,由于是不同的范围,因此按照范围大小执行,顺序为及a,b,c,dsessionmoduleclassfunction
import pytest
shi
@pytest.fixture(scope="session")
def a():
    print("my session")

@pytest.fixture(scope="module")
def b():
    print("my module")

@pytest.fixture(scope="class")
def c():
    print("my class")

@pytest.fixture(scope="function")
def d():
    print("my function")

def test_demo(d, c, b, a):
    pass

pytest.main(["-sv", "test1.py"])

pytest的fixture梳理,pytest,python,开发语言文章来源地址https://www.toymoban.com/news/detail-649897.html

到了这里,关于pytest的fixture梳理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Pytest使用fixture实现token共享

    同学们在做pytest接口自动化时,会遇到一个场景就是不同的测试用例需要有一个 登录 的前置步骤,登录完成后会获取到 token ,用于之后的代码中。首先我先演示一个常规的做法。 首先在conftest定义一个login的方法,方法返回token 2.在测试用例方法中引入这个方法,所有用到

    2024年02月12日
    浏览(26)
  • Pytest fixture参数传递的4种方式

    最近使用Pytest中的fixture和conftest时,遇到需要在conftest中的setup和teardown方法里传递参数。这里记录以下4种实现的方式。 结果: 结果: 结果:

    2024年02月16日
    浏览(27)
  • pytest fixture 创建一个 requests.session() 对象

    当你运行这段代码时,它会执行以下操作: 1. 导入必要的库:`pytest` 和 `requests`。 2. 定义一个夹具(fixture)函数 `session`,使用 `@pytest.fixture(scope=\\\'session\\\')` 装饰器进行标记。这个夹具函数在整个测试会话期间只会被执行一次。 3. 在 `session` 夹具函数中,创建一个 `requests.sess

    2024年02月11日
    浏览(29)
  • 自动化测试 —— Pytest fixture及conftest详解

    fixture是在测试函数运行前后,由pytest执行的外壳函数。fixture中的代码可以定制,满足多变的测试需求,包括定义传入测试中的数据集、配置测试前系统的初始状态、为批量测试提供数据源等等。fixture是pytest的精髓所在,类似unittest中setup/teardown,但是比它们要强大、灵活很多

    2024年04月08日
    浏览(23)
  • Pytest测试技巧之Fixture:模块化管理测试数据

    在 Pytest 测试中,有效管理测试数据是提高测试质量和可维护性的关键。本文将深入探讨 Pytest 中的 Fixture,特别是如何利用 Fixture 实现测试数据的模块化管理,以提高测试用例的清晰度和可复用性。  什么是Fixture? 在 Pytest 中,Fixture 是一种用于为测试用例提供设置和资源的

    2024年02月22日
    浏览(33)
  • Pytest中使用Fixture替换Unittest的Setupclass及Pytest使用装饰器应用参数化

            Pytest中夹具(Fixture)有几种生命周期:function-model-class-session-packages,其中默认为function。             在类外写Fixture,通过@pytest.para.usefixtures(\\\"fixture name\\\")来调用。              fixture中不使用参数,测试用例使用参数化。

    2024年02月05日
    浏览(26)
  • 超强,Pytest自动化测试框架 fixture 传参实战(案例)

    为了提高复用性,我们在写测试用例的时候,会用到不同的fixture,比如:最常见的登录操作,大部分的用例的前置条件都是登录 假设不同的用例想登录不同的测试账号,那么登录fixture就不能把账号写死,需要通过传参的方式来完成登录操作 案例1:传单个参数 执行结果 添加

    2024年02月12日
    浏览(31)
  • 精通自动化,Pytest自动化测试框架-fixture用例的前后置(实现)

    测试用例实现前后置,有多种方法。在实际编写测试脚本时,要根据实际情况选择 1、xunit类型 2、unittest类型 3、pytest中的fixture类型 定义夹具

    2024年02月15日
    浏览(36)
  • 超详细从入门到精通,pytest自动化测试框架实战-fixture多样玩法(九)

    在编写测试用例,都会涉及到用例执行之前的环境准备工作,和用例执行之后的环境清理工作。 代码版的测试用例也不例外。 pytest自动化测试框架:https://www.bilibili.com/video/BV18K411m7FH/ 在自动化测试框架当中,我们也需要编写: 用例执行之前的环境准备工作代码(前置工作代码

    2023年04月11日
    浏览(37)
  • 从0到1精通自动化测试,pytest自动化测试框架,fixture之autouse=True(十二)

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

    2024年02月11日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包