python-unittest 框架利用 PageObject 設計模式在 BasePage 類中呼叫不到 send_keys 方法,執行報錯'NoneType' object has no attribute 'send_keys'

王子夜發表於2020-07-30

BasePage類程式碼如下:
from selenium.webdriver.support.wait import WebDriverWait as WD
from selenium.webdriver.support import expected_conditions as EC

class BasePage(object):

def init(self, driver):
self.driver = driver

def find_element(self, *loc):
try:
WD(self.driver, 60).until(EC.visibility_of_element_located(*loc))
return self.find_element(*loc)
except:
print("元素沒找到")

def send_keys(self, value, *loc):
self.find_element(*loc).send_keys(value)

第一個問題:上面的BasePage類中的driver是從TestCase類中傳過來的,但是我在寫def send_keys(self, value, *loc)這個方法的時候,寫self.find_element(*loc).send_keys(value)的時候,send_keys(value)這個方法是呼叫不出來的,是不是說明我的driver沒有傳遞過來?如下圖:

HomePage類繼承了BasePage類,程式碼如下:

from basepage import BasePage
from selenium.webdriver.common.by import By

class HomePage(BasePage):

search_input = (By.XPATH, "//div[@id='home-search']//input[@class='typeahead form-control']")
search_button = (By.XPATH, "//div[@id='home-search']//span[@class='icon-search']")

def input_search(self, value):
self.send_keys(value, self.search_input)

def click_search_button(self):
self.find_element(self.search_button).click()

TestCase類的程式碼如下:

import unittest
from selenium import webdriver
from homepage import HomePage

class TestSearch(unittest.TestCase):

@classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome()
cls.homepage = HomePage(cls.driver)
cls.driver.get("https://support.lenovo.com/us/en")

def test_search(self):
self.homepage.input_search("lenovo")
self.homepage.click_search_button()

@classmethod
def tearDownClass(cls):
cls.driver.quit()

if name == 'main':
unittest.main()

上面的TestCase類中driver通過cls.homepage = HomePage(cls.driver)傳遞給homepage類,然後傳遞給BasePage類中的driver,但是BasePage類中的driver卻呼叫不到 selenium webdriver的一些常用方法,比如send_keys(), page_souce()等,是driver沒有傳遞到BasePage類中嗎?

然後我執行我的TestCase, 果然在這裡 self.find_element(*loc).send_keys(value),報錯了,錯誤如下:

File "D:\automationTestProject\johnunittest\basepage.py", line 20, in send_keys
return self.find_element(*loc).send_keys(value)
AttributeError: 'NoneType' object has no attribute 'send_keys'

小弟以前是學JAVA的,剛剛學習python自動化,請各位大神,指點一下,非常感謝!

相關文章