Wednesday, 27 May 2015

Thread.Sleep really required in Selenium Automation?

I have seen many automation engineers using fixed wait (sleep) statements in selenium or any other automation tool. My personal opinion says that we should never use fixed wait statements in the code as it will slow down the test execution unnecessarily. Sometimes fixed sleep statements might solve your problems. Let us say you added a statement to wait for 5 seconds and the code is working fine today but what will happen if in next release 5 second wait is not sufficient. We never know. This is a risky approach and a bad coding practice.

When the test cases are failing due to synchronization issues, we often tend to blame the network speed, application latency or browser limitations. But that is not the case at all times. You can avoid these wait statements in your code by adopting standard coding practices as mentioned below.

  1. Use WebDriverWait and ExpectedConditions class - I recommend that we should use these classes whenever we think that test might fail due to synchronization issue. With the help of these classes we can make selenium webdriver wait until some condition is satisfied like specific element getting enabled or displayed.
  2. While switching to the new browser window, ensure that the web document is really loaded into the window before trying to perform any operation. In one of the projects, I faced the issue in which I was trying to switch to the window. But due to the latency, test was failing unpredictably. I ensured that count of window handles is 2. But still I was facing the issue in random runs. I used 10 second fix wait but still problem persisted. I kept on increasing the sleep time but finally I realized that there must be better technique to handle this scenario. Then I used a loop to check that title of the window has changed  as per the expected one and then I tried to switch to it. This made my code more robust. This is how I got rid of sleep statements in the code. If you are still not able to switch to the new window, try to switch to the first window and re-switch to the new window. 
  3. Another scenario where testers often use wait statements is when selecting the value from the drop down. The issue here is - After selecting the value from the drop down box, new web controls or elements are added or removed from the page dynamically. In this situation, sometimes page itself become unresponsive. In this case, we can use custom function which will use loop until we have performed our operation successfully.

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

Monday, 25 May 2015

How to check if alert pop up exists in selenium webdriver

You can use below code to check if Alert pop up (Modal Dialog) is open on the web page or not.

    try
    {
        driver.switchTo().alert();
     
      // Alert exists and we switched to it
    }
    catch (NoAlertPresentException exception)
    {
       
       //this block will be executed in case alert is not present
    }

You will need this code in scenario where you can not predict the presence of the Pop up Alert.

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

Saturday, 23 May 2015

Handling dates and time manipulation in Selenium and C#

Date fields are very common in web applications. So you should know how to perform below operations on date in C#.Net in case you are using C# + Selenium API.

  1. Find current system date/time and format it as required.
  2. Find next nth business date (Excluding holidays and weekends)
  3. Find previous nth business date (Excluding holidays and weekends)
  4. Find the difference between 2 dates in terms of days, months, weeks, years.
  5. Compare 2 dates.
  6. Convert string to date and vice versa

Let us try to go one step at a time to learn how we can do all these operations.
Finding current system date in C#.Net

DateTime now = DateTime.Now;
             Console.WriteLine(now);
             String formattedDate1 = now.ToString("MMM ddd d HH:mm yyyy");
             String formattedDate2 = now.ToString("MM/dd/yyyy");
             String formattedDate3 = now.ToString("dd/MM/yyyy");
             String formattedDate4 = now.ToString("dd-MMM-yyyy");
             Console.WriteLine(formattedDate1);
             Console.WriteLine(formattedDate2);
             Console.WriteLine(formattedDate3);
             Console.WriteLine(formattedDate4);


             IFormatProvider culture = new System.Globalization.CultureInfo("en-AU", true);
             DateTime newDate = DateTime.Parse(formattedDate3, culture, System.Globalization.DateTimeStyles.AssumeLocal);
             Console.WriteLine("Year: {0}, Month: {1}, Day {2}", newDate.Year, newDate.Month, newDate.Day);

             Console.WriteLine(newDate.AddDays(3));


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

Finding relative elements in Selenium using XPath

Why finding the relative elements on the page is required?
Well- most of the elements on the webpage can be found using 8 methods then why do we need to find the elements with reference to other elements? There are 2 reasons for this.

  1. Sometimes developers do not provide the id for the element making it difficult to find the element. We can find the element by other methods but they will return many elements.
  2. Sometimes developers provide the id attributes but their value contains numbers. An if you write xpath or use id having numbers, you are heading to the hell. Because such id values are never reliable and fixed.
How to write XPath expressions that find the relative elements?
We can use following-sibling and preceding-sibling keywords as shown below.
In below image, we have input box with name as "q". Yes, we can use xpath directly in this case. But consider a scenario where you do not have name attribute or the textbox attributes are changing at run time. 
In that case, you have a very robust method to find out the textbox using label next to it. There is a rare possibility that label for the textbox will change. So how to write xpath now? We can use following-sibling keyword as shown below. So even if the position of the textbox changes tomorrow, below xpath will be able to find that easily.

//td[contains(text(),'Name')]//following-sibling::td//input























Or other way around, We can find the label of the textbox using below xpath.

//input[@name='q']//parent::td//preceding-sibling::td

More xpath expressions are given below.

  1. //th[contains(text(),'Example')]//following-sibling::th//text()
  2. //span[text()='abc']//parent::td//following-sibling::td
  3. //input[contains(@value,'Google')]
  4. //span[text()='Contents']//preceding-sibling::input
  5. //a[contains(@id,'xyz')]
  6. (//span[text()='" + key + "']//parent::td//following-sibling::td//span)[1]
  7. //span[text()='Exp Date']//ancestor::td
  8. //span[text()='Exp Date']//ancestor::td//preceding-sibling::td
  9. //span[text()='Exp Date']//ancestor::td[1]//preceding-sibling::td
  10. (//a[contains(@id,'xyz')])[2]
Another example to understand the relative element concept is given below.

On below url, we have a table with update button in each row.
http://www.softpost.org/selenium-test-page/

Imagine that you have a requirement where in you have to click on Update button for a given Employee Id. So if you are asked to click on Update button for Employee with Id 142, it should click on second update button. Ordinary developer will use the copy and paste the XPATH for second button. But we have a problem here. The number of employees are not constant. So if today we have a Employee Id 142 at second row. But after few days, it might move to 6th position or any other position. So we should write the xpath expression in such a way that we should be able to click on the correct Update button even though position of the row changes.

If columns are fixed, you can use below XPATH.
//td[contains(text(),'172')]//following-sibling::td[2]//button

If columns are not fixed, you can use below XPATH provided that a row has only one button.
//td[contains(text(),'172')]//parent::tr//button

Both the xpath expressions above, find the button relative to the TD tag that contains Employee Id. So even if Employee Id row changes, Selenium will find the correct button using relative xpath expression.


Above XPATH expressions can also be used to clicking button in specific cell.


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

windowhandles.count returns count as 1 when expected 2 in Selenium

Sometimes, when we click on the link or button, another browser window opens .
Then we can switch to new window using window handle of that window.

Working on one project, I encountered some weird issue. What happened is that after new window was opened, I tried to find the count of window handles. On one machine I was getting the count as 2 while on other I was getting the count as 1. I was using a Internet Explorer 8 browser. 

All automation testers were baffled due to the issue. Then Suddenly I realized that this might be happening due to browser settings. I made below change in the security settings of the browser and it started working magically.

I enabled the protected mode for all security zones.



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 test PDF documents in Selenium, QTP and other tools

Many testers find it very tough to verify the contents of the PDF documents using any testing tools like Selenium, QTP, TestComplete or Tosca.

But let me tell you that it is much easier than what you might be thinking.
Below example will show how to do it.Please note that you will have to add the reference to the iTextSharp dll files or you can even install them from the Nuget Package manager in Visual Studio.

using System;
using System.Collections.Generic;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;

namespace pdfdoc
{
    class Program
    {
        static void Main(string[] args)
        {

            PdfReader reader
                 = new PdfReader("f:\\travel\\letter.pdf");
            // total number of pages
            int n = reader.NumberOfPages;
            Console.WriteLine("Total Number of pages in PDF " + n);
           // Get text from the first page
string txt = PdfTextExtractor.GetTextFromPage(reader,1, new LocationTextExtractionStrategy()); Console.WriteLine("Contents of First Page" + txt); if (txt.Contains("Brisbane")) { Console.WriteLine("Brisbane Exists"); } } } }

Now you may counter question me saying that it is pretty easy doing it from the C#.Net. But we want to do it in QTP and other tools where C# is not used.

Well - Answer to above question is simple. You can create a workable program using C#.Net with command lines where you will pass the pdf file path and contents to be checked as an arguments. Then you can easily convert this program into exe file which can be launched by QTP using shell commands.

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

Explicit Wait Conditions in Selenium Webdriver

We have below wait conditions in Selenium C# API.

  1. Wait until Element exists in page
  2. Wait until Element becomes visible on page
  3. Wait until page title becomes as expected

Below code waits for element with ID login until it exists. Please note that timeOut variable contains total number of seconds you need to wait.

new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.Id(login))));
Below code waits for element with ID login until it gets visible on the page
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementIsVisible((By.Id(login))));
Below code waits until Page title becomes Yahoo News
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.TitleIs("Yahoo News"));
Below code waits until Page title contains News word
 new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.TitleContains("News"));

In Selenium-Java API, we have more such conditions like wait until the element is refreshed, wait  until the element is hidden or wait until text value of the element becomes as expected.

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 check if Element exists on the page in Selenium Webdriver

Automation testing with Selenium often lands in the situation where you need to check if specific element exists.

We can do it very easily using below lines of code in Java.

if (driver.findElements(By.id("abc")).size() != 0)
    System.out.println("Element is present");
else    System.out.println("Element is not present");

In other language APIs like Java or Python, you can use similar method to check if element exists or not.

Please note that if you use FindElement method, NoSuchElementException will be thrown

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 kill process by name in C#.Net

When working with Selenium or any other automation tool, we face the situation wherein we need to kill all the processes of specific name say iexplore or chrome or any application process.

We can use below code in c#.Net to kill the process by name.

Please note that Process class is available in System.Diagnostics namespace. So you will need to use that namespace in the program.

using System.Diagnostics;

 public void KillProcess()
        {

            try
            {
                foreach (Process process in Process.GetProcessesByName("IExplore"))
                { 
                    //kill the process 
                    process.Kill();
                }
            }
            catch (Exception ex)
            {
                //show the exceptions if any here
                Console.WriteLine(ex.ToString());
            };

        }

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

Switch to default content in Selenium

When we have multiple frames in the web page, we need to switch to the frames to perform operations in specific frame.

There are 2 possibilities.

  1. Page contains frame set
  2. Page contains iframe

In first case, DefaultContent() will hand over the control to the first frame in the frame set. In second case, DefaultContent() will hand over the control to the main document in the page.

Example code in C# is given below.

 //switch to first frame in the frameset.
 driver.SwitchTo().DefaultContent();
//if there are inline frames in the page, switch to the main document of the page.

In JAVA API, we can use similar statement as shown below.
driver.switchTo().defaultContent();


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

Friday, 22 May 2015

Selenium Webdriver Capabilities significance

Java Context

In Selenium, we have a Webdriver Interface and there are lot of classes that implement this interface.
So let us first try to understand this interface.

What is inside this WebDriver Interface?
Important methods declared inside this interface are -
  1. get
  2. findElement
  3. getTitle
  4. getPageSource....etc
The classes that implement this interface are given below.
  1. ChromeDriver
  2. EventFiringWebDriver
  3. FirefoxDriver
  4. HtmlUnitDriver
  5. InternetExplorerDriver
  6. OperaDriver
  7. RemoteWebDriver
  8. SafariDriver

Now let us take a look at different constructors for ChromeDriver.

  1. ChromeDriver()
  2. ChromeDriver(Capabilities capabilities)
  3. ChromeDriver(ChromeDriverService service)
  4. ChromeDriver(ChromeDriverService service, Capabilities capabilities)
  5. ChromeDriver(ChromeDriverService service, ChromeOptions options)
  6. ChromeDriver(ChromeOptions options)
As you can see, in Java Selenium API, we have 6 constructors for the ChromeDriver class.
The first constructor takes no arguments. But rest of them are taking the arguments as mentioned below.
  1. Capabilities
  2. ChromeDriverService
  3. ChromeOptions

Now let us try to understand the significance of these classes.

Capabilities are used to manage the browser attributes. For example - we can set the browser name, version, platform using capabilities.
ChromeDriverService is used to manage the chrome server (exe). Finally, ChromeOptions are used to set the options specific to the chrome browser like adding extensions, setting the binary path etc.

Constructors for other classes also take similar arguments as mentioned above.

Capabilities used by Selenium Server

  1. browserName - chrome|firefox|internet explorer|htmlunit|android|iPhone|iPad|opera|safari
  2. version
  3. platform - WINDOWS|MAC|LINUX|UNIX|ANDROID
Some other important Capabilities
  1. acceptSslCerts
  2. nativeEvents
  3. proxy
IE specific Capabilities
  1. ignoreZoomSetting
  2. ie.ensureCleanSession
Firefox specific Capabilities
  1. firefox_binary
You can find more information on the link - https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities.

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

Sunday, 10 May 2015

Element is disabled exception in Selenium Webdriver.

Sometimes you need to enter data into web controls which are disabled.
But Selenium will throw exceptions saying element is disabled.

So you need to make use of JavaScriptExecutor interface in this scenario.
With JavaScriptExecutor, you can set the data into editbox easily using below syntax.

(JavaScriptExecutor (driver)).executeScript("arguments[0].value = abc", webelement );



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

Http request to the remote webdriver server for url timed out in Selenium

You may face the error saying Http request to the remote webdriver server for url timed out after 60 seconds in Selenium Webdriver.

Solution -

You can edit the browser profile and increase timeout to say 180 seconds from default 60 seconds. Please note that this constructor is available in .Net API only. I am wondering why this kind of constructor is not available in Java API. If anyone has any idea, kindly write in comment.

WebDriver driver = new FirefoxDriver(new FirefoxBinary(), new FirefoxProfile(), TimeSpan.FromMinutes(3));

For internet explorer driver, you can use below syntax.

driver = new InternetExplorerDriver(@"z:\seleniumc", new InternetExplorerOptions(),TimeSpan.FromMinutes(5));

So if you launch the browser with above configuration, then you will not receive any error.

Hope you also fix yours.

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 comment a code block in c#.net visual studio

To comment a block of code, select the block and use below short cut key in C#.Net visual studio.

ctrl+k+c

To remove the comments from a block of code, select the block and use below short cut key.

ctrl+k+u

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

What is the Thread.sleep() equivalent method in C#.Net?

In Java, we have Thread.sleep(5000) method which makes thread wait for specific time.

In C#.net, we can use below statement to sleep for few seconds.

System.Threading.Thread.Sleep(5000);

Note that time is given in milliseconds. So above code will make thread wait for 5 seconds.

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

Unexpected Modal Dialog found error in Selenium Webdriver

When automating the test cases using Selenium WebDriver, we often encounter this error saying "Unexpected Modal Dialog found".

This error usually comes when Selenium Webdriver is not able to perform any operation on the page due to Alert dialog being open on the page.

To fix this error, you need to handle that alert.
You can click on ok or cancel based upon your requirement.
Below links will help you.

  1. Handle alerts in Java
  2. Handle alerts in C#.Net


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 the members (classes, interfaces) inside namespaces or dll files in C#?

Many times we need to explore the classes and their methods. So we can do this by using object explorer in Visual Studio.

If you are given a dll file, you can even explore the namespaces, classes, methods inside it using object browser.
As shown in below images, we can right click on any reference library (dll file) and then we can click on view in object browser.


As shown in below image, object browser is showing all namespaces, classes, interfaces, fields inside the reference library.



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

Can not resolve actions class in Selenium in C#.Net?

Please note that in C# Selenium library, Actions class is kept in OpenQA.Selenium.Interactions namespace. Hence you must write below line of code in the beginning of the program in C#.Net.

using OpenQA.Selenium.Interactions


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

Missing Support type in OpenQA.Selenium.Support.UI

Have you encountered the error saying Missing Support type in OpenQA.Selenium.Support.UI?

The reason for this issue is that you have not added the reference of  required dll - WebDriver.Support.dll file in your .net project.

Remember that when working with Selenium webdriver from visual studio, you need to add 2 dll references as mentioned below.

  1. WebDriver.dll
  2. WebDriver.Support.dll

This solves the problem. Hope it helps.

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