Please post your Web Driver questions in official Web Driver forum

Thursday, December 8, 2016

File upload and WebDriver (Where is my File?)

You may have come across file upload use case when working with WebDriver. File upload 
is quite easy since it is same as typing in a text box but herein we need to pass path of file
to be uploaded. I used to keep a static file in src/test/resources folder of maven project and 
would use it for upload operation. But you can also generate file during run time using 
java.nio.file.Files class.  Files class has createTempFile(java.lang.String, java.lang.String, java.nio.file.attribute.FileAttribute...) method which can be used to generate temporary files. For ex, you can generate a temporary pdf file and get back the File object as following - 

File file = Files.createTempFile("test-" + accountNumber, ".pdf").toFile();
generatePDF(file, StringUtils.repeat("Dummy PDF", 10));
And this is how generatePDF looks -
public static File generatePDF(File file, String content) {
    try {
        Document e = new Document();
        PdfWriter.getInstance(e, new FileOutputStream(file));
        e.open();
        e.add(new Paragraph(content));
        e.close();
        return file;
    } catch (FileNotFoundException | DocumentException var3) {
        throw new RuntimeException(var3);
    }
}

Now you can get absolute path of file and pass it to upload text box -  

getDriver.findElement(byLocator).sendKeys(file.getAbsolutePath());

Following this approach you don't have to keep a static file on my project.
So how do you handle file for file upload operation?

Thursday, December 1, 2016

Recording curl request with JMeter Recorder

Though it is quite east to convert curl requests to corresponding JMeter request. At times you might be stuck with issue like I faced when uploading a file with JMeter HTTP request
In a gist I kept getting 404 error when using REStful service to upload a file. After days of investigations I found it that I should be using HTTP request implementation java and not HttpClient4. JMeter HTTPs Test Script recorder was of great help to debug this issue. This post describes the process of recording curl request through JMeter HTTPs Test Script recorder.

If you have never used JMeter HTTPs Test Script recorder then create a new JMeter Plan and under WorkBench > Add > Non Test Element > HTTP(s) Test Script Recorder. 
Specify Global Setting > Port as 8090

If we were using browser to record web application then we would configure its proxy to 127.0.0.1 (Since http proxy server would work on localhost) and port 8090 -





Any way, we are not going to record browser actions but a curl request.

Under Test Plan element add Thread Group, Recording Controller and HTTP Request Default. Under HTTP Request Defaults mention Server IP as localhost” and port as 8090. This is to avoid duplication from HTTP Requests during recording. Recording Controller is where recorded samples would appear.

In the end Test Plan would looks as - 



To be able to record curl request on JMeter, we have to specify proxy server on curl using --proxy 127.0.0.1:8090 flag. The curl request looks as - 

curl -k --proxy 127.0.0.1:8090 -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: bearer xxx' -F upload_file=@"/Users/tbhadauria/Documents/test.pdf"  'https://xxx'

Notice that I also added flag "k" to turn off curl's verification of certificate. Now hit the "Start" button on HTTPs Test Script Recorder and execute curl command. Following this you would find recorded elements under Recording Controller as following - 



I had already setup curl request on JMeter and comparing it to recorded elements I found that the only difference was the HTTP Request Implementation. I was using HTTP Request Implementation HTTPClient4 which would result in 400 error while recorded element had HTTP Request Implementation Java and it worked successfully. 

And this solved the issue of 400 error when uploading document using JMeter :) 

Monday, November 28, 2016

How to remove duplicate page object methods

You may come across situation when you find page object methods on various classes having similar operations. For ex in following example there are two different different methods doing almost same thing. Both methods get the count of ticket in opening and outgoing queue in a system. The only difference is the element locator. One method uses element locator openingTicketCount while other uses outgoingTicketCount -

public int getOpeningTicketCount() {
   final String count = fluent(openingTicketCount).getText();
   return count.length() == 0 ? 0 : Integer.valueOf(count);
}

public int getOutgoingTicketCount() {
   final String count = fluent(outgoingTicketCount).getText();
   return count.length() == 0 ? 0 : Integer.valueOf(count);
}

We can extract the common steps and create a new private method to encapsulate them - 

private int getTicketCount(By locator) {
   final String count = fluent(locator).getText();
   return count.length() == 0 ? 0 : Integer.valueOf(count);
}

And previous page object methods can call this method with required element locator - 

public int getOpeningTicketCount() {
   return getTicketCount(openingTicketCount);
}

public int getOutgoingTicketCount() {
   return getTicketCount(outgoingTicketCount);
}

What do you think of this approach? How would you handle duplicate element locators?

Monday, November 21, 2016

What else should page object test?

As we know that objective of page object is to provide services offered by page (or part of it). In its true sense page object does not advocate asserting page condition in page object class. Except the page object constructor which can check if control is on right page on it, like following -


Screenshot from 2016-06-06 15:12:12.png


But this is not the only use case of a check on page object. When returning data set from page object one could also check if data set is empty, for ex following method checks if collection of webelement is empty using Preconditions.checkState() method before returning it’s content -


Screenshot from 2016-06-06 15:16:36.png


In the above code snippet, if element list is empty then page object method would throw IllegalStateException exception. This check could also be carried out on test method which receives the member name list. But I prefer to keep such checks on page object method and focus on assertion on test method. What do you think of this approach? Do you also have such checks in your page object methods?

Saturday, November 12, 2016

Using chrome console to test xPath and css selectors

Since the advent of selenium there have been many plugin to test xPath / css selectors but you don’t need any of them if you have chrome browser. Using Chrome console you can test both xPath and css selectors. Launch website to be tested in chrome browser and hit F-12 and you would see chrome console opened in lower pane of application -


Screenshot from 2016-07-27 13:35:38.png

Hit escape key and console would open another pane to write element locators -


Screenshot from 2016-07-27 13:37:30.png

And now you can start writing xPath or css selectors in chrome console and test them -
The syntax for writing css id - $$(“”)


Screenshot from 2016-07-27 13:43:27.png


And hit the enter key. If your expression is right then html snippet of the application element corresponding to the css selector would be displayed -


Screenshot from 2016-07-27 13:45:11.png


If you mouse over the html snippet in chrome console then it would highlight the corresponding element in application -

Screenshot from 2016-07-27 13:47:51.png

If you want to clean console of previously written element selectors then just hit ctrl+L keys and chrome console would be empty again.


Process of testing xPath selector is same as css selector except that syntax to test xPath is -


$x(“your_xpath_selector”)


Screenshot from 2016-07-27 13:55:04.png

So no more using any plugin to test element locators :-)

Is there any other innovative way you use to test your element locator?

Monday, November 7, 2016

Structure of test automation project

Have you come across situation when you did not know where you should keep the test class, page object or any supporting class. I am going to share some of the practices I follow when working on test automation project. Given that I work with java and maven, it solves the problem of the directory structure. Maven project may have many directory but these are the ones I use most -

src/main/java - any non test class, i.e - page object etc
src/main/resources - resources like - properties file, text file etc used by main classes
src/test/java - the test classes
src/test/resources - resources like - properties file, text file etc used by test classes.
target - this directory is created automatically building a maven project and

Let’s focus on src/main/java - this is a directory which contains all of non test code. I usually end up having following structure on src/main/java -

src/main/java
com.google
core
dataobjects
groups
model
navigation
pageobject
util

Hence it looks as -

Screenshot from 2016-07-27 10:16:07.png
Package core contains SelTestCase class which takes care of setup and teardown. Given that I use STF, I don’t have to set up browser myself and setup method is mere access to application URL, test environment etc

Screenshot from 2016-07-27 10:21:45.png

Package dataobjects contains the test data objects used by the test classes -

Screenshot from 2016-07-27 10:32:41.png

Package groups contains TestNG test group. It is set of classes with String constants so that I can easily change the group name by modifying the String constants.

Package model contains the API definition which are used by either test classes or page objects -

Screenshot from 2016-07-27 10:34:56.png

