Selenium with CDP (Chrome Developer Protocol) - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Monday, 13 January 2020

Selenium with CDP (Chrome Developer Protocol)

Add Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.selenium</groupId>
    <artifactId>selenium4-CDP-samples</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.0.0-alpha-2</version>
        </dependency>

       <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.9</version>
</dependency>

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.7.1</version>
        </dependency>
    </dependencies>
</project>


Sample Class


import static java.time.Duration.ofSeconds;
import static org.openqa.selenium.devtools.network.Network.*;
import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable;
import static java.util.Optional.of;
import static java.util.Optional.empty;
import static org.testng.Assert.*;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
import org.openqa.selenium.devtools.network.model.*;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.*;

public class DevToolsTest {

private DevTools devTools;
private ChromeDriver driver;
private WebDriverWait webDriverWait;

private By whereAmI = By.tagName("button");
private By latitude = By.id("lat-value");
private By longitude = By.id("long-value");

@BeforeMethod
public void before(){
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
devTools = driver.getDevTools();
devTools.createSession();
webDriverWait = new WebDriverWait(driver, ofSeconds(3));
}

@Test
public void setGeoLocationTest() {
driver.get("https://the-internet.herokuapp.com/geolocation");
webDriverWait.until(elementToBeClickable(whereAmI)).click();
String lat = webDriverWait.until(elementToBeClickable(latitude)).getText();
String lng = driver.findElement(longitude).getText();

Map<String, Object> params = new HashMap<>();
params.put("latitude", 27.1751);
params.put("longitude", 78.0421);
params.put("accuracy", 1);

driver.executeCdpCommand("Emulation.setGeolocationOverride", params);
webDriverWait.until(elementToBeClickable(whereAmI)).click();

assertNotEquals(webDriverWait.until(elementToBeClickable(latitude)).getText(), lat);
assertNotEquals(driver.findElement(longitude).getText(), lng);
}


}

Explanation

setGeolocationOverride event under the Emulation domain overrides GeoLocation position with user-provided latitude, longitude, and accuracy. Loading a web application post this will emulate user-provided Geo-Location in it. 



Basically we are using Chrome Developer tools in following way




User Agent Change


 @Test
    public void userAgentOverride(){

        String fakeAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36";

        driver.navigate().to("https://www.whoishostingthis.com/tools/user-agent/");

        Assert.assertNotEquals(driver.findElement(By.cssSelector(".info-box.user-agent")).getText(),fakeAgent);

        devTools.send(Network.setUserAgentOverride(fakeAgent,
                Optional.empty(), Optional.empty()));

        driver.navigate().to("https://www.whoishostingthis.com/tools/user-agent/");

        Assert.assertEquals(driver.findElement(By.cssSelector(".info-box.user-agent")).getText(),fakeAgent);
    }
    
    @Test
    public void webToMobileView(){

        String fakeAgent = "Mozilla/5.0 (Linux; Android 7.0; SM-G930V Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.125 Mobile Safari/537.36";

        devTools.send(Network.setUserAgentOverride(fakeAgent,
                Optional.empty(), Optional.empty()));

        driver.navigate().to("https://www.amazon.com");

    }

Access Insecure Sites

 @Test
    public void loadInsecureWebsite() {
        devTools.send(Security.enable());
        devTools.send(Security.setIgnoreCertificateErrors(true));
        driver.get("https://expired.badssl.com/");
    }


Emulate Network Speed
@Test
    public  void emulateNetworkConditionTest(){

        devTools.send(Network.enable(Optional.of(1000000), Optional.empty(), Optional.empty()));
        devTools.send(
                emulateNetworkConditions(false,100,200000,100000, Optional.of(ConnectionType.cellular2g))); // here false means internet is active, if you set it to true //means internet won't be accessed

        long startTime = System.currentTimeMillis();
        driver.navigate().to("https://www.swtestacademy.com");

        long endTime = System.currentTimeMillis();

        System.out.println("Load time is "+ (endTime-startTime));
    }


Validate Cookies


@Test
    public void validateCookiesTest() {
        devTools.send(enable(of(100000000), of(0), of(0)));

        driver.navigate().to("https://ads.google.com/intl/en_IN/home/");
        Cookies allCookies = devTools.send(getAllCookies());
        assertNotNull(allCookies.asSeleniumCookies().stream().filter(cookie -> "_ga".equalsIgnoreCase(cookie.getName())).findAny().orElse(null));

        devTools.send(clearBrowserCookies());
        assertTrue(devTools.send(getAllCookies()).asSeleniumCookies().size() == 0);
    }


Network Speed Throttle


@Test
    public void testing2() throws IOException {
        CommandExecutor executor = driver.getCommandExecutor();

//Set the conditions
        Map map = new HashMap();
        map.put("offline", false);
        map.put("latency", 5);
        map.put("download_throughput", 100000);
        map.put("upload_throughput", 70000);

        Response response = executor.execute(new Command(driver.getSessionId(), "setNetworkConditions", ImmutableMap.of("network_conditions", ImmutableMap.copyOf(map))));

        driver.get("http://facebook.com");
    }

ValidateNetworkResponseTest

 @Test
    public void validateNetworkResponseTest() {
        final RequestId[] requestIds = new RequestId[1];
        devTools.send(Network.enable(of(100000000), empty(), empty()));

        devTools.addListener(responseReceived(), responseReceived -> {
            assertNotNull(responseReceived.getResponse());
            requestIds[0] = responseReceived.getRequestId();
        });

        driver.navigate().to("http://dummy.restapiexample.com/api/v1/employee/1");
        ResponseBody responseBody = devTools.send(getResponseBody(requestIds[0]));
        assertTrue(responseBody.getBody().contains("id"));
    }

No comments:

Post a Comment