1
votes

Having a testclass and testcases like below:

class TestSomething():
    ...
    @pytest.fixture(autouse=True)
    def before_and_after_testcases(self):
        setup()
        yield
        cleanup()

    def test_abc_1():
        ...
    def test_abc_2():
        ...
    def test_def_1():
        ...
    def test_def_2():
        ...

Problem is, before_and_after_testcases() would run for each testcase in the test class. Is it possible to let the fixture apply to testcases with abc pattern in the function name only? The fixture is not supposed to run on test_def_xxx, but I don't know how to exclude those testcases.

1
remove autouse=True and then use @pytest.mark.usefixtures('before_and_after_testcases') to decorate those functions -- or split it into two classes are my suggestionsAnthony Sottile
Thank you, @AnthonySottile. Would you please convert your comment to the answer so that I can select it?Qiang Xu

1 Answers

2
votes

The autouse=True fixture is automatically applied to all of the tests, to remove that auto-application you'll remove autouse=True

but now that fixture isn't applied to any!

to manually apply that fixture to the tests that need it you can either:

  1. add that fixture's name as a parameter (if you need the value that the fixture has)
  2. decorate the tests which need that fixture with @pytest.mark.usefixtures('fixture_name_here')

Another approach is to split your one test class into multiple test classes, grouping the tests which need the particular auto-used fixtures


disclaimer: I'm a pytest developer, though I don't think that's entirely relevant to this answer SO just requires disclosure of affiliation