Problem with devTools.send(Emulation.setDeviceMetricsOverride selenium 4 - selenium

Selenium 4:
I have an error on this line of code :
devTools.send(Emulation.setDeviceMetricsOverride(600, 1000, 50, true, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()));
the error:
The method
setDeviceMetricsOverride(Integer, Integer, Number, Boolean, Optional, Optional, Optional, Optional, Optional, Optional, Optional, Optional, Optional)
in the type Emulation is not applicable for the arguments
(int, int, int, boolean, Optional, Optional, Optional, Optional, Optional, Optional, Optional, Optional, Optional)

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v85.emulation.Emulation;
public class CDPFeatures {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","D:\\chromedriver_win32\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
Map deviceMetrics = new HashMap()
{{
put("width", 600);
put("height", 1000);
put("mobile", true);
put("deviceScaleFactor", 50);
}};
driver.executeCdpCommand("Emulation.setDeviceMetricsOverride", deviceMetrics);
driver.get("https://google.com");
}
}

Even I faced this issue but through some hit and trial method I was able to solve it. Hopefully it might help you. posting my code below:
import java.net.MalformedURLException;
import java.util.Optional;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v101.emulation.Emulation;
import org.openqa.selenium.devtools.v101.emulation.model.DisplayFeature;
import org.openqa.selenium.devtools.v101.emulation.model.ScreenOrientation;
import org.openqa.selenium.devtools.v101.page.model.Viewport;
public class EmulationCDP {
public static void main(String[] args) throws MalformedURLException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","G:\\Driver\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Emulation.setDeviceMetricsOverride(700, 1000, 50, true, Optional.<Number> empty(),
Optional.<Integer> empty(), Optional.<Integer> empty(), Optional.<Integer> empty(),
Optional.<Integer> empty(), Optional.<Boolean> empty(), Optional.<ScreenOrientation> empty(),
Optional.<Viewport> empty(), Optional.<DisplayFeature> empty()));
driver.get("https://www.google.com/");
}
}

Related

i need change lenguage of microsoft edge for selenium automation --lang=es

i need change the language to --lang=es in microsoft-edge selenium java.
Because can't the page see in english and need in spanish
Try this code, its working:
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.edge.options import Options
options = Options()
options.add_argument("--lang=es")
options.add_experimental_option('excludeSwitches', ['enable-logging'])
prefs = {"translate_whitelists": {'en':'es'},
"translate":{"enabled":"true"}}
options.add_experimental_option("prefs", prefs)
driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install()), options=options)
driver.maximize_window()
driver.get("https://www.microsoft.com")
Based on AbiSaran's answer (which is in Python), I modified it into a Java one.
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class EdgeTest {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.edge.driver", "C:\\path\\to\\msedgedriver.exe");
EdgeOptions options = new EdgeOptions();
options.addArguments("--lang=es");
EdgeDriver driver = new EdgeDriver(options);
try {
driver.get("https://bing.com");
WebElement element = driver.findElement(By.id("sb_form_q"));
element.sendKeys("WebDriver");
element.submit();
Thread.sleep(5000);
} finally {
driver.quit();
}
}
}

Junit 5 tests are not running in parallel

