AttributeError:通过Python unittest执行测试时,“ GoogleSearch”对象没有属性“ driver”

时间:2019-01-24 18:04:32

标签: python selenium selenium-webdriver webdriver python-unittest

我使用这篇文章http://www.autotest.org.ua/first-autotest-with-selenium-webdriver-and-python/,并在PyCharm中创建了项目

This is a photo

代码试用:

from selenium import webdriver
import unittest
from selenium.webdriver.common.keys import Keys


class GoogleSearch(unittest.TestCase):
    def setUpp(self):
        self.driver = webdriver.Chrome(executable_path="C:\Python37-32\geckodriver-v0.23.0-win64\geckodriver.exe")
        self.driver.get('https://www.google.by')
        self.driver.maximize_window()
        self.driver.implicitly_wait(10)

    def test_01(self):
        driver = self.driver
        input_field = driver.find_element_by_class_name('class="gLFyf gsfi"')
        input_field.send_keys('python')
        input_field.send_keys(Keys.ENTER)

错误:

FAILED (errors=1)

Error
Traceback (most recent call last):
  File "C:\Python37-32\lib\unittest\case.py", line 59, in testPartExecutor
    yield
  File "C:\Python37-32\lib\unittest\case.py", line 615, in run
    testMethod()
  File "D:\QA\untitled\test.py", line 13, in test_01
    driver = self.driver
AttributeError: 'GoogleSearch' object has no attribute 'driver'


Process finished with exit code 1

我不知道如何解决...

1 个答案:

答案 0 :(得分:-1)

此错误消息...

AttributeError: 'GoogleSearch' object has no attribute 'driver'

...表示 unittest 出现初始化错误。

我在您的代码块中没有看到任何此类错误,但是setUp()方法中存在问题。几句话:

  • def setUp(self): setUp() 是初始化的一部分,该方法将在要在此测试用例类中编写的每个测试函数之前调用。您将setUp(self)拼写为 setUpp(self)
  • 如果您使用的是webdriver.Chrome(),则需要通过 chromedriver 绝对路径,但是您已经提供了 geckodriver 。 / li>
  • 在传递 Key executable_path时,请通过单引号和原始r开关提供 Value
  • def tearDown(self)::每个测试方法之后都会调用 tearDown() 方法。这是执行所有清理操作的方法。
  • if __name__ == '__main__'::此行将__name__变量设置为值"__main__"。如果此文件是从另一个模块导入的,则__name__将被设置为另一个模块的名称。
  • 您将在What does if name == “main”: do?
  • 中找到详细的讨论
  • 基于上述几点,您的有效代码块将为:

    import unittest
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    class GoogleSearch(unittest.TestCase):
    
        def setUp(self):
            self.driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
            self.driver.get('https://www.google.by')
            self.driver.maximize_window()
            self.driver.implicitly_wait(10)
    
        def test_01(self):
            driver = self.driver
            input_field = driver.find_element_by_class_name('class="gLFyf gsfi"')
            input_field.send_keys('python')
            input_field.send_keys(Keys.ENTER)
    
        def tearDown(self):
            self.driver.quit()
    
    if __name__ == "__main__":
        unittest.main()
    
  • 您可以在Python + WebDriver — No browser launched while using unittest module

  • 中找到相关的讨论