使用pytest为selenium python自动化测试生成html和json报告

yqkkidmi  于 2023-05-30  发布在  Python
关注(0)|答案(2)|浏览(159)

我有一个selenium python自动化测试,它工作得很好,现在我想生成Html和JSON报告,并在报告中使用pytest截图。我是自动化和Python的新手,所以我不太清楚它是如何完成的。
下面是我的代码
test_screenshot.py

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytest_html
from selenium.common.exceptions import InvalidSessionIdException

def test_Openurl(setup):
    driver = setup["driver"]
    url = setup["url"]
    try:
        driver.get(url)
    except Exception as e:
        print(e.message)

    assert driver.current_url == URL
    driver.save_screenshot("ss.png")
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    driver.save_screenshot("ss1.png")
    driver.close()

conftest.py

import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

def pytest_addoption(parser):
    parser.addoption("--url", action="store", default="https://google.com/")

@pytest.fixture()
def setup(pytestconfig):
    s = Service("C:/Users/Yash/Downloads/chromedriver_win32/chromedriver.exe") 
    driver = webdriver.Chrome(service=s)
    driver.maximize_window()
    yield {"driver":driver, "url": pytestconfig.getoption("url")}

我运行了这个
pytest test_screenshot.py --url“https://www.netflix.com/in/“
测试用例通过。如何生成HTML和JSON报告?我试过这个
pytest -v -s --json-report --json-report-indent=4 --json-report-file=report/report.json --html=report/report.html test_screenshot.py
但是得到了这个错误
错误:用法:pytest [options] [file_or_dir] [file_or_dir] [...] pytest:错误:无法识别的参数:--json-report --json-report-indent=4 --json-report-file=report/report.json初始化文件:无

yduiuuwa

yduiuuwa2#

安装此库以生成HTML报告pip install pytest-html
在www.example.com中添加以下两个函数conftest.py

@pytest.mark.hookwrapper
def pytest_runtest_makereport(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"
            _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_name
                extra.append(pytest_html.extras.html(html))
        report.extra = extra

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

当测试用例出现任何故障时,该功能将自动进行屏幕截图。
执行以下命令以生成报告

pytest -v -s --html=report.html

相关问题