Pytest 从不同的测试用例文件中排序

Pytest ordering from different test case files

您好,我使用 pytest 并且在一个文件夹中有以下 2 个 py 文件。

test_abc.py如下:

class MyTest(unittest.TestCase):
    @classmethod
    def setup_class(cls):
        cls.a = 10

    @classmethod
    def teardown_class(cls):
        cls.a = 20

    @pytest.mark.run(order=2)
    def test_method1(self):
       logging.warning('order2 in test_abc')
       assert (10,self.a)    # fail for demo purposes

    @pytest.mark.run(order=1)
    def test_method2(self):
        logging.warning('order1 in test_abc')
        assert 0, self.db   # fail for demo purposes

test_sample2.py如下,

class MyTest1(unittest.TestCase):
    @classmethod
    def setup_class(cls):
        cls.a = 10

    @classmethod
    def teardown_class(cls):
        cls.a = 20

    @pytest.mark.run(order=2)
    def test_mtd1(self):
       logging.warning('order2 in test_samp')
       assert (10,self.a)    # fail for demo purposes

    @pytest.mark.run(order=1)
    def test_mtd2(self):
        logging.warning('order1 in test_samp')
        assert 0, self.db   # fail for demo purposes

现在我 运行 使用命令:

py.test --tb=long --junit-xml=results.xml --html=results.html -vv

这里发生的是来自两个测试用例文件的 test_method2 首先是 运行s(因为它已作为 order1 给出),然后是来自 test_method1 运行s两个文件(因为它已作为订单 2 提供)

所以我在这里注意到的是测试的整体排序 运行 而不是个人 class/files

有什么办法可以解决这个问题吗?现在我对所有文件都使用订购号,比如我给出的第一个文件 (1,2) 然后在下一个文件中我给出 (3,4) 并且它工作正常。

但我不想在所有测试中都订购 class 只在我需要的几个地方订​​购。是否有任何钩子可以说 pytest 仅在特定文件中查看排序?

我假设您使用的是 pytest-ordering 插件——如果您的测试中只有特定区域需要排序,您可以使用相对排序:

@pytest.mark.run(after='test_second')
def test_third():
    assert True

def test_second():
    assert True

@pytest.mark.run(before='test_second')
def test_first():
    assert True

参考:(http://pytest-ordering.readthedocs.org/en/develop/#relative-to-other-tests)

我不小心被这个问题绊倒了,发现接受的答案不起作用,所以这是一个更正/补充。 提到的 pytest-ordering 文档在标题为“Aspirational”的章节中,虽然有几个 PR 提供了该功能,但它们从未被合并。

由于插件不再维护,我将其分叉到pytest-order, which is now the successor to pytest-ordering. It also contains the functionality for relative markers

使用该插件,以下将起作用:

@pytest.mark.order(after='test_second')
def test_third():
    assert True

def test_second():
    assert True

@pytest.mark.order(before='test_second')
def test_first():
    assert True

请注意,除了标记外,这与接受的答案几乎相同,标记在 pytest-order 中始终是 order

不过,这可能仍然不是原始问题的正确答案,它要求在单独的文件中单独排序。对于 pytest-order,这可以通过使用 --order-scope 选项来实现。如果在测试调用中使用 --order-scope=module,则在每个测试模块中分别进行排序。这将使问题中的代码按预期工作,如果还替换标记(例如,而不是 @pytest.mark.run(order=2) 使用 @pytest.mark.order(2).