py.test method to be executed only once per run

大城市里の小女人 提交于 2019-12-12 03:47:33

问题


Im new to pytest(and python). In have set of things to be executed only once before all my tests(ex:- starting android emulator, creating appium driver, instantiating all my page classes so that I can use them in tests). Btw, I have my tests in multiple classes. After bit of reading I thought @pytest.yield_fixture(scope="session", autouse=True) would do the trick.. but thats not what I see.. Please see below example..

import pytest

class TestBase():
    @pytest.yield_fixture(scope="session", autouse=True)
    def fixture_session(self):
        # start emulator, create driver and instantiate all page
        # classes with driver create above
        print "\n in fixture_session! @session "   
        yield
        # tear down
        print "in fixture_session after yield @session"
    @pytest.yield_fixture(scope="module", autouse=True)
    def fixture_module(request):
        print 'in fixture_module @module'
        # tear down
        yield
        print "in fixture_module after yield @module"

class TestOne(TestBase):
    def test_a(self):
        # write test with page objects created in TestBase
        print "in test_a of TestOne"  
    def test_b(self):
        print "in test_b of TestOne"

class TestTwo(TestBase):
    def test_a(self):
        print "in test_a of TestTwo"

    def test_b(self):
        print "in test_b of TestTwo"

Running this gives

test_base.py
 in fixture_session! @session
in fixture_module @module
in test_a of TestOne
.in test_b of TestOne
.
 in fixture_session! @session
in fixture_module @module
in test_a of TestTwo
.in test_b of TestTwo
.in fixture_module after yield @module
in fixture_module after yield @module
in fixture_session after yield @session
in fixture_session after yield @session

What am I missing ?? Why @pytest.yield_fixture(scope="session", autouse=True) is being executed per test class and why tear down is happen after complete test run? Over all, is this right way of setting up test framework in Pytest ?


回答1:


This happens because you define your fixtures inside a class and then subclass it, causing the fixtures to be defined twice.

Instead you should just define the fixtures as normal functions, and either change your tests to be functions as well, or not inherit from any base class if you want to use classes for grouping tests.



来源:https://stackoverflow.com/questions/37100459/py-test-method-to-be-executed-only-once-per-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!