I have a selenium python automation test, which calculates Response time and adds it to JSON report. The problem is the code that I have calculates response time as before opening the URL and after it stops the test. I want to calculate the time it takes to load the URL page.
following is my code
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)}
I am getting confused how i should calculate load time in conftest.py.
CodePudding user response:
What you need to do is pass the value of the response_time
variable to pytest through a fixture so that it's available to
the pytest_json_modifyreport
hook.
Since I wanted to add multiple timers to an individual test case, my solution to this was to create a new fixture that provides a factory, something like this (though I used a custom object in the factory, I'm guessing/hoping a dictionary like this will work):
@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
your test class uses the fixture, and the test case gets an instance. something like:
@mark.usefixtures('timings')
class TestFuzzyBear:
...
response_time = int(now_time) - int(before_time)
first_url_response_time = timings('first_resp_time', response_time)
now all of your response times are in a list of dictionaries in the json_report metadata's environment attribute. from within the pytest_json_modifyreport hook:
@hookimpl(optionalhook=True)
def pytest_json_modifyreport(json_report):
...
stopwatches = json_report['environment']['stopwatches']
and now you can do what you need to do with the information.
[note that I have pasted and manipulated the info here, so it may not work as written, but it should give you a direction to follow.]