Search code examples
pythonseleniumselenium-webdriverautomated-testspytest

How do I create a BaseTest class for pytest


I am trying to create a class that will be inherited by all my other test classes. I seem to have a misunderstanding on how to go about it because when I try and run pytest it cant find my tests and throws an Empty suite error.

This is what I have now. Note this is for web ui testing using Selenium

base_test.py:

@pytest.mark.usefixtures('chrome_driver_init')
class BaseTest:
        def __init__(self):
                self.login_page = LoginPage(self.driver)
                self.home_page = HomePage(self.driver)
                self.details_page = DetailsPage(self.driver)

I just want this to create instances of my Web Page Objects to be used by my Test Classes

test_login.py

class TestLogin(BaseTest):
    def test_login(self):
        self.login_page.login()
        assert 'Login Succesfull' in self.home_page.welcome_text()

welcome_text() is a simple method that finds a web element and returns its text

and finally just to be through my conftest.py:

@pytest.fixture()
def chrome_driver_init(request):
    driver = webdriver.Chrome(options=opts, executable_path=ChromeDriverManager(path=TEST_PATH).install())
    request.cls.driver = driver
    driver.get(URL)
    driver.maximize_window()
    yield
    driver.quit()

I have a feelin that my BaseTest needs to inherit some pytest class and call super().__init__() but I cant find any documentaion or answers on the web to what that class would be.

Any ideas on how to implement this?

EDIT: As MrBean Suggested, I added self. to my page objects in BaseTest. Still get the same result though


Solution

  • Finally figured it out. Added my page object initialization to my pytest fixture. No need for a BaseTest class. So my final code is

    conftest.py

    def page_object_init(request, driver):
        request.cls.login_page = LoginPage(driver)
        request.cls.home_page = HomePage(driver)
        request.cls.details_page = DetailsPage(driver)
    
    
    @pytest.fixture()
    def chrome_driver_init(request):
        driver = webdriver.Chrome(options=opts, executable_path=ChromeDriverManager(path=TEST_PATH).install())
        request.cls.driver = driver
        page_object_init(request, driver)
        driver.get(URL)
        driver.maximize_window()
        yield
        driver.quit()
    

    test_login.py

    class TestLogin():
        def test_login(self):
            self.login_page.login()
            assert 'Login Succesfull' in self.home_page.welcome_text()
    

    Thanks to MrBean for pointing me in the right direction