Pytest 使您能够 parameterize fixtures:
@pytest.fixture(params = ['a'])
def root(request):
return request.param
所以现在在标有我们的固定装置“root”的文本中,我们可以使用我们的参数:
def test_something(root):
assert root == 'a' #this will pass
我们可以用另一个 fixture 扩展我们的 fixture :
@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 上发表了演讲它使用一个带有参数的 fixture ,该 fixture 使用另一个带有参数的 fixture (就像在我的玩具示例中一样)。然而,演示者的期望很简单:
assert inst.it_works
这似乎回避了问题。
问题是(在我的示例中)此时我们创建了一个“测试树”,根部为“a”,叶子为“ab”和“ac”:
'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而不是深度嵌套的固定装置。但我很好奇是否有办法动态管理期望。或者,如果这种测试工具在其他语言中有任何示例。我四处寻找,但没有找到任何东西。
最佳答案
好吧……在我看来,如果您对不同的输入有不同的测试结果预期,那么您有数据测试参数化,而不是 fixture 。参数化和 fixture 有很多重叠,因此很难弄清楚何时使用其中一个或另一个。但是当你的结果根据输入而变化时,这对我来说是“参数化”。所有输入的结果应该相同吗?那叫着“fixture”。
不过我们可以混合搭配:
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
但是如果您有多个根值,您将需要在参数化中明确地拼出它们,连同预期值。您一次只能改变一件事,但仍然有可读的测试。
关于python - 如何管理使用带参数的 fixture 的测试的期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29287439/