如何管理使用带参数的夹具的测试的期望

时间:2015-03-26 19:42:00

标签: python testing pytest

Pytest使您能够parameterize fixtures:

@pytest.fixture(params = ['a'])
def root(request):
    return request.param

所以现在在标有我们的灯具的文本中" root"我们可以使用我们的参数:

def test_something(root):
    assert root == 'a' #this will pass

我们可以用另一个夹具扩展我们的夹具:

@pytest.fixture(params = ['a'])
def root(request, leaf):
    return request.param + leaf


@pytest.fixture(params = ['b', 'c'])
def root(request):
    return request.param

现在我们已经完成了这项工作,但尚不清楚如何管理我们的测试期望。

要明确,但我的意思是测试期望......

def test_something(root):
    assert root == expectation??? <---- this has to be hardcoded.

作为解决这个问题的玩具解决方案我们可以做到

def test_something(root):
    assert root == {"ac": "ac", "ab": "ab"}[leaf]

但由于一系列显而易见的原因,这太可怕了。在EuroCon 2014上,他们在Advanced used of pytest fixtures上进行了一次谈话,它使用了一个带有参数的夹具,这个参数使用另一个带有参数的夹具(就像在我的玩具示例中一样)。然而,主持人的期望很简单:

assert inst.it_works

这似乎排除了这些问题。

问题在于(在我的例子中),此时我们已经创建了一个测试树&#39;用&#39; a&#39;在根和&#39; ab&#39;和&#39; ac&#39;如叶子:

       'a'        
+-----+   +-----+ 
|               | 
|               | 
+>             <+ 

ab              ac

虽然在这种情况下很容易跟踪最终状态(叶子),但它需要毫不费力,明显和前期(平坦)才能使其工作。

一种测试工具的想法可以让你以这种方式使用带有参数的嵌套灯具看起来非常强大:

  • 可以轻松测试所有相关状态。在典型的测试套件中,您需要手动编写所有测试,这里将为您生成。
  • 它将允许引脚指向树故障发生的位置,允许您精确定位可能导致问题根源的夹具。

所以,我很好奇是否存在工具,python或其他提供此功能的语言,同时允许我们管理我们的测试期望。

这样的工具会是什么样子?好吧,我的猜测是它必须为用户提供一种输入测试期望的方法。像

这样的东西
> "test_ab_cd)
> inspect info("test_ab_cd")
> ab == ???
> ac == ???
> some testing info
> "ab" === ???
> enter what "ab" should equal?
> some information about the test
> "ac" === ???
> inspect info("test_ab_cd")
> ab == ab
> ac == ???

另外还提供了日志和测试文件,以便于阅读......类似......

test_something.txt
=========================
- test_something_ab
assert ab == ab
- test_someting_ac
assert ac == ac

在一个更复杂的例子中需要看起来像这样(常规测试看起来很重要)

test_something.txt
====================
- test_something_graph
x = 1
y = 2
start = node(x, y)
que = SimplePriority()
finish_node == graph(start,que) 
assert finish_node == 5

必须通过检查所涉及的各种text_fixtures来生成。

这里的解决方案更可能是damp tests而不是深度嵌套的灯具。但我很好奇是否有办法动态管理期望。或者,如果在这样的测试工具的其他语言中有任何示例。我四处寻找但没找到任何东西。

1 个答案:

答案 0 :(得分:1)

好的......在我看来,如果你对不同的输入有不同的测试结果预期,那么你有数据测试参数化,而不是夹具。参数化和夹具有很多重叠,因此弄清楚何时使用其中一个可能很棘手。但是当你的结果根据输入而变化时,会向我发出“参数化”的声音。所有输入的结果应该相同?那声称“夹具”。

我们可以混合搭配,但是:

import pytest


def something(root, leaf):
    return root + leaf


@pytest.fixture(params=['a'])
def root(request):
    return request.param


@pytest.mark.parametrize('leaf,expected', [
    ('b', 'ab'),
    ('c', 'ac'),
])
def test_something(root, leaf, expected):
    assert something(root, leaf) == expected

但是如果你有多个root值,那么你需要在参数化中明确拼写它们以及预期的值。你一次只能改变一件事,但仍然有可读的测试。