Web code samples

Send keystrokes to the AUT (Windows only)

// Describe the search edit field 
EditField ef = browser.describe(EditField.class, new EditFieldDescription.Builder()
.type("text").tagName("INPUT").name("_nkw").build());
       
// Type "ft" in the search box
ef.setValue("ft");
       
// Use the Mouse class to click on the edit field 
java.awt.Point abs = ef.getAbsoluteLocation();
java.awt.Point p = new java.awt.Point(abs.x + 5, abs.y + 5);
Mouse.click(p);
       
// Use the Keyboard class to send the Enter key
Keyboard.pressKey((byte)28);

Back to top

Navigate to a web site

This example uses the Assert command to verify navigation to a web site.

@Test
public void verify_linkNavigatesToAboutTravelSite() throws Exception {			
 //Launch the Chrome browser.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);

 // Use try-catch to add a warning to the run report if the assert validation fails.      
 try{			
  // Navigate to the New Tours website.
  browser.navigate("http://newtours.demoaut.com/");
			
  // Click the "Business Travel @ About.com" link (in the bottom-right corner of the page).			
  browser.describe(Link.class, new LinkDescription.Builder()			
  .tagName("A").innerText("Business Travel @ About.com").build()).click();
            			
  // Wait for the browser to complete the navigation.			
  browser.sync();          
			
  // Enclosing the assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.
 
  // Verify that the correct Web page opens.			
  assertEquals("http://businesstravel.about.com/?PM=78_101_T&cob=home", browser.getURL());			
 }			
 catch(AssertionError e){			
  // Adds a step to the results report on failure.
  Reporter.reportEvent("Verify_AboutOpensCorrectly","Failed during validation",Status.Failed, e);			
  throw e;			
 }			
 finally{			
  browser.close();			
 }			
}

Back to top

Access Web objects in a tab opened by the AUT

LeanFTrecognizes browser windows and tabs that it opens (for example, via BrowserFactory.Launch).

However, if a browser is opened outside of the LeanFTcontext, you need to use the Attach method to acquire the IBrowser Interface instance for the browser tab or window.

For example, you need to attach a browser if:

  • You open a browser manually while setting up a scenario prior to running a LeanFT test
  • A step in your test clicks a link that opens a new or replacement browser tab or window

This example attaches a newly opened browser tab.

@Test
public void Verify_AboutOpensCorrectly() throws Exception{
				
 //Launch the Chrome browser.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);
        				
 // Use try-catch to add a warning to the run report if the assert validation fails.
 try{				
  // Navigate to the New Tours website.  				
  browser.navigate("http://newtours.demoaut.com/");
				
  // Click the "Cruises" link (on the left side of the page).				
  browser.describe(Link.class, new LinkDescription.Builder()				
  .tagName("A").innerText("Cruises").build()).click();            
				
  // Attach the new (replacement) browser tab.
  Browser aboutTab = BrowserFactory.attach(new BrowserDescription.Builder().title("Cruises: Mercury Tours").build());
				
  // Create a description for the page title.
  WebElement aboutTitle = aboutTab.describe(WebElement.class, new WebElementDescription.Builder()				
  .tagName("LI").innerText("Cruises").index(0).build());            
				
  // Enclosing the assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false. 

  // Validate that a page title exists.				
  assertTrue(aboutTitle.exists());				
 }				
 catch(AssertionError e){				
  // Adds a step to the results report on failure.
  Reporter.reportEvent("Verify_AboutOpensCorrectly","Failed during validation",Status.Failed, e);				
  throw e;				
 }				
 finally{				
  browser.close();				
 }				
}			

Back to top

Use Assert to verify edit fields

This example validates the status of edit fields for logon credentials after inserting the credentials at least once.

@Test
public void verify_UserCanEnterCredentialsAfterSignOff() throws Exception {
			
 // Navigate to the New Tours website.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);			
 browser.navigate("http://newtours.demoaut.com/");       
			
 // Use try-catch to add a warning to the run report if the assert validation fails. 
 try{			
  // Log on to the web site.
  EditField username = browser.describe(EditField.class, new EditFieldDescription.Builder()			
  .type("text").name("userName").build());			
  EditField password = browser.describe(EditField.class, new EditFieldDescription.Builder()			
  .type("password").name("password").build());          
			
  username.setValue("mercury");			
  password.setValue("55940fd62c96a30a62b4ab4d3db57c430de69cde");			
  browser.describe(Image.class, new ImageDescription.Builder()			
  .alt("Sign-In").type(com.hp.lft.sdk.web.ImageType.BUTTON).tagName("INPUT").build()).click();
            			
  // Log off.			
  browser.describe(Link.class, new LinkDescription.Builder()			
  .innerText("SIGN-OFF").build()).click();           
			
  // Enclosing the assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Verify that user name and password fields are writable after logging off.			
  assertFalse(username.isReadOnly());			
  assertFalse(password.isReadOnly());			
 }			
 catch(AssertionError e){			
  // Adds a step to the results report on failure. 
  Reporter.reportEvent("verify_UserCanEnterCredentialsAfterSignOff","Failed during validation",Status.Failed, e);			
  throw e;			
 }			
 finally{			
  browser.close();			
 }			
}

Back to top

Identify an object by its XPath

This example will use a label's XPath to locate it and verify that the text represents the current date.

@Test
public void verify_CurrentDateIsPresented() throws Exception {			
 // Suppose you want to verify that the AUT's home page displays today's date, but the date label does not have identification properties, and the text is dynamic.
 // You can use the label's XPath to locate it and verify that the text represents the current date.

 //Open the Chrome browser.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);
			
 // Use try-catch to add a warning to the run report if the assert validation fails. 
 try			
 {			
  // Navigate to the New Tours website. 			
  browser.navigate("http://newtours.demoaut.com/");
			
  // Locate the label using its XPath.
  WebElement dateLabel = browser.describe(WebElement.class,  			
   new XPathDescription("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/form/table/tbody/tr[1]/td/font/b"));
		
  // Convert the date into a Java object.
  DateFormat df = new SimpleDateFormat("MMM d, yyyy",Locale.ENGLISH);			
  Date presentedDate = (Date) df.parse(dateLabel.getInnerText().trim());;           
			
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Verify that today's date matches the date displayed.
  Date currentDate = new Date();         
			
  // Enclosing the assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.
            			
  assertEquals(currentDate.getDate(),presentedDate.getDate());			
 }			
 catch(AssertionError e){			
  // Adds a step to the results report on failure.
  Reporter.reportEvent("verify_CurrentDateIsPresented","Failed during validation",Status.Failed, e);			
  throw e;			
 }			
 finally{			
  browser.close();			
 }			
}		

Back to top

Identify an edit box via a CSS selector

This example shows how to verify that a suggestion box opens when a value is entered in a search box.

It includes:

  • Firing an event that triggers the opening of a suggestion box
  • Identifying the suggestion box using a CSS selector
  • Using a WaitUntil statement to ensure that the suggestion box opens before continuing
  • Using an Assert command to validate that the suggestion box opens
  • Using a try-catch statement to add a message to the report if the validation fails
@Test
public void verify_SearchSuggestionsAreOpenUponUserInput() throws Exception{
				
 //Launch the Chrome browser and navigate to the web site.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);				
 browser.navigate("http://www.google.com");       
				
 // Use try-catch to add a warning to the run report if the assert validation fails.
 try				
 {				
  // Enter the value "LeanFT" in the search box.
  EditField search = browser.describe(EditField.class,new EditFieldDescription.Builder().name("q").build());				
  search.setValue("LeanFT");           
				
  // Simulate a single key down event to trigger the opening of the suggestion box.				
  search.fireEvent(EventInfoFactory.createEventInfo("onkeydown"));
				
  // Wait until the suggestion box opens.
  WebElement suggestions = browser.describe(WebElement.class,new CSSDescription(".sbsb_a"));				
  WaitUntilTestObjectState.waitUntil(suggestions,new WaitUntilEvaluator<WebElement>(){				
   public boolean evaluate(WebElement suggestionBox){				
    try{				
     return suggestionBox.exists() && suggestionBox.isVisible();                                    				
    }				
    catch(Exception e){				
     return false;				
    }				
   }				
  });
            				
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Use Assert to verify that the suggestion box exists.				
  assertTrue(suggestions.exists());				
  assertTrue(suggestions.isVisible());				
 }				
 catch(AssertionError e){				
  // Adds a step to the results report on failure.
  Reporter.reportEvent("verify_SearchSuggestionsAreOpenUponUserInput","Failed during validation",Status.Failed, e);				
  throw e;				
 }				
 finally{				
  browser.close();				
 }				
}			

Back to top

Retrieve and sort list items

This example shows how to retrieve a list from a combo box and sort the results.

The test will:

  1. Sign in to the AUT.
  2. Retrieve the list of departure cities.
  3. Sort the list by the city name.
  4. Verify that both the original list and the sorted one are identical.
@Test
public void verify_departureListIsSorted() throws Exception {			
 //Open the Chrome browser.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);
			
 // Use try-catch to add a warning to the run report if the assert validation fails. 
 try			
 {			
  //Navigate to the New Tours website. 			
  browser.navigate("http://newtours.demoaut.com/");
			
  //Log on to the web site.			
  signIn(browser);
			
  // Retrieve a list of departure cities.
  ListBox departureCombo = browser.describe(ListBox.class,new ListBoxDescription.Builder().tagName("SELECT").name("fromPort").build());
            			
  //Sort the list of cities.
  List<ListItem> departureCities = departureCombo.getItems();			
  List<ListItem> sortedList = new ArrayList<ListItem>(departureCities); 			
  Collections.sort(sortedList, new Comparator<ListItem>(){
			
   @Override
   public int compare(ListItem arg0, ListItem arg1) {			
    try {			
     return arg0.getText().compareToIgnoreCase(arg1.getText());			
    } catch (GeneralLeanFtException e) {			
     // TODO Auto-generated catch block			
     e.printStackTrace();			
     return 0;			
    }			
   }			
  });            
			
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Compares the two lists to verify that the data is identical.			
  assertEquals(departureCities, sortedList);			
 }			
 catch (AssertionError e)			
 {			
  // Adds a step to the results report on failure.
  Reporter.reportEvent("verify_CitiesAreSorted", "Validation Failed", Status.Failed, e);			
  throw e;			
 }			
 finally			
 {			
  browser.close();			
 }			
}		

Back to top

Retrieve and validate table values

This example will validate values in a table in the main page of the application.

@Test
public void verify_PriceIsPresentedInTheSpecialOffers() throws Exception {				
 //The test checks each row in the "special offers" table and verifies that the currency values are listed in dollars.

 //Open the Chrome browser.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);
        				
 // Use try-catch to add a warning to the run report if the assert validation fails.   
 try				
 {				
  // Navigate to the New Tours website.				
  browser.navigate("http://newtours.demoaut.com/");
				
  Table specialOffers = browser.describe(Table.class,new TableDescription.Builder().tagName("TABLE").index(9).build());
				
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Verify the currency values are listed in dollars.
  for (TableRow offer : specialOffers.getRows())				
  {				
   assertTrue(offer.getCells().get(1).getText().startsWith("$"));				
  }				
 }				
 catch(AssertionError e){				
  // Adds a step to the results report on failure.
  Reporter.reportEvent("verify_PriceIsPresentedInTheSpecialOffers","Failed during validation",Status.Failed, e);				
  throw e;				
 }				
 finally{				
  browser.close();				
 }				
}			

Back to top

Verify a suggestion box contains values

This example shows how to verify that a suggestion box contains suggestions. This test:

  1. Navigates to the AUT.
  2. Opens the suggestion box from the search box.
  3. Waits until the suggestion box opens.
  4. Verifies that the suggestion box contains at least one suggestion.
@Test
public void verify_SearchSuggestionsAreOpenUponUserInputAndShowsSuggestions() throws Exception{			
 //Launch the Chrome browser and navigate to the web site.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);			
 browser.navigate("http://www.google.com");
			
 // Use try-catch to add a warning to the run report if the assert validation fails.
 try			
 {			
  // Enter the value "LeanFT" in the search box.
  EditField search = browser.describe(EditField.class,new EditFieldDescription.Builder().name("q").build());			
  search.setValue("LeanFT");
            			
  // Simulate a single key down event to trigger the opening of the suggestion box.			
  search.fireEvent(EventInfoFactory.createEventInfo("onkeydown"));
			
  // Identify the suggestion box using a CSS selector and wait until the suggestion box opens.
  WebElement suggestions = browser.describe(WebElement.class,new WebElementDescription.Builder().cssSelector(".sbsb_a").build());			
   WaitUntilTestObjectState.waitUntil(suggestions,new WaitUntilEvaluator<WebElement>(){			
   public boolean evaluate(WebElement suggestionBox){			
    try{			
     return suggestionBox.exists() && suggestionBox.isVisible();                                    			
    }			
    catch(Exception e){			
     return false;			
    }			
   }			
  });
            			
  WebElement[] suggestionList = suggestions.findChildren(WebElement.class, new WebElementDescription.Builder().tagName("LI").build());
         			
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Verify that the suggestion box exists and contains content.			
  assertTrue(suggestions.isVisible());			
  assertTrue(suggestionList.length > 0);			
 }			
 catch(AssertionError e){			
  // Adds a step to the results report on failure.
  Reporter.reportEvent("verify_SearchSuggestionsAreOpenUponUserInput","Failed during validation",Status.Failed, e);			
  browser.close();			
  throw e;			
 }			
}		

Back to top

Identify an object using Visual Relation Identifiers (VRI)

This example signs in to the AUT and checks the edit field values using visual relation identifiers.

Since the edit fields are automatically generated IDs we cannot use the identification properties.

@Test
public void Verify_SignInIsAvailable() throws Exception{			
 //Open the Chrome browser and navigate to the New Tours Web site.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);			
 browser.navigate("http://newtours.demoaut.com/");        
			
 // Use try-catch to add a warning to the run report if the assert validation fails.  
 try			
 {			
  // Define the labels that will be used for identifications of the fields.
  WebElement usernameLabel = browser.describe(WebElement.class,new WebElementDescription.Builder().tagName("TD").innerText("User Name:").build());			
  WebElement passwordLabel = browser.describe(WebElement.class,new WebElementDescription.Builder().tagName("TD").innerText("Password:").build());            
			
  // Define the visual relation identifier of the username edit field.
  VisualRelation usernameVRI = new VisualRelation();			
  usernameVRI.setTestObject(usernameLabel);			
  usernameVRI.setHorizontalRelation(HorizontalVisualRelation.LEFT_AND_INLINE);			
  browser.describe(EditField.class,new EditFieldDescription.Builder().vri(usernameVRI).build()).setValue("mercury");            
			
  // Enter the logon credentials using the labels.
  VisualRelation passwordVRI = new VisualRelation();			
  passwordVRI.setTestObject(passwordLabel);			
  passwordVRI.setHorizontalRelation(HorizontalVisualRelation.LEFT_AND_INLINE);			
  browser.describe(EditField.class,new EditFieldDescription.Builder().vri(passwordVRI).build()).setSecure("55940fd62c96a30a62b4ab4d3db57c430de69cde")           
			
  // Click the Sign In button.			
  browser.describe(Image.class,new ImageDescription.Builder().alt("Sign-In").type(ImageType.BUTTON).tagName("INPUT").build()).click();
			
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Verify that a Sign out link is available.			
  assertTrue(browser.describe(Link.class,new LinkDescription.Builder().tagName("A").innerText("SIGN-OFF").build()).exists());			
 }			
 catch (AssertionError e)			
 {			
  // Adds a step to the results report on failure.
  Reporter.reportEvent("Verify_UserCanEnterCredentialsAfterSignOff", "Validation Failed", Status.Failed, e);			
  throw e;			
 }			
 finally			
 {			
  browser.close();			
 }			
}		

Back to top

Verify objects using HTML attributes

This example will get all the images in the AUT's main page and verify that all images contains ALT attribute.

@Test
public void verify_AllImagesContainsAltAttribute() throws Exception			
 {      			
 //Launch the Chrome browser and navigate to the New Tours site.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);			
 browser.navigate("http://newtours.demoaut.com/");
			
 // Use try-catch to add a warning to the run report if the assert validation fails.  
 try			
 {			
  Image[] images = browser.findChildren(Image.class,null);           
			
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Verify the image contains an alt attribute and that it has a value.  
  for (Image image : images)			
  {			
   assertNotNull(image.getAttribute("alt"));			
   assertFalse(image.getAttribute("alt").isEmpty());			
  }			
 }			
 catch (AssertionError e)			
 {			
  // Adds a step to the results report on failure.
  Reporter.reportEvent("Verify_UserCanEnterCredentialsAfterSignOff", "Validation Failed", Status.Failed, e);			
  throw e;			
 }			
 finally			
 {			
  browser.close();			
 }			
}	

Back to top

Use JavaScript to check that spell check is enabled

This example shows how to inject JavaScript code into your webpage to verify that the spell check functionality is enabled.

@Test
public void verify_suggestionBoxIsUsingSpellcheck() throws Exception {
			
 //Launch the Chrome browser and navigate to google.com.
 Browser browser = BrowserFactory.launch(BrowserType.CHROME);			
 browser.navigate("http://www.google.com");
			
 // Use try-catch to add a warning to the run report if the assert validation fails.  
 try			
 {			
  // Use the JavaScript spellcheck property to determine if the spell check is enabled.
  String performSpellCheck = browser.getPage().runJavaScript("document.querySelectorAll('.sbdd_b')[0].spellcheck.toString();");            
			
  // Enclosing the Assert method in a try-catch statement ensures the application does not throw a runtime error if the Assert returns false.

  // Verify that spell check is enabled.			
  assertTrue(Boolean.parseBoolean(performSpellCheck));			
 }			
 catch (AssertionError e)			
 {			
  // Adds a step to the results report on failure.
  Reporter.reportEvent("Verify_UserCanEnterCredentialsAfterSignOff", "Validation Failed", Status.Failed, e);			
  throw e;			
 }			
 finally			
 {			
  browser.close();			
 }			
}		

Back to top

Open the Home page using browser controls

This example uses the Describe method to create a regular expression to locate an object.

@Test			
public void verify_TipIsPresentedInAUTHomePage() throws Exception {
        			
 // Navigate to the home page of the browser using the browser control.			
 com.hp.lft.sdk.stdwin.EditField addressField = Desktop.describe(Window.class, new WindowDescription.Builder()			
 .ownedWindow(false).childWindow(false).windowClassRegExp("Afx:").windowTitleRegExp("JSCall").build()).describe(Window.class, new WindowDescription.Builder()			
 .ownedWindow(false).childWindow(true).windowClassRegExp("Afx:").windowTitleRegExp("http://localhost/t112.html").build()).describe(com.hp.lft.sdk.stdwin.EditField.class, new com.hp.lft.sdk.stdwin.EditFieldDescription.Builder()			
 .attachedText("URL:").nativeClass("Edit").build());
        			
 addressField.setText("http://newtours.demoaut.com/");			
 addressField.click();			
 addressField.sendKeys(Keys.RETURN);
        			
 // Describe the tip image. Since the tip index is generated we will use a regular expression to find it.			
 Image tip = Desktop.describe(Window.class, new WindowDescription.Builder()			
 .ownedWindow(false).childWindow(false).windowClassRegExp("Afx:").windowTitleRegExp("JSCall").build()).describe(Window.class, new WindowDescription.Builder()			
 .ownedWindow(false).childWindow(true).windowClassRegExp("Afx:").windowTitleRegExp("http://newtours.demoaut.com/").build()).describe(Page.class, new PageDescription()).describe(Image.class, new ImageDescription.Builder()			
 .alt(new RegExpProperty("Tip.*")).type(com.hp.lft.sdk.web.ImageType.NORMAL).tagName("IMG").build());
        			
 // As the Assert method is not enclosed in a try-catch statement, the application will throw a runtime error if the Assert returns false.

 //Verifies that the tip is found.
 assertTrue(tip.exists());			
}		

Back to top

See also: