TransWikia.com

Is it possible to add specific tests to the collected tests?

Software Quality Assurance & Testing Asked on November 11, 2021

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

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.

Answered by pavelsaman on November 11, 2021

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

Answered by Alexander Pushkarev on November 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP