Friday 8 July 2016

How to extract digits from a String in Java

Many times, we have to verify the numbers from a given string.

Below Java code will help get the digits from the string.

public String extractDigits(String str){
       return str.replaceAll("[^0-9]","");
    }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Monday 4 July 2016

How to auto download a file in Selenium

When you try to download a file from a website in Selenium, window dialog may appear. But Selenium can not handle such native windows. We may use AUTOIT scripts for handling native windows. But that's only possible on Windows OS.

Better solution is to change the driver settings so that file is automatically downloaded to system bypassing the File save dialog.

If you are using Firefox, you can use below code to start the driver with below profile.

FirefoxProfile myprofile= new FirefoxProfile();
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", "c:\\mydownloadlocation\\xyz");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
WebDriver driver = new FirefoxDriver(myprofile);

If you are using Chrome driver, you can use below code to skip the download window.

        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.prompt_for_download", false);
        prefs.put("download.default_directory", "path-to-download-directory");
        options.setExperimentalOption("prefs", prefs);
        WebDriver driver = new ChromeDriver(options);

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to find total number of rows and columns in a table in Selenium

We can use below XPATH expressions to find count of rows and columns in a table.

  1. //table//th  - Find total number of columns in a table. Note that this will only work if all columns are marked using th tag
  2. //table//tr - Find total number of rows in a table.
  3. //table//tr[1]//td - Find total number of TD tags inside a given table row. 

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to verify if text is present on a web page in Selenium

We can use below xpath selector to verify if the text is present on a web page in Selenium.

//*[contains(text(),'text data')]

Note that above xpath will identify text wrapped in any element like div, span etc.
Only condition is that text should be inside one specific tag.


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to clear data from a text box using JavaScriptExecutor in Selenium

Sometimes, clear method does not work. It does not clear the data from text box. In those situations, we can use Java Script to clear the data.
Below line clears the data from edit box.

((JavascriptExecutor) driver).executeScript("arguments[0].value ='';", element);

Note that second parameter is the name of Web Element (Text box).

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday 2 July 2016

Selenium IDE Add-On for Firefox

Selenium IDE is a Firefox Add-On that can be used to record and playback the Selenium scripts. We can also export the scripts to various programming languages like C#, Java, Ruby and Python.

You can download the Add-On XPI file from the link - https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/

Next you can install the Add-On in Firefox. Once installation is successful you will notice the Selenium IDE menu in Tools as shown in below image.

Selenium IDE menu

Below image shows the Selenium IDE GUI. We can record the script by clicking on red circle icon.


Below image shows that we can export the recorded script to Ruby, Python, Java, C# etc.




What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Limitations of Selenium WebDriver

Even though Selenium is the most popular automation testing tool, it has got below limitations.

  1. We can only test web applications. We can not test desktop based applications. 
  2. We can test mobile applications but we need to use the Appium for that.
  3. We can not automate the CAPTCHA 
  4. We can not automate the complex control like Flash, Silver light Components, Applet controls, native window dialogs etc
  5. We often encounter issues like Selenium not launching latest browsers due to incompatibility issues. In such scenarios, we have to downgrade the browser in order to automate it.


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Selecting drop down value using JavaScript in Selenium

In some web applications, when we select a value from the drop down, new controls or elements appear or disappear on the webpage. In short, change event is fired. But sometimes, change event does not get fired after selecting the value from drop down using selenium.

In such scenarios, we can use JavascriptExecutor to fire the change event on drop down element as shown in below code.

protected void fireChangeEvent(WebElement element){
        ((JavascriptExecutor) driver).executeScript(" var evt = 
document.createEvent('HTMLEvents'); evt.initEvent('change',true,true); 
arguments[0].dispatchEvent(evt);",element);
    }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Enter data in text box using JavaScript in Selenium

Sometimes, sendKeys method does not work on text boxes. In such scenarios, you can use JavascriptExecutor to set the value in edit box. Below method takes 2 arguments. It sets the value passed in second argument in text box identified as first parameter.

protected void setValueByJavaScript(WebElement element,String value) {
        ((JavascriptExecutor) driver).executeScript("arguments[0].value ='"+
value+"';", element);
    }


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Setting up Selenium and Maven project

In Maven project, you can add below dependency and start writing the tests in JUnit or TestNG framework.

<dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
</dependency>

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Wednesday 22 June 2016

Listeners in Selenium

When Selenium performs any of the operations like click, navigate etc, events are fired.
We can write custom code when these events are fired.

We will need to create a class that implements the methods to be called after event is fired.

Below class implements the WebDriverEventListener.

package chrometest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverEventListener;

/**
 * Created by Sagar on 22-06-2016.
 */
public class ListenerImplementation  implements WebDriverEventListener {
    @Override
    public void beforeNavigateTo(String s, WebDriver webDriver) {
        System.out.println("Before navigating to " + s);
    }

    @Override
    public void afterNavigateTo(String s, WebDriver webDriver) {

    }

    @Override
    public void beforeNavigateBack(WebDriver webDriver) {

    }

    @Override
    public void afterNavigateBack(WebDriver webDriver) {

    }

    @Override
    public void beforeNavigateForward(WebDriver webDriver) {

    }

    @Override
    public void afterNavigateForward(WebDriver webDriver) {

    }

    @Override
    public void beforeFindBy(By by, WebElement webElement, WebDriver webDriver) {
        System.out.println("Before find by");
    }

    @Override
    public void afterFindBy(By by, WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void beforeClickOn(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void afterClickOn(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void beforeChangeValueOf(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void afterChangeValueOf(WebElement webElement, WebDriver webDriver) {

    }

    @Override
    public void beforeScript(String s, WebDriver webDriver) {

    }

    @Override
    public void afterScript(String s, WebDriver webDriver) {

    }

    @Override
    public void onException(Throwable throwable, WebDriver webDriver) {
        System.out.println("Exception");
    }
}

Next we need to register the instance of this class with driver as shown in highlighted code below. beforeNavigateTo method is called when execute below code. In fact, all the methods for corresponding events are called automatically.

package chrometest;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import java.util.concurrent.TimeUnit;
/** * Created by Sagar on 17-02-2016. */
public class LaunchEventFiringChrome {
    static WebDriver driver = null;

    @Test    public void launchChromeTest() throws Exception{
        System.setProperty("webdriver.chrome.driver",
 "C:\\Users\\Sagar\\Videos\\chromedriver_win32\\chromedriver.exe");
        driver = new ChromeDriver();
        EventFiringWebDriver eventFiringWebDriverDriver  =
 new EventFiringWebDriver(driver);
        ListenerImplementation listenerImplementation = 
new ListenerImplementation();
        eventFiringWebDriverDriver.register(listenerImplementation);

        eventFiringWebDriverDriver.manage().timeouts().implicitlyWait
(10, TimeUnit.SECONDS);
        eventFiringWebDriverDriver.manage().window().maximize();
        String domain = "http://www.softpost.org";
        eventFiringWebDriverDriver.get(domain);
        System.out.println(eventFiringWebDriverDriver.getTitle());
        eventFiringWebDriverDriver.close();
        eventFiringWebDriverDriver.quit();

    }
}

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

RemoteWebdriver in Selenium

You will need to use RemoteWebdriver if you want to connect to selenium server. We pass the capabilities to remote server which passes the commands to appropriate machine where the driver with given capabilities is available.

RemoteWebdriver is mainly useful when you are using Selenium Grid or running tests in Cloud.
One of the constructors of RemoteWebdriver takes 2 parameters - url of selenium server and capabilities

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Tuesday 21 June 2016

Headless execution using HTML Unit in Selenium

Headless mean without any user interface. HtmlUnit allows you to execute tests in Headless manner. You will not see browser opening the web pages or performing any operation like clicking buttons or entering data. All these operations happen in memory. This kind of execution is useful if you want to test the functionality. Also headless execution is much faster than normal execution. Downside is that you will not be able to test how the web page actually looks like on specific browser.

You will have to add below dependency in your project.

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

By default, JavaScript is not enabled. You need to use below line to execute JavaScript.
((HtmlUnitDriver)driver).setJavascriptEnabled(true);

Here is the complete code to execute selenium tests using HtmlUnitDriver.

package htmlunit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

/**
 * Created by Sagar on 21-06-2016.
 */
public class testHtmlUnit {
    public static void main(String[] args) {
        WebDriver driver = new HtmlUnitDriver();
        ((HtmlUnitDriver) driver).setJavascriptEnabled(true);
        driver.get("http://www.softpost.org");
        driver.close();
        driver.quit();
    }
}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Resizing and moving browser window in Selenium

To resize the browser window, we can use below line. Dimension constructor takes 2 parameters - Height and width of the window.

driver.manage().window().setSize(new Dimension(100,100));

To set the browser window position, you can use below line of code. Point constructor takes 2 parameters - X and Y co-ordinates of the browser window. Below statement will move the window down by 200 pixel.

driver.manage().window().setPosition(new Point(0,200));

To maximize window, you can use below line of code.

driver.manage().window().maximize();

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Switching to default content in Selenium

A browser window can have multiple frames inside it. A frame can have multiple child frames inside it.

Suppose there are 2 frames with names f1 and f2 at the top level. There is one child frame with name cf1 inside frame f1. To switch to frame cf1, you will have to use 2 lines of code.

//After below statement is executed, context is switched to frame - f1

driver.switchTo.frame("f1");

//Now we are inside frame f1. To switch the context to child frame - cf1, we will have to use below command.

driver.switchTo.frame("cf1");

Now we are inside frame cf1.  

To switch the context to default content (main window content), you can use below line.

driver.switchTo().defaultContent();

Notice that while switching to the child frame - cf1, we have to switch the context to each parent frame. But to switch the context to main window, we can directly use defaultContent() method.



What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Comparison between Selenium and Appium

Here is the comparison between Selenium and Appium
  1. Selenium is an open source tool to test web applications running in desktop browsers. Appium is an open source tool to test the web applications running in mobile browsers. Appium also supports automation of native and hybrid mobile applications developed for iOS and Android OS. Appium uses selenium API to test the applications.
  2. Appium wraps vendor specific API into Webdriver API which is common for automating all types of mobile browsers. For example - Android API is different than iOS API. But Webdriver API is same. That's what Appium does for you!
  3. Appium can be used to test applications on various devices and platforms like Android phones, Apple iPads, Apple iPhones etc
Below image shows the difference between Selenium and Appium.



What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Comparison between Selenium and LeanFT


Here is the main difference between Selenium and LeanFT
  1. Selenium is open source. LeanFT is licensed tool developed by HP
  2. Selenium can be used to automate only Web applications. LeanFT can be used to automate web as well as desktop applications
  3. Selenium uses the locators like XPATH, CSS. LeanFT uses properties and value pairs. But we can also use XPATH
  4. Selenium is better in cross browser testing than LeanFT
  5. Both are platform independent. 
  6. LeanFT scripts can be developed in only Java and C#. Selenium scripts can be written many languages like Java, C#, Perl, PHP, Python, Ruby, JavaScript etc.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Monday 20 June 2016

Launching Safari browser using Selenium

Before automating the Safari Browser, ensure that you do below settings.

  1. Create Safari Extension developer certificate on Apple developer website.
  2. Install webdriver extension in Safari Browser. You can download webdriver extension http://selenium-release.storage.googleapis.com/index.html?path=2.48/
Below image shows the sample extension on the google site.




Below code will launch the Safari browser.

Webdriver driver = new SafariDriver();                
driver.get("http://www.softpost.org");


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Launching Microsoft Edge Browser using Selenium

We can launch the Microsoft Edge Browser using below code. Note that you will have to download the Microsoft Edge driver from the link -  https://www.microsoft.com/en-us/download/details.aspx?id=48740 and set the property - webdriver.edge.driver in code. Also make sure that you are aware of IE settings required for Selenium.


package msedgetests;

import org.junit.Test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import java.util.concurrent.TimeUnit;

/**
 * Created by Sagar on 19-02-2016.
 */
public class LaunchEdge {

    @Test
    public void launchEdgeBrowser() throws Exception{
        WebDriver driver = null;

       System.setProperty("webdriver.edge.driver",
        "C:\\Program Files (x86)\\Microsoft Web Driver\\MicrosoftWebDriver.exe");

        driver = new EdgeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        String domain = "http://www.softpost.org";
        driver.get(domain);
        System.out.println(driver.getTitle());
        driver.close();
        driver.quit();
    }
}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Executing the selenium tests on iPhone 5 and 6S using mobile emulation in Chrome

Below example illustrates how to execute the Selenium tests on iPhone 5 S using mobile emulation feature provided in chrome. Similarly we can run tests on other devices like Apple iPad, Google Nexus 5 etc.

package browsertests;

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by sagar on 06-12-2015.
 */
public class MobileEmulationOnChrome {
    @Test
            public void launchChrome() {
        Map<String, String> mobileEmulation = new HashMap<String, String>();
       // mobileEmulation.put("deviceName", "Google Nexus 5");
        mobileEmulation.put("deviceName", "Apple iPhone 5");
        //mobileEmulation.put("deviceName", "Apple iPad");
        Map<String, Object> chromeOptions = new HashMap<String, Object>();
        chromeOptions.put("mobileEmulation", mobileEmulation);

        DesiredCapabilities capabilities = DesiredCapabilities.chrome();
        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
        System.setProperty("webdriver.chrome.driver","G:\\softwares\\selenium\\chromedriver2.2.exe");

        WebDriver driver = new ChromeDriver(capabilities);
        driver.get("http://softpost.org");
        driver.quit();
    }
}




What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to get html source code of current page

Below code can be used to get the html source of the current web page in Selenium.

String pageSource = driver.getPageSource();


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to get current url in Selenium

We can get the current url in a browser in Selenium using below code.

String currentUrl =  driver.getCurrentUrl() ;

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to refresh page in Selenium

You can use below code to refresh the page in Selenium.

driver.navigate().refresh();

Alternatively, you can refresh the page by pressing F5 key using sendKeys method or Robotium.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to navigate back and forward in Selenium

You can use below code to navigate back and forward in Selenium.

driver.navigate().back();
driver.navigate().forward();

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to press control and shift keys in Selenium

We can use below code to press control, delete and shift keys in Selenium.

 driver.findElement(By.id("abc")).sendKeys(Keys.CONTROL + "a"); 
 driver.findElement(By.id("abc")).sendKeys(Keys.DELETE);   
 String keys = Keys.chord(Keys.ALT, Keys.SHIFT,"p"); 
 driver.findElement(By.id("abc")).sendKeys(keys);
 driver.findElement(By.name("name")).sendKeys(Keys.TAB);


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday 18 June 2016

Launching Firefox browser using Selenium

To launch the Firefox using Selenium, you do not need to download and run the Firefox driver separately.  Below line of code will start the Firefox from standard location.

WebDriver driver = new FirefoxDriver(myprofile);

Using different Firefox profile

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("XYZ");
caps.setCapability(FirefoxDriver.PROFILE, profile);

Or you can also create new profile on the fly and pass that capability as shown in below code.

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("plugin.state.flash", 1);
caps.setCapability(FirefoxDriver.PROFILE, profile);

Using specific Firefox binary
Sometimes, we need to execute the tests on specific version of Firefox. We can download portable firefox from https://sourceforge.net/projects/portableapps/files/Mozilla%20Firefox%2C%20Portable%20Ed./
and run that binary as shown in below code.

File pathToBinary = new File("c:\\FirefoxPortable_p.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Friday 17 June 2016

Wait until any of the elements is displayed in Selenium

Below code waits until any of the elements is displayed in Selenium.

public void waitUntilElements(){
        List<By> listOfElements = new ArrayList<By>();
        listOfElements.add(By.id("resultsPage"))
        listOfElements.add(By.xpath("//*[contains(text(),'xyz')]"))
        listOfElements.add(By.xpath("//*[contains(text(),'pqr')]"))
        listOfElements.add(By.xpath("//*[contains(text(),'abc')]"))
        waitUntilAnyOfTheElementIsDisplayed(listOfElements)
    }

    boolean waitUntilAnyOfTheElementIsDisplayed(List<By> byList) {
        for (int i=1;i<=60;i++) {
            for (int j = 0; j < byList.size(); j++){
                if (waitUntilElementIsDisplayed(byList.get(j), 1)) {
                    return true;
                }
            }
            sleep(1000)
        }
        return false
    }

public boolean waitUntilElementIsDisplayed(By by, int seconds){
        if (checkElementExists(by,seconds)){
            for (int i=0;i<seconds;i++){
                 if (driver.findElement(by).isDisplayed())
                     return true;
                 else
                     sleep(1000)
                }
                    return false;
        }
        else
        {
            return false;
        }
    }


public boolean checkElementExists(By by, int seconds){
        boolean result=false;
        try {
            driver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
            driver.findElement(by);
            result = true;
        }catch (org.openqa.selenium.NoSuchElementException ex){
            result = false;
        }
        finally {
            DriverUtil.settingImplicitWait()
        }
        return  result;
    }


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Wait until element disappears in Selenium

Below code waits until element disappears in Selenium.

public void waitUntilElementDisappear(By by){
        for (int i=0;i<=60;i++)
        {
            if (checkElementExists(by))
                sleep(1000)
            else
                break;
        }
    }


public boolean checkElementExists(By by, int seconds){
        boolean result=false;
        try {
            driver.manage().timeouts().
implicitlyWait(seconds, TimeUnit.SECONDS);
            driver.findElement(by);
            result = true;
        }catch (org.openqa.selenium.NoSuchElementException ex){
            result = false;
        }
        finally {
            driver.manage().timeouts().
implicitlyWait(20, TimeUnit.SECONDS);
} return result; }


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Wait until page title changes in Selenium

Below method will wait until page title changes to the one passed as parameter in Selenium.

public boolean waitUntilTitleChanges(String title){
        for (int i=0;i<60;i++){
            if (driver.getTitle().equalsIgnoreCase(title))
                return true
            else
                sleep(1000)
        }
        return false
    }


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Check if element really exists in Selenium

Below code demonstrates how to check if an element exists. The code returns true if element exists. It returns false if element is not found. Please note that code will not throw the exception if element is not present.

public boolean checkElementExists(By by, int seconds){
        boolean result=false;
        try {
            driver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
            driver.findElement(by);
            result = true;
        }catch (org.openqa.selenium.NoSuchElementException ex){
            result = false;
        }
        finally {
            driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        }
        return  result;
    }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Wait until element is displayed in Selenium

Below example illustrates how to wait until element is displayed in Selenium. Please note that we are not using any wait conditions. Below methods are useful when handling Ajax requests. Ajax gets the data from server and displays it on the page dynamically. So we can use below method until element is displayed.

public boolean waitUntilElementIsDisplayed(By by, int seconds){
        if (checkElementExists(by,seconds)){
            for (int i=0;i<seconds;i++){
                 if (driver.findElement(by).isDisplayed())
                     return true;
                 else
                     sleep(1000)
                }
                    return false;
        }
        else
        {
            return false;
        }
    }


public boolean checkElementExists(By by, int seconds){
        boolean result=false;
        try {
            driver.manage().timeouts().
implicitlyWait(seconds, TimeUnit.SECONDS);
            driver.findElement(by);
            result = true;
        }catch (org.openqa.selenium.NoSuchElementException ex){
            result = false;
        }
        finally {
            driver.manage().timeouts().
implicitlyWait(20, TimeUnit.SECONDS);
} return result; }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Viewing the remote machine desktop of Linux using VNC

Most of the times, tests are run on the remote Linux machines. We can view the execution on remote Linux machine using virtual desktop. We need below 2 binaries running on the server.
  1. xvfb - Virtual frame buffer - display server that implements X11 display server protocol. It does not show anything on screen. Another option is Xdummy. So in short, xvfb creates the virtual display in memory.
  2. VNC Server - xvnc - Virtual network computing (Virtual display server). RealVNC, x11vnc and TightVNC are other tools that you can use. In short, VNC server allows you to start the server attached to
    display created by xvfb.
  3. On the client side, you need to install VNC client. VNC client connects to the VNC server allowing you to view the virtual display.
Starting the virtual display and VNC server

if [ -z "${DISPLAY}" ]
then
   echo "DISPLAY environment variable is not set"
   exit 1
fi

XVFB_RUNNING=`ps -efa | grep "Xvfb :97" | grep -v grep | cat`
if [ ! -z "${XVFB_RUNNING}" ]
then
   echo Xvfb is running: ${XVFB_RUNNING}
   exit 2
fi
XVNC_RUNNING=`ps -efa | grep "Xvnc" | grep -v grep | cat`
if [ ! -z "${XVNC_RUNNING}" ]
then
   echo Xvnc is running: ${XVNC_RUNNING}
   exit 2
fi


rm -rf /tmp/.X*
/usr/bin/Xvfb :97 -screen 0 1280x1024x24 1>/dev/null 2>&1 &
/usr/bin/vncserver "$DISPLAY" -geometry 1280x1024


Killing all processes with name Xvnc
/usr/bin/killall -q -u `whoami` Xvnc | cat

XVFB also allows you to run the Firefox tests on Linux in headless manner. RealVNC also provides VNC server and clients.

Then from the VNC client we can connect to the VNC server at port say 97 and view the virtual display.


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Thursday 16 June 2016

Selenium Framework related utilities in Java

Let us take a look at below utility methods.

  1. Killing processes in Java
  2. Generating unique random numbers
  3. Get formatted amount
  4. Date utilities
  5. Executing Linux and windows commands
  6. Managing properties in Java
  7. Extract digits from a String


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Executing Windows and Linux commands in Java

Below example illustrates how to execute the Windows and Linux commands in Java.Note that we are using org.apache.commons.lang.SystemUtils class to determine OS type.

if(SystemUtils.IS_OS_LINUX) {
            cmd= [ "/bin/bash", "-c", " ps -fu`whoami`|grep p1|grep -v grep" ]
        } else if (SystemUtils.IS_OS_WINDOWS) {
            cmd= ["bash", "-c", "tasklist | grep p1"]
        }

 StringBuffer output = new StringBuffer();
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            List<String> result = IOUtils.readLines(p.getInputStream());
            for (String line : result) {
                System.out.println(line);
                output.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return output.toString();


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Converting the amount from string into double in Java

Below method returns the amount in double format in Java

double getFormattedAmount(String amount){

String digitalAmount = amount.replaceAll("[\$,]","");

return Double.parseDouble(digitalAmount);

}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Date and time utilities in Java

Adding or subtracting the specific duration from the date

static Calendar calculateDate(String date) {

    
        int durationToBeAddedOrSubtracted;
        Calendar newDate = Calendar.getInstance();


        //-20 years
        durationToBeAddedOrSubtracted = Integer.parseInt(date.split(" ")[0]);
      
        if (date.toLowerCase().contains("months")){
            newDate.add(Calendar.MONTH, durationToBeAddedOrSubtracted);
        } else if (date.toLowerCase().contains("years")){
            newDate.add(Calendar.YEAR, durationToBeAddedOrSubtracted);
        }else{
            newDate.add(Calendar.DATE, durationToBeAddedOrSubtracted);
        }

        return newDate;
    }

Getting the parts from a date in Java.


public void getDateParts(Calendar date){
        String day = String.valueOf(date.get(Calendar.DAY_OF_MONTH));
        String month = String.valueOf(date.get(Calendar.MONTH)+1);
        String year = String.valueOf(date.get(Calendar.YEAR));

        if (day.length()==1){
                    day = "0"+day;
         }
        if (month.length()==1){
                  month = "0"+month;
         }
       
    }

Creating Calendar object from the date parts in Java.

    
           int day = Integer.parseInt(dob[0]);
            int month = Integer.parseInt(dob[1])-1;
            int year = Integer.parseInt(dob[2]);

            Calendar newDate = Calendar.getInstance();
            newDate.set(year, month, day, 0, 0);
   


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Setting and getting System Properties in Java

To set the System property

System.setProperty("p1","v1");

Loading System properties from a settings file say xyz.properties

Properties prop = new Properties();

try {
InputStream inputStream = URLReader.class.getClassLoader().
getResourceAsStream("xyz.properties");
prop.load(inputStream);
} catch (IOException ex) {

}

Reading System property


System.getProperty("os.name")
System.getProperty("user.dir");

Similarly we can read user.timezone, user.home, java.version, file.separator

Reading all System properties


System.getProperties().list(System.out);

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Generating unique random numbers and alphanumeric values in Java

Below code generates unique random numbers and alphanumeric values in Java.

Calendar date = Calendar.getInstance();
        String day = String.valueOf(date.get(Calendar.DAY_OF_MONTH));
        String month = String.valueOf(date.get(Calendar.MONTH)+1);
        String year = String.valueOf(date.get(Calendar.YEAR));

        if (day.length()==1){day = "0"+day;}
        if (month.length()==1){month = "0"+month;}

        String time =  String.valueOf(date.get(Calendar.HOUR_OF_DAY)) 
+ String.valueOf(date.get(Calendar.MINUTE)) +
 String.valueOf(date.get(Calendar.SECOND));
        System.out.println("Unique timeStamp is -> " + time +
 year + month + day);

        //Generates random hash string containing numbers and digits
        UUID id1 = UUID.randomUUID();
        System.out.println("Unique id is -> "+ id1);

        java.util.Date date1= new java.util.Date();
        System.out.println("Unique timestamp is -> " +
 new Timestamp(date1.getTime()));


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Buy Best Selenium Books

Contributors