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



我有一个selenium python自动化测试,它运行良好,现在我想使用pytest生成Html和JSON报告,并在报告中进行屏幕截图。我是自动化和python的新手,所以我不太清楚它是如何做到的。

以下是我的代码

testrongcreenshot.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 testrongcreenshot.py——url"https://www.netflix.com/in/">

测试用例已通过。如何生成HTML和JSON报告?我试过这个

pytest-v-s--json report--json report indent=4--json报告文件=report/report.json--html=report/rereport.html testrongcreenshot.py

但得到此错误

错误:用法:pytest[options][file_or_dir][file_or_dir][…]pytest:error:无法识别的参数:--json-report--json-report indent=4--json-rereport-file=report/report.jsoninifile:无

您需要安装以下两个库:https://pypi.org/project/pytest-json-report/&https://pypi.org/project/pytest-html/

安装此库以生成HTML报告pip install pytest-html

在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

相关内容

  • 没有找到相关文章

最新更新