简体   繁体   中英

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

Generally, I have two test classes which share all the test cases except the setup_class and teardown_class. The two test classes run the same client operation tests towards two different servers that need to be setup differently. And depending on where/when the test is run, I may want to skip certain test as that server might not be available. So I come up with a design:

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):
       ... 

It works fine if no class is skipped. However, if condition1 is met and TestA is skipped, then test functions in AllTests will also not run for TestB (which obviously is not what I want!).

So how to solve this issue?

Or is there any other design to fulfill my requirement (test classes which share all the test cases except the setup_class and teardown_class and each of them should be able to be skipped)? Is "parametrize" usable? I tried but just can not come up with the right codes :(

This is indeed a side effect of the implementation. The class mark is just populated to the functions.

Using parametrization is a viable alternative. It is especially good if your setup and teardown functions are similar. You can use a yield fixture with parameterization:

@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)

If you don't need the result ( a here) then you can use autouse=True and have the fixture auto-run.

For more information refer to the pytest documentation about fixtures: https://docs.pytest.org/en/latest/fixture.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM