Sunday, May 6, 2012

Tracert - Visually trace the packet flow

Tracert - Visually trace the packet flow.

"Tracert" is a command line program to find number of hops between source and destination. Visual Trace display the hops in the google map, so that people understand the packet route easily.

http://www.yougetsignal.com/tools/visual-tracert/

To start the trace from your computer, type the desired domain and select "Proxy Trace".


---

Understanding cloud response time

Understanding cloud response time

There are many cloud hosting providers, in order to understand the effect of latency on distance select this link.
It provide global statistics from specific geographical locations, so that you can select the right cloud service provider based on your targeted geographical locations.


---

Saturday, May 5, 2012

Gartner report on Application Performance Monitoring(APM)

Magic Quadrant for Application Performance Monitoring(APM)

Gartner report on APM providers list.


APM technologies is subdivided into five dimensions of functionality:
(1)End-user experience monitoring
(2)Application runtime architecture discovery, modeling and display
(3)User-defined transaction profiling
(4)Component deep-dive monitoring in application context
(5)Application performance analytics


Magic Quadrant


For more details select this link

---

Wednesday, April 18, 2012

JavaScript - Generate random number(Integer) with in a range.

JavaScript - Generate random number(Integer) with in a range.

Recently I was working on Neoload script (Performance Testing) where I need to generate random number between 10 to 300.

Random number can be generated using random()
alert(Math.random()); // returns number like 0.98899988888

To generate integers with in the range, I have used following logic.

alert(randomXToY(10,300));
function randomXToY(minVal,maxVal,floatVal)
{
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

minVal - Minimum value
maxVal - Maximum value
floatVal - (Optional) Floating point digits. Value is not defined, it will round to integer value.


---

Friday, April 6, 2012

Webdriver - Timeouts

Webdriver - Timeouts

In webdriver there are three different kinds of time outs. Proper values should be assigned, so that your script run efficiently without waiting for too log or short when page is not loaded and element not preset.

Method Summary
 WebDriver.TimeoutsimplicitlyWait(long time, java.util.concurrent.TimeUnit unit)
          Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.
 WebDriver.TimeoutspageLoadTimeout(long time, java.util.concurrent.TimeUnit unit)
          Sets the amount of time to wait for a page load to complete before throwing an error.
 WebDriver.TimeoutssetScriptTimeout(long time, java.util.concurrent.TimeUnit unit)
          Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error.

Timeouts can also be implemented using TestNG @Test annotation

Example

driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);


Timeouts can also be implemented using TestNG @Test annotation
@Test(groups = { "SampleTest" }, enabled = true, timeOut = 9000)


driver.manage().timeouts().implicitlyWait(ImplicitWait,TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(PageLoadWait,TimeUnit.SECONDS); (Not implemented in IE)
driver.manage().timeouts().setScriptTimeout(AsyScripWait,TimeUnit.SECONDS);

Method Detail

implicitlyWait

WebDriver.Timeouts implicitlyWait(long time,
                                  java.util.concurrent.TimeUnit unit)
Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.When searching for a single element, the driver should poll the page until the element has been found, or this timeout expires before throwing aNoSuchElementException. When searching for multiple elements, the driver should poll the page until at least one element has been found or this timeout has expired.
Increasing the implicit wait timeout should be used judiciously as it will have an adverse effect on test run time, especially when used with slower location strategies like XPath.
Parameters:
time - The amount of time to wait.
unit - The unit of measure for time.
Returns:
A self reference.


setScriptTimeout

WebDriver.Timeouts setScriptTimeout(long time,
                                    java.util.concurrent.TimeUnit unit)
Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.
Parameters:
time - The timeout value.
unit - The unit of time.
Returns:
A self reference.
See Also:
JavascriptExecutor.executeAsyncScript(String, Object...)


pageLoadTimeout

WebDriver.Timeouts pageLoadTimeout(long time,
                                   java.util.concurrent.TimeUnit unit)
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.
Parameters:
time - The timeout value.
unit - The unit of time.
Returns:


Thursday, April 5, 2012

Webdriver - Can't Click On element

Webdriver - Can't Click On element

Can't Click On element?
Webdriver identified the element correctly, but the element is hidden or disabled so it can't click on it. This is built in validation in webdriver aka Selenium2, this kind of validation was not there in Selenium1.

This kind of validation is good, but some time I am not sure why it throws the error "Can't Click On element".

I came across a scenario where elements are visible on the screen and I am able to select it, but for Webdriver element is not displayed. Run the following statements to check how Webdriver is considering the element attributes.

System.out.println(driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).isDisplayed());

System.out.println(driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).isEnabled());

These kind of issues occur when there are dynamic changes on the screen using JavaScript, due to some reason Webdriver is not able to update the with the new attributes.

If the element was having an id, I would have run the following statement to click using JavaScript.


script = "document.getElementById('ctl00_cpheRFx_btnCriteriaAdd').click();";
((JavascriptExecutor) driver).executeScript(script);

I will explain my issue using below screenshot. When user select from the drop down, boxes appear on the screen, need to select the icons(Pointed in the screen shot). When I click using following state it says "Can't Click On element".

driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).click();


When verified the properties
.isDisplayed() = false
isEnabled() = true

Then I came to the conclusion that I can't use webdriver to click it as the built in validation block the code.
So started working on the click action using JavaScript. Below code resolved my problem. Carefully change the class names and regular expression as per your html.


String Script = "";
Script += "var elements = document.getElementsByTagName('img');";
Script += "var regex = new RegExp('^Copy Criterion');";
Script += "for(i=0;i<elements.length;i++){";
Script += "  if(elements[i].title.match(regex)){";
Script += "     elements[i].click();";
Script += "   }";
Script += "}";
((JavascriptExecutor) driver).executeScript(Script);


Now you got power to click any element on the screen.

Also read

Webdriver -  Issues with Sendkeys & Click

Webdriver - Select list box items
--


Wednesday, April 4, 2012

Webdriver - Store data on disk

Webdriver - Store data on disk.

There are situations where the data of the current test need to be used in the next test. In this scenario we can't store the values in variables, they are lost once the test is completed (Java program closed). It is advisable to store the data on disk using Java files.

Following are the two methods that are used to read and write data to the files.
I have used one single string where all the values are separated by ";". I can use split method to split the string into separate values.

public static void xFileWriteData(String FileName, String DataSemicolnSeperated) throws Exception   {
FileOutputStream out; 
PrintStream p; 
try
{
out = new FileOutputStream(FileName);
p = new PrintStream(out);
p.println (DataSemicolnSeperated); //Insert for loop if there is more than one line
p.close();
out.close();
}
catch (Exception e)
{
Print("Error writing to file");
}
}

