自动化测试框架Pytest介绍(5)——前置和后置之fixture

本文介绍了Pytest中的fixture功能,包括参数详细说明、利用yield实现后置操作、params和ids参数的代码实例。fixture提供灵活的用例前置和后置控制,支持作用域设置如function、class、module、package和session,以及参数化测试。通过示例展示了fixture在不同场景下的使用方式,包括直接作为参数、@pytest.mark.usefixtures装饰器和autouse=True自动执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        

目录

1、fixture参数说明

1.1参数详细说明

1.2利用yield实现后置

1.3params和ids参数的代码实例

2、fixture在用例中的调用

3、不同scope的代码实例


        在第4篇中,我们讲了前置和后置的各种setup和teardown,但是在实际应用中,有可能有的用例需要用到用例的前置,而有的用例又不需要,这样用setup和teardown实现起来就比较麻烦了。pytest提供了fixture的方法,让使用者自己灵活应用。

1、fixture参数说明

1.1参数详细说明

@pytest.fixture(scope="function",autouse=False, params=["fixture1","fixture2","fixture13"],ids=[1,2,3])

scope :作用域,默认为function:测试用例级别,class:测试类、module:模块、package:包、session:测试会话。

        比较常用的是function,在没用例判断是否调用

        session,在所有用例执行前执行前置,所有用例执行结束后执行后置,并且可以跨文件

autouser:是否自主执行,默认是False,如果设为True就跟各种setup和teardown的效果一样了。

params和ids配套使用,params是参数化,像前置函数传递列表作为参数,根据列表中元素的个数,该前置会被调用多次,调用该前置的测试用例也会执行多次。ids是为参数取别名,当参数很长时便于识别。

1.2利用yield实现后置

在fixture修饰的函数里面用yield实现对应的后置函数

1.3params和ids参数的代码实例

'''
前置传入列表参数
对应的前置函数要获取参数需要用request,获取参数要用request.param,注意这里是param表示是params中的元素
'''
from BaseLog import logger
import pytest

fixture_params = ["我是参数我虽然很长但是没有意义fixture1","我是参数我虽然很长但是没有意义fixture2","我是参数我虽然很长但是没有意义fixture13"]
@pytest.fixture(scope="function",autouse=False, params=fixture_params)
def fix_function(request):
    #特别注意这里需要一个参数request,并且调用参数是request.param,而不是request.params
    print ("这里是fix_function,",request.param)
    #用yield实现后置函数
    yield
    print("这里是fix_function的后置")

def test_case1(fix_function):
    #测试函数
    Expected = 2
    Actual = 2
    print("我是test_case1")
    assert Expected == Actual

if __name__ =="__main__":
    # -s:显示用例中的输出
    # -v:输出更详细的用例执行信息
    # __file__:本文件
    pytest.main(["-vs","BASE/file_test.py"])
    

执行结果,可以看出前置、后置、测试用例都根据传入的参数执行多次,另外可以看到在执行结果中测试用例里面显示了传入的参数

[Running] python -u "d:\Test\Android_Test\BASE\file_test.py"
============================= test session starts =============================
platform win32 -- Python 3.10.9, pytest-7.2.1, pluggy-1.0.0 -- D:\Python310\python.exe
cachedir: .pytest_cache
rootdir: d:\Test\Android_Test
plugins: rerunfailur
### pytest Framework Setup and Teardown Methods In the context of `pytest`, setup and teardown methods are used to define actions that should be executed before or after tests. These mechanisms ensure that each test runs in an isolated environment, preventing side effects from one test affecting others. #### Using Fixtures for Setup and Teardown `pytest` provides fixtures as a powerful mechanism for managing setup and teardown operations. A fixture is defined using the `@pytest.fixture` decorator, and it can perform initialization (setup) when requested by a test function and cleanup (teardown) once the test completes[^1]. Here is an example demonstrating how to use fixtures: ```python import pytest @pytest.fixture def resource_setup(): print("\nSetup called.") yield "Resource" print("\nTeardown called.") def test_example(resource_setup): print(f"\nTest running with {resource_setup}.") assert True ``` The above code defines a fixture named `resource_setup`. The `yield` statement separates the setup phase (before yielding) from the teardown phase (after yielding). When the test concludes, the teardown logic executes automatically[^2]. #### Class-Level Setup and Teardown For scenarios where you need class-level setup and teardown, you can combine fixtures with scope parameters. By setting the `scope="class"` argument within the `@pytest.fixture` decorator, the same fixture instance will persist across all methods inside a single test class[^3]: ```python import pytest @pytest.fixture(scope="class") def class_resource_setup(request): request.cls.resource = "Class Resource" print("\nClass level setup.") yield print("\nClass level teardown.") @pytest.mark.usefixtures("class_resource_setup") class TestExample: def test_one(self): print(f"\nTest One uses {self.resource}.") assert self.resource == "Class Resource" def test_two(self): print(f"\nTest Two also uses {self.resource}.") assert self.resource == "Class Resource" ``` This ensures both `test_one` and `test_two` share the same setup while executing their respective assertions independently[^4]. #### Module and Session Scopes Fixtures support broader scopes such as module (`scope="module"`) or session (`scope="session"`), which execute only once per module or entire test suite respectively. This reduces redundant setups during large-scale testing sessions but requires careful handling due to shared states between multiple tests[^3]. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六天测试工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值