Search code examples
seleniumselenium-webdriverpytestfixtures

pytest - is there a way to ignore an autouse fixture?


I have this autouse fixture that will create a webdriver instance for each test:

@pytest.fixture(autouse=True)
def use_phantomjs(self):
    self.wd = webdriver.PhantomJS()
    yield
    self.close_wd()

However, some of our tests cannot run on PhantomJS due to a bug with one of our APIs. These tests can only run on Chrome (or Firefox), so I created another method for a webdriver instance using Chrome:

def use_chrome(self):
    self.wd = webdriver.Chrome()

which I plan to use on those tests, but I cannot get around the autouse fixture above.

Is there a way to somehow override the autouse fixture for some of our tests? I have tried using pytest.mark.usefixtures for each test but it doesn't seem ideal having to put that decorator on each and every test. Someone mentioned using metaclasses but I haven't fully understood how they work yet, so I was wondering if there was some other way that I might have missed.


Solution

  • ----- UPDATE for latest versions of pytest----- use request.node.get_closest_marker() to get the marker. Refer get_closest_marker


    You can achieve this in many ways , one way is to use the request fixture along with pytest mark fix. All you need to do is, create a new generic fixture

    @pytest.fixture(autouse=True)
    def browser(request):
        # _browser = request.node.get_marker('browser')
        _browser = request.node.get_closest_marker('browser')
        if _browser:
           if _browser.kwargs.get("use") == "chrome" :
                # Do chrome related setup
           elif _browser.kwargs.get("use") == "phantom" :
                # Do Phantom.js related setup
       else:
           # No mark up ,use default setup
    

    and mark your tests like this

    @pytest.mark.browser(use="chrome")
    def test_some_chrome_test():
        # browser here would return chrome driver
    
    @pytest.mark.browser(use="phantom")
    def test_some_phantomjs_test():
        # browser here would return phantom driver