public static String xFileReadData(String FileName) throws Exception   {
String DataSemicolnSeperated = null;
String Line;
try
{
BufferedReader br = new BufferedReader(new FileReader(FileName));
while ((Line = br.readLine()) != null) { 
DataSemicolnSeperated = Line;

br.close();

catch (Exception e)
{
Print("Error reading the file");
}
return DataSemicolnSeperated;
}


---- 

Webdiver - Developed in following language

Webdiver - Developed in following language

Select this link for more details


---

Tuesday, April 3, 2012

Webdriver - Not functioning or Missing clicks

Webdriver - Not functioning or Missing clicks.

I ran Webdriver code on different systems. There are instances where the code work fine in all the systems except 1 or 2 systems.
Following are the some of the solutions in this kind of scenario.

1. Files not copied properly or ant build file not created properly.

2. Browser zoom should be 100%. If it is more or less, clicks will fail.


3. When browser loose focus, sometimes clicks are not processed.

4. Browser to be operated in maximized mode. There are situation where Auto suggests values are not selected when working on not maximized mode.
JS code to maximize the browser

String script = "if (window.screen){window.moveTo(0,0);window.resizeTo(window.screen.availWidth,window.screen.availHeight);};"; 
((JavascriptExecutor) driver).executeScript(script);  

5. LAN settings to be Automatically detect settings

There are some of the trouble shooting areas.

Monday, April 2, 2012

Webdriver - How to handle UltraWebGrid

Webdriver - How to handle UltraWebGrid.

In my application to update any cell, use need to "DoubleClick" to get the cell focus and type the text. Initially I have used "SendKeys" and ".innerHTML" values get displayed on the screen, but they are not getting saved.

I have used below code to solve the issue.


Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")));
action.perform();
action.sendKeys(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")), "Bharath");
action.perform();
Wait(5000);
action.doubleClick(driver.findElement(By.id("ctl00_cpheRFx_lblComputed")));
action.perform();
Wait(5000);

driver.findElement(By.id("ctl00_cpheRFx_btnAddRow")).click();
Wait(5000);

UltraWebGrid Screen shot



---



Webdriver - Doubleclick an element

Webdriver - Doubleclick an element.

In order to perform there events we need to use actions class. Below is the sample code.


Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")));
action.perform();
action.sendKeys(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")), "Bharath");
action.perform();
Wait(5000);


---

Friday, March 30, 2012

Webdriver - Select list box items

Webdriver - Select list box items

HTML for the list box


I prefer using this code to select an option

driver.findElement(By.xpath("//select[@id='ctl00_cpheRFx_ddlCriteriaType']/option[@value='"+Value+"']"
)).click();

The below code also perform the same job

   WebElement ListBox = driver.findElement(By.id("ctl00_cpheRFx_ddlCriteriaType"));
   java.util.List<WebElement> options = ListBox.findElements(By.tagName("option"));
   for(WebElement option : options){
    Print(option.getText());
       if(option.getText().equals("Internal")){
           option.click();
           Print("Selected");
           break;
       }
   }


Above logic is not working for the below HTML (Below is the possible explanation)


There is one place where the IE driver does not interact with elements using native events. This is in clicking <option> elements within a<select> element. Under normal circumstances, the IE driver calculates where to click based on the position and size of the element, typically as returned by the JavaScript getBoundingClientRect() method. However, for <option> elements, getBoundingClientRect() returns a rectangle with zero position and zero size. The IE driver handles this one scenario by using the click() Automation Atom, which essentially sets the .selected property of the element and simulates the onChange event in JavaScript. However, this means that if the onChange event of the<select> element contains JavaScript code that calls alert(), confirm() or prompt(), calling WebElement's click() method will hang until the modal dialog is manually dismissed. There is no known workaround for this behavior using only WebDriver code.





I am getting empty values for "option.getText()". To over come this Webdriver limitation I have created following Java Script code.


var ListBox = document.getElementById('ctl00_cpheRFx_ddleRFxTitle');
var i;
for (i=0;i<ListBox.length;i++)
{
if (ListBox.options[i].text == 'S_05_56_52PM29_Mar_2012')
    {
    ListBox.options[i].selected ='1';
}

}


javascript:ddleRFxTitle_Change(); //To fire on change event, look at the HTML for better understanding

The same can be implemented in the Webdriver in the following way (I prefer this)


String Script = ""; Script += "var ListBox = document.getElementById('ctl00_cpheRFx_ddleRFxTitle');"; Script += "var i;"; Script += "for (i=0;i<ListBox.length;i++)"; Script += "{"; Script += " if (ListBox.options[i].text == '"+Title+"')"; Script += "{"; Script += "ListBox.options[i].selected ='1';"; Script += "}"; Script += "}"; ((JavascriptExecutor) driver).executeScript(Script); Wait(5000); Script = ""; Script += "javascript:ddleRFxTitle_Change();"; ((JavascriptExecutor) driver).executeScript(Script);



---

Thursday, March 22, 2012

Webdriver - Element Exist

Webdriver - Element Exist

I use following code to check whether an element exist.
.size() will provide the total number of elements. Make sure that your id or xPath will return the size as 1.

     if((driver.findElements(By.id("ctl00_cpheRFx_dgSuppliers_ctl0_lnkCompanyName")).size())== 1){
   
    }
    else {
    fail("Supplier Not Added Successfully");
    Print("Supplier Not Added Successfully");
     }

---- 

Monday, March 19, 2012

Webdriver - Type in FCKeditor

Webdriver - Type in FCKeditor

FCK editor is one of the complex object to handle through any automation tool.

After going through the page HTML, I have noticed two i frames. I have used following code to send message to FCK editor.



     driver.switchTo().frame(driver.findElement(By.id("ctl00_cpheRFx_Section_desc___Frame")));
    Print("Switched");
    driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@src='javascript:void(0)']")));
    Print("Switched1");    
    driver.findElement(By.xpath("//body[@contentEditable='true']"));
    WebElement editable = driver.switchTo().activeElement();
    editable.sendKeys("Selenium");
    //Inside iFrane, come back to main page
try
{
Set<String> availableWindows = driver.getWindowHandles();
Print("Handle Size:" +availableWindows.size());
//Retreive all the window handles into variables
String WindowIDparent= null, WindowIDModal = null;
int counter = 1;
for (String windowId : availableWindows) {
if (counter == 1){
Print(Integer.toString(counter)+" " + windowId);
WindowIDparent = windowId;
}
counter++;
}
//Navigate to Parent window
driver.switchTo().window(WindowIDparent);
Print("In the Parent");
Wait(2000);

}
catch (WebDriverException e)
{
e.printStackTrace();
Print("Issue in the Switch");
xKillIEs(); //driver.quit() not working with modal dialog
}


----

Webdriver - Mouse over events (Hover).

Webdriver - Mouse over events (Hover).

Read the following text from the webdriver team with respect to hovering problem.

When you attempt to hover over elements, and your physical mouse cursor is within the boundaries of the IE browser window, the hover will not work. More specifically, the hover will appear to work for a fraction of a second, and then the element will revert back to its previous state. The prevailing theory why this occurs is that IE is doing hit-testing of some sort during its event loop, which causes it to respond to the physical mouse position when the physical cursor is within the window bounds. The WebDriver development team has been unable to discover a workaround for this behavior of IE.

There are few objects and images on my web page where click() functionality is not working. I have taken lot of approaches, but the best solution found so far is below

     driver.findElement(By.xpath("//a[@id='Create']"));
    driver.findElement(By.xpath("//a[@id='Create']")).click();
The first statement will focus the element, next statement actually click the object.


I have another scenario where Image is displayed when I bring the mouse pointer on that row. To handle this situation I have used Actions class.

Below image shows display of icon when user bring the mouse pointer.


Webdriver code to click above pointed image.


Actions action = new Actions(driver);


action.moveToElement(driver.findElement(By.id("ctl00_CphePurchase_agvApprovalRequisitions$3$0$aReqNumber")));//id of requisition number
action.perform();


action.click(driver.findElement(By.id("ctl00_CphePurchase_agvApprovalRequisitions$3$0$imgBtnTrackStatus"))); //id of the image
action.perform();


Above code will not move the actual mouse pointer, but it will convey to IE that it has received a mouse input in that particular location.

For better understanding read the text from Jim (IE driver project lead).

Let me try to explain this. When simulating mouse movements with 
WebDriver, the actual mouse cursor does not move. Let me repeat that 
for emphasis. The actual physical mouse pointer on the screen *will* 
*not* *move*. If you are expecting that, you'll be disappointed. 

What WebDriver does on Windows is it sends the same messages to the IE 
window that it would receive from the input manager by the actual 
mouse. You won't see a change in the pointer on the screen, but if the 
element on the page responds to mouseover events, it should react as 
if you moved the mouse over it. 

The advantage here is that if something like an alert() method is 
called in the element's mouseOver event, WebDriver can still handle 
it. Additionally, it's a more accurate representation of the actual 
mouse movement, firing ancillary events like mouseEnter and so on. 
Contrast this approach with that of Selenium RC, which simply fires 
the mouseOver event directly via JavaScript. 

--Jim 

Still if you want to move the mouse pointer physically, you need to take different approach using Robot class


Point coordinates = driver.findElement(By.id("ctl00_portalmaster_txtUserName")).getLocation();
Robot robot = new Robot();
robot.mouseMove(coordinates.getX(),coordinates.getY()+120);

Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.

Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked.
In all browsers these are in event.screenX and event.screenY.

Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want.
In all browsers these are in event.clientX and event.clientY.

Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.

For more details select this link.



---

Thursday, March 15, 2012

Loadrunner - Short term web and mobile application testing.

Loadrunner - Short term web and mobile application testing.

Loadrunner can be used on shot term basis by purchasing the licence through HP OEM partners. For more details select below link.

www.orasicloudperform.com
www.j9tech.com
 Genilogix
ResultsPositive.

---

Wednesday, March 7, 2012

Webdriver - Keyword driven framework using page objects

Webdriver - Keyword driven framework using page objects.


Select this link.


---

Friday, March 2, 2012

SeleniumWebdriver - Page objects Implementation

SeleniumWebdriver - Page objects Implementation.

I have implemented complex QTP hybrid frameworks. Now I am working on Selenium2 aka. Selenium Webdriver and implemented the similar framework. Why? Open source, No licence fee, multi browser os language support.
I would like to share my experience through this post.

Following are the challenges that I came across during implementation.

1. Email Notifications of test results - Initially I have used Hudson CI to schedule the test and receive email notifications. IE Driver is not stable in few scenarios like Modal-Dialog, it keep on waiting for ever without moving ahead, user need to close the IEs and restart the test again. There is option of sending attachments through Hudson. So I started invoking the ANT using .VBS where I have better control of the execution and I can kill the process if it is not responding. Email notification component is written in VBS, where I can send email with attachments. Any .vbs file can be invoked easily through Java.

2. Building JAR file - You have option to execute the test directly on eclipse. When it is scheduled we need to compile all the files into a single JAR file so that it can be invoked using ANT and easily distributed to other systems. Build.xml is created to handle all these activities.

3. TestNG - Pass/Fail/Skipped test cases count is recorded using TestNG, but this report is generated after completion of all the methods. Lets assume we ran test for 10 hours, browser or Selenium don't respond; all your test results are lost. Implemented intermediate test status update using VBS, so that even the application crashed at-least I can get the results till the test executed.

4. Screenshot on Failure - Take screen shot and send it in the email along with the test results.

5. Backup the results - Before each run all the test results need to be copied in separate folder, so that results are not lot and can be verified in future. If do it manually, you may miss to copy the files.

6. Page Object Implementations - In QTP Page Objects Implementation is accomplished used dual function design. In Webdriver Page Objects are independent class where all the methods and locators of a particular page is kept in one class, this is the design feature which I like in Webdriver.

7. TestData - My project has lot of test data. Initially I have used TestNG xml and pass it as parameters. I felt it was difficult to maintain 100+ fields, so I have decided to create a new class for test data.

8. Test case log - Lets assume a single test case run for 30 min, how will you trace if some thing goes wrong in between? using logs. Statements are generated at important points like saved, deleted, ID=1234dd....

I started my carrier with Winrunner and love the Mercury Tours Site. This is the website on which I have learnt my first automation skills. All the page objects are created based on this site, any one can access this site.

Project folder structure screen shot below.

1. Package Mercury Tours - This is the base folder where Initilize.java, TC(Test Cases), SendEmail.Java files are stored.
Initilize.Java - File call Initilize.vbs that copies all the previous test results if there are any from ScreenShots and Test_reports folder to a backup folder.


package MercuryTours;

import java.io.File;
import org.testng.annotations.Test;

import MercuryTours.PageObjects.UtilityScript;

public class initilize extends UtilityScript {
@Test
public void Test_initilize_main() throws Exception {
File directory = new File (".");
try{Runtime.getRuntime().exec("wscript.exe "+directory.getCanonicalPath()+"\\initilize.vbs" );
}
 catch(Exception e){e.printStackTrace();
}
xKillIEs();
Wait(3000);
 }

}


2. TC(Test Cases) - Test case logic is written here by using page objects. All the test cases have separate files TC1, TC2....


package MercuryTours;

import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import MercuryTours.PageObjects.UtilityScript;
import MercuryTours.PageObjects._01_Initilize;
import MercuryTours.PageObjects._02_Login;
import MercuryTours.PageObjects._03_FindAFlight;
import MercuryTours.PageObjects._04_SelectAFlight;
import MercuryTours.PageObjects._05_BookAFlight;
import MercuryTours.PageObjects._06_FlightConformation;

//@Listeners({ p2pZions.TestNG.TestNGCustom.class, p2pZions.TestNG.TestNGCustomeListener.class })
public class MercuryTours_TC_01 extends UtilityScript {

InternetExplorerDriver driver;

@BeforeClass(alwaysRun = true)
protected void setUp() throws Exception {
driver = new InternetExplorerDriver();
}

@AfterClass(alwaysRun = true)
protected void tearDown() throws Exception {
driver.quit();
xKillIEs();
}

@Test(groups = { "MercuryToursTestCases" }, enabled = true)
public void Test_E2E_01() throws Exception {
MethodName = MethodName + "TC_01-";  //Used while sending email to report the test cases executed
Method = "TC_01"; //Used while sending email to report the test cases executed
Print("Start:" + xGetDateTimeIP());
_01_Initilize Initilize = PageFactory.initElements(driver,_01_Initilize.class);
Initilize.zOpen(Url);
_02_Login Login = PageFactory.initElements(driver,_02_Login.class);
Login.zEnterCrediantials("qtp123", "qtp123");
_03_FindAFlight FindAFlight = PageFactory.initElements(driver,_03_FindAFlight.class);
FindAFlight.zTripTypeOneWay();
FindAFlight.zNumberOfPassengers("4");
FindAFlight.zDepartingFrom("London");
FindAFlight.zDepartingOnDay("2");
FindAFlight.zDepartingOnMonth("2");
FindAFlight.zArrivingIn("Seattle");
FindAFlight.zFirstClass();
FindAFlight.zContinue();
_04_SelectAFlight SelectAFlight = PageFactory.initElements(driver,_04_SelectAFlight.class);
SelectAFlight.zDepartFlightSelection();
SelectAFlight.zContinue();
_05_BookAFlight BookAFlight = PageFactory.initElements(driver,_05_BookAFlight.class);
BookAFlight.zPassengerDetails("FirstName1", "LastName1", "HNML", "0");
BookAFlight.zPassengerDetails("FirstName2", "LastName2", "HNML", "1");
BookAFlight.zPassengerDetails("FirstName3", "LastName3", "HNML", "2");
BookAFlight.zPassengerDetails("FirstName4", "LastName4", "HNML", "3");
BookAFlight.zCardDetails("123456789111");
BookAFlight.zContinue();
_06_FlightConformation FlightConformation = PageFactory.initElements(driver,_06_FlightConformation.class);
FlightConformation.zGetConformationNumber();
FlightConformation.zLogOut();

}
}



3. SendEmail.Java - This file is used to call the SendEmail.vbs file with all the executed test cases (Variable MethodName)


package MercuryTours;

import java.io.File;

import org.testng.annotations.Test;

import MercuryTours.PageObjects.UtilityScript;

public class SendEmail extends UtilityScript {
@Test
public void Test_SendEmail_main() throws InterruptedException {
Wait(3000);
File directory = new File(".");
// Print(MethodName);
try {
Runtime.getRuntime().exec(
"wscript.exe " + directory.getCanonicalPath()
+ "\\sendemail.vbs " + MethodName);
} catch (Exception e) {
e.printStackTrace();
}
}

}



4. _01_initilize.java - This file is used to open the browser, open the URL and set the implicit timeouts.


package MercuryTours.PageObjects;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class _01_Initilize extends UtilityScript {

private WebDriver driver;

public _01_Initilize(WebDriver driver) throws InterruptedException {
this.driver = driver;
}

public _01_Initilize zOpen(String url) throws Exception {
driver.manage().timeouts()
.implicitlyWait(ImplicitWait, TimeUnit.SECONDS);
// Code to mazimize the window. Reason some times Auto suggest,some
// objects will fail if not maximized
String script = "if (window.screen){window.moveTo(0,0);window.resizeTo(window.screen.availWidth,window.screen.availHeight);};";
((JavascriptExecutor) driver).executeScript(script);
driver.get(url);
return this;
}

}


5. _02_Login.Java - All the locators pertaining to the login page. I group similar page objects into one group so I have used _01,_02.....


package MercuryTours.PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class _02_Login extends UtilityScript {
private WebDriver driver;

public _02_Login(WebDriver driver) throws InterruptedException {
this.driver = driver;
}

public _02_Login zEnterCrediantials(String UserNameTxt, String PasswordTxt)
throws InterruptedException {
Wait(3000);
driver.findElement(By.name("userName")).sendKeys(UserNameTxt);
driver.findElement(By.name("password")).sendKeys(UserNameTxt);
driver.findElement(By.name("login")).click();
Print("UserName:" + UserNameTxt);
Print("---Login");
Wait(3000);
return this;
}

}


6. _03_FindAFlight.java


package MercuryTours.PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class _03_FindAFlight extends UtilityScript {

private WebDriver driver;

public _03_FindAFlight(WebDriver driver) throws InterruptedException {
this.driver = driver;
}

public void zTripTypeOneWay() throws InterruptedException {
driver.findElement(By.xpath("//input[@value='oneway']")).click();
}

public void zTripTypeRoundTrip() throws InterruptedException {
driver.findElement(By.xpath("//input[@value='roundtrip']")).click();
}

public void zNumberOfPassengers(String Values_1to4)
throws InterruptedException {
driver.findElement(
By.xpath("//select[@name='passCount']/option[@value='"
+ Values_1to4 + "']")).click();
}

public void zDepartingFrom(String DepartingPlace)
throws InterruptedException {
driver.findElement(
By.xpath("//select[@name='fromPort']/option[@value='"
+ DepartingPlace + "']")).click();
}

public void zDepartingOnMonth(String Month_1to12)
throws InterruptedException {
driver.findElement(
By.xpath("//select[@name='fromMonth']/option[@value='"
+ Month_1to12 + "']")).click();
}

public void zDepartingOnDay(String Day_1to31) throws InterruptedException {
driver.findElement(
By.xpath("//select[@name='fromDay']/option[@value='"
+ Day_1to31 + "']")).click();
}

public void zArrivingIn(String ArrivingPlace) throws InterruptedException {
driver.findElement(
By.xpath("//select[@name='toPort']/option[@value='"
+ ArrivingPlace + "']")).click();
}

public void zReturningOnMonth(String Month_1to12)
throws InterruptedException {
driver.findElement(
By.xpath("//select[@name='toMonth']/option[@value='"
+ Month_1to12 + "']")).click();
}

public void zReturingOnDay(String Day_1to31) throws InterruptedException {
driver.findElement(
By.xpath("//select[@name='toDay']/option[@value='" + Day_1to31
+ "']")).click();
}

public void zEconomyClass() throws InterruptedException {
driver.findElement(By.xpath("//input[@value='Coach']")).click();
}

public void zBusinessClass() throws InterruptedException {
driver.findElement(By.xpath("//input[@value='Business']")).click();
}

public void zFirstClass() throws InterruptedException {
driver.findElement(By.xpath("//input[@value='First']")).click();
}

public _03_FindAFlight zContinue() throws InterruptedException {
driver.findElement(By.name("findFlights")).click();
Wait(3000);
return this;
}

}




7. _04_SelectAFlight.Java


package MercuryTours.PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


public class _04_SelectAFlight extends UtilityScript  {

    private WebDriver driver;
 
    public _04_SelectAFlight(WebDriver driver) throws InterruptedException {
    this.driver = driver;
    }

    public void zDepartFlightSelection () throws InterruptedException {
    //Implement logic to choose the flight based on Airline, Price
    //Selected Second option (ODD numbers 3 5 7 8 there are some blank divs between)
    driver.findElement(By.xpath("//tr[5]/td/input[@name='outFlight']")).click();
    }
 
    public void zReturnFlightSelection () throws InterruptedException {
    //Implement logic to choose the flight based on Airline, Price
    driver.findElement(By.xpath("//input[@name='inFlight'][1]")).click();
    }  
 
    public _04_SelectAFlight zContinue () throws InterruptedException  {
   driver.findElement(By.name("reserveFlights")).click();
   Wait(3000);
   return this;
    }  

}



8. _05_BookAFlight


package MercuryTours.PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class _05_BookAFlight extends UtilityScript  {

    private WebDriver driver;
 
    public _05_BookAFlight(WebDriver driver) throws InterruptedException {
    this.driver = driver;
    }

    public void zPassengerDetails (String FirstName, String LastName, String Meal, String IndexStartFrom0) throws InterruptedException {
    driver.findElement(By.name("passFirst"+IndexStartFrom0)).sendKeys(FirstName);
    driver.findElement(By.name("passLast"+IndexStartFrom0)).sendKeys(LastName);
    driver.findElement(By.xpath("//select[@name='pass."+IndexStartFrom0+".meal']/option[@value='"+ Meal +"']")).click();
    }
 
    public void zCardDetails (String CardNumber) throws InterruptedException {
    driver.findElement(By.name("creditnumber")).sendKeys(CardNumber);
    }  
 
    public _05_BookAFlight zContinue () throws InterruptedException  {
   driver.findElement(By.name("buyFlights")).click();
   Wait(3000);
   return this;
    }  

}



9. _06_FlightConformation

package MercuryTours.PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


public class _06_FlightConformation extends UtilityScript  {
    private WebDriver driver;
    
    public _06_FlightConformation(WebDriver driver) throws InterruptedException {
    this.driver = driver;
    }

    public void zGetConformationNumber () throws InterruptedException {
    Print(driver.findElement(By.xpath("//tr/td/b/font/font/b/font[1]")).getText());
    }
    
    public _06_FlightConformation zLogOut () throws InterruptedException  {
   driver.findElement(By.xpath("//tbody/tr/td[3]/a")).click();
   Print("---Logout---");
   Wait(3000);
   return this;
    }       
    

}



9. TestData.java

package MercuryTours.PageObjects;


public class TestData extends MercuryTours.TestNG.TestNGAssertionsCustom {
public static final String Url = "http://newtours.demoaut.com/";
public static final String UserName = "qtp123";
public static final String UserNameP = "qtp123";

//##################################################################################
// Don't change any thing below ####################################################
//##################################################################################
//Assigned variables****************************************************************
public static final int ImplicitWait =  5;
public static final int TimeOut10 =  10000;
public static final int TimeOut20 =  20000;

//Date Data*************************************************************************
//public static final String DateFormat = "dd.MM.yyyy_hh:mm a";
public static final String DateTimeFormat = "MM/dd/yyyy_hh:mm a";

//public static final String DateFormat = "dd.MM.yyyy";
public static final String DateFormat = "MM/dd/yyyy";
public static final String DateFormat1 = "MMM dd, yyyy";

//Non Assigned variables ***********************************************************

public static String NewDate, NewTime, Script, MethodName = "",Method="";
public static String Temp, Temp1,sMessages ="";

}

10. UtilityScript.java
There are lot of custom function written based on project requirement


package MercuryTours.PageObjects;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;

import org.testng.Reporter;

public class UtilityScript extends TestData {

// Get date time
public java.lang.String xGetDateTime() throws Exception {
// get current date time with Date() to create unique file name
DateFormat dateFormat = new SimpleDateFormat("hh_mm_ssaadd_MMM_yyyy");
// get current date time with Date()
Date date = new Date();
return (dateFormat.format(date));
}

// DateFormat = "MMM dd, yyyy";
public java.lang.String xGetDate(String DateFormat) throws Exception {
// get current date time with Date() to create unique file name
DateFormat dateFormat = new SimpleDateFormat(DateFormat);
// get current date time with Date()
Date date = new Date();
return (dateFormat.format(date));
}

// Get date time with SelText
public java.lang.String xGetDateTimeSel() throws Exception {
// get current date time with Date() to create unique file name
DateFormat dateFormat = new SimpleDateFormat("hh_mm_ssaadd_MMM_yyyy");
// get current date time with Date()
Date date = new Date();
return ("S_" + dateFormat.format(date));
}

// Get date time with System IP
public java.lang.String xGetDateTimeIP() throws Exception {
// get current date time with Date() to create unique file name
DateFormat dateFormat = new SimpleDateFormat("hh_mm_ssaa_dd_MMM_yyyy");
// get current date time with Date()
Date date = new Date();
// To identify the system
InetAddress ownIP = InetAddress.getLocalHost();
return (dateFormat.format(date) + "_IP" + ownIP.getHostAddress());
}

public static void Wait(int MilliSec) throws InterruptedException {
Thread.sleep(MilliSec);
}

public void Print(String Text) {
System.out.println(Text);
Reporter.log(Text);
String Temp = Text;
sMessages = sMessages + Temp.replaceAll(" ", "_") + "#";
//System.out.println(Temp);
//System.out.println(sMessages);
}

public java.lang.String xAddMinutesToTheDateTime(String Date_TimeFormat,
int NumberOfMinutes) throws InterruptedException, ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(DateTimeFormat);
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(Date_TimeFormat));
c.add(Calendar.MINUTE, NumberOfMinutes); // number of minutes
String str = sdf.format(c.getTime());
String delimiter = "_";
String[] temp;
temp = str.split(delimiter);
for (int i = 0; i < temp.length - 1; i++) {
NewDate = temp[i];
NewTime = temp[i + 1];
}
// Print(NewDate);
// Print(NewTime);

return (str); // dt is now the new date
}

public java.lang.String xAddDaysToTheDateTime(String CurrentDate,
int NumberOfDays, String DateFormat)
throws InterruptedException, ParseException {
SimpleDateFormat sdf = new SimpleDateFormat(DateFormat);
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(CurrentDate));
c.add(Calendar.DATE, NumberOfDays); // number of days
String str = sdf.format(c.getTime());
return (str); // dt is now the new date
}

public java.lang.String xGetCurrentDateEST(String DateFormat) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat(DateFormat);
dateFormat.setTimeZone(TimeZone.getTimeZone("EST5EDT"));
NewDate = dateFormat.format(new Date());
return (NewDate);
}

public java.lang.String xGetCurrentTimeEST() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a");
dateFormat.setTimeZone(TimeZone.getTimeZone("EST5EDT"));
NewTime = dateFormat.format(new Date());
return (NewTime);
}

public void xKillIEs() throws Exception {
// I felt this is not closing the IEs effectively, so started relaying
// on VB script
Wait(3000);
/*
* final String KILL = "taskkill /IM "; String processName =
* "iexplore.exe"; // IE process Runtime.getRuntime().exec(KILL +
* processName);
*/

File directory = new File(".");
try {
Runtime.getRuntime().exec(
"wscript.exe " + directory.getCanonicalPath()
+ "\\KillIEs.vbs");
} catch (Exception e) {
e.printStackTrace();
}
Wait(5000); // Allow OS to kill the process
}

public boolean xFileExist(String FileNameWithPath) throws Exception {
java.io.File myDir = new java.io.File(FileNameWithPath);
if (myDir.exists()) {
Print("file exist");
return true;
} else {
Print("file does not exist");
assertTrue(false);
return false;
}
}

public void xMakeFileCopy(String NewFileNameWithPath,
String FileNameWithPath) throws Exception {
java.io.File base = new java.io.File(FileNameWithPath);
java.io.File newfile = new java.io.File(NewFileNameWithPath);
if (xFileExist(FileNameWithPath)) {
FileUtils.copyFile(base, newfile);
} else {
Print("file does not existcould not copy");
assertTrue(false);
}
if (xFileExist(NewFileNameWithPath)) {
Print("file copied sucessfully");
}

}

