在 pytest 中,如果 test class 是 subclass,则 skipif 不会按预期工作

In pytest, skipif doesn't work as expected if test class is a subclass

通常,我有两个测试 classes,它们共享除 setup_class 和 teardown_class 之外的所有测试用例。这两个测试 classes 运行 相同的客户端操作针对需要不同设置的两个不同服务器进行测试。并且根据 where/when 测试是 运行,我可能想跳过某些测试,因为该服务器可能不可用。所以我想出了一个设计:

class AllTests:
   def test_1(self):
       ...
   def test_2(self):
       ...

@pytest.mark.skipif(condition1)
class TestA(AllTests):
   @classmethod
   def setup_class(cls):
       ...
   @classmethod
   def teardown_class(cls):
       ...

@pytest.mark.skipif(condition2)
class TestB(AllTests):
   @classmethod
   def setup_class(cls):
       ...
   @classmethod
   def teardown_class(cls):
       ... 

如果没有跳过 class,它工作正常。 但是,如果满足条件 1 并跳过 TestA,那么 AllTests 中的测试函数也不会 运行 用于 TestB(这显然不是我想要的!)。

那么如何解决这个问题呢?

或者是否有任何其他设计可以满足我的要求(测试 classes 共享除 setup_class 和 teardown_class 之外的所有测试用例,并且它们中的每一个都应该能够被跳过)? "parametrize"可以用吗?我试过了,但就是想不出正确的代码:(

这确实是实施的副作用。 class 标记只是填充到函数中。

使用参数化是一种可行的替代方法。如果您的设置和拆卸功能相似,那就特别好。您可以使用带有参数化的 yield fixture:

@pytest.fixture(scope="class", params=['a', 'b'])
def do_setup(request):
    # setup
    a = open(request.param)
    yield a  # provide the fixture value
    # teardown
    close(a)

如果您不需要结果(此处为 a),那么您可以使用 autouse=True 并让夹具自动 运行.

有关更多信息,请参阅有关固定装置的 pytest 文档:https://docs.pytest.org/en/latest/fixture.html