如何在 selenium python 报告中添加响应时间

How can i add response time in selenium python report

我有一个 selenium-python 自动化测试,我正在使用 Pytest 生成 HTML/JSON 报告。我想在 HTML/JSON 报告中添加响应时间,这可能吗?

以下是我的代码

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:
            before_time = datetime.now().strftime('%H%M%S%f')  #  Timestamp
            driver.get(url)
            now_time = datetime.now().strftime('%H%M%S%f')  #  Timestamp
            response_time = int(now_time) - int(before_time)
        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 -v -s --json-report --json-report-indent=4 --json-report-file=report/report.json --html=report/report.html test_screenshot.py

您可以对 JSON 报告使用一些挂钩来执行此操作。你的 conftest.py 文件中的一些内容:

@hookimpl(optionalhook=True)
def pytest_json_runtest_metadata(call):
    """
    fixture from the pytest-json-report plugin that will add your info
    """
    if call.when != 'call':
       return {}

    # collect the start and finish times in ISO format for the US/Eastern timezone
    start_iso_dt = timezone('US/Eastern').localize(datetime.fromtimestamp(call.start)).isoformat()
    stop_iso_dt = timezone('US/Eastern').localize(datetime.fromtimestamp(call.stop)).isoformat()
    return {'start': start_iso_dt, 'stop': stop_iso_dt

这将出现在您的 json_report 元数据中。 (我的代码需要 US/Eastern 时区,你显然可以相应地调整,或者只在这个函数中做差异计算和 return {'response_time': mydiff}