public void xDeleteFile(String FileNameWithPath) throws Exception {
java.io.File file = new java.io.File(FileNameWithPath);
if (xFileExist(FileNameWithPath)) {
FileUtils.deleteQuietly(file);
Print("File Deleted Successfully");
} else {
Print("file does not exist.Could not Delete");
// assertTrue(false);
}
}

public static void xScreenShot() {
try {

String NewFileNamePath;

java.awt.Dimension resolution = Toolkit.getDefaultToolkit()
.getScreenSize();
Rectangle rectangle = new Rectangle(resolution);

// Get the dir path
File directory = new File(".");
// System.out.println(directory.getCanonicalPath());

// get current date time with Date() to create unique file name
DateFormat dateFormat = new SimpleDateFormat(
"MMM_dd_yyyy__hh_mm_ssaa");
// get current date time with Date()
Date date = new Date();
// System.out.println(dateFormat.format(date));

// To identify the system
InetAddress ownIP = InetAddress.getLocalHost();
// System.out.println("IP of my system is := "+ownIP.getHostAddress());

NewFileNamePath = directory.getCanonicalPath() + "\\ScreenShots\\"
+ Method + "___" + dateFormat.format(date) + "_"
+ ownIP.getHostAddress() + ".png";
System.out.println(NewFileNamePath);

// Capture the screen shot of the area of the screen defined by the
// rectangle
Robot robot = new Robot();
BufferedImage bi = robot.createScreenCapture(new Rectangle(
rectangle));
ImageIO.write(bi, "png", new File(NewFileNamePath));
NewFileNamePath = "<a href=" + NewFileNamePath + ">ScreenShot"
+ "</a>";
// Place the reference in TestNG web report
Reporter.log(NewFileNamePath);

} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void xUpdateTestDetails(String Status) throws Exception   {
File directory = new File(".");
String Temp = Method + "_" + Status;
if (Method != ""){
try {
Runtime.getRuntime().exec(
"wscript.exe " + directory.getCanonicalPath()
+ "\\UpdateTestDetails.vbs "+ Temp + " " + sMessages);
Method = "";
sMessages = "";
} catch (Exception e) {
e.printStackTrace();
}
}
Wait(5000); // Allow OS to kill the process
}

}
 


In Progress...