pythonpytestpytest-fixtures

AttributeError: module 'conftest' has no attribute 'driver'


I'm trying to run the tests but I'm stuck with this error:

AttributeError: module 'conftest' has no attribute 'driver'

This is my code, Could someone tell me where the error is?

conftest

import pytest
from selenium import webdriver

driver:webdriver.Remote


@pytest.fixture
def setup_teardown():
    #setup
    global driver
    driver = webdriver.Chrome()
    driver.implicitly_wait(5)
    driver.maximize_window()
    driver.get("https://www.saucedemo.com/v1/")

    #run test
    yield

    #teardown
    driver.quit()

test login

import pytest
from selenium.webdriver.common.by import By
import conftest


@pytest.mark.usefixture("setup_teardown")
class TestCT01:
    def test_ct01_login_valido(self):
        driver = conftest.driver
        driver.find_element(By.ID, "user-name").send_keys("standard_user")
        driver.find_element(By.ID, "password").send_keys("secret_sauce")
        driver.find_element(By.ID, "login-button").click()
        assert driver.find_element(By.CLASS_NAME, "product_label").is_displayed()

Screenshot

Link


Solution

  • Your marker has missing 's' at the end that's why your test code is not triggering the fixture to initiate driver.

    change your marker to:

    @pytest.mark.usefixtures("setup_teardown")
    class TestCT01:
    

    However, here is my suggestion that would be better for your situation:

    1- You don't need to import conftest.py to your test code.

    2- You don't need to have global variable for driver

    conftest.py

    import pytest
    from selenium import webdriver
    
    
    @pytest.fixture
    def get_driver():
        #setup
        driver = webdriver.Chrome()
        driver.implicitly_wait(5)
        driver.maximize_window()
        driver.get("https://www.saucedemo.com/v1/")
    
        #run test
        yield driver
    
        #teardown
        driver.quit()
    

    test_login.py

    import pytest
    from selenium.webdriver.common.by import By
    
    
    class TestCT01:
    
        def test_ct01_login_valido(self, get_driver):
            get_driver.find_element(By.ID, "user-name").send_keys("standard_user")
            get_driver.find_element(By.ID, "password").send_keys("secret_sauce")
            get_driver.find_element(By.ID, "login-button").click()
            assert get_driver.find_element(By.CLASS_NAME, "product_label").is_displayed()