Why am I getting 'AttributeError: 'NoneType' object has no attribute 'get_screenshot_as_file' ? full code shown Pycharm/Pytest

Why am I getting 'AttributeError: 'NoneType' object has no attribute 'get_screenshot_as_file' ? full code shown Pycharm/Pytest

我查看了类似的问题,但 none 的答案似乎解决了我的问题。

我是 运行 通过 Pycharm (Python 3.9) 进行的测试 'test_HomePage',使用 Pytest 作为测试运行程序

代码如下:

Conftest.py:

import pytest
from selenium import webdriver
import time
driver = None

def pytest_addoption(parser):
    parser.addoption(
        "--browser_name", action="store", default="chrome"
    )


@pytest.fixture(scope="class")
def setup(request):
    
    global driver
    browser_name=request.config.getoption("browser_name")
    if browser_name == "chrome":
        driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
    elif browser_name == "firefox":
        driver = webdriver.Firefox(executable_path="C:\geckodriver.exe")

    driver.get("https://rahulshettyacademy.com/angularpractice/")
    driver.maximize_window()

    request.cls.driver = driver
    yield
    driver.close()


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            _capture_screenshot(file_name)
            if file_name:
                html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % file_name
                extra.append(pytest_html.extras.html(html))
        report.extra = extra


def _capture_screenshot(name):
        driver.get_screenshot_as_file(name)

Baseclass.py:


import inspect
import logging

import pytest
import TestData.HomePageData
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select

@pytest.mark.usefixtures("setup")
class BaseClass:

    def getLogger(self):
        loggerName = inspect.stack()[1][3]
        logger = logging.getLogger(loggerName)
        fileHandler = logging.FileHandler('logfile.log')
        formatter = logging.Formatter("%(asctime)s :%(levelname)s : %(name)s :%(message)s")
        fileHandler.setFormatter(formatter)

        logger.addHandler(fileHandler)  # filehandler object

        logger.setLevel(logging.DEBUG)
        return logger

    def verifyLinkPresence(self, text):
        element = WebDriverWait(self.driver, 10).until(
        EC.presence_of_element_located((By.LINK_TEXT, text)))

    def selectOptionByText(self,locator,text):
        sel = Select(locator)
        sel.select_by_visible_text(text)

test_HomePage.py:

from selenium.webdriver.support.select import Select
from selenium import webdriver
import pytest

from TestData.HomePageData import HomePageData
from pageObjects.HomePage import HomePage
from utilities.BaseClass import BaseClass

class TestHomePage(BaseClass):

    def test_formSubmission(self,getData):
        log = self.getLogger()
        homepage= HomePage(self.driver)
        log.info("first name is "+getData["firstname"])
        homepage.getName().send_keys(getData["firstname"])
        homepage.getEmail().send_keys(getData["lastname"])
        homepage.getCheckBox().click()
        self.selectOptionByText(homepage.getGender(), getData["gender"])

        homepage.submitForm().click()

        alertText = homepage.getSuccessMessage().text

        assert ("Success" in alertText)
        self.driver.refresh()

    @pytest.fixture(params=HomePageData.getTestData("Testcase2"))
    def getData(self, request):
        return request.param

HomePageData.py:

class HomePageData:


    #data dictionary to pass to the 'test_homepage' test section
    test_HomePage_data = [{"firstname": "Matt", "lastname": "Smith", "gender": "Male"}, {"firstname": "Jane", "lastname": "Smith", "gender": "Female"}]


import openpyxl


class HomePageData:
    test_HomePage_data = [{"firstname": "Matt", "lastname": "Smith", "gender": "Male"},
                          {"firstname": "Jane", "lastname": "Smith", "gender": "Female"}]

    #below is for using excel data import in the place of the above data line
    #static method declared, so 'self' is not required prior to 'test_case_name'
    @staticmethod
    def getTestData(test_case_name):
        Dict = {}
        book = openpyxl.load_workbook("C:\PythonExcel\PythonDemo.xlsx")
        sheet = book.active
        for i in range(1, sheet.max_row + 1):  # to get rows
            if sheet.cell(row=i, column=1).value == test_case_name:

                for j in range(2, sheet.max_column + 1):  # to get columns
                    # Dict["lastname"]="shetty
                    Dict[sheet.cell(row=1, column=j).value] = sheet.cell(row=i, column=j).value
        return[Dict]

显示 folder/file 结构的屏幕截图:

Folder structure within Pycharm


收到的错误全文:

U:\PythonMN\SeleniumFramework\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2021.1.2\plugins\python-ce\helpers\pycharm_jb_pytest_runner.py" --path U:/PythonMN/SeleniumFramework/tests/test_HomePage.py -- -s -v Testing started at 11:31 ... Launching pytest with arguments -s -v U:/PythonMN/SeleniumFramework/tests/test_HomePage.py --no-header --no-summary -q in U:\PythonMN\SeleniumFramework\tests

============================= test session starts ============================= collected 1 item

test_HomePage.py::TestHomePage::test_formSubmission[getData0] -INTERNALERROR> Traceback (most recent call last): -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages_pytest\main.py", line 269, in wrap_session -INTERNALERROR> session.exitstatus = doit(config, session) or 0 -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages_pytest\main.py", line 323, in _main -INTERNALERROR> config.hook.pytest_runtestloop(session=session) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\hooks.py", line 286, in call -INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\manager.py", line 93, in _hookexec -INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\manager.py", line 84, in -INTERNALERROR> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall( -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\callers.py", line 208, in _multicall -INTERNALERROR> return outcome.get_result() -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\callers.py", line 80, in get_result -INTERNALERROR> raise ex1.with_traceback(ex[2]) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\callers.py", line 187, in _multicall -INTERNALERROR> res = hook_impl.function(*args) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages_pytest\main.py", line 348, in pytest_runtestloop -INTERNALERROR> item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\hooks.py", line 286, in call -INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\manager.py", line 93, in _hookexec -INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\manager.py", line 84, in -INTERNALERROR> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall( -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\callers.py", line 208, in _multicall -INTERNALERROR> return outcome.get_result() -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\callers.py", line 80, in get_result -INTERNALERROR> raise ex1.with_traceback(ex[2]) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\callers.py", line 187, in _multicall -INTERNALERROR> res = hook_impl.function(*args) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages_pytest\runner.py", line 109, in pytest_runtest_protocol -INTERNALERROR> runtestprotocol(item, nextitem=nextitem) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages_pytest\runner.py", line 120, in runtestprotocol -INTERNALERROR> rep = call_and_report(item, "setup", log) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages_pytest\runner.py", line 217, in call_and_report -INTERNALERROR> report: TestReport = hook.pytest_runtest_makereport(item=item, call=call) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\hooks.py", line 286, in call -INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\manager.py", line 93, in _hookexec -INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\manager.py", line 84, in -INTERNALERROR> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall( -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\lib\site-packages\pluggy\callers.py", line 203, in _multicall -INTERNALERROR> gen.send(outcome) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\tests\conftest.py", line 48, in pytest_runtest_makereport -INTERNALERROR> _capture_screenshot(file_name) -INTERNALERROR> File "U:\PythonMN\SeleniumFramework\tests\conftest.py", line 57, in _capture_screenshot -INTERNALERROR> driver.get_screenshot_as_file(name) -INTERNALERROR> AttributeError: 'NoneType' object has no attribute 'get_screenshot_as_file'

============================ no tests ran in 0.82s ============================

Process finished with exit code 3


提前致谢

表示driver对象没有在_capture_screenshot方法内部实例化
未实例化的变量在Python.
中被定义为None类型的对象 显然这样的对象没有webdriverclass

的方法和属性