【问题标题】:How to pass testCase value to next one with Pytest如何使用 Pytest 将 testCase 值传递给下一个
【发布时间】:2018-03-20 01:36:49
【问题描述】:
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]

Test_math.test_sub 仅使用预定义数据 [3] 执行,这不是我的预期 [2,3,3]。如何解决?

更新 [1,2,3]-> [2,3,3]

【问题讨论】:

  • 为什么[1,2,3]是你的期望?你给test_sub 列表testData2,它只有一个元素长。好的,我明白你为什么会期待不同的东西了。
  • 我认为testData2.append(result)会修改testData2,新的testData2会传递给下一次执行,但它没有
  • 我认为这是一个糟糕的设计(答案中有更多详细信息),可以通过将testData1testData2 作为类属性来实现这一点(尚未测试)。
  • 很遗憾,它不起作用

标签: python pytest python-unittest parameterized-unit-test


【解决方案1】:

不完全确定为什么它不起作用,但这样做是个坏主意,因为不能保证测试的顺序(除非您实现临时代码来排序测试的执行)。

除了测试设计的这个问题和其他问题之外,您可以通过在pytest.mark.parametrize 装饰器中加入testData1testData2 来在一定程度上实现您想要的。

@pytest.mark.parametrize('n', testData1 + testData2)
def test_sub(self, n):
    result = sub(n)
    assert result == 3

现在,请记住,使用您的测试定义,这将始终失败,因为 sub(n)testData1 + testData2 的结果永远不会是 3

【讨论】:

    【解决方案2】:
    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) 
            assert result == 5, "FAILED"
            return testData2
    
        def add():
            for i in testData1:
                res = add(i)
                testData2.append(res)  
                print(testData2)         
            return testData2
    
        @pytest.mark.parametrize('n', add())
        def test_sub(self, n):
            result = sub(n)
            assert result == 3, "FAILED"
    
    if __name__ == '__main__':
        pytest.main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      相关资源
      最近更新 更多