Selenium tests for custom portlets - selenium

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();
}
}

Related

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

Getting org.openqa.selenium.ElementNotInteractableException error

Here is my program below on running it I'm getting an error org.openqa.selenium.ElementNotInteractableException.
In this program, I am trying to test a login page with 4 different sets of data using DataProvider annotation so my script is running
Chrome gets initiated
website gets open
click and enter username and password
And the above three steps happen for each set of data provided.
But still on the completion of the whole thing, I'm getting this error. Please help!
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import basePage.*;
//Login to edureka website
public class myPorfileupdate
{
WebDriver driver1;
#Test (dataProvider ="edulogin")
public void myLogin(String username, String password) throws IOException, InterruptedException
{ AppTest a =new AppTest();
driver1 = a.initializeDriver();
driver1.findElement(By.xpath("//span[#data-button-name='Login']")).click();
driver1.findElement(By.xpath("//input[#type='email']")).clear();
driver1.findElement(By.xpath("//input[#type='email']")).sendKeys(username);
driver1.findElement(By.xpath("//input[#type='password']")).sendKeys(password);
driver1.findElement(By.xpath("//*[#id=\"new_sign_up_optim\"]/div/div/div[2]/div[3]/form/button")).click();
Thread.sleep(1000);
driver1.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try{
WebElement d= driver1.findElement(By.linkText("Trending Courses"));
System.out.println(d);
}
catch (Exception Ex){
// Get text displayes on login page
System.out.println("Userid/password is incorrect");
}
}
#DataProvider(name="edulogin")
public Object[][] testData() {
Object[][] data = new Object[4][2];
data[0][0] = "ambika97.singh#gmail.com";
data[0][1] = "Omsairam#1234";
//2nd row
data[1][0] = "abc";
data[1][1] = "Omsairam#1234";
//3rd row
data[2][0] = "ambika97.singh#gmail.com";
data[2][1] = "xyz";
//4th row
data[3][0] = "abc";
data[3][1] = "xyz";
return data;
}
}```
**First two lines of my console are**
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation.

Selenium grid is not working on latest selenium version

After upgrading to latest selenium, Selenium grid is giving an error for RegistrationRequest(). I am getting req.setRole(), req.setConfiguration(), etc. not found. look like RegistrationRequest() class got change in selenium new version but not sure how to use that class and modify my existing code. Any idea how to resolve this?
Here is my code,
package selenium;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openqa.grid.common.GridRole;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.internal.utils.configuration.GridHubConfiguration;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SeleniumGrid {
private static Hub hub;
private static URL remoteURL;
private static RegistrationRequest req = new RegistrationRequest();
private Map<String, Object> nodeConfig = new HashMap<String, Object>();
private static SelfRegisteringRemote remote = new SelfRegisteringRemote(req);
SeleniumBase sb = new SeleniumBase();
public void setup() throws Exception {
hub = getHub("localhost", 4458);
remoteURL = new URL("http://" + hub.getUrl() + ":" + 5555);
// req = setRegRequest();
req.setRole(GridRole.NODE);
req.addDesiredCapability(sb.getCapability());
List<DesiredCapabilities> dc = req.getCapabilities();
for (DesiredCapabilities c : dc) {
System.out.println("Using capabilities: " + c.toString());
}
// nodeConfig.put(req.AUTO_REGISTER, true);
nodeConfig.put(req.HUB_HOST, hub.getHost());
nodeConfig.put(req.HUB_PORT, hub.getPort());
nodeConfig.put(req.PORT, 5555);
// nodeConfig.put(RegistrationRequest.PROXY_CLASS, "org.openqa.grid.selenium.proxy.DefaultRemoteProxy");
nodeConfig.put(req.MAX_SESSION, 1);
// nodeConfig.put(RegistrationRequest.CLEAN_UP_CYCLE, 2000);
nodeConfig.put(req.REMOTE_HOST, remoteURL);
nodeConfig.put(req.MAX_INSTANCES, 1);
nodeConfig.put(req.BROWSER, "firefox");
nodeConfig.put(req.UNREGISTER_IF_STILL_DOWN_AFTER, 20000);
nodeConfig.put(req.HOST, hub.getHost());
System.out.println("Hub Port: " + hub.getHost() + hub.getPort());
System.out.println(req.HOST);
System.out.println(req.HUB_HOST);
System.out.println(req.HUB_PORT);
req.setConfiguration(nodeConfig);
remote.startRemoteServer();
remote.startRegistrationProcess();
}
public RegistrationRequest setRegRequest() {
RegistrationRequest request = new RegistrationRequest();
request.setRole(GridRole.NODE);
request.addDesiredCapability(sb.getCapability());
List<DesiredCapabilities> dc = request.getCapabilities();
for (DesiredCapabilities c : dc) {
System.out.println("Using capabilities: " + c.toString());
}
return request;
}
public Hub getHub(String host, int port) {
GridHubConfiguration config = new GridHubConfiguration();
config.setHost(host);
config.setPort(port);
Hub someHub = new Hub(config);
return someHub;
}
public void tearDown() throws Exception {
remote.stopRemoteServer();
hub.stop();
}
}
Here's a full fledged working example that starts a hub, starts a node, wires up the node to the hub, runs a test against the locally spun off hub, and then goes on to shut down the node and then the hub.
import org.openqa.grid.common.GridRole;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.internal.utils.configuration.GridHubConfiguration;
import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;
import org.openqa.grid.selenium.proxy.DefaultRemoteProxy;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.server.SeleniumServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class SeleniumGrid {
private Hub hub;
private SelfRegisteringRemote remote;
#BeforeClass
public void setup() throws Exception {
hub = getHub("localhost", 4458);
hub.start();
remote = new SelfRegisteringRemote(getNodeConfiguration());
remote.addBrowser(DesiredCapabilities.firefox(), 2);
SeleniumServer server = new SeleniumServer(remote.getConfiguration());
remote.setRemoteServer(server);
remote.startRemoteServer();
remote.startRegistrationProcess();
}
#Test
public void test() throws MalformedURLException {
URL url = new URL(hub.getUrl() + "/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url, DesiredCapabilities.firefox());
try {
driver.get("http://www.google.com");
System.err.println("Title " + driver.getTitle());
} finally {
driver.quit();
}
}
#AfterClass
public void tearDown() throws Exception {
remote.stopRemoteServer();
hub.stop();
}
private GridNodeConfiguration getNodeConfiguration() {
GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
nodeConfiguration.register = true;
nodeConfiguration.hub = String.format("http://%s:%d", hub.getConfiguration().host, hub.getConfiguration().port);
nodeConfiguration.port = 5555;
nodeConfiguration.proxy = DefaultRemoteProxy.class.getCanonicalName();
nodeConfiguration.maxSession = 1;
nodeConfiguration.cleanUpCycle = 2000;
nodeConfiguration.unregisterIfStillDownAfter = 20000;
nodeConfiguration.role = GridRole.NODE.toString();
nodeConfiguration.port = 5555;
nodeConfiguration.getHubHost();
nodeConfiguration.hub = String.format("http://%s:%d", hub.getConfiguration().host, hub.getConfiguration().port);
return nodeConfiguration;
}
private Hub getHub(String host, int port) {
GridHubConfiguration config = new GridHubConfiguration();
config.host = host;
config.port = port;
return new Hub(config);
}
}

for loop to send assert result to excel using jxl

i am trying to write selenium script which writes pass/fail based on assert.
the problem i am facing here is the assert results are not getting inserted into excel properly. There is some issue with the for loop which i have written. please help me in fixing it.
thanks in advance.
This is the code which i have written
package DDT;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class TestPass extends ExeclUtility
{
WebDriver driver;
Map<String,Object[]> Exp;
#BeforeClass
public void openBrowser()//opening of the browser is done only 1s before executing the test data
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\DELL\\Desktop\\shree\\qsp_java_selenium\\selenium\\selenium_web_driver\\chrome_driver\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("file:///C:/Users/DELL/Desktop/USN%20and%20Sem.html");
}
#Test(dataProvider="TestData")
public void datasend(String username,String phnum,String Exp) throws InterruptedException, RowsExceededException, WriteException
{
WebElement name=driver.findElement(By.id("field1"));
name.clear();
name.sendKeys(username);
WebElement pwd=driver.findElement(By.id("field2"));
pwd.clear();
pwd.sendKeys(phnum);
WebElement but=driver.findElement(By.id("field4"));
but.click();
Alert alert=driver.switchTo().alert();
SoftAssert assertion=new SoftAssert();
for(int i=0;i<6;i++){
try
{
assertion.assertEquals(Exp, alert.getText());// compares the expected result in excel v/s the actual o/p
Testcase="pass";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}
catch(Exception e)
{
Testcase="fail";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}}
assertion.assertEquals(Exp, alert.getText());
alert.accept();
assertion.assertAll();
Thread.sleep(3000);
}
#AfterClass
public void closeBrowser()//browser is closed 1s after all the test data are executed
{
driver.quit();
}
#DataProvider(name = "TestData")
public Object[][] ExcelData() throws BiffException, IOException
{
String Filepath="D:\\selenium_pgms\\intern_practice\\Book1.xls";
FileInputStream Excelfile=new FileInputStream(Filepath);
Workbook Exbook=Workbook.getWorkbook(Excelfile);
Sheet Exsheet=Exbook.getSheet("Sheet1");
int Rows=Exsheet.getRows();
int Columns=Exsheet.getColumns();
String Testdata[][]= new String[Rows-1][Columns];
int count=0;
for(int i=1;i<Rows;i++)
{
for(int j=0;j<Columns;j++)
{
Cell Excell = Exsheet.getCell(j,i);
Testdata[count][j]=Excell.getContents();
}
count++;
}
Excelfile.close();
return Testdata;
}
}

How to solve this error in selenium?

i write the code to test the sign up form and i am getting this error for browser.
ERROR:-
org.openqa.selenium.firefox.NotConnectedException: Unable to
connect to host 127.0.0.1 on port 7055 after 45000 ms.
gcr.java class:
package SeleniumWebdriver;
//import java.util.Date;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class gcr {
public static void main(String args[]) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.gcrit.com/build3/");
driver.findElement(By.linkText("create an account")).click();
driver.findElement(By.xpath(".//*[#id='bodyContent']/form/div/div[2]/table/tbody/tr[1]/td[2]/input[1]")).click();
driver.findElement(By.name("firstname")).sendKeys("piyush");
driver.findElement(By.name("lastname")).sendKeys("kansal");
driver.findElement(By.name("dob")).sendKeys("10/01/1993");
/*Date date=new Date();
int x=date. getSeconds();*/
//String Email= "piyush#gmail.com";
driver.findElement(By.name("email_address")).sendKeys("piyush#gmail.com");
driver.findElement(By.name("street_address")).sendKeys("innotical");
driver.findElement(By.name("postcode")).sendKeys("251001");
driver.findElement(By.name("city")).sendKeys("noida");
driver.findElement(By.name("state")).sendKeys("Up");
Select Dropdown = new Select(driver.findElement(By.name("country")));
Dropdown.selectByVisibleText("India");
driver.findElement(By.name("telephone")).sendKeys("9958097200");
driver.findElement(By.name("password")).sendKeys("9958097200");
driver.findElement(By.name("confirmation")).sendKeys("9958097200");
driver.findElement(By.id("tdb4")).click();
String Message = driver.findElement(By.xpath(".//*[#id='bodyContent']/h1")).getText();
if (Message.equals("Your Account Has Been Created!")) {
System.out.println("Account has created-passed");
} else {
System.out.println("Account not created-failed");
}
//driver.close();
}
}