• pytest启动浏览器,失败用例截图


    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、运行结果:

  • 相关阅读:
    73. Set Matrix Zeroes (Array)
    79. Word Search (Array; DFS,Back-Track)
    59. Spiral Matrix II (Array)
    PAT 1082. Read Number in Chinese
    PAT 1067 Sort with Swap(0,*)
    LeetCode Min Stack
    LeetCode Find Minimum In Rotated Sorted Array
    PAT 1071. Speech Patterns
    PAT 1022. Digital Library
    PAT 1041. Be Unique
  • 原文地址:https://www.cnblogs.com/guo2733/p/10525755.html
Copyright © 2020-2023  润新知