我有一个使用selenium IDE导出到python的selenium webdriver测试用例。然后想要添加一些额外的功能,以便在selenium测试用例之间插入自定义代码。
现在的问题是 - 如果我犯了一个错误或自定义编写的python代码返回错误 - 仍然是selenium测试用例继续执行
然而,如果出现此类错误,我希望停止执行selenium测试用例。已经使用简单的谷歌搜索复制了下面的场景,然后使用shutil模块
进行日志移动代码from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
import os, shutil
class SeleniumException(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(30)
self.base_url = "https://www.google.co.in/"
self.verificationErrors = []
self.attachment = 1
self.file_source_location = "F:\\python_test\\logfiles\\"
self.file_move_location = "F:\\logfiles_back\\"
def test_selenium_exception(self):
driver = self.driver
driver.get(self.base_url + "/")
driver.find_element_by_id("gbqfq").clear()
driver.find_element_by_id("gbqfq").send_keys("Check this out")
if self.attachment:
try:
for contents in os.listdir(self.file_source_location):
src_file = os.path.join(self.file_source_location, contents)
dst_file = os.path.join(self.file_move_location, contents)
shutil.move(src_file, dst_file)
print'files_moved_success'
driver.find_element_by_link_text("check out - definition of check out by the Free Online Dictionary ...").click()
except Exception as e:
print e
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
在这段代码中 - 如果从logfiles到logfiles_back的移动由于错误路径等原因而失败...等执行catch块并且我希望selenium测试用例退出报告错误
现在正在发生的是它报告错误并完成测试用例的执行
如何实现这一目标?
答案 0 :(得分:6)
如果要引发触发的实际异常,可以单独调用raise
,这将引发最后一个活动异常:
try:
for contents in os.listdir(self.file_source_location):
src_file = os.path.join(self.file_source_location, contents)
dst_file = os.path.join(self.file_move_location, contents)
shutil.move(src_file, dst_file)
print'files_moved_success'
driver.find_element_by_link_text("check out - definition of check out by the Free Online Dictionary ...").click()
except Exception as e:
print e
raise # Raise the exception that brought you here
如果您不想追溯并且只想退出,您还可以在sys.exit(1)
之后调用print e
(或您要使用的任何错误代码):
import sys
# ...
try:
for contents in os.listdir(self.file_source_location):
src_file = os.path.join(self.file_source_location, contents)
dst_file = os.path.join(self.file_move_location, contents)
shutil.move(src_file, dst_file)
print'files_moved_success'
driver.find_element_by_link_text("check out - definition of check out by the Free Online Dictionary ...").click()
except Exception as e:
print e
sys.exit(1)