如何计算在 selenium python 自动化中加载 URl 的时间

How to calculate time to load URl in selenium python automation

我有一个 selenium python 自动化测试,它计算响应时间并将其添加到 JSON 报告中。问题是我在打开 URL 之前和它停止测试之后计算响应时间的代码。我想计算加载 URL 页面所需的时间。

以下是我的代码

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)
            yield {"driver":driver, "url": pytestconfig.getoption("url")}
        
        @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('Asia/Kolkata').localize(datetime.fromtimestamp(call.start))
            stop_iso_dt = timezone('Asia/Kolkata').localize(datetime.fromtimestamp(call.stop))
            response_time = (stop_iso_dt - start_iso_dt).total_seconds()
            return {'response_time': str(response_time)}

我很困惑我应该如何计算 conftest.py 中的加载时间。

你需要做的是通过夹具将 response_time 变量的值传递给 pytest,以便它可以用于 pytest_json_modifyreport 钩子。

由于我想向单个测试用例添加多个计时器,我的解决方案是创建一个提供工厂的新夹具,就像这样(虽然我在工厂中使用了自定义对象,但我guessing/hoping 这样的字典就可以了):

@fixture(scope='session')
def timings(metadata):
    """
    used to track stopwatch timings taken during a session
    """
    stopwatches = []

    def factory(stopwatch_name, response_time):
        fsw = {'name': stopwatch_name, 'response_time': response_time}
        stopwatches.append(fsw)
        return fsw

    yield factory

    # add our stopwatches to the session's json_report metadata so that we can report it out
    metadata['stopwatches'] = stopwatches

你的测试class使用夹具,测试用例得到一个实例。类似于:

@mark.usefixtures('timings')
class TestFuzzyBear:
    ...
    response_time = int(now_time) - int(before_time)
    first_url_response_time = timings('first_resp_time', response_time)

现在您所有的响应时间都在 json_report 元数据的环境属性的字典列表中。来自 pytest_json_modifyreport 钩子:

@hookimpl(optionalhook=True)
def pytest_json_modifyreport(json_report):
    ...
    stopwatches = json_report['environment']['stopwatches']

现在您可以使用这些信息做您需要做的事了。

[请注意,我已在此处粘贴并操纵了信息,因此它可能无法像写的那样工作,但它应该为您提供遵循的方向。]