Selenium WebDriver Testing

Selenium WebDriver tests are meant to be run after a new stack has been built or code has been updated to run sanity tests against a development or production environment. These tests are meant to check for main site functionality such as particular parts of the site loading/being reachable (My Account, Workspaces, DMDII Member Portal and Projects, My Organization, etc). The code for this can be found in the QA Repository in BitBucket.

Prerequisites (Downloads and Installing)

It is recommended to create and run your tests on a linux operating system or in a VirtualBox linux environment. in order to be able to run Java, Selenium WebDriver Tests the following will need to be installed on your computer:

  • Java 8 JDK
    • Check to see if java is installed already and what version you are currently using
      • java -version
    • If not installed or using and older verision use the following instructions/commands
      • sudo apt-get update
      • sudo apt-get upgrade
      • sudo add-apt-repository ppa:openjdk-r/ppa
      • sudo apt-get update
      • sudo apt-get install openjdk-8-jdk
      • sudo apt-get update
      • close and reopen terminal
      • sudo update-alternatives --config java
    • Ensure that there is a file named 'java-8-openjdk-amd64
      • ls /usr/lib/jvm/

Recommended: Install the Firebug add-on  for Firefox as it can help to find Ids, css, and xpaths that will need to include in your code.

Configuration

In order to begin writing Selenium/Selenese Code, you will need to configure your Eclipse Properties to allow running of Selenium Functions and methods. The following are the steps that need to be taken.

Step 1:

  1. Open Eclipse Mars 1 and choose a workspace.
  2. Click on File, New, Java Project and name you’re Java Project
  3. Under JRE select JavaSE-1.8 and click Finish.

You will see that under the created project, a new src folder and the JRE System Library folder have been created.

Step 2:

Go the Selenium website and download Selenium Standalone Server and the respective Selenium Client & WebDriver Language Binding. Extract the jar files in a folder. They Can be found at: http://www.seleniumhq.org/download/

  • Or directly download from here:
    • Stand Alone Server Download: 3.4.0
    • Java Language Binding: Download

Step 3:

To create Selenium WebDriver Test Cases you will need to configure the Selenium WebDriver Functionality by adding jar files to the project.

  1. Right click on project folder, go to properties, Java Build Path and select Libraries.
  2. The JRE System Library will already be included.
  3. Click Add External JARs.. and add the selenium-server-standalone-3.4.0.jar, client-combined-3.4.0-nodeps.jar, and all the jar files in the “lib” folder.

Once the jar files have been added the user can view them in the Referenced Libraries folder under Package Explorer.

Opening an Existing Selenium Project

In order to load the dmcqa repository or an existing selenium code into Eclipse, take the following steps.

  1. Use Git to pull down the dmcqa repository
    1. If you have enabled SSH with your GitHub account you can use the following terminal command
      1. git clone git@github.com:dmc-uilabs/dmcqa.git
  2. Open the Eclipse program
  3. In the package explorer right click in the whitespace and choose import from the list
  4. In the new window double click on: Git
    1. Double click on Projects from Git
    2. Double click on Existing Repository
  5. In the next window click on the add button
  6. Navigate to the root of the dmcqa repository in the file explorer and click on the open button in the file explorer
  7. Check the box next to your selected file path and click on the finish button
  8. On the next window, choose the repository directory and click the next button
    1. Make sure that the import as general project radial button is selected and click on the next button
  9. Name your project as click on the finish button
  10. When the project gets loaded into the Eclipse program, click on the project name in the project explorer
    1. Right click project root directory in the Package Explorer tab on the left hand side panel
    2. Hover over Configure, and choose Convert to Maven Project
  11. The process is complete. You should be able now run any tests that have been written and update the code as well

Example Code

Setting System Environment Variables

To help anonymize our testing accounts and not expose these in our code base, we set our gmail username and password as environment variables on local machines. In a terminal window run: sudo nano /etc/profile. Add the following lines to the bottom of the file:

export Selenium_User1="example@gmail.com"
export Selenium_Pass1="examplePa$$word"
  1. Save your changes and log out of your computer and log back in.
  2. Run the command: env | grep Selenium
    1. You should get back the variable names and values. If not try running the command
    2. source /etc/profile
  3. In the selenium java code, now create a string variable that you will reference as your password with it value equal to:
    1. System.getenv("<environment variable>");

Opening a Web Browser

System.setProperty("webdriver.chrome.driver", "/home/<username>/file/path/to/chromedriver");

There are some functional  issues with opening a firefox browser, so at this time it is recommended to use Google Chrome.

Maximizing Browser Window Size

So Tests when conducted tend to ste=op or fail if the browser window has not been maximized. so the following line of code can be used to maximize the browser window:

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

Visiting a Web Page

driver.get("http://beta.opendmc.org");

Clicking on Hyper-link or Button

driver.findElement(By.id("idOfElement")).click();
driver.findElement(By.cssSelector("cssToElementLocation")).click();
driver.findElement(By.xpath("actualXpathToElement")).click();

Writing into a text field

driver.findElement(By.if("idOfElement")).sendKeys("Text to add to Text field");
driver.findElement(By.cssSelector("cssToElementLocation")).sendKeys("Text to add to Text field");
driver.findElement(By.xpath("actualXpathToElement")).sendKeys("Text to add to Text field");

Using Keyboard Commands and Uploading a Document

The following function was created to allow for the browser to automatically be able to take a file name provided as a string to then be automatically found and uploaded to the website.

import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
public static void fileLocationUpload(String documentLocation)
import java.awt.Robot;

    {
        try
        {   
            //System.out.println("About to press down.");
            Robot robot1 = new Robot();
            robot1.delay(1000);
            robot1.keyPress(KeyEvent.VK_DOWN);
            robot1.keyRelease(KeyEvent.VK_DOWN);
            robot1.delay(1000);
            //System.out.println("Pressed down already.");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        //System.out.println("Typing out file location.");

        for(int i = 0; i < documentLocation.length(); i++)
        {
            try
            {
                Robot robot = new Robot();
                //robot.delay(1000);
                //char letter = '/';
                char letter = documentLocation.charAt(i);

                if (letter != '/' && letter != '.' && letter != ' ' && letter != '-' && letter != '_')
                {
                    //System.out.println("I'm inside the IF! ...Somehow.");
                    boolean upperCase = Character.isUpperCase(letter);
                    char upperLetter = Character.toUpperCase(letter);
                    String variableName = "VK_" + upperLetter;
                    Class clazz = KeyEvent.class;
                    Field field = clazz.getField( variableName );
                    int keyCode = field.getInt(null);
                    
                    if (upperCase) robot.keyPress( KeyEvent.VK_SHIFT );
                    robot.keyPress( keyCode );
                    robot.keyRelease( keyCode );
                    if (upperCase) robot.keyRelease( KeyEvent.VK_SHIFT );
                }

                if (letter == '/')
                {
                    robot.keyPress( KeyEvent.VK_SLASH );
                    robot.keyRelease( KeyEvent.VK_SLASH );
                }
                
                if (letter == '.')
                {
                    robot.keyPress( KeyEvent.VK_PERIOD );
                    robot.keyRelease( KeyEvent.VK_PERIOD );
                }
                
//                if (letter == '\')
//                {
//                    robot.keyRelease( KeyEvent.VK_QUOTE );
//                }
                
                if (letter == ' ')
                {
                    robot.keyPress( KeyEvent.VK_SPACE );
                    robot.keyRelease( KeyEvent.VK_SPACE );
                }
                
                if (letter == '-')
                {
                    robot.keyPress( KeyEvent.VK_MINUS );
                    robot.keyRelease( KeyEvent.VK_MINUS );
                }
                
                if (letter == '_')
                {
                    robot.keyPress( KeyEvent.VK_UNDERSCORE );
                    robot.keyRelease( KeyEvent.VK_UNDERSCORE );
                }
                
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
        
        try
        {
            Robot robot2 = new Robot();
            robot2.keyPress(KeyEvent.VK_ENTER);
              robot2.keyRelease(KeyEvent.VK_ENTER);
            robot2.delay(1000);
            robot2.keyPress(KeyEvent.VK_ENTER);
              robot2.keyRelease(KeyEvent.VK_ENTER);
            robot2.delay(1000);
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }


Wait for Element to Load

WebDriverWait wait = new WebDriverWait(driver, 10);

  • The line of code above initializes wait

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("idOfElement")));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("cssToElementLocation")));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("actualXpathToElement")));

  • Example of calling wait to wait for a particular element

How to Grab Words on Web Page

WebElement workspaceNameCreated = driver.findElement(By.cssSelector("cssToElementLocation"));
String workspaceNameCreatedStr = "Workspace name Not Found";
workspaceNameCreatedStr = workspaceNameCreated.getText();
System.out.println(workspaceNameCreatedStr);