-1
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()

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 only executes with predefined data [3] which is not my expectation [2,3,3]. How to fix it?

update [1,2,3]-> [2,3,3]

4

2 回答 2

1

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

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

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

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

于 2018-03-20T09:11:58.300 回答
0
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()
于 2022-01-21T05:17:49.027 回答