首页 > 解决方案 > 如何在 HTMLTestRunner 报告中包含屏幕截图?

问题描述

我正在使用 Python / Selenium / unittest / HTMLTestRunner

我想在每个测试套件失败的测试中包含屏幕截图。

有了这个它运行测试套件并创建报告

h = HTMLTestRunner(template="tests/reports/template/report_template.html", combine_reports=True, report_name="MyReport", add_timestamp=True).run(suite)

在这里tearDown创建屏幕截图并关闭测试。如果套件包含更多测试,则打开新浏览器并继续执行下一个测试步骤,最后再次创建屏幕截图并关闭,依此类推,直到最后一次测试。

@classmethod
def tearDown(cls):
now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
cls.driver.get_screenshot_as_file('reports/screenshot-%s.png' % now)
cls.driver.quit()

如何获取正确的屏幕截图并将其放入创建该屏幕截图的测试报告中?

标签: htmlselenium-webdriverscreenshotpython-unittest

解决方案


我也面临同样的问题,这是我基于的方法。

tearDown,

@classmethod
def tearDown(cls):
     for method, error in self.outcome.errors:
          if error: # Screenshot will be taken if there's an error raised
               now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
               name = 'reports/screenshot-%s.png' % now
               cls.driver.get_screenshot_as_file(name)
               print(name)

     cls.driver.quit()

然后在report_template.html我假设的你的这个模板的基础上,在这个 HTML 代码中做一些调整。

{%- if (test_case.stdout or test_case.err or test_case.err) and test_case.outcome != test_case.SKIP %}
<tr style="display:none;">
 <td class="col-xs-9" colspan="3">
   {%- if test_case.err %}<p style="color:maroon;">{{ test_case.err[0].__name__ }}: {{ test_case.err[1] }}</p>{% endif %}
   {%- if test_case.err %}<p style="color:maroon;">{{ test_case.test_exception_info }}</p>{% endif %}
   {%- if test_case.stdout %}<p>{{ test_case.stdout }}</p>{% endif %}
   <img src="your path to the image here" />
  </td>
 </tr>
{%- endif %}

推荐阅读