1.环境准备

/*@param:

作者:流浪的python 

Date:2019/01/19

env:python 3.7(由于3.0-3.5以下部分pytest可能有部分兼容问题安装建议2.7-2.9,3.5-最新)

pip install pytest专属 pytest框架包

pip install pytest-html  pytest自己专属报告包

pip install pytest-rerunfailures 失败重跑包也是pytest专属

并发的也可以安下,利用多cpu运行调高用例执行速度

python -m pip install xdist

2.用例配置conftest.py编写,这个文件名必须是这个,官网指定的,pytest运行前会自己寻找这个文件,如果有会按里面配置跑没有就默认按用例设置跑,conftest.py仅对同目录,同目录下文件生效,超出按自己的conftest.py配置,每个包可以有自己的conftest.py

目录结构:​​https://docs.pytest.org/en/latest/pythonpath.html#test-modules-conftest-py-files-inside-packages​

参考以上链接官网解释

这里我给出我的结构供参考:

project/
|- __init__.py
|- conftest.py
|- bar/
|- __init__.py
|- tests/
|- __init__.py
|- test_foo.py

pytest 失败重跑截图_python

conftest.py

# coding=utf-8
from selenium import webdriver
import pytest
import os
driver = None


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
"""
Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
:param item:
"""
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])

if report.when == 'call' or report.when == "setup":
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
dirpng=r'./report/png/'
if os.path.exists(dirpng) and os.path.isdir(dirpng):
pass
else:
os.mkdir(dirpng)
file_name = dirpng + report.nodeid.replace("::", "_")+".png"
file_name1=r'./png/'+ report.nodeid.replace("::", "_")+".png"
_capture_screenshot(file_name)
if file_name:
html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
'onclick="window.open(this.src)" align="right"/></div>' % file_name1
extra.append(pytest_html.extras.html(html))
report.extra = extra


def _capture_screenshot(name):
driver.get_screenshot_as_file(name)



@pytest.fixture(scope='session', autouse=True)
def browser():
global driver
if driver is None:
driver = webdriver.Chrome()
return driver

pytest 失败重跑截图_python_02

3例脚本编写

# coding=utf-8
import pytest

class TestFailScreenShoot(object):

def test_run001(self):
assert 1==2

def test_run002(self):
assert 1==1

def test_screenshot_on_test_failure(self,browser):
browser.get("https://www.baidu.com")
assert False

# if __name__ == "__main__":
# pytest.main('-s','-q')

pytest 失败重跑截图_用例_03

4.cmd 到用例所在目录,Tests目录retry次数2,失败重跑延迟间隔2秒

输入: py.test  --html=./report/test_report.html -v --reruns 2 --reruns-delay 2 看到cmd提示如下:

generated html file: C:\Users\Administrator\PycharmProjects\pytestframe\foo\bar\Tests\report\test_report.html

根据提示浏览器地址栏输入file:///C:/Users/Administrator/PycharmProjects/pytestframe/foo/bar/Tests/report/test_report.html

pytest 失败重跑截图_用例_04

pytest 失败重跑截图_python_05


pytest 失败重跑截图_用例_06

pytest 失败重跑截图_用例_07