如何使用 Pytest 将 testCase 值传递给下一个 [英] How to pass testCase value to next one with Pytest
问题描述
import pytest
def add(x):
return x + 1
def sub(x):
return x - 1
testData1 = [1, 2]
testData2 = [3]
class Test_math(object):
@pytest.mark.parametrize('n', testData1)
def test_add(self, n):
result = add(n)
testData2.append(result) <-------- Modify testData here
assert result == 5
@pytest.mark.parametrize('n', testData2)
def test_sub(self, n):
result = sub(n)
assert result == 3
if __name__ == '__main__':
pytest.main()
只有 3 个测试:Test_math.test_add[1]
,Test_math.test_add[2]
,Test_math.test_sub[3]
在这个场景中执行.
there are only 3 tests :Test_math.test_add[1]
,Test_math.test_add[2]
,Test_math.test_sub[3]
executed in this scenario.
Test_math.test_sub
仅使用预定义的数据 [3]
执行,这不是我的期望 [2,3,3]
.如何解决?
Test_math.test_sub
only executes with predefined data [3]
which is not my expectation [2,3,3]
. How to fix it?
更新 [1,2,3]-> [2,3,3]
update [1,2,3]-> [2,3,3]
推荐答案
不完全确定为什么它不起作用,但这样做是个坏主意,因为不能保证测试的顺序(除非您实施广告-用于命令测试执行的 hoc 代码).
Not exactly sure why it didn't work, but doing it like that it's a bad idea since the order of tests is not guaranteed (unless you implement ad-hoc code to order the execution of tests).
除了测试设计的这个问题和其他问题之外,你可以通过在 pytest.mark 中加入
装饰器.testData1
和 testData2
来实现你想要的.parametrize
Besides this and other issues of test design, the way you can somewhat achieve what you want would be by joining testData1
and testData2
in the pytest.mark.parametrize
decorator.
@pytest.mark.parametrize('n', testData1 + testData2)
def test_sub(self, n):
result = sub(n)
assert result == 3
现在,请记住,对于您的测试定义,这将始终失败,因为 sub(n)
与 testData1 + testData2
的结果永远不会是 3
.
Now, keep in mind that with your test definition, this will always fail because the result of sub(n)
with testData1 + testData2
will never be 3
.
这篇关于如何使用 Pytest 将 testCase 值传递给下一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!