我正在尝试用selenium编写py.test
测试来测试复杂的网站。由于设置很复杂,因此即使在实际测试之前测试也会失败。但在这种情况下,我希望能够调用一个'debug'函数(可能是一个teardown
函数,我可以使用它来调试东西。
示例:
测试使用一个返回硒webdriver的夹具
def test1(driver):
driver.get("my page")
...
other tests, login, etc etc
但现在呼叫driver.get
因任何原因而失败。但在这种情况下,我希望能够调查像
def debug(driver):
driver.screenshot(...)
print(driver.page_source)
...
driver.quit()
(包括关闭驱动程序,因为浏览器将保持打开状态)与测试方法中使用的driver
实例相同。
有办法吗?
答案 0 :(得分:1)
最棘手的部分是将测试结果传递到夹具中,其余部分非常简单。在pytest
示例Making test result information available in fixtures之后,在conftest.py
中添加自定义摘要:
import pytest
@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
setattr(item, "rep_" + rep.when, rep)
return rep
现在,您可以使用自定义拆卸逻辑增强driver
夹具,以防测试失败:
# test_selenium.py
import pytest
from selenium import webdriver
def debug(driver):
print('debug: ', driver.title)
@pytest.fixture
def driver(request):
driver = webdriver.Firefox()
yield driver
if request.node.rep_setup.passed and request.node.rep_call.failed:
# this is the teardown code executed on test failure only
debug(driver)
# this is the teardown code that is always executed
driver.quit()
def test_fail(driver):
driver.get('http://wtf')
def test_ok(driver):
driver.get('https://www.google.de')
运行测试产生:
$ pytest -sv
=============================== test session starts ===============================
platform darwin -- Python 3.6.3, ...
cachedir: .cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-48521762, inifile:
plugins: ...
collecting ... collected 2 items
test_spam.py::test_fail FAILED [ 50%]
debug Server Not Found
test_spam.py::test_ok PASSED [100%]
==================================== FAILURES =====================================
____________________________________ test_fail ____________________________________
driver = <selenium.webdriver.firefox.webdriver.WebDriver( ...
...
------------------------------- Captured log setup --------------------------------
remote_connection.py 474 DEBUG POST http://127.0.0.1:50319/session { ...
...
remote_connection.py 561 DEBUG Finished Request
======================== 1 failed, 1 passed in 7.23 seconds =======================