Search code examples
pythonseleniumselenium-webdriverpytestpytest-html

Pytest Selenium Web Driver Coming Back as NoneType When using getfixturevalue


Can anyone help me figure out why driver is coming back as a NoneType in my pytest.hookimpl fixture?

Here is my conftest.py

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


# Adds a screenshot to the pytest-html report for a failed test
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    pytest_html = item.config.pluginmanager.getplugin("html")
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, "extra", [])
    if report.when == "call":
        feature_request = item.funcargs['request']
        driver = feature_request.getfixturevalue('chrome_driver_init')
        nodeid = item.nodeid
        xfail = hasattr(report, "wasxfail")
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = f'{nodeid}_{datetime.today().strftime("%Y-%m-%d_%H:%M")}.png'.replace("/", "_").replace("::", "_")
            img_path = os.path.join(REPORT_PATH, "screenshots", file_name)
            driver.save_screenshot(img_path)
            extra.append(pytest_html.extras.image(img_path))
        report.extra = extra

The error happens at driver.save_screenshot() but I am assuming the true problem is that

driver = feature_request.getfixturevalue('chrome_driver_init') is not actually returning my webdriver and is returning None.

I have racked my brain trying to work around this. I assume it has something to do with my fixture being scoped to class or I am missing something with the use of request in my driver fixture?

Any help would be appreciated.

Here is my error log for added detail

INTERNALERROR>   File "~/pytest_project\scr\tests\conftest.py", line 57, in pytest_runtest_makereport
INTERNALERROR>     driver.save_screenshot(img_path)
INTERNALERROR> AttributeError: 'NoneType' object has no attribute 'save_screenshot'

I scrubbed my personal computers path with the "~"


Solution

  • All glory goes to hoefling.

    as he said in the comments, I forgot to yield my actual driver.

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