[英]Parametrize Pytest test with list returned from fixture
I have a test that iterates over a list of dictionaries (parsed from a csv file in S3) returned from a fixture and performs assertions.我有一个测试迭代从夹具返回的字典列表(从 S3 中的 csv 文件解析)并执行断言。
In pseudocode:在伪代码中:
# s_3 is a fixture
def my_fixture(s_3):
s_3.get_data_from_s3()
yield s_3_data_as_list_of_dicts
def my_test(my_fixture):
for entry in my_fixture:
do my assertions
I also had this written where I passed in the output into @pytest.mark.parametrize
, but it wasn't from a fixture, but rather from just a method where I had to instantiate/connect S3.我也写了这个,我将 output 传递到@pytest.mark.parametrize
,但它不是来自夹具,而只是来自我必须实例化/连接 S3 的方法。
I want to be able to leverage my fixtures to get the data and parametrize the test based on the output, as in:我希望能够利用我的夹具来获取数据并基于 output 对测试进行参数化,如下所示:
# s_3 is a fixture
def my_fixture(s_3):
s_3.get_data_from_s3()
yield s_3_data_as_list_of_dicts
@pytest.mark.parametrize("entries", [output from my_fixture])
def my_test(entries):
do my assertions
I have seen things along these lines, but nothing that was able to help be resolve this issue - if there is a resolution other than just using a non-fixture method.我已经看到了这些方面的事情,但没有什么可以帮助解决这个问题 - 如果除了使用非固定方法之外还有其他解决方案。
You can use yield
instead of return
in my_fixture
您可以在my_fixture
中使用yield
而不是return
@pytest.fixture
def my_fixture(s_3):
s_3.get_data_from_s3()
yield s_3_data_as_list_of_dicts
def my_test(my_fixture):
print(my_fixture) # my_fixture is a list of dicts
Edit:编辑:
@pytest.mark.parametrize
is executed in collection time, when pytest is collecting all the tests that need to run. @pytest.mark.parametrize
在收集时间执行,此时 pytest 正在收集所有需要运行的测试。 @pytest.fixture
is executed in execution time, when the current test/module/session (depends on scope) is running. @pytest.fixture
在当前测试/模块/会话(取决于范围)正在运行时在执行时执行。
If you would like each dictionary as a parameter to the test you can build non-fixture function and send it as a parameter to parametrize
如果您希望将每个字典作为测试的参数,您可以构建非夹具 function 并将其作为参数发送到parametrize
def data_source():
for d in s_3_data_as_list_of_dicts:
yield d
@pytest.mark.parametrize('d', data_source())
def test_my_test(d):
print(d) # d is a single dict
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.