I have created a simple program to intialte crome and one SYSO statement. I want to run the 2 #Test in parallel. But it is executing alwasy is seq. What could be teh reason for it to not recognise the parallel execution?
Here is the code:
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Proxy.ProxyType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
#Execution(ExecutionMode.CONCURRENT)
public class Parallel {
static String driverPath = "C:/BestX/workspace/chromedriver_win32/chromedriver.exe";
static String downloadFilepath = "C:\\BestX";
#Execution(ExecutionMode.CONCURRENT)
#Test
void test1() throws Exception {
createDriver();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+" => test1"); //.currentThread.getName() -just to display current running thread name
}
#Execution(ExecutionMode.CONCURRENT)
#Test
void test2() throws Exception {
createDriver();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+" => test1"); //.currentThread.getName() -just to display current running thread name
}
public void createDriver() {
DesiredCapabilities dcaps = new DesiredCapabilities();
dcaps.setCapability("takesScreenshot", true);
System.setProperty("webdriver.chrome.driver", driverPath);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments(new String[] { "--no-sandbox" });
chromeOptions.addArguments(new String[] { "--max_old_space_size=4096" });
dcaps.setCapability("goog:chromeOptions", chromeOptions);
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("download.default_directory", downloadFilepath);
chromeOptions.setAcceptInsecureCerts(true);
chromeOptions.setExperimentalOption("prefs", chromePrefs);
WebDriver driver = new ChromeDriver(chromeOptions);
driver.manage().window().setSize(new Dimension(1920, 1200));
}
}
'''
and here is the "junit-platform.properties" under resource folder
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
It is workign now. Was a silly mistake in folder structure. The junit-platform.properties file was under tests->resources instead of test->resources folder

Groovy, Selenium, Cucumber, adding ChromeOptions arguments

I wanted to create a BaseTest.groovy where i implement the Webdriver with headless mode.
package api
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
class BaseTest{
ChromeOptions chromeOptions = new ChromeOptions()
chromeOptions.addArguments(["--headless", "--no-sandbox"])
static WebDriver driver = new ChromeDriver(chromeOptions)
}
I have a LoginSteps.groovy stepdefinitions file
package stepDefinitions
import api.Helper.helper
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import static cucumber.api.groovy.EN.*
Given(~/^I am on the xyz login page$/) { ->
helper.setPage("https://xyzTestpage.com/")
}
When(~/^I sign in as "([^"]*)"$/) { String arg1 ->
helper.signIn("username","password")
}
Then(~/^I load the homepage$/) { ->
helper.setPreset()
}
And i have a helper.groovy file where i implement the methods
package api.Helper
import api.BaseTest
import api.Xpaths.LoginPageXpaths
import api.Tools.tools
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
class helper extends BaseTest {
static void setPage(String url){
driver.get(url)
}
static void signIn(String username, String password){
WebElement uname = driver.findElement(By.xpath(LoginPageXpaths.userNameField()))
uname.sendKeys(username)
WebElement pwd = driver.findElement(By.xpath(LoginPageXpaths.passWordField()))
pwd.sendKeys(password)
WebElement loginButton = driver.findElement(By.xpath(LoginPageXpaths.loginButton()))
loginButton.click()
}
static void setPreset(){
WebElement multiCountry = driver.findElement(By.xpath(LoginPageXpaths.multiCountryButton()))
multiCountry.click()
WebElement openButton = driver.findElement(By.xpath(LoginPageXpaths.openButton()))
openButton.click()
String inputWindow = driver.getWindowHandle()
for(String loggedInWindow : driver.getWindowHandles()){
driver.switchTo().window(loggedInWindow)
}
WebElement lineItem = driver.findElement(By.xpath(LoginPageXpaths.calculateButtonXpath()))
tools.waitForElementToBeClickable(driver,lineItem,25)
driver.quit()
}
}
So my problem is, i don't know where should i set the headless mode, because i got error, when i run this.
Can you please try adding arguments separately as below and run it
class BaseTest{
ChromeOptions chromeOptions = new ChromeOptions()
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--no-sandbox");
static WebDriver driver = new ChromeDriver(chromeOptions)
}

Trying to run an eclipse JAVA program in Sauce Labs. But getting an issue with constructor and remote webdriver.

Written below code to run an eclipse program in Sauce Labs. Workflow is showing an issue "The constructor Remote WebDriver(String, DesiredCapabilities) is undefined".
Still I tried to run the program then below issue came.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor RemoteWebDriver(URL, DesiredCapabilities) is undefined
The constructor URL(String) is undefined at sauceprog.main(sauceprog.java:40)
CODE:
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.gargoylesoftware.htmlunit.javascript.host.URL;
public class sauceprog
{
public static void main(String[] args) throws InterruptedException, MalformedURLException
{
String browser = "safari-saucelabs";
String URL = "https://rpautomation4:27763475-7193-4984-8074-a4fe2f9982f7#ondemand.saucelabs.com:443/wd/hub";
DesiredCapabilities caps = null;
switch(browser.toLowerCase())
{
case "internetexplorer-win-saucelabs":
caps = DesiredCapabilities.internetExplorer();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "11.103");
caps.setCapability("recordVideo", "false");
caps.setCapability("screenResolution", "1024x768");
break;
case "chrome-win-saucelabs":
caps = DesiredCapabilities.chrome();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "69.0");
caps.setCapability("recordVideo", "false");
break;
case "firefox-win-saucelabs":
caps = DesiredCapabilities.firefox();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "62.0");
caps.setCapability("recordVideo", "false");
default:
System.out.println("you passed incorrect values. Please check next time");
}
RemoteWebDriver driver = new RemoteWebDriver(URL,caps);
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("selenium");
Thread.sleep(2000);
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
driver.quit();
}
}
You are using an incorrect import statement. Ideally, your program should use import java.net.URL; instead of import com.gargoylesoftware.htmlunit.javascript.host.URL;
I have posted the complete updated code snippet below:
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
public class sauceprog
{
public static void main(String[] args) throws InterruptedException, MalformedURLException
{
String browser = "safari-saucelabs";
String URL = "https://<sauce_user>:<key>#ondemand.saucelabs.com:443/wd/hub";
DesiredCapabilities caps = null;
switch(browser.toLowerCase())
{
case "internetexplorer-win-saucelabs":
caps = DesiredCapabilities.internetExplorer();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "11.103");
caps.setCapability("recordVideo", "false");
caps.setCapability("screenResolution", "1024x768");
break;
case "chrome-win-saucelabs":
caps = DesiredCapabilities.chrome();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "69.0");
caps.setCapability("recordVideo", "false");
break;
case "firefox-win-saucelabs":
caps = DesiredCapabilities.firefox();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "62.0");
caps.setCapability("recordVideo", "false");
default:
System.out.println("you passed incorrect values. Please check next time");
}
RemoteWebDriver driver = new RemoteWebDriver(new URL(URL),caps);
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("selenium");
Thread.sleep(2000);
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
driver.quit();
}
}
Also, I would suggest you update your sauce username and key if not already done. Since you posted the username and key publicly, anyone can run their tests on your account using the same.

Selenium tests for custom portlets

Can anyone provide me a link/document with information on how to write and test custom liferay portlets with Selenium.
I am using Liferay 6.1EE
Thanks
Same as with other tests, assuming you want to run as JUnit test
package org.ood.selenium.test;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.IncorrectnessListener;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptErrorListener;
import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.regex.Pattern;
public class MyTest extends SeleneseTestBase {
WebDriver driver =null;
#Before
public void setUp() throws Exception {
DesiredCapabilities dc = DesiredCapabilities.firefox();
// dc.setCapability(FirefoxDriver.BINARY, new
//File("C:/Program Files (x86)/Mozilla Firefox/firefox.exe").getAbsolutePath());
dc.setJavascriptEnabled(true);
// driver= new HtmlUnitDriver(true);//Not properly working
driver = new FirefoxDriver(dc);
String baseUrl = "http://localhost:8080/web/guest/home";
selenium = new WebDriverBackedSelenium(driver, baseUrl);
}
/* #Test
public void homePage() throws Exception {
final WebClient webClient = new WebClient();
//HTMLUNit throws lots of errors
webClient.setJavaScriptEnabled(true);
webClient.setJavaScriptErrorListener(new JavaScriptErrorListener() {
public void timeoutError(HtmlPage htmlPage, long allowedTime,
long executionTime) {
// TODO Auto-generated method stub
}
public void scriptException(HtmlPage htmlPage,
ScriptException scriptException) {
System.out.println(scriptException.getMessage());
}
public void malformedScriptURL(HtmlPage htmlPage, String url,
MalformedURLException malformedURLException) {
System.out.println(url);
}
public void loadScriptError(HtmlPage htmlPage, URL scriptUrl,
Exception exception) {
// TODO Auto-generated method stub
}
});
//webClient.setThrowExceptionOnFailingStatusCode(false);
webClient.setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://localhost:8080/web/guest/home");
webClient.getCache().clear();
page.getElementById("sign-in").click();
page.getElementById("_58_login").type("test#liferay.com");
page.getElementById("_58_password").type("test#liferay.com");
final HtmlButton submit = (HtmlButton)page.getByXPath("//input").get(0);
submit.click();
//assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
System.out.println("Title= " +page.getTitleText());
final String pageAsXml = page.asXml();
// assertTrue(pageAsXml.contains("<body class=\"composite\">"));
System.out.println("pageAsXml=" +pageAsXml);
final String pageAsText = page.asText();
//assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
System.out.println("pageAsText="+pageAsText);
webClient.closeAllWindows();
}*/
#Test //Using Graphical GUI
public void testMytest() throws Exception {
//driver.get("http://localhost:8080/web/guest/home");
selenium.open("/");
//selenium.click("id=sign-in");
driver.findElement(By.id("sign-in")).click();
driver.findElement(By.name("_58_login")).clear();
driver.findElement(By.name("_58_login")).sendKeys("test#liferay.com");
driver.findElement(By.name("_58_password")).sendKeys("123");
//driver.findElement(By.name("_58_login")).sendKeys("test#nsn.com");
//driver.findElement(By.name("_58_password")).sendKeys("test");
driver.findElement(By.className("aui-button-input-submit")).submit();
//selenium.setSpeed("1000");
//selenium.waitForPageToLoad("5000");
//Select a nested div( the NodeTree)
driver.findElement(By.xpath("//div[contains(#class,'aui-tree-node-content')" +
" and (contains(.,'TreeNodeX'))]//div[contains(#class,'aui-tree-hitarea')]"))
.click();
//selenium.captureScreenshot("d:/_del/sel_screen.png");//this throws an error
//workaround
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("d:/_del/sel_screen.png"));
System.out.println("Bodytex=[" +selenium.getBodyText() +"]End Body Text");
String[] titles= selenium.getAllWindowTitles();
System.out.println("Titles Start-");
for (int i = 0; i < titles.length; i++) {
System.out.println(titles[i]);
}
System.out.println("Titles End");
verifyEquals(true, selenium.getBodyText().contains("Site View"));
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}