将 pytest 函数参数传递给夹具
Passing pytest function arguments to a fixture
我正在尝试创建一个仅打印 pytest 测试用例参数的修复程序。
例如:
@pytest.fixture(scope='function')
def print_test_function_arguments(request):
# Get the value of argument_1 from the run of the test function
print(f'argument_1 = {value_1}')
def test_something(print_test_function_arguments, argument_1, argument_2):
assert False
如果您想进行任何类型的内省,request
fixture 是您的不二之选。 request.node
为您提供当前测试项,request.node.function
test_something
函数对象和 request.getfixturevalue("spam")
将评估夹具 spam
和 return 其结果(或如果之前已经评估过,则从夹具缓存中获取它)。一个简单的 args 自省示例(未测试):
import inspect
import pytest
@pytest.fixture(scope='function')
def print_test_function_arguments(request):
argspec = inspect.getfullargspec(request.node.function)
positional_args = argspec.args
positional_args.remove("print_test_function_arguments")
for argname in positional_args:
print(argname, "=", request.getfixturevalue(argname))
当然,你不能在它的主体中计算夹具print_test_function_arguments
,否则它会陷入无限递归,所以它的名字必须先从参数列表中删除。
我正在尝试创建一个仅打印 pytest 测试用例参数的修复程序。
例如:
@pytest.fixture(scope='function')
def print_test_function_arguments(request):
# Get the value of argument_1 from the run of the test function
print(f'argument_1 = {value_1}')
def test_something(print_test_function_arguments, argument_1, argument_2):
assert False
如果您想进行任何类型的内省,request
fixture 是您的不二之选。 request.node
为您提供当前测试项,request.node.function
test_something
函数对象和 request.getfixturevalue("spam")
将评估夹具 spam
和 return 其结果(或如果之前已经评估过,则从夹具缓存中获取它)。一个简单的 args 自省示例(未测试):
import inspect
import pytest
@pytest.fixture(scope='function')
def print_test_function_arguments(request):
argspec = inspect.getfullargspec(request.node.function)
positional_args = argspec.args
positional_args.remove("print_test_function_arguments")
for argname in positional_args:
print(argname, "=", request.getfixturevalue(argname))
当然,你不能在它的主体中计算夹具print_test_function_arguments
,否则它会陷入无限递归,所以它的名字必须先从参数列表中删除。