1

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?

0

You want to consider using fixtures

@pytest.fixture
def f1():
    pass # your steps should be here

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

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

| improve this answer | |
0

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

class TestSetupTeardownExample:

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

    @classmethod
    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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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