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.
1 | WinWaitActive( "Choose file" ) |
2 | Send( "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.
03 | import java.io.IOException; |
04 | import com.thoughtworks.selenium.Selenium; |
06 | public class AddAttachment { |
07 | public static void attach(Selenium selenium, String fileName) { |
09 | String[] commands = new String[]{}; |
10 | commands = new String[]{ "c:\\test\\attachFile.exe" }; |
11 | Runtime.getRuntime().exec(commands); |
12 | } catch (IOException e) {} |
15 | selenium.click( "name=browseButton" ); |
The above seems to be the easiest way to deal with file uploads and attachments using Selenium.
Thanks for testing excellence guy....
Comments
Post a Comment