简体   繁体   English

来自函数作用域夹具的 pytest 访问参数

[英]pytest access parameters from function scope fixture

Let's assume I have the following code:假设我有以下代码:

@pytest.mark.parametrize("argument", [1])
def test_func(self, function_context, argument)

And I have the following function scope fixture:我有以下功能范围夹具:

@pytest.fixture(scope='function')
def function_context(session_context):
    # .... do something ....

Is it possible to access the current function argument from within the function_context fixture?是否可以从function_context夹具中访问当前函数参数?

In my case - I want to get the value 1 that is being passed in parametrize from within function_context .就我而言 - 我想从function_context获取在parametrize中传递的值1

Fixtures in pytest are instantiated before the actual tests are ran, so it shouldn't be possible to access the test function argument at the fixture definition stage. pytest中的夹具在实际测试运行之前被实例化,因此在夹具定义阶段应该不可能访问测试函数参数。 However, I can think of two ways to bypass this:但是,我可以想到两种方法来绕过这个:

1. Monkeypatching 1. 猴子补丁

You can monkeypatch the fixture, ie temporarily change some of its attributes, based on the parameter of the function that uses this fixture.您可以根据使用此设备的函数的参数对设备进行猴子修补,即临时更改其某些属性。 For example:例如:

@pytest.fixture(scope='function')
def function_context(session_context):
    # .... do something ....

@pytest.mark.parametrize("argument", [1])
def test_func(self, function_context, argument, monkeypatch):
    monkeypatch.setattr(function_context, "number", argument) # assuming you want to change the attribute "number" of the function context
    # .... do something ....

Although your fixture is valid for the scope of the function only anyhow, monkeypatching is also only valid for a single run of the test.尽管您的装置无论如何仅对函数的范围有效,但monkeypatching 也仅对测试的单次运行有效。

2. Parametrizing the fixture instead of the test function 2. 参数化夹具而不是测试函数

Alternatively, you can also choose to parametrize the fixture itself instead of the test_func .或者,您也可以选择参数化夹具本身而不是test_func For example:例如:

@pytest.fixture(scope='function', params=[0, 1])
def function_context(session_context, request):
    param = requests.param # now you can use param in the fixture
    # .... do something ...

def test_func(self, function_context):
    # .... do something ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM