Best FluentLenium code snippet using org.fluentlenium.core.performance.PerformanceTimingEvent
Source:DefaultPerformanceTimingMetrics.java
...5import java.util.concurrent.TimeUnit;6import java.util.function.Function;7import static java.util.Objects.requireNonNull;8import static java.util.stream.Collectors.toMap;9import static org.fluentlenium.core.performance.PerformanceTimingEvent.NAVIGATION_START;10import static org.fluentlenium.core.performance.PerformanceTimingEvent.SECURE_CONNECTION_START;11/**12 * Default implementation of {@link PerformanceTimingMetrics} storing the metrics value as a {@link Map}.13 * <p>14 * It also provides an option to convert all values in the current object to an arbitrary {@link TimeUnit}.15 * For that you can call {@link #in(TimeUnit)} on the current object.16 * <p>17 * The values returned from this object are not epoch values as querying the corresponding Javascript attribute18 * directly would return, but it rather handles {@code navigationStart} as zero and returns time values passed19 * since that point in time.20 * <p>21 * Take into account that when there is a time difference like {@code 1675ms}, and it is converted to e.g. seconds,22 * the conversion will return {@code 1sec} for that instead of rounding it up to {@code 2sec}.23 * <p>24 * If a query for a certain metric returns 0 it means it happened at the same moment (at least in epoch)25 * than {@code navigationStart}.26 * <p>27 * A query for a certain metrics returns a negative value if the event has not been registered on the page,28 * or it is not feasible/valid for the given page/page load/redirect.29 *30 * @see DefaultPerformanceTiming31 */32public class DefaultPerformanceTimingMetrics implements PerformanceTimingMetrics<DefaultPerformanceTimingMetrics> {33 /**34 * The values are stored as {@link Object}s because not all values have type {@code long}.35 */36 private final Map<String, Object> timingMetrics = new HashMap<>();37 private final TimeUnit sourceTimeUnit;38 /**39 * Creates a new {@link DefaultPerformanceTimingMetrics} object from the argument epoch values.40 * <p>41 * It calculates and converts the epoch values into the differences/times passed since {@code navigationStart}.42 *43 * @param timingMetrics the timing metrics in epoch44 */45 public DefaultPerformanceTimingMetrics(Map<String, Object> timingMetrics) {46 this.timingMetrics.putAll(calculateTimesSinceNavigationStart(requireNonNull(timingMetrics)));47 this.sourceTimeUnit = TimeUnit.MILLISECONDS;48 }49 /**50 * Creates a new {@link DefaultPerformanceTimingMetrics} object from the argument metrics (in the given time unit).51 *52 * @param timingMetrics the metrics53 * @param timeUnit the time unit of the metrics54 */55 protected DefaultPerformanceTimingMetrics(Map<String, Object> timingMetrics, TimeUnit timeUnit) {56 this.timingMetrics.putAll(requireNonNull(timingMetrics));57 this.sourceTimeUnit = timeUnit;58 }59 /**60 * Returns a new metrics object having all metric values converted to the target {@link TimeUnit}.61 * <p>62 * Values that can have other than long values are converted if they are {@code long} values,63 * otherwise added to the new metrics object unchanged.64 *65 * @param targetTimeUnit the time unit to convert the metrics to66 * @return the converted metrics object67 */68 @Override69 public DefaultPerformanceTimingMetrics in(TimeUnit targetTimeUnit) {70 Map<String, Object> metrics = convertEntriesBy(timingMetrics,71 entryValue -> targetTimeUnit.convert((Long) entryValue, sourceTimeUnit));72 //Add metrics that can have values other than long73 metrics.putIfAbsent(SECURE_CONNECTION_START.getEvent(), timingMetrics.get(SECURE_CONNECTION_START.getEvent()));74 return new DefaultPerformanceTimingMetrics(metrics, targetTimeUnit);75 }76 public Map<String, Object> getAllMetrics() {77 return ImmutableMap.copyOf(timingMetrics);78 }79 public TimeUnit getSourceTimeUnit() {80 return sourceTimeUnit;81 }82 @Override83 public long getUnloadEventStart() {84 return getEvent(PerformanceTimingEvent.UNLOAD_EVENT_START);85 }86 @Override87 public long getUnloadEventEnd() {88 return getEvent(PerformanceTimingEvent.UNLOAD_EVENT_END);89 }90 @Override91 public long getRedirectStart() {92 return getEvent(PerformanceTimingEvent.REDIRECT_START);93 }94 @Override95 public long getRedirectEnd() {96 return getEvent(PerformanceTimingEvent.REDIRECT_END);97 }98 @Override99 public long getNavigationStart() {100 return getEvent(NAVIGATION_START);101 }102 @Override103 public long getFetchStart() {104 return getEvent(PerformanceTimingEvent.FETCH_START);105 }106 @Override107 public long getDomainLookupStart() {108 return getEvent(PerformanceTimingEvent.DOMAIN_LOOKUP_START);109 }110 @Override111 public long getDomainLookupEnd() {112 return getEvent(PerformanceTimingEvent.DOMAIN_LOOKUP_END);113 }114 @Override115 public long getConnectStart() {116 return getEvent(PerformanceTimingEvent.CONNECT_START);117 }118 @Override119 public long getConnectEnd() {120 return getEvent(PerformanceTimingEvent.CONNECT_END);121 }122 @Override123 public Object getSecureConnectionStart() {124 return timingMetrics.get(SECURE_CONNECTION_START.getEvent());125 }126 @Override127 public long getRequestStart() {128 return getEvent(PerformanceTimingEvent.REQUEST_START);129 }130 @Override131 public long getResponseStart() {132 return getEvent(PerformanceTimingEvent.RESPONSE_START);133 }134 @Override135 public long getResponseEnd() {136 return getEvent(PerformanceTimingEvent.RESPONSE_END);137 }138 @Override139 public long getDomLoading() {140 return getEvent(PerformanceTimingEvent.DOM_LOADING);141 }142 @Override143 public long getDomInteractive() {144 return getEvent(PerformanceTimingEvent.DOM_INTERACTIVE);145 }146 @Override147 public long getDomContentLoadedEventStart() {148 return getEvent(PerformanceTimingEvent.DOM_CONTENT_LOADED_EVENT_START);149 }150 @Override151 public long getDomContentLoadedEventEnd() {152 return getEvent(PerformanceTimingEvent.DOM_CONTENT_LOADED_EVENT_END);153 }154 @Override155 public long getDomComplete() {156 return getEvent(PerformanceTimingEvent.DOM_COMPLETE);157 }158 @Override159 public long getLoadEventStart() {160 return getEvent(PerformanceTimingEvent.LOAD_EVENT_START);161 }162 @Override163 public long getLoadEventEnd() {164 return getEvent(PerformanceTimingEvent.LOAD_EVENT_END);165 }166 private Map<String, Object> calculateTimesSinceNavigationStart(Map<String, Object> timingMetrics) {167 long navigationStartEpoch = (Long) timingMetrics.get(NAVIGATION_START.getEvent());168 Map<String, Object> metrics = convertEntriesBy(169 timingMetrics, entryValue -> ((Long) entryValue) - navigationStartEpoch);170 //Add metrics that can have values other than long171 metrics.putIfAbsent(SECURE_CONNECTION_START.getEvent(), timingMetrics.get(SECURE_CONNECTION_START.getEvent()));172 return metrics;173 }174 private Map<String, Object> convertEntriesBy(Map<String, Object> timingMetrics, Function<Object, Long> valueMapper) {175 return timingMetrics.entrySet()176 .stream()177 .filter(entry -> canBeCastToLong(entry.getValue()))178 .collect(toMap(179 Map.Entry::getKey,180 entry -> valueMapper.apply(entry.getValue())181 ));182 }183 private long getEvent(PerformanceTimingEvent event) {184 return (Long) timingMetrics.get(event.getEvent());185 }186 private boolean canBeCastToLong(Object value) {187 try {188 long converted = (Long) value;189 return true;190 } catch (ClassCastException cce) {191 return false;192 }193 }194}...
Source:PerformanceTimingTest.java
1package org.fluentlenium.examples.performance;2import org.assertj.core.api.SoftAssertions;3import org.fluentlenium.adapter.junit.FluentTest;4import org.fluentlenium.core.annotation.Page;5import org.fluentlenium.core.performance.PerformanceTimingEvent;6import org.fluentlenium.core.performance.PerformanceTimingMetrics;7import org.fluentlenium.examples.pages.DuckDuckMainPage;8import org.junit.Test;9import org.openqa.selenium.WebDriver;10import org.openqa.selenium.chrome.ChromeDriver;11import static java.util.concurrent.TimeUnit.MILLISECONDS;12import static java.util.concurrent.TimeUnit.SECONDS;13public class PerformanceTimingTest extends FluentTest {14 private static final String PERFORMANCE_TIMING_EVENTS_SCRIPT = "return window.performance.timing.%s;";15 @Page16 private DuckDuckMainPage duckDuckMainPage;17 @Override18 public WebDriver newWebDriver() {19 return new ChromeDriver();20 }21 @Test22 public void demonstrateRelativePerformanceTimingValues() {23 goTo(duckDuckMainPage);24 //Navigation start will always be 0 because all other metrics are calculated relatively to this25 long navigationStart = performanceTiming().navigationStart();26 //Retrieve a single metric value containing the time passed in milliseconds since the moment of navigationStart27 long loadEventStart = performanceTiming().loadEventStart();28 //Same as the previous query only that it is converted to seconds29 long loadEventStartInSecs = performanceTiming().loadEventStart(SECONDS);30 //Retrieve a single metric value by parameter containing the time passed since the moment of navigationStart31 long domComplete = performanceTiming().getEventValue(PerformanceTimingEvent.DOM_COMPLETE);32 //Same as the previous query only that it is converted to seconds33 long domCompleteInSecs = performanceTiming().getEventValue(PerformanceTimingEvent.DOM_COMPLETE, SECONDS);34 SoftAssertions softly = new SoftAssertions();35 softly.assertThat(navigationStart).isZero();36 softly.assertThat(loadEventStart).isEqualTo(timePassedSinceNavigationStart("loadEventStart"));37 softly.assertThat(loadEventStartInSecs).isEqualTo(convertToSeconds(loadEventStart));38 softly.assertThat(domComplete).isEqualTo(timePassedSinceNavigationStart("domComplete"));39 softly.assertThat(domCompleteInSecs).isEqualTo(convertToSeconds(domComplete));40 softly.assertAll();41 }42 @Test43 public void demonstrateBulkPerformanceTimingMetrics() {44 String searchPhrase = "searchPhrase";45 goTo(this.duckDuckMainPage)46 .typeSearchPhraseIn(searchPhrase)47 .submitSearchForm()...
Source:DefaultPerformanceTiming.java
1package org.fluentlenium.core.performance;2import org.openqa.selenium.JavascriptExecutor;3import org.openqa.selenium.WebDriver;4import static org.fluentlenium.core.performance.PerformanceTimingEvent.NAVIGATION_START;5import static org.fluentlenium.core.performance.PerformanceTimingEvent.SECURE_CONNECTION_START;6import static org.fluentlenium.utils.Preconditions.checkArgument;7/**8 * Default implementation of {@link PerformanceTiming}.9 * <p>10 * Via this implementation you can retrieve the W3C Performance Timing event values from the browser relative to11 * the value of the {@code navigationStart} attribute value, thus it won't return epoch values as querying the12 * corresponding Javascript attribute directly would, but rather handles {@code navigationStart} as zero and returns13 * time values passed since that point in time.14 * <p>15 * This implementation executes the query ({@code window.performance.timing.}) with a simple {@link JavascriptExecutor}16 * in a synchronous way.17 * <p>18 * If a query for a certain metric returns 0 it means it happened at the same moment (at least in epoch)19 * than {@code navigationStart}.20 * <p>21 * A query for a certain metrics returns a negative value if the event has not been registered on the page,22 * or it is not feasible/valid for the given page/page load/redirect.23 */24public class DefaultPerformanceTiming implements PerformanceTiming {25 private static final String PERFORMANCE_TIMING_SCRIPT = "return window.performance.timing;";26 private static final String PERFORMANCE_TIMING_EVENTS_SCRIPT = "return window.performance.timing.%s;";27 private final WebDriver driver;28 private final PerformanceTimingMetricsFactory metricsFactory = new PerformanceTimingMetricsFactory();29 public DefaultPerformanceTiming(WebDriver driver) {30 this.driver = driver;31 }32 @Override33 public long getEventValue(PerformanceTimingEvent event) {34 checkArgument(event, "The event should not be null.");35 return timePassedUntil(execute(scriptFor(event)));36 }37 @Override38 public Object secureConnectionStart() {39 Object secureConnectionStart = execute(scriptFor(SECURE_CONNECTION_START));40 if (secureConnectionStart instanceof Long) {41 secureConnectionStart = timePassedUntil(secureConnectionStart);42 }43 return secureConnectionStart;44 }45 @Override46 public PerformanceTimingMetrics getMetrics() {47 return metricsFactory.createFor(execute(PERFORMANCE_TIMING_SCRIPT));48 }49 private long timePassedUntil(Object eventTime) {50 return ((Long) eventTime) - getNavigationStart();51 }52 private Object execute(String command) {53 return ((JavascriptExecutor) driver).executeScript(command);54 }55 private String scriptFor(PerformanceTimingEvent event) {56 return String.format(PERFORMANCE_TIMING_EVENTS_SCRIPT, event);57 }58 /**59 * Returns the navigation start epoch value.60 * <p>61 * Using this additional method is necessary to avoid running into an infinite loop when calling62 * {@link #getEventValue(PerformanceTimingEvent)}63 */64 private long getNavigationStart() {65 return (Long) execute(scriptFor(NAVIGATION_START));66 }67}...
PerformanceTimingEvent
Using AI Code Generation
1import org.fluentlenium.adapter.FluentTest;2import org.fluentlenium.core.performance.PerformanceTimingEvent;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.openqa.selenium.WebDriver;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.chrome.ChromeOptions;8import org.openqa.selenium.firefox.FirefoxDriver;9import org.openqa.selenium.firefox.FirefoxOptions;10import org.openqa.selenium.firefox.FirefoxProfile;11import org.openqa.selenium.remote.DesiredCapabilities;12import org.openqa.selenium.support.events.EventFiringWebDriver;13import org.openqa.selenium.support.events.WebDriverEventListener;14import org.springframework.beans.factory.annotation.Autowired;15import org.springframework.boot.test.context.SpringBootTest;16import org.springframework.test.context.junit4.SpringRunner;17import java.util.HashMap;18import java.util.Map;19import java.util.concurrent.TimeUnit;20@RunWith(SpringRunner.class)21@SpringBootTest(classes = {Application.class})22public class PerformanceTest extends FluentTest {23 private WebDriver webDriver;24 public void test() {25 await().atMost(10, TimeUnit.SECONDS).untilPage().isLoaded();26 Map<String, PerformanceTimingEvent> performanceTimingEvents = getPerformanceTimingEvents();27 System.out.println(performanceTimingEvents);28 }29 public WebDriver getDefaultDriver() {30 String browser = "firefox";31 String driverPath = "C:\\Users\\User\\Downloads\\geckodriver-v0.23.0-win64\\geckodriver.exe";32 System.setProperty("webdriver.gecko.driver", driverPath);33 FirefoxOptions options = new FirefoxOptions();34 options.addArguments("--headless");35 options.addArguments("--disable-gpu");36 options.addArguments("--window-size=1920,1200");37 FirefoxProfile profile = new FirefoxProfile();38 profile.setPreference("browser.cache.disk.enable", false);39 profile.setPreference("browser.cache.memory.enable", false);40 profile.setPreference("browser.cache.offline.enable", false);41 profile.setPreference("network.http.use-cache", false);42 profile.setPreference("network.dns.disablePrefetch", true);43 profile.setPreference("network.http.speculative-parallel-limit", 0);
PerformanceTimingEvent
Using AI Code Generation
1package io.github.bonigarcia.seljup;2import static org.assertj.core.api.Assertions.assertThat;3import org.fluentlenium.core.performance.PerformanceTimingEvent;4import org.junit.jupiter.api.Test;5import org.junit.jupiter.api.extension.ExtendWith;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.WebElement;8import org.openqa.selenium.chrome.ChromeDriver;9import org.openqa.selenium.chrome.ChromeOptions;10import org.openqa.selenium.support.FindBy;11import org.openqa.selenium.support.How;12import io.github.bonigarcia.seljup.SeleniumJupiter;13@ExtendWith(SeleniumJupiter.class)14class PerformanceTimingEventJupiterTest {15 @FindBy(how = How.TAG_NAME, using = "h1")16 WebElement h1;17 void testPerformanceTimingEvent(ChromeDriver driver) {18 .getPerformanceTimingEvent();19 assertThat(performanceTimingEvent.getConnectEnd()).isGreaterThan(0);20 }21}22package io.github.bonigarcia.seljup;23import static org.assertj.core.api.Assertions.assertThat;24import org.fluentlenium.core.performance.PerformanceTimingEvent;25import org.junit.jupiter.api.Test;26import org.junit.jupiter.api.extension.ExtendWith;27import org.openqa.selenium.WebDriver;28import org.openqa.selenium.chrome.ChromeDriver;29import org.openqa.selenium.chrome.ChromeOptions;30import org.openqa.selenium.support.FindBy;31import org.openqa.selenium.support.How;32import io.github.bonigarcia.seljup.SeleniumJupiter;33@ExtendWith(SeleniumJupiter.class)34class PerformanceTimingEventJupiterTest {35 @FindBy(how = How.TAG_NAME, using = "h1")36 WebElement h1;37 void testPerformanceTimingEvent(ChromeDriver driver) {38 .getPerformanceTimingEvent();39 assertThat(performanceTimingEvent.getConnectEnd()).isGreaterThan(0);40 }41}42package io.github.bonigarcia.seljup;43import static org.assertj.core.api.Assertions.assertThat;44import org.fl
PerformanceTimingEvent
Using AI Code Generation
1package com.freshworks.performance;2import org.fluentlenium.adapter.FluentTest;3import org.fluentlenium.configuration.ConfigurationProperties.DriverLifecycle;4import org.fluentlenium.configuration.FluentConfiguration;5import org.fluentlenium.core.performance.PerformanceTimingEvent;6import org.openqa.selenium.WebDriver;7import org.openqa.selenium.chrome.ChromeDriver;8import org.openqa.selenium.chrome.ChromeOptions;9import org.openqa.selenium.support.events.EventFiringWebDriver;10@FluentConfiguration(webDriver = "chrome", driverLifecycle = DriverLifecycle.PER_CLASS)11public class TestPerformance extends FluentTest {12 public WebDriver newWebDriver() {13 ChromeOptions options = new ChromeOptions();14 options.addArguments("--ignore-certificate-errors");15 options.addArguments("--disable-extensions");16 options.addArguments("--disable-popup-blocking");17 options.addArguments("--disable-translate");18 options.addArguments("--disable-notifications");19 options.addArguments("--disable-infobars");20 options.addArguments("--disable-web-security");21 options.addArguments("--allow-running-insecure-content");22 options.addArguments("--allow-insecure-localhost");23 options.addArguments("--start-maximized");24 options.addArguments("--no-sandbox");25 options.addArguments("--disable-dev-shm-usage");26 options.addArguments("--headless");27 options.addArguments("--disable-gpu");28 options.addArguments("--disable-software-rasterizer");29 options.addArguments("--disable-dev-shm-usage");30 EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(new ChromeDriver(options));31 eventFiringWebDriver.register(new PerformanceTimingEvent());32 return eventFiringWebDriver;33 }34 public String getBaseUrl() {35 }36 public static void main(String[] args) {
PerformanceTimingEvent
Using AI Code Generation
1package com.mycompany.app;2import org.fluentlenium.adapter.testng.FluentTestNg;3import org.fluentlenium.core.performance.PerformanceTimingEvent;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.chrome.ChromeDriver;6import org.testng.annotations.Test;7public class AppTest extends FluentTestNg {8 public void test() {9 WebDriver driver = new ChromeDriver();10 PerformanceTimingEvent performanceTimingEvent = new PerformanceTimingEvent(driver);11 System.out.println("The page loaded in " + performanceTimingEvent.getLoadTime() + " milliseconds");12 }13}14package com.mycompany.app;15import org.fluentlenium.adapter.testng.FluentTestNg;16import org.fluentlenium.core.performance.PerformanceTimingEvent;17import org.openqa.selenium.WebDriver;18import org.openqa.selenium.chrome.ChromeDriver;19import org.testng.annotations.Test;20public class AppTest extends FluentTestNg {21 public void test() {22 WebDriver driver = new ChromeDriver();23 PerformanceTimingEvent performanceTimingEvent = new PerformanceTimingEvent(driver);24 System.out.println("The page loaded in " + performanceTimingEvent.getLoadTime() + " milliseconds");25 }26}27package com.mycompany.app;28import org.fluentlenium.adapter.testng.FluentTestNg;29import org.fluentlenium.core.performance.PerformanceTimingEvent;30import org.openqa.selenium.WebDriver;31import org.openqa.selenium.chrome.ChromeDriver;32import org.testng.annotations.Test;33public class AppTest extends FluentTestNg {34 public void test() {35 WebDriver driver = new ChromeDriver();36 PerformanceTimingEvent performanceTimingEvent = new PerformanceTimingEvent(driver);37 System.out.println("The page loaded in " + performanceTimingEvent.getLoadTime() + " milliseconds");38 }39}
PerformanceTimingEvent
Using AI Code Generation
1public class PerformanceTimingEventTest extends FluentTest {2 public void testPerformanceTimingEvent() {3 PerformanceTimingEvent performanceTimingEvent = new PerformanceTimingEvent(getDriver());4 System.out.println("Redirect Count: " + performanceTimingEvent.getRedirectCount());5 System.out.println("Time to First Byte: " + performanceTimingEvent.getTimeToFirstByte());6 System.out.println("Time to Last Byte: " + performanceTimingEvent.getTimeToLastByte());7 System.out.println("Time to Load Event: " + performanceTimingEvent.getTimeToLoadEvent());8 System.out.println("Time to DOM Content Loaded Event: " + performanceTimingEvent.getTimeToDomContentLoadedEvent());9 System.out.println("Time to DOM Interactive: " + performanceTimingEvent.getTimeToDomInteractive());10 System.out.println("Time to DOM Complete: " + performanceTimingEvent.getTimeToDomComplete());11 System.out.println("Time to Response Start: " + performanceTimingEvent.getTimeToResponseStart());12 System.out.println("Time to Response End: " + performanceTimingEvent.getTimeToResponseEnd());13 System.out.println("Time to Request Start: " + performanceTimingEvent.getTimeToRequestStart());14 }15}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!