Package navigation contains the Navigation APIs for navigating through application pages. Hence navigation steps don’t have to be repeated in test classes or page objects -

Screenshot from 2016-07-27 10:40:02.png

Package pageobject does not need any introduction :-). I further divide pageobject package into application areas for which page objects are to be created -

Screenshot from 2016-07-27 10:45:12.png

I further divide /resources package into application environment related entities. I set up environment parameter in testng.xml file and depending on the environment corresponding data set is picked up for test run -

Screenshot from 2016-07-27 10:49:45.png

The test package contains the test classes. Like the page object, I created various packages to contain test classes of application area -

Screenshot from 2016-07-27 10:54:30.png

At times I also create util package containing utility classes. Though I would not recommend this approach as util package tends to become dumping ground of unrelated classes. A better approach would be to create dedicated packages for those classes.

This brings us end to this post. What do you think of this package structure? How does your test structure look like?

Saturday, October 29, 2016

Are your selenium element locators static ?

I usually declare element locator static as well as the helper method using them, since element locators is a class variable or constant and is not dependent on a specific instance of class. For example in the following code snippet, element locators - imageElement and teamDeletionSucessMessage are static. Also, method - isTeamDeletionSucessMessageDisplayed is static -


Screenshot from 2016-04-19 15:59:39.png


From one of the SO answer, following can be the requirement to make method static -

  1. If you are writing utility classes and they are not supposed to be changed.
  2. If the method is not using any instance variable(s) or instance method(s). {some thing I consider most important when declaring a variable static}
  3. If any operation is not dependent on instance creation.
  4. If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
  5. If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
What is your take on this? Are your element locators also static (or even static final)?

Sunday, October 23, 2016

Processing JMeter Results using awk

awk is Pattern scanning and processing language. Its name is derived from its authors “Aho, Weinberger, and Kernighan”.
Some of its features are:
  • Awk views a text file as records and fields
  • Awk has variables, conditionals and loops
  • Awk has arithmetic and string operators
  • Awk can generate formatted reports
Syntax:
awk '/search pattern1/ {Actions}
    
/search pattern2/ {Actions}' file
Herein :
  • search pattern is a regular expression.
  • Actions – statement (s) to be performed.
  • several patterns and actions can be used in Awk.
  • file is the Input file.
  • Single quotes around program avoids shell interpreting any special characters.


Let’s Consider following jmeter summary file -


summary +    41 in  15.4s =    2.7/s Avg:  2234 Min:   383 Max:  6974 Err: 0 (0.00%)
summary +    57 in  21.5s =    2.6/s Avg:  2548 Min:   618 Max:  4528 Err: 0 (0.00%)
summary =    98 in  32.5s =    3.0/s Avg:  2416 Min:   383 Max:  6974 Err: 0 (0.00%)
summary +   108 in  21.8s =    5.0/s Avg:  1291 Min:   229 Max:  6317 Err: 0 (0.00%)
summary =   206 in  52.5s =    3.9/s Avg:  1827 Min:   229 Max:  6974 Err: 0 (0.00%)


Let’s assume that we want to print lines where avg response time is more than 2500ms
awk '{if($9>2500){print $0}}' file.txt


Herein $9 is the the 9th field in log file and $0 denotes all of record


Hence we would get following output -
summary +    57 in  21.5s =    2.6/s Avg:  2548 Min:   618 Max:  4528 Err: 0 (0.00%)


Or printing the records with avg response time more than 2400ms


awk '{if($9>2400){print $0}}' file.txt


And we would get following output -


summary +    57 in  21.5s =    2.6/s Avg:  2548 Min:   618 Max:  4528 Err: 0 (0.00%)
summary =    98 in  32.5s =    3.0/s Avg:  2416 Min:   383 Max:  6974 Err: 0 (0.00%)


Find the total number of record in jmeter.log file -


wc file.txt | awk ‘{print $0}’


Consider that you are logging custom variables on Jmeter log file (i.e. email address etc) and now you want to figure out which email address caused higher latency. Can you guess how you can achieve it?
Fork me on GitHub