簡體   English   中英

為什么我收到 'AttributeError: 'NoneType' object has no attribute 'get_screenshot_as_file' ? 顯示完整代碼 Pycharm/Pytest

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

我瀏覽了類似的 Q,但似乎沒有一個答案能解決我的問題。

我正在通過 Pycharm(Python 3.9)使用 Pytest 作為測試運行器運行測試“test_HomePage”

代碼如下:

比賽.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)

基類.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

主頁數據.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]

顯示文件夾/文件結構的屏幕截圖:

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 測試於 11:31 開始......使用參數啟動 pytest -s -v U:/PythonMN/SeleniumFramework/tests/test_HomePage.py --no-header --no-summary -q 在 U:\\PythonMN\\SeleniumFramework\\tests

============================ 測試會話開始 ================== ============ 收集到 1 件物品

test_HomePage.py::TestHomePage::test_formSubmission[getData0] -INTERNALERROR> Traceback(最近一次調用最后一次):-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.multi call( -INTERNALERROR> File "U:\\PythonMN\\SeleniumFramework\\lib\\site-packages\\pluggy\\callers.py", line 208, in _multicall -INTERNALERROR> return result.get_result() -INTERNALERROR> File "U:\\PythonMN \\SeleniumFramework\\lib\\site-packages\\pluggy\\callers.py”,第 80 行,在 get_result -INTERNALERROR> raise ex 1 .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",第 348 行,在 pytest_runtestloop -INTERNALERROR> item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem) -INTERNALERROR> 文件“U:\\PythonMN\\SeleniumFramework\\lib\\site-packages\\pluggy\\hooks.py”,行286,在調用-INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs) -INTERNALERROR> 文件“U:\\PythonMN\\SeleniumFramework\\lib\\site-packages\\pluggy\\manager.py”,第 93 行,在 _hookexec -INTERNALERRO R> 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鈎子,方法,kwargs:hook.multicall( -INTERNALERROR> File "U:\\PythonMN\\SeleniumFramework\\lib\\site-packages\\pluggy\\callers.py", line 208, in _multicall -INTERNALERROR> return results.get_result() - INTERNALERROR> File "U:\\PythonMN\\SeleniumFramework\\lib\\site-packages\\pluggy\\callers.py", line 80, in get_result -INTERNALERROR> raise ex 1 .with_traceback(ex[2]) -INTERNALERROR> File "U: \\PythonMN\\SeleniumFramework\\lib\\site-packages\\pluggy\\callers.py”,第 187 行,在 _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、在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>報告: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>文件“U:\\PythonMN\\SeleniumFramework\\tests\\conftest.py”,第 48 行,在 pytest_runtest_makereport -INTERNALERROR> _capture_screenshot(file_name) -INTERNALERROR> 文件“U:\\PythonMN\\SeleniumFramework\\tests\\conftest.py”,第 57 行,在 _capture_screenshot -INTERNALERROR> driver.get_screenshot_as_file(name) -INTERNALERROR> AttributeError: 'NoneType' 對象沒有屬性 'get_screenshot_as_file'

============================ 沒有測試在 0.82 秒內運行 ================ ============

進程以退出代碼 3 結束


提前致謝

這意味着driver對象未在_capture_screenshot方法內實例化。
未實例化的變量在 Python 中被定義為None類型的對象。
顯然這樣的對象沒有webdriver類的方法和屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM