I'm using pytest with Appium for mobile testing.

I have multiple test cases and scenarios, and all of them must start with the same specific test steps.

I don't want to write this steps in all other test files to ease maintanace for later.

So I'm interested if there is any way, to add (prepend) specific test file, to collected test?

2 Answers 2


You can also use x-unit style for setups and teardowns:

class TestSetupTeardownExample:

    def setup_class(cls):
        print("setup class")

    def teardown_class(cls):
        print("teardown class")

    def setup_method(self, method):
        print("setup method")

    def teardown_method(self, method):
        print("teardown method")

    def test_setup_teardown_example(self):
        assert 1 == 1

When I run this test, the following will be printed:

setup class
teardown class
setup method
teardown method

You can see that when you run it with -s option: $ pytest -s.

I think the methods are pretty self-explanatory, but it really does this:

  • setup_class: runs once before all test cases
  • teardown_class: runs once after all test cases
  • setup_method: runs before every test case in the class
  • teardown_method: runs after every test case in the class

I think fixtures are a bit more powerful, but this is perhaps a bit more readable and understandable than decorators which might not be easy to understand when you see it for the first time.


You want to consider using fixtures

def f1():
    pass # your steps should be here

# you can also use fixtures to do steps after test:
def f2():
    pass # your "before test" steps should be here
    pass # your "after test" steps should be here

More information: https://docs.pytest.org/en/latest/fixture.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.