1、conftest.py
# coding:utf-8 from selenium import webdriver import pytest driver = None @pytest.mark.hookwrapper def pytest_runtest_makereport(item): """ 当测试失败的时候,自动截图,展示到html报告中 :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): file_name = report.nodeid.replace("::", "_")+".png" screen_img = _capture_screenshot() if file_name: html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="600px;height:300px;" ' 'onclick="window.open(this.src)" align="right"/></div>' % screen_img extra.append(pytest_html.extras.html(html)) report.extra = extra def _capture_screenshot(): ''' 截图保存为base64,展示到html中 :return: ''' return driver.get_screenshot_as_base64() @pytest.fixture(scope='session', autouse=True) def browser(): global driver if driver is None: driver =webdriver.Chrome() return driver
2、test_01.py
from selenium import webdriver
import time
def test_yoyo_01(browser):
browser.get("https://www.baidu.com/")
time.sleep(2)
t = browser.title
assert t == "郭林莉"
3、test_03.py
from selenium import webdriver
import time
def test_yoyo_01(browser):
browser.get("https://www.baidu.com/")
time.sleep(2)
t = browser.title
assert "baidu" in t
4、cmd运行用例:pytest --html=report.html --self-contained-html
5、运行结果: