My Blog List

Tuesday, April 26, 2011

Selenium with AutoIt - Example

Many web applications contain HTML forms which interact with the user. The user is able to enter data in to the form fields and submit the data to a server. Selenium is able to handle form inputs such as entering text in text fields, selecting radio buttons, selecting a value from a drop-down menu and so on. Things get a little tricky when dealing with input form fields of type “file”, to allow users to browse for a file and attach the file to the HTML form and submit the file.

So, what is the problem?
I can’t seem to use Selenium Core to upload a file; 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.

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

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.

04import com.thoughtworks.selenium.Selenium;
06public 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) {}
14 //autoit executable is now waiting for a "Choose file" dialog to popup
16 //once the "Choose file" dialog is opened, the autoit will input the path and file name
17 }

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

Thanks for testing excellence guy....

1 comment:

  1. Thanks for sharing great information in your blog. Got to learn new things from your Blog . It was very nice blog to learn about Selenium