我正在将Python 3.6.5与以下库一起使用:
现在,我需要在测试失败的情况下捕获屏幕截图,所以我故意放了一个错误的陈述
self.driver.find_element_by_css_selector('test')
。
我正在使用sys.exc_info()
。但是,当我使用命令py.test untitled.py
或python3 -m unittest untitled.py
执行以下代码时,不会捕获它。
代码:
import sys, time, unittest2
from selenium import webdriver
class FB360(unittest2.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_user_can_login(self):
self.driver.get('https://www.google.co.in')
self.driver.find_element_by_css_selector('test')
def tearDown(self):
print(sys.exc_info())
if sys.exc_info()[0]:
test_method_name = self._testMethodName
self.driver.save_screenshot(test_method_name + str(time.time()) + '.png')
self.driver.quit()
if __name__ == '__main__':
unittest2.main()
O / P:
(无,无,无)
E
================================================ ======================= 错误:test_user_can_login(无标题。FB360)
回溯(最近通话最近): 在test_user_can_login的第11行,文件“ /Volumes/Harry/Projects/pythonScreenshots/untitled.py” self.driver.find_element_by_css_selector('test') 在find_element_by_css_selector的第498行中,文件“ /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py” 返回self.find_element(by = By.CSS_SELECTOR,value = css_selector) 文件“ /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py”,行832,在find_element中 'value':value})['value'] 执行中的文件“ /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py”,第297行 self.error_handler.check_response(响应) 文件“ /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py”,行194,在check_response中 引发exception_class(消息,屏幕,堆栈跟踪) selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“方法”:“ css选择器”,“选择器”:“测试”} (会议信息:chrome = 67.0.3396.99) (驱动程序信息:chromedriver = 2.40.565386(45a059dc425e08165f9a10324bd1380cc13ca363),platform = Mac OS X 10.13.5 x86_64)
我的创办人:
print(sys.exc_info())
打印:(无,无,无)。这意味着即使我收到以下异常,我的测试用例也通过了:selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“方法”:“ css选择器”,“选择器”:“测试”}
sys.exc_info())
条件下,if
返回(无,无,无)执行不会所以我主要担心的是,即使我收到NoSuchElementException,为什么sys.exc_info())
仍返回(无,无,无)?
答案 0 :(得分:3)
我用它来拍摄失败的测试的屏幕截图
@pytest.fixture()
def browser(request):
options = Options()
options.add_argument("--headless") # Runs Chrome in headless mode.
_chrome = webdriver.Chrome(options=options)
failed_before = request.session.testsfailed
yield _chrome
if request.session.testsfailed != failed_before:
test_name = request.node.name
take_screenshot(_chrome, test_name)
_chrome.close()
def take_screenshot(browser, test_name):
screenshots_dir = "path_to/functional_tests/failure_screenshots"
screenshot_file_path = "{}/{}.png".format(screenshots_dir, test_name)
browser.save_screenshot(
screenshot_file_path
)