简体   繁体   English

Pytest:参数化夹具返回路径或读取数据

[英]Pytest: parameterized fixture returning path or read data

I have following test case:我有以下测试用例:

@pytest.mark.parametrize('env_a, env_b', [(env_a, env_b)], indirect=True) #its existing fixture, cannot modify it
@pytest.mark.parametrize('platform_a, platform_b', [(platform_a, platform_b)])
@pytest.mark.parametrize('resource', [resource1, resource2, resource3, resource4])
def test_compare_items_lists(env_a, env_b, platform_a, platform_b, resource):

    path_a = env_a / platform_a / resource / file.txt #move to fixture
    path_b = env_b / platform_b / resource / file.txt #move to fixture

    list_of_items_in_a = path_a.read() #move to fixture
    list_of_items_in_b = path_b.read() #move to fixture

    extras_in_a = get_extras(list_of_items_in_a, list_of_items_in_b)
    extras_in_b = get_extras(list_of_items_in_b, list_of_items_in_a)

    assert not extras_in_a and not extras_in_b

This parameterized test do:这个参数化测试做:

  • path preparation路径准备
  • data read数据读取
  • data compare数据比较

but it's test, so should only compare data.但它是测试,所以应该只比较数据。

So I guess fixture(s?) should be created to prepare paths and read files.所以我想应该创建 fixture(s?) 来准备路径和读取文件。 Then it should be passed to test which should only compare data.然后应该将其传递给只比较数据的测试。 But how to do it?但是怎么做呢?

pytest fixtures can be parametrized by setting the params option. pytest灯具可以通过设置params选项进行参数化

You can extract each marker to a separate fixture.您可以将每个标记提取到单独的夹具中。

@pytest.fixture(params=[(platform_a, platform_b)], ids=['platform_a,platform_b'])
def platform(request):
    yield request.param

@pytest.fixture(params=[(env_a, env_b)], ids=['env_a,env_b'])
def env(request):
    yield request.param

@pytest.fixture(params=[resource1, resource2, resource3, resource4])
def resource(request):
    yield request.param

Then use them in another fixture that builds the resource path and returns the contents from it.然后在另一个构建资源路径并从中返回内容的装置中使用它们。

@pytest.fixture
def diffable_resources(request, env, platform, resource):
    env_a, env_b = env
    platform_a, platform_b = platform
    resource = resource

    path_a = env_a / platform_a / resource / 'file.txt'
    path_b = env_b / platform_b / resource / 'file.txt'
    yield (path_a.read(), path_b.read())

That way your test can be like:这样你的测试可以是这样的:

def test_foo(diffable_resources):
    list_of_items_in_a, list_of_items_in_b = diffable_resources
    extras_in_a = get_extras(list_of_items_in_a, list_of_items_in_b)
    extras_in_b = get_extras(list_of_items_in_b, list_of_items_in_a)

    assert not extras_in_a and not extras_in_b

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

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