小工具知识网

当前位置: 首页 > 行业知识 > pytest的fixture梳理

行业知识

pytest的fixture梳理

2026-12-03 03:27:34 来源:互联网转载

fixture特性

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

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

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

import pytest# Arrange@pytest.fixturedef first_entry():    return "a"# Arrange@pytest.fixturedef second_entry():    return 2# Arrange@pytest.fixturedef order(first_entry, second_entry):    return [first_entry, second_entry]
2.1 如果多个装置存在yield,则是先进后出
import pytest@pytest.fixturedef a():    print("hello")    yield    print("this is a")@pytest.fixturedef 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"])

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

  • 如果一个fixture存在返回值,那么可以通过函数名直接使用其返回值,如下所示:
    import pytest@pytest.fixturedef first_entry():    return "a"def test_a(first_entry):    print(first_entry)if __name__ == '__main__':    pytest.main(["-sv","test1.py"])

    4. fixfure多重嵌套

    • 如下append_first、test_string_only并且此fixture缓存即order

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

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

      import pytest# Arrange@pytest.fixturedef first_entry():    return "a"# Arrange@pytest.fixturedef order():    return []    # Act@pytest.fixturedef append_first(order, first_entry):    order.append(first_entry)    return orderdef 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.fixturedef 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的内容

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

                如order会接收一个参数

                import pytest# Arrange@pytest.fixturedef first_entry():    print("hello")    return "a"# Arrange@pytest.fixturedef 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"]

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

                • 存在以下fixture,test_demo(d, c, b, a): 如果d,c,b,a都是function级别执行顺序应该是d,c,b,a,由于是不同的范围,因此按照范围大小执行,顺序为及a,b,c,d即session、module、class、function
                  import pytestshi@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):    passpytest.main(["-sv", "test1.py"])

上一篇:服务器怎么知道硬件损坏?

下一篇:最新电脑操作起步教程