[英]Python AttributeError: Object has no attribute in Unittest
[英]AttributeError: 'GoogleSearch' object has no attribute 'driver' while executing tests through Python unittest
我使用这篇文章http://www.autotest.org.ua/first-autotest-with-selenium-webdriver-and-python/并在PyCharm中制作了项目
代码试用:
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
我不知道该如何解决...
此错误消息...
AttributeError: 'GoogleSearch' object has no attribute 'driver'
......意味着单元测试有一个初始化错误。
我在您的代码块中没有看到任何此类错误,但是setUp()
方法中存在问题。 几句话:
def setUp(self):
setUp()
是初始化的一部分,将在要在此测试用例类中编写的每个测试函数之前调用此方法。 您将setUp(self)
setUpp(self)
设为setUpp(self)
。 webdriver.Chrome()
,则需要传递chromedriver的绝对路径 ,但您已经提供了geckodriver 。 executable_path
路径时,请使用单引号将值提供给原始r
开关。 def tearDown(self):
在每个测试方法之后都会调用tearDown()
方法。 这是执行所有清理操作的方法。 if __name__ == '__main__':
::此行将__name__
变量设置为具有值"__main__"
。 如果此文件是从另一个模块导入的,则__name__
将设置为另一个模块的名称。 基于以上几点,有效的代码块将是:
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中找到相关的讨论-使用unittest模块时未启动浏览器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.