3

我试图避免在我的测试中重复太多样板,我想以更结构化的方式重写它们。假设我有两个不同的解析器,它们都可以将文本解析为doc. 然后该文档将用于其他测试。最终目标是公开一个doc()可以在其他测试中使用的夹具,并且以这样的方式进行参数化,即它运行给定解析器和文本的所有组合。

@pytest.fixture
def parser_a():
    return "parser_a"  # actually a parser object

@pytest.fixture
def parser_b():
    return "parser_b"  # actually a parser object

@pytest.fixture
def short_text():
    return "Lorem ipsum"

@pytest.fixture
def long_text():
    return "If I only knew how to bake cookies I could make everyone happy."

现在的问题是,如何创建一个doc()看起来像这样的夹具:

@pytest.fixture(params=???)
def doc(parser, text):
    return parser.parse(text)

其中parser参数化为 parser_a 和 parser_b,以及textshort_text 和 long_text。这意味着总共doc将测试解析器和文本的四种组合。

PyTest 的参数化装置的文档非常模糊,我找不到如何解决这个问题的答案。欢迎大家帮忙。

4

2 回答 2

1

您的夹具应如下所示:

@pytest.fixture(scope='function')
def doc_fixture(request):
    parser = request.param[0]
    text = request.param[1]
    return parser.parse(text)

并以下列方式使用它:

@pytest.mark.parametrize('doc_fixture', [parser_1, 'short text'], indirect=True)
def test_sth(doc_fixture):
    ...  # Perform tests

您可以使用混合和匹配参数组合pytest.mark.parametrize

这是另一个提供不同参数组合的示例:

from argparse import Namespace
import pytest

@pytest.fixture(scope='function')
def doc_fixture(request):
    first_arg, second_arg = request.param
    s = Namespace()
    s.one = first_arg
    s.two = second_arg
    return s


@pytest.mark.parametrize(
    'doc_fixture',
    [
        ('parserA', 'ShortText'),
        ('parserA', 'LongText'),
        ('parserB', 'ShortText'),
        ('parserB', 'LongText')
    ],
    indirect=True
)
def test_something(doc_fixture):
    assert doc_fixture == ''

以及一个示例运行结果(如预期的那样测试失败):

=========================================================================================== short test summary info ============================================================================================
FAILED ../../tmp/::test_something[doc_fixture0] - AssertionError: assert Namespace(one='parserA', two='ShortText') == ''
FAILED ../../tmp/::test_something[doc_fixture1] - AssertionError: assert Namespace(one='parserA', two='LongText') == ''
FAILED ../../tmp/::test_something[doc_fixture2] - AssertionError: assert Namespace(one='parserB', two='ShortText') == ''
FAILED ../../tmp/::test_something[doc_fixture3] - AssertionError: assert Namespace(one='parserB', two='LongText') == ''
于 2020-04-28T13:00:46.470 回答
1

不确定这是否正是您所需要的,但您可以只使用函数而不是固定装置,并将它们组合在固定装置中:

import pytest

class Parser:  # dummy parser for testing
    def __init__(self, name):
        self.name = name

    def parse(self, text):
        return f'{self.name}({text})'


class ParserFactory:  # do not recreate existing parsers
    parsers = {}

    @classmethod
    def instance(cls, name):
        if name not in cls.parsers:
            cls.parsers[name] = Parser(name)
        return cls.parsers[name]

def parser_a():
    return ParserFactory.instance("parser_a") 

def parser_b():
    return ParserFactory.instance("parser_b")

def short_text():
    return "Lorem ipsum"

def long_text():
    return "If I only knew how to bake cookies I could make everyone happy."


@pytest.fixture(params=[long_text, short_text])
def text(request):
    yield request.param

@pytest.fixture(params=[parser_a, parser_b])
def parser(request):
    yield request.param

@pytest.fixture
def doc(parser, text):
    yield parser().parse(text())

def test_doc(doc):
    print(doc)

生成的 pytest 输出为:

============================= test session starts =============================
...
collecting ... collected 4 items

test_combine_fixt.py::test_doc[parser_a-long_text] PASSED                [ 25%]parser_a(If I only knew how to bake cookies I could make everyone happy.)

test_combine_fixt.py::test_doc[parser_a-short_text] PASSED               [ 50%]parser_a(Lorem ipsum)

test_combine_fixt.py::test_doc[parser_b-long_text] PASSED                [ 75%]parser_b(If I only knew how to bake cookies I could make everyone happy.)

test_combine_fixt.py::test_doc[parser_b-short_text] PASSED               [100%]parser_b(Lorem ipsum)


============================== 4 passed in 0.05s ==============================

更新: 我为解析器添加了一个单例工厂,如评论中所讨论的示例。

注意: 我尝试pytest.lazy_fixture按照@hoefling 的建议使用。这行得通,并且可以直接从固定装置传递解析器和文本,但我(还)不能让它以每个解析器只实例化一次的方式工作。作为参考,如果使用以下是更改后的代码pytest.lazy_fixture

@pytest.fixture
def parser_a():
    return Parser("parser_a")

@pytest.fixture
def parser_b():
    return Parser("parser_b")

@pytest.fixture
def short_text():
    return "Lorem ipsum"

@pytest.fixture
def long_text():
    return "If I only knew how to bake cookies I could make everyone happy."


@pytest.fixture(params=[pytest.lazy_fixture('long_text'),
                        pytest.lazy_fixture('short_text')])
def text(request):
    yield request.param

@pytest.fixture(params=[pytest.lazy_fixture('parser_a'),
                        pytest.lazy_fixture('parser_b')])
def parser(request):
    yield request.param


@pytest.fixture
def doc(parser, text):
    yield parser.parse(text)


def test_doc(doc):
    print(doc)
于 2020-04-28T18:01:47.823 回答