log in in all browsers with selenium - java

There is problem I cant resolve for 2 days. I need to login in many browsers in many machines on same sites. Its time-consuming task so I decide to do it with Selenium. I think problem is that while running test selenium does not save cookies. I find that its real to save cookies in file and then open them in next selenium tests but i need all browsers are logged in for manual testing. Here is my code
package automationFramework;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class FirstTestCase {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
File profileDirectory = new File(
"C:\\Users\\User\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\n8a2y7sp.default");//path to firefox profile
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
driver = new FirefoxDriver(profile);
baseUrl = "http://facebook.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testVk() throws Exception {
driver.get(baseUrl);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(""); // login
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(""); //password
driver.findElement(By.id("loginbutton")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

What exactly do you mean? Do you try to achieve multiple browsers that access the same site simultaneously? If so, you will need to set up more than one driver instance.
If you'd like to achieve it sequentially, just use a loop where you open the driver and get the URL, do your thing, then kill the driver instance, repeat.

Related

How to solve the error of data provider if only one browser is taking the complete input data?

I'm trying to achieve parallel execution through data provider, but unable to do it. can someone help me with this.
The error is two browsers are opening but the data is going to only one browser.
Here, is my program code:
package PracticePrograms;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataProviderSample1{
public WebDriver driver;
#BeforeMethod
public void setUp() throws InterruptedException {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(6));
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
}
#Test(dataProvider = "inputData")
public void testLogin(String UserName, String Password ) throws InterruptedException {
driver.findElement(By.name("username")).sendKeys(UserName);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.xpath("//button[#type='submit']")).click();
}
#DataProvider(name = "inputData", parallel = true)
public static Object[][] loginData() {
Object[][] data = new Object[2][2];
data[0][0] = "Admin";
data[0][1] = "admin123";
data[1][0] = "admin";
data[1][1] = "admin123";
return data;
}
#AfterMethod
public void tear_down() throws InterruptedException {
driver.quit();
}
}
I appreciate u r help on this.
Despite your method logic runs in parallel all your threads still use the same instance of your test class. Hence they share the same instance of your driver field.
This leads to the case when the setUp() executed "after" overwrites the value set by setUp that has been executed "before"..
So to overcome this you need to introduce ThreadLocal variable. Instead of public WebDriver driver; you would have ThreadLocal<WebDriver> driver = new ThreadLocal<>();
Now instead of driver = new FirefoxDriver(); you would have driver.set( new FirefoxDriver());
After you have set that driver to ThreadLocal, wherever you obtain its value you have to do driver.get(). For example:
driver.get().manage().deleteAllCookies();
driver.get().manage().timeouts().implicitlyWait(Duration.ofSeconds(6));
driver.get().get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

How to create two object drivers of type WebDriver and use the same Classes and Methods

I have a question related to improving my Selenium Java code. I am really beginner in Java and Selenium either.
I have written a code which I got an example from the internet and adapted to my reality. The coding works fine as described below:
package test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import page.Login;
public class LoginTest extends BaseTest {
Login login = new Login(driver);
#Test
public void loginWithSuccess() {
sendLoginData("my_user#something.com", "my_password");
login.clickLogin();
assertEquals("View Posted Jobs", login.checkLoginSuccess());
}
private void sendLoginData(String user, String password) {
login.sendUser(user);
login.sendPassword(password);
}
}
The above program is testing and performing a loginWithSucess in the WebSite
package config;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebDriverFactory {
public static WebDriver createFirefoxDriver() {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
In this above example I am instancing a new object WebDriver called driver.
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import config.WebDriverFactory;
public class BaseTest {
protected static WebDriver driver;
private static boolean setUpIsDone = false;
#BeforeClass
public static void setUp() {
if (setUpIsDone) {
return;
}
// Creating first browser for student login
driver = WebDriverFactory.createFirefoxDriver();
driver.get("http://test-tuitiondesk.rhcloud.com/auth");
driver.manage().window().maximize();
setUpIsDone = true;
}
The above example is where I open my WebSite to authenticate
package page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Login {
private WebDriver driver;
public Login(WebDriver driver) {
this.driver = driver;
}
public void sendUser(String user) {
driver.findElement(By.xpath("//*[#id='email']")).sendKeys(user);
}
public void sendPassword(String password) {
driver.findElement(By.id("password")).sendKeys(password);
}
public void clickLogin() {
driver.findElement(By.xpath("//*[#id='login-box']/div/div[1]/form/fieldset/div[2]/button")).click();
}
public String checkLoginSuccess() {
return driver.findElement(By.xpath("//a[contains(text(),'View Posted Jobs')]")).getText();
}
}
The above example I have methods which will send a user id and password to the webpage.
So far is everything working fine. The program is performing the following steps:
1 - Open the firefox
2 - Open the webpage
3 - Send the correct user_id, password and click in login button
4 - Check if login was performed with success.
My question now is that I need open a new firefox driver and login with different user_id and this new user_id will interact some actions with the first user_id, so I will need two browsers opened to perform actions with both users in the same time.
I would like to write this implementation the best way than simply write every method again with the second driver. What I thought for the first time was create a new WebDriver called driver2 and create again all methods referring to driver2, but I think I should reuse my methods and classes in a clever way.
Does Anybody have any idea how to implement this second browser in my code?
Thank you
André
You can do this simply by entering this code:
driver2 = WebDriverFactory.createFirefoxDriver();
driver2.get("http://test-tuitiondesk.rhcloud.com/auth");
//call log in function for driver2
//code to interact driver2 with driver1

Created a java test script in eclipse, how do i run it in a headless linux CentOS VM?

The question above covers what I need I have created successful test scripts using eclipse on windows, but now i need to be able to run it in a linux vm through SSH and I have tried many things online and not had any success I know some changes may need to be done to the code also but I havnt managed to do that successfully either so please see the code below.
I have copied the src(test scripts) and libs(jars) files from the eclipse workspace to the linux vm and understood that to execute the selenium standalone server i use java -jar but that is about it. If you could walk me through the steps that need to be taken to run a test on firefox in the vm.
I have java and firefox installed.
Test Script
package test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class CorrectTestBackLink {
public BrowserList.DriverToUse used_driver = BrowserList.DriverToUse.IEXPLORER;
private BrowserSelector selectedDriver = new BrowserSelector(used_driver);
private WebDriver driver = selectedDriver.getDriver();
private StringBuffer verificationErrors = new StringBuffer();
private String baseUrl;
private static String resulterValue = "110";
private String valuecheck1;
#Before
public void setUp() throws Exception {
baseUrl = "http://url/";
//Set the column number and datatype of column by using either StringColumnNumber"Letter" or IntColumnNumber"Letter.
// Add aditional columns to database class where necessary.
}
public void calcResultChecker(){
driver.findElement(By.id("resulter")).getAttribute("value");
String valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
if (valuecheck1.equals(resulterValue)){
System.out.println("The Resulting value ("+valuecheck1+") is CORRRECT!");
}else{
System.err.println("The Resulting value is ("+valuecheck1+") is INCORRRECT!");
}
}
#Test
public void test2() throws Exception {
//calc page
driver.get(baseUrl + "calc.php");
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Entering 10 into 'firstnumber' field!");
driver.findElement(By.name("firstnumber")).sendKeys("10");
Thread.sleep(200);
driver.findElement(By.name("secondnumber")).sendKeys("11");
System.out.println("Entering 11 into 'secondnumber' field!");
Thread.sleep(200);
System.out.println("Clicking calculate button!");
driver.findElement(By.name("Calculate")).click();
Thread.sleep(200);
//calc results page
assertEquals(baseUrl + "calcresult.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
assertEquals(valuecheck1, resulterValue);
Thread.sleep(200);
System.out.println("Clicking back Link!");
driver.findElement(By.linkText("Back")).click();
Thread.sleep(200);
//calc page check
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Test Complete");
Thread.sleep(200);
driver.quit();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
Browser Selector
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class BrowserSelector {
private WebDriver driver;
public BrowserSelector(BrowserList.DriverToUse used_driver){
switch (used_driver){
case CHROME:{
System.setProperty("webdriver.chrome.driver", "C:/path/chromedriver.exe");
driver = new ChromeDriver();
break;
}
case FIREFOX:{
driver = new FirefoxDriver();
break;
}
case IEXPLORER:{
System.setProperty("webdriver.ie.driver","C:/path/IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capabilities);
break;
}
}
}
public WebDriver getDriver(){
return driver;
}
}
People usually use either PhantomJS or "Headless Chrome" to run in a headless environment. Also, some people run regular browsers from a XVFB framebuffer. Here is a blog article that I found that explains how to install XVFB.
xvfb-run --server-args='-screen 0, 1024x768x16' google-chrome
-start-maximized http://example.com > /dev/null &
Using XVFB and VNC, you could probably login remotely and watch your tests run on the headless box but I haven't tried this. You would have to experiment with it.

Maintain and re-use existing webdriver browser instance - java

Basically every time I run my java code from eclipse, webdriver launches a new ie browser and executes my tests successfully for the most part. However, I have a lot of tests to run, and it's a pain that webdriver starts up a new browser session every time. I need a way to re-use a previously opened browser; so webdriver would open ie the first time, then the second time, i run my eclipse program, I want it to simply pick up the previous browser instance and continue to run my tests on that same instance. That way, I am NOT starting up a new browser session every time I run my program.
Say you have 100 tests to run in eclipse, you hit that run button and they all run, then at about the 87th test you get an error. You then go back to eclipse, fix that error, but then you have to re-run all 100 test again from scratch.
It would be nice to fix the error on that 87th test and then resume the execution from that 87th test as opposed to re-executing all tests from scratch, i.e from test 0 all the way to 100.
Hopefully, I am clear enough to get some help from you guys, thanks btw.
Here's my attempt below at trying to maintain and re-use a webdriver internet explorer browser instance:
public class demo extends RemoteWebDriver {
public static WebDriver driver;
public Selenium selenium;
public WebDriverWait wait;
public String propertyFile;
String getSessionId;
public demo() { // constructor
DesiredCapabilities ieCapabilities = DesiredCapabilities
.internetExplorer();
ieCapabilities
.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
driver = new InternetExplorerDriver(ieCapabilities);
this.saveSessionIdToSomeStorage(getSessionId);
this.startSession(ieCapabilities);
driver.manage().window().maximize();
}
#Override
protected void startSession(Capabilities desiredCapabilities) {
String sid = getPreviousSessionIdFromSomeStorage();
if (sid != null) {
setSessionId(sid);
try {
getCurrentUrl();
} catch (WebDriverException e) {
// session is not valid
sid = null;
}
}
if (sid == null) {
super.startSession(desiredCapabilities);
saveSessionIdToSomeStorage(getSessionId().toString());
}
}
private void saveSessionIdToSomeStorage(String session) {
session=((RemoteWebDriver) driver).getSessionId().toString();
}
private String getPreviousSessionIdFromSomeStorage() {
return getSessionId;
}
}
My hope here was that by overriding the startSession() method from remoteWebdriver, it would somehow check that I already had an instance of webdriver browser opened in i.e and it would instead use that instance as opposed to re-creating a new instance everytime I hit that "run" button in eclipse.
I can also see that because I am creating a "new driver instance" from my constructor, since constructor always execute first, it creates that new driver instance automatically, so I might need to alter that somehow, but don't know how.
I am a newbie on both stackoverflow and with selenium webdriver and hope someone here can help.
Thanks!
To answer your question:
No. You can't use a browser that is currently running on your computer. You can use the same browser for the different tests, however, as long as it is on the same execution.
However, it sounds like your real problem is running 100 tests over and over again. I would recommend using a testing framework (like TestNG or JUnit). With these, you can specify which tests you want to run (TestNG will generate an XML file of all of the tests that fail, so when you run it, it will only execute the failed tests).
Actually you can re-use the same session again..
In node client you can use following code to attach to existing selenium session
var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
// The 'capabilities' object as returned by sessionCapabilities
if (err) { /* that session doesn't exist */ }
else {
browser.elementByCss("button.groovy-button", function(err, el) {
...
});
}
});
...
browser.detach();
To get selenium session id,
driver.getSessionId();
Note:
This is available in Node Client only..
To do the same thing in JAVA or C#, you have to override execute method of selenium to capture the sessionId and save it in local file and read it again to attach with existing selenium session
I have tried the below steps to use the same browser instance and it worked for me:
If you are having generic or Class 1 in different package the below code snippet will work -
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
// Class 1 :
public class Generics {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "url";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
// Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
#Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
driver.findElement(By.cssSelector("")).sendKeys("");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
driver.findElement(By.xpath("")).sendKeys("");
}
}
If your Generics class is in the same package you just need to make below change in your code:
public class Generics {
public Generics(){}
WebDriver driver; }
Just remove the protected word from Webdriver code line. Rest code of class 1 remain as it is.
Regards,
Mohit Baluja
I have tried it by extension of classes(Java Inheritance) and creating an xml file. I hope below examples will help:
Class 1 :
package zgenerics;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
public class SetUp {
public Generics(){}
protected WebDriver driver;
#BeforeTest
public void maxmen() throws InterruptedException, IOException{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
String appURL= "URL";
driver.get(appURL);
String expectedTitle = "Title";
String actualTitle= driver.getTitle();
if(actualTitle.equals(expectedTitle)){
System.out.println("Verification passed");
}
else {
System.out.println("Verification failed");
} }
Class 2 :
package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import zgenerics.SetUp
public class Conditions extends SetUp {
#Test
public void visible() throws InterruptedException{
Thread.sleep(5000);
boolean signINbutton=driver.findElement(By.xpath("xpath")).isEnabled();
System.out.println(signINbutton);
boolean SIGNTEXT=driver.findElement(By.xpath("xpath")).isDisplayed();
System.out.println(SIGNTEXT);
if (signINbutton==true && SIGNTEXT==true){
System.out.println("Text and button is present");
}
else{
System.out.println("Nothing is visible");
}
}
}
Class 3:
package automationScripts;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Test;
public class Footer extends Conditions {
#Test
public void footerNew () throws InterruptedException{
WebElement aboutUs = driver.findElement(By.cssSelector("CssSelector"));
aboutUs.click();
WebElement cancel = driver.findElement(By.xpath("xpath"));
cancel.click();
Thread.sleep(1000);
WebElement TermsNCond = driver.findElement(By.xpath("xpath"));
TermsNCond.click();
}
}
Now Create an xml file with below code for example and run the testng.xml as testng suite:
copy and paste below code and edit it accordingly.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="classes" thread-count="3">
<test name="PackTest">
<classes>
<class name="automationScripts.Footer"/>
</classes>
This will run above three classes. That means one browser and different tests.
We can set the execution sequence by setting the class names in alphabetical order as i have done in above classes.

Selenium click action directs to page other than by Selenium IDE

I am trying to click on a web element using Selenium WebDriver(2.21.0).
When I try driving through the Selenium IDE it works properly but when I try the same set of actions using the Java implementation of Firefox driver- it leads to the wrong page.
While the code is running and I manually scroll to the desired element, it works.
I am making sure that the web element is visible and enabled using
By by = By.xpath("(//a[contains(#href, 'javascript:void(0);')])[26]"); //**Edit:** this is how i
//am getting the locator
WebElement element = driver.findElement(by);
return (element.isEnabled() || element.isDisplayed()) ? element : null;
which returns some element but not the one I am expecting.
This looks strange to me as Selenium webdriver mostly scrolls to an element(if not visible on the screen) by itself and does the required interaction.
I have tried some answers like one, two with no success.
Thanks in advance!
EDIT: here is the IDE's exported code(java/JUnit4/webdriver)
package com.example.tests;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Bandar {
private WebDriver driver;
private String baseUrl;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://e.weibo.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testBandar() throws Exception {
driver.get(baseUrl + "/nescafechina");
driver.findElement(By.xpath("(//a[contains(#href, 'javascript:void(0);')])[26]")).click();
driver.findElement(By.xpath("(//a[contains(#href, 'javascript:void(0);')])[12]")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
Ishank,
What I have done is gone through and created a test that shows the different kind of asserts that you can use in your testing. They do look a little different from what you are looking at, I feel your main problem is WebElement element = driver.findElement(by); because you are not giving it an actual element. The (by); section is looking for a string that can be found on the page. Acceptable strings would be; id("gbfqb"); or xpath("(//a[contains(#href, 'javascript:void(0);')])[26]"); or even name("find-button");.
/**
* Test the main Google page.
* #throws InterruptedException
*
*/
#Test
public void signUp() throws InterruptedException {
String testId = "TestStack01";
entered(testId);
webDriver.get("www.google.com");
webDriver.findElement(By.id("gbqfq")).clear();
webDriver.findElement(By.id("gbqfq")).sendKeys("Test");
assertEquals("", webDriver.findElement(By.id("gbqfb")).getText());
WebElement whatyourlookingfor = webDriver.findElement(By.id("gbqfb"));
assertTrue(selenium.isElementPresent("gbqfb"));
assertTrue(whatyourlookingfor.isEnabled());
assertTrue(whatyourlookingfor.isDisplayed());
assertFalse(whatyourlookingfor.isSelected());
webDriver.findElement(By.id("gbqfb")).click();
leaving(testId);
}
I hope that this has helped in getting which element is being returned.
Curtis Miller

Categories

Resources