Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pytest.mark.parametrize does not work with classes in pytest?

Following code does not collect any test cases (i expect 4 to be found). Why?

import pytest
import uuid

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

class TestClass:
    def __init__(self):
        self.browser = webdriver.Remote(
            desired_capabilities=webdriver.DesiredCapabilities.FIREFOX,
            command_executor='http://my-selenium:4444/wd/hub'
        )

    @pytest.mark.parametrize('data', [1,2,3,4])    
    def test_buybuttons(self, data):
        self.browser.get('http://example.com/' + data)
        assert '<noindex>' not in self.browser.page_source

    def __del__(self):
        self.browser.quit()

If i remove __init__ and __del__ methods, it will collect tests correctly. But how i can setup and tear test down? :/

like image 972
avasin Avatar asked Feb 18 '26 03:02

avasin


1 Answers

pytest won't collect test classes with an __init__ method, a more detailed explanation of why is that can be found here: py.test skips test class if constructor is defined.

You should use fixtures to define setup and tear down operations, as they are more powerful and flexible.

If you have existing tests that already have setup/tear-down methods and want to convert them to pytest, this is one straightforward approach:

class TestClass:

    @pytest.yield_fixture(autouse=True)
    def init_browser(self):
        self.browser = webdriver.Remote(
            desired_capabilities=webdriver.DesiredCapabilities.FIREFOX,
            command_executor='http://my-selenium:4444/wd/hub'
        )
        yield  # everything after 'yield' is executed on tear-down
        self.browser.quit()


    @pytest.mark.parametrize('data', [1,2,3,4])    
    def test_buybuttons(self, data):
        self.browser.get('http://example.com/' + data)
        assert '<noindex>' not in self.browser.page_source

More details can be found here: autouse fixtures and accessing other fixtures

like image 94
Bruno Oliveira Avatar answered Feb 19 '26 16:02

Bruno Oliveira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!