Tuesday, October 12, 2010

Selenium automation problems

Handling Ajax events:

If you want to automate an UI which is having some UI elements are behaving based on ajax events.
Suppose there is an UI element (text field),when you type some text on the field  that will invoke some ajax call for hitting the server and get some info from server and showing on the screen.
Now problem is when you use the type command in selenium ,it wont call the ajax events.You need to call
ajax events after type the text into the text field.

Selenium is providing the following commands for automate the ajax events.

Selenium.type(xpath of element,some text); // this will do the type the text ,but it wont invokes the ajax events
Selenium.fireEvent(xpath of element,"blur"); //this will do the ajax calls.

Verify vertical scrollbar appears for the text-area element:

Selenium is not providing any command to checking the appearance of the vertical scrollbar.
We need to findout by using java script and need to invoke the script by the selenium.
Selenium API is providing the command for executing the java script.

Use below script when you know only the classname for the text-area.

Selenium.type(xpath of the text-area element,text value);
String str1=Selenium.getEval("this.browserbot.getCurrentWindow().document.getElementsByClassName('cssclassname')[0].clientHeight");
String str = Selenium.getEval("this.browserbot.getCurrentWindow().document.getElementsByClassName('cssclassname')[0].scrollHeight");
int clientHeight = Integer.parseInt(str1);
int scrollHeight = Integer.parseInt(str);

if(clientHeight < scrollHeight){
System.out.println("Vertical scrollbar appears");
}else{
System.out.println("Vertical scrollbar is not appear");
}

Note: If you know the Id or Name of the text-area field then
use getElementById() or getElementByName() instead of the getElementByClassName method.

I'm unable to upload a file using selenium core; when I try to type in the file upload text field, nothing happens!

There seems to be two inter-related problems:

1 – Unfortunately, this is yet another JavaScript security restriction; JS is not allowed to modify the value of input type=”file” form fields. You can work around this by running your tests under Selenium IDE or under Selenium RC running in the experimental “*chrome” mode for Firefox, but at present there is no straight forward way to do this in Selenium Core.

2 – Handling of the “Choose File” dialog box with Selenium alone is not possible. We need to have another program running to select the path and file from the “Choose File” dialog box.

So, How can we upload files?
Fortunately, there exists a workaround to the above problems. This is where the magic of AutoIt and Selenium combination can work wonders!

First we will write a simple script in AutoIt and save the file as an executable: (please read documentation on AutoIt website to learn how to save the scripts as an executable file)


1    WinWaitActive("Choose file")
2    Send("C:\attach\samplefile.txt") \\location of the file you want to attach to the form and submit
3    Send("{ENTER}")

We shall name the above file as attachFile.exe

Now, within a Java code, we can run a process which will execute the above program just before when we want to upload and submit a file.

01    package com.company;
02   
03    import java.io.IOException;
04    import com.thoughtworks.selenium.Selenium;
05   
06    public class AddAttachment {
07       public static void attach(Selenium selenium, String fileName) {
08          try {
09             String[] commands = new String[]{};
10             commands = new String[]{"c:\\test\\attachFile.exe"}; //location of the autoit executable
11             Runtime.getRuntime().exec(commands);
12          } catch (IOException e) {}
13   
14          //autoit executable is now waiting for a "Choose file" dialog to popup
15          selenium.click("name=browseButton");
16          //once the "Choose file" dialog is opened, the autoit will input the path and file name
17       }
18    }

The above seems to be the easiest way to deal with file uploads and attachments using Selenium.

Note: Use AutoIt for the things which are not automated by the selenium-core like handling browser certification,authentication popups etc.

How to start selenium server using Java code

When test automating a web application using Selenium, we have to start the Selenium server first, so that a new Selenium session is created to talk to the web browser. This can be either done manually, i.e user running a command line to start the Selenium server, or to get the pure automation effect of Selenium, it is best to start the Selenium server via a program code.

01    package com.company;
02    import org.openqa.selenium.server.RemoteControlConfiguration;
03    import org.openqa.selenium.server.SeleniumServer;
04    import com.thoughtworks.selenium.Selenium;
05    import java.net.BindException;
06    import java.net.ServerSocket;
07   
08    public class Server {
09        public static SeleniumServer server;
10        public static void startSeleniumServer() throws Exception {
11   
12           try {
13            ServerSocket serverSocket = new ServerSocket(RemoteControlConfiguration.DEFAULT_PORT);
14            serverSocket.close();
15                    //Server not up, start it
16                    try {
17                     RemoteControlConfiguration rcc = new RemoteControlConfiguration();
18                     rcc.setPort(RemoteControlConfiguration.DEFAULT_PORT);
19                     server = new SeleniumServer(false, rcc);
20   
21                    } catch (Exception e) {
22                        System.err.println("Could not create Selenium Server because of: "
23                                + e.getMessage());
24                        e.printStackTrace();
25                    }
26                    try {
27                        server.start();
28                        System.out.println("Server started");
29                    } catch (Exception e) {
30                        System.err.println("Could not start Selenium Server because of: "
31                                + e.getMessage());
32                        e.printStackTrace();
33                    }
34                } catch (BindException e) {
35                    System.out.println("Selenium server already up, will reuse...");
36                }
37        }
38   
39        public static void stopSeleniumServer(Selenium selenium){
40            selenium.stop();
41            if (server != null)
42              {
43                 try
44                 {
45                     selenium.shutDownSeleniumServer();
46                     server.stop();
47   
48                    server = null;
49                 }
50                 catch (Exception e)
51                 {
52                    e.printStackTrace();
53                 }
54              }
55        }
56   
57    }

Selenium Failed to start new browser in iexplore mode when starting/stoping the server dynamically by the code in IE.

I'm unable to run my scripts with IE using iexplore mode when starting the server using java code(dynamically) and I'm getting below error

java.lang.RuntimeException: Could not start Selenium session: Failed to start new browser session: Error while launching browser
    at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:89)
    at com.aol.patch.util.SeleniumBase.openBrowser(SeleniumBase.java:91)
    at com.aol.patch.tests.CommonTest.testEnter(CommonTest.java:28)
Caused by: com.thoughtworks.selenium.SeleniumException: Failed to start new browser session: Error while launching browser
    at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
    at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
    at com.thoughtworks.selenium.HttpCommandProcessor.getString(HttpCommandProcessor.java:262)
    at com.thoughtworks.selenium.HttpCommandProcessor.start(HttpCommandProcessor.java:223)
    at com.thoughtworks.selenium.DefaultSelenium.start(DefaultSelenium.java:81)
   
Here the problem is selenium is trying to start in iehta mode eventhough  specified that start in a iexplore mode.


After doing some quick search, I found that there is work around to start a selenium in iehta mode.

The only way to get the original iexplore is to change the browser mode to "*iexploreproxy" or "piiexplore".

So, I changed my config file to start selenium using "*iexploreproxy" instead of "*iexplore" and  working fine with IE.
I hope this can be helpful.

28 comments:

  1. Thanks for the tip on vertical scrollbar. Is horizontal scrollbar similar, with a check via:

    if(clientWidth < scrollWidth)

    ReplyDelete
  2. Also wanted to note that the scrollbar checking method may be more optimized by using browserbot.findElement instead of getCurrentWindow then using document.getElement... approach. browserbot.findElement will allow you reference element by any of the supported Selenium methods (name, id, xpath, css, etc.) which gives you more element locating power. An example of how to do so, but not in terms of scrollbars can be found in my post about DOM access tricks in RC: http://autumnator.wordpress.com/2011/11/06/special-element-state-validation-with-selenium-and-css-and-dom/

    ReplyDelete
  3. Also wanted to mention, trick to adapt scrollbar code to WebDriver is like this:

    int height = (int) ((JavascriptExecutor) driver).executeScript("return arguments[0].clientHeight;",yourWebElement);

    and follow same for rest of code as needed yourWebElement is the WebElement returned from a findElement method call.

    ReplyDelete
  4. Just came across this today, here's how you'd do it using jQuery, which can be executed with Selenium/WebDriver as well:

    http://hasin.me/2013/08/17/detecting-if-a-dom-element-has-scrollbar/

    ReplyDelete
  5. The Selenium automation problems are explained well my sincere thanks for sharing this post and please continue to share this kind of post
    Selenium Training in Chennai

    ReplyDelete
  6. nice post had been shared by you thank you for sharing such kind of an interesting blogs. so keep on sharing such kind of an interesting blogs.
    selenium training in chennai

    ReplyDelete
  7. Hey informative blog..

    If you are looking for SELENIUM TRAINING IN CHENNAI here is the link

    http://thecreatingexperts.com/selenium-training-in-chennai/

    contact +91-08122241286

    ReplyDelete
  8. ruly a very good article on how to handle the future technology. After reading your post,thanks for taking the time to discuss this, I feel happy about and I love learning more about this topic. Learn selenium


    Selenium Training in Bangalore

    ReplyDelete
  9. Nicely explained. Here you described the well written article from your in-depth knowledge. Truly impressive and nice information.. keep update.. Software Testing Training in Chennai | Selenium Training in Chennai

    ReplyDelete
  10. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.
    Java Training in chennai |Python Training in Chennai

    ReplyDelete
  11. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.
    Software Testing Training in Bangalore

    Software Testing Training in BTM Layout

    Software Testing Training in Marathahalli




    ReplyDelete
  12. Sap fico training institute in Noida

    Sap fico training institute in Noida - Webtrackker Technology is IT Company which is providing the web designing, development, mobile application, and sap installation, digital marketing service in Noida, India and out of India. Webtrackker is also providing the sap fico training in Noida with working trainers.


    WEBTRACKKER TECHNOLOGY (P) LTD.
    C - 67, sector- 63, Noida, India.
    F -1 Sector 3 (Near Sector 16 metro station) Noida, India.

    +91 - 8802820025
    0120-433-0760
    0120-4204716
    EMAIL: info@webtrackker.com
    Website: www.webtrackker.com

    ReplyDelete
  13. Thanks For Sharing The Information The information Shared Is Very valuable Please keep updating us Time Just Went On reading The article Python Online Course AWS Online Course Devops Online Course DataScience Online Course

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Your post shows all your effort and great experience towards your work...Gained lots of Information from it, Keep Updating...
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  16. It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!
    iot course training in Guwahati

    ReplyDelete
  17. You actually make it look so easy with your performance but I find this matter to be actually something which I think I would never comprehend.highly informative and professionally written and I am glad to be a visitor of this perfect blog, thank youJava training in Chennai

    Java Online training in Chennai

    Java Course in Chennai

    Best JAVA Training Institutes in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  18. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.Very useful and informative content has been shared out here, Thanks for sharing it


    Azure Training in Chennai

    Azure Training in Bangalore

    Azure Training in Hyderabad

    Azure Training in Pune

    Azure Training | microsoft azure certification | Azure Online Training Course

    Azure Online Training

    ReplyDelete
  19. nice post had been shared by you thank you for sharing such kind of an interesting blogs. so keep on sharing such kind of an interesting blogs.


    AWS Course in Bangalore

    AWS Course in Hyderabad

    AWS Course in Coimbatore

    AWS Course

    AWS Certification Course

    AWS Certification Training

    AWS Online Training

    AWS Training

    ReplyDelete
  20. This blog is very nice to learn and easy to understand.Am really impressed about this blog,this is very useful for all the beginners.Mainly this blog is very useful for the college students and teachers to take a clear notes.
    For more information Visit
    Data Science Training In Chennai

    Data Science Online Training In Chennai

    Data Science Training In Bangalore

    Data Science Training In Hyderabad

    Data Science Training In Coimbatore

    Data Science Training

    Data Science Online Training

    ReplyDelete
  21. This is a wonderful article, Given so much info in ExcelR Machine Learning Course Pune it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    ReplyDelete