My Blog List

Sunday, March 27, 2011

ActiveX OLE COM Objects used in Automation


Have listed some of the often used objects while automating using QTP and other tools...


  • FileSystemObject - File system operations
  • Scripting.Dictionary - Dictionary to store/read values in key-value pairs
  • Excel.Application - Excel application
  • Word.Application - Word application
  • Wscript.Shell - Command prompt
  • cdo.message - To send email
  • AcroExch.PDDoc & AcroExch.App - PDF Access but need to be AdobeAcrobat installed.
  • Microsoft.XMLDOM - To read/parse XML doc
  • ADODB.Connection & ADODB.RecordSet - To connect/read/write database
  • System.Collections.ArrayList - To create/read/write array lists
  • InternetExplorer.Application - Internet Explorer browser
  • Microsoft.XMLHTTP - HTTP to send request/get response


Automation Object Models -QTP:
1. QuickTest.Application
2. QuickTest.TestLibaraies like for every Dialog in UI of QTP application which contains options that we can modify will have a AOM object. We can use that to handle in script dynamically


Welcome all to share objects like these. It will help a lot in automation....

Handling Dialogs in Selenium Automation


According to me Selenium is one of the best open source, free tool for testing web applications. It's quite powerful and gives you the facility to write down your test case in your favorite language ( from the plenty of languages it supports ). But it sucks when it comes to handle the dialogs. Dialog boxes are like ghosts to selenium, It can't even see them.

That's because dialogs are native to the operating system you are running and selenium are designed to identify only web component.

After searching too much on the Internet and other forums, I finally got the solution to all my problems. The solution is too simple. As you can't handle the dialog box through selenium, use the other software to do this. And AutoIT is best at this.

Download Execuable (exe) to Handle Save Dialog of Firefox

Download Execuable (exe) to Handle Save Dialog of Internet Explorer

Download Execuable (exe) to Handle Authentication Dialog


User Name and password dialog box


AutoIt
Autoit is a free scripting language designed to automate the windows component. It's just like an extensive VB Script and it allows you to convert the script in executable (exe). So what you can do is, write down the script to handle dialog box using AutoIt, convert it into executable and then call the executable when required. So let's see guys how to do it. But before we begin you need to downloadand install the Autoit. Download it from the following link
Download AutoIt


Handling alertbox
Alertbox is special kind of modal dialog created though JavaScript. As it's modal dialog box the things in the parent window will not be accessible until close it.

selenium provides the method to handle the alertbox, It will click on the OK button of the alertbox and will return the text of the alertbox to verify. However it will not able to identify the alertbox if it has appeared through page load event. ( i.e. should not appeared when you navigate to site or when refresh it).


Handle Alertbox at page load event
Selenium is not able to indentify the dialogs appeard at the pageload event. look at this.

So we tried to click on the OK button with AutoIt script. I make the Autoit script, not a big was just three line code and tested it with both the browser and it did well. But when I call the same script (exe) from my testcase it fails to indentify the alertbox and my testcase failed. I am still finding out why the hell this is happening.
Following is the script to handle alertbox appeard at body load event.


AutoItSetOption("WinTitleMatchMode","2")
WinWait($CmdLine[1])
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
MsgBox(0,"",$title)
WinActivate($title)
WinClose($title);


Confirmbox
Confirm box is a kind of alertbox with OK and Cancel button as compared to only OK button in alerbox.
Selenium provides following APIs to handle this.

chooseOkOnNextConfirmation() - This will click on the OK button if the confirm box appears after executing the very next step.
chooseCancelOnNextConfirmation() - This will click on the cancel button if the confirm box appears after executing the very next step.

You need to write down any of the above functions (depends on you requirement, ofcourse) just before the step which opens the confirmbox.

import org.testng.annotations.*;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class Handle_Alert {
   private Selenium selenium;
  @BeforeClass
    public void startSelenium() {
    selenium = new DefaultSelenium("localhost", 4444, "*chrome","http://gaurangnshah.googlepages.com/");
    selenium.start();
  }
@AfterClass(alwaysRun=true)
 public void stopSelenium() {
   this.selenium.stop();
  }
@Test
public void handleAlert() throws Exception{
  selenium.open("selenium_test");
  selenium.click("Alert");
  String a = selenium.getAlert();
  System.out.println(a);
 }

@Test
public void handleConfirmBox() throws Exception {
selenium.open("selenium_test");
selenium.chooseCancelOnNextConfirmation();
selenium.click("Confirm");
}

}


Handing Modal Dialogs
Modal Dialog box mean once it has appeared all the focus of that application will be on that dialog box only. You will not able to access any of the other component of parent window until you close the dialog box.

Some of the modal dialog boxes that we face frequently during web application testing are


Save Dialog Box
Save dialog box is bit different in IE and in Firefox. So I have write down two separate script for that.

AutoIt script to handle Firefox Save Dialog box
In Firefox when you click on the button/link to download a file. First it will ask you for you permission once you select yes, If you have selected to ask you for the path then only a dialog box will display.

If you will click on download link following dialogbox will appear in Firfox.

If you click "Save File" on above dialogbox this dialog box will apppears, Yeah if you have choose to ask where to save file from Option.

The executable and the script below will handle both of these dialogboxes. You just need to call it in proper way. Your need to pass arguments while calling the script or executable as following.
Save_Dialog_FF Operation FilePath
Operaion: Operation you want to perform when dialog box appears. Can be any of the following
cancel: Press Cancel on the dialog box
Save: Press the Save as Dialog box
FilePath: It's an option argument. It's a full path where you want to save the file.

i.e. C:\myfile.txt


AutoItSetOption("WinTitleMatchMode","2")
if $CmdLine[0] < 2 then
msgbox(0,"Error","Supply all the Arguments, Dialog title,Save/Cancel and Path to save(optional)")
Exit
EndIf


WinWait($CmdLine[1]) ; match the window with substring
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
WinActive($title);
If (StringCompare($CmdLine[2],"Save",0) = 0) Then
WinActivate($title)
WinWaitActive($title)
Sleep(1)
send("{TAB}")
Send("{ENTER}")
if ( StringCompare(WinGetTitle("[active]"),$title,0) = 0 ) Then
WinActivate($title)
send("{TAB}")
Send("{ENTER}")
EndIf

if WinExists("Enter name") Then
$title = WinGetTitle("Enter name")
if($CmdLine[0] = 2) Then
WinActivate($title)
ControlClick($title,"","Button2")
Else
WinActivate($title)
WinWaitActive($title)
ControlSetText($title,"","Edit1",$CmdLine[3])
ControlClick($title,"","Button2")
EndIf

Else
Exit
EndIf

EndIf

If (StringCompare($CmdLine[2],"Cancel",0) = 0) Then
WinWaitActive($title)
Send("{ESCAPE}")
EndIf


Now you just need to copy and paste above scripts in Autoit IDE, convert those into executables, Save those to the project folder. And then just make a call to the executables with proper arguments, just before you execute the step which invokes the dialog box as shows here.


import org.testng.annotations.*;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;


public class Handle_Dialogs {
private Selenium selenium;
@BeforeClass
public void startSelenium() {
selenium = new DefaultSelenium("localhost", 4444, "*chrome","http://www.autoitscript.com/");
selenium.start();
}

@AfterClass(alwaysRun=true)
  public void stopSelenium() {
 this.selenium.stop();
}


@Test
public void handleSaveDialog() throws Exception {
String[] dialog;
selenium.open("/site/autoit/downloads/");
selenium.waitForPageToLoad("3000");
selenium.click("//img[@alt='Download AutoIt']");
Thread.sleep(2000);
String browser = selenium.getEval("navigator.userAgent");
if(browser.contains("IE")){
System.out.print("Browser= IE "+browser);
dialog = new String[]{ "Save_Dialog_IE.exe","Download","Save" };
Runtime.getRuntime().exec(dialog);
}

if(browser.contains("Firefox")){
System.out.print("Browser= Firefox "+browser);
dialog = new String[] { "Save_Dialog_FF.exe","Opening","save" };
Runtime.getRuntime().exec(dialog);
  }
 }
}


User Name and Password Dialog Box.

Following is the AutoIt script to handle to User name and password dialog box.

AutoItSetOption("WinTitleMatchMode","2")
if $CmdLine[0] < 3 then
msgbox(0,"Error","Supply all the Arguments, Dialog title User Name, Password")
Exit
EndIf


WinWait($CmdLine[1]) ; match the window with substring
$title = WinGetTitle($CmdLine[1]) ; retrives whole window title
ControlSend($title,"","Edit2",$CmdLine[2]);Sets User Name
ControlSend($title,"","Edit3",$CmdLine[3]);Sets Password
ControlClick($title,"","OK");



Thanks to Gaurang Shah for this post.....

Handling PopupWindows, modal dialogs etc

If your application has a link or a button which opens a new window, and you want to perform some action on the newly opened window though selenium, it's not that hard to handle if you have title, name or the variable associated with that window.

However this is not the case always, sometime you don’t have name of the window or any variable associated with it, and you are not even able able to identify window using title, at the time selenium sucks to identify the window. However there are some alternative ways to resolve this (which might work, not sure). But before we see that let’s see how to select the windows that can be identified easily.

Select window using SelectWindow API


When SelectWindow API fails to Identify Window

Select window using SelectWindow API
Selenium provides the selectWindow API which takes any of the following argument to identify the window.
Title: Use whatever appears on title bar of the window you want to select as argument to selct window API.
However be careful while using title to select the window. Because it may happen that multiple windows have same titles.And in this case Selenium just says that it will choose one, but doesn't mention which one. If this is the case where both have same title I would suggest not to use the title for selecting window. And sometimes the titles of windows are dynamic, and that may create some extra noise.

Name: You can use windows name to identify the window.
For example if the code to open a new window is like as below.

window.open("http://google.co.in","Google Window");

(The second parameter here is windows name. Developer uses this to identify the window in order to use that in further part of the coding.)

You can use "Google Window" as the argument to selectWindow, to select the window as shown below if the code to open the window is as shown above.
1.selenium.selectWindow("Google Window"); // select new window
2.//Do whatever you want to do on new window
3.Selenium.close(); //Close the newly opened window
4.selenium.selectWindow(null); //To choose the original window back.

Variable name: If opened window is assigned to some variable you can use that variable to identify and select that window.

For example if the code to open a new window is like as below.

GoogleWindow = window.open("http://google.co.in");

You can use "GoogleWindow" as argument to SelectWindow API, to select the window as shown in the code.
view sourceprint?
1.selenium.waitForPopUp("GoogleWindow""30000");
2.selenium.selectWindow("GoogleWindow");
3.//Execute steps on new window
4.selenium.close(); //close the new window
5.selenium.selectWindow("null"); // select original window.

Using inbuilt API to retrieve Windows Names, Titles and IDs
Selenium provides some APIs to find out the names, Titles and IDs of the all opened windows. So you can use this APIs with SelectWindow API to select the window.

getAllWindowNames() – this will return you the array of all the opened windows names.
getAllWindowTitles() - this will return you the array of all the opened windows names.
getAllWindowIDs() - this will return you the array of all the opened windows names.

So if you have opened only single window you can use something like this to select the newly opened window.
view sourceprint?
1.selenium.selectWindow(getAllWindowNames()[1]);
OR
view sourceprint?
1.selenium.selectWindow(getAllWindowTitles()[1]);
OR
view sourceprint?
1.selenium.selectWindow(getAllWindowIDs ()[1]);

When SelectWindow API fails to Identify Window
Sometimes it happens that you use all the things to select the window but it fails to identify the windows. At the time you can use one of the following ways

Check the selenium logs.
The document of the selectWindow API says that if selenium is not able to identify the window after using all the things mention above you should check out for the window name in selenium log. To do that just start your selenium server with –log argument, something like following:

Java – jar path of selenium-server.jar –log log.txt

Write down the test case to open the window and execute it. Now shutdown the selenium server and checkout the logs for something like this.

Debug: window.open call intercepted; window ID
If you find this you can use this window ID to identify and select the window as the argument to selectWindow API.


Selecting the Window Using openWindow API
Sometimes selenium is not able to identify the window, one of the case is when the window is opened through onload event. Something likes this

<body onload='window.open("http://google.co.in");'>

In this case you can force selenium to identify the window using openwindow command, with URL as blank and name as you like.
view sourceprint?
1.Selenium.openWindow("","MyWindow");
2.selenium.selectWindow("MyWindow");

But if your window is not opening through onload event, and though selenium is not able to select the window after doing all the above things. The only thing left is to open the window using openwindow API with URL same as it would be if would have been opend through button or link click and name as you like. Something like as below.
view sourceprint?
1.Selenium.openWindow("http://google.co.in","MyWindow");
2.Selenium.selectWindow("MyWindow")