Web code samples

Send keystrokes to the AUT

To send the Enter key, use the Keyboard class:

Keyboard.PressKey(28);

To send the Enter key to a specific web control, you sometimes need to make sure it has the focus.

This can be done using one of the following:

  • the click() method of the control:

    browser.Describe<IEditField>(newCSSDescription(@"input#newCommentInput")).Click(MouseButton.Left);
    

  • the Mouse class

    var edit = browser.Describe<IEditField>(newCSSDescription(@"input#newCommentInput"));
     
    // Use Mouse class to click on the edit field
    var loc = edit.AbsoluteLocation; var p = newPoint(loc.X + 5, loc.Y + 5); Mouse.Click(p, MouseButton.Left);

Back to top

Simple link click

The following example demonstrates a simple Click step on a Web link.

[Test] public void TestLinkClick() { // Launch the Chrome browser. IBrowser testBrowser = BrowserFactory.Launch(BrowserType.Chrome); // Navigate to hp.com testBrowser.Navigate("hp.com"); // Create a test object with a unique description for the 'Tablets' link. var tabletLink = testBrowser.Describe<ILink>new LinkDescription {InnerText="Tablets", Index=4}); // Click the link. tabletLink.Click(); }

Back to top

Programmatic description vs. Application Model code

The Programmatic description example shows a set of steps with test objects created using programmatic descriptions.

The Application Model code example shows a similar set of steps using test objects from an application model.

Programmatic description example

This example uses an Assert command to verify the price of a tablet.

To see how to perform this assert with an application model, see the Application Model code example.

// Launch the browser and navigate to HP's shopping site.
var browser = BrowserFactory.Launch(BrowserType.InternetExplorer);
browser.Navigate("http://www.hp.com/country/us/en/uc/welcome.html");

// Click the link for HP Slate 10 HD.
browser.Describe<IImage>(new ImageDescription
{
	Alt = "HP Slate 10 HD",
		TagName = "IMG"
}).Click();

// Define the object that displays the price.
var priceElem =
	browser.Describe<IWebElement>(new WebElementDescription
		{
			XPath = "//SPAN",
		TagName = "SPAN",
		InnerText = As.RegExp("$279.*")
		});
// Verify that the price in the object is as expected.
Assert.AreEqual("$279.99*",priceElem.InnerText);       

Application Model code example

This example uses an Assert on an object from an application model to perform the same type of check as in the Programmatic description example.

// Launch the browser and navigate to HP's shopping site. var browser = BrowserFactory.Launch(BrowserType.InternetExplorer); browser.Navigate("http://www.hp.com/country/us/en/uc/welcome.html"); // Create an instance of the application model and provide the browser defined above as the parent object. DiscoverAppModel app = new DiscoverAppModel(browser); // Click the section for tablets. app.Tablets.Click(); // Click the HP 10 Plus link. app.TabletsPage.HP10Plus.Click(); // Use an Assert to verify the price. Assert.AreEqual("$279.99*", app.TabletsPage.Price.InnerText); //cleanup browser.Close(); // This is the equivalent of as (browser as IDisposeable).Dispose();

Back to top

Navigate to a Web site

The following example uses an Assert command to verify navigation to a web site.

[Test] public void Verify_linkNavigatesToAboutTravelSite() { //Launch the Chrome browser. var browser = BrowserFactory.Launch(BrowserType.Chrome); 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<ILink>(new LinkDescription { TagName = @"A", InnerText = @"Business Travel @ About.com" }).Click(); //Wait for the browser to complete the navigation. browser.Sync(); //Verify that the correct page Web page opens. Assert.AreEqual("http://businesstravel.about.com/?PM=78_101_T&cob=home", browser.URL); } catch (AssertionException e) { Reporter.ReportEvent("Verify_linkNavigatesToAboutTravelSite", "Failed during validation", Status.Failed, e); throw; } finally { browser.Close(); } }

Back to top

Access Web objects in a tab opened by the AUT

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

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

Attach a browser when:

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

The example below attaches a newly opened browser tab.

[Test]
public void Verify_AboutOpensCorrectly()
{
	//Launch the Chrome browser.
	var 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<ILink>(new LinkDescription
		{
			TagName = @"A",
			InnerText = @"Cruises"
		}).Click();

		//Attach the new (replacement) browser tab.
		var aboutTab = BrowserFactory.Attach(new BrowserDescription
		{
			Title = "Cruises: Mercury Tours"
		});

		//Create a description for the page title.
		var aboutTitle = aboutTab.Describe<IWebElement>(new WebElementDescription
		{
			TagName = @"LI",
			InnerText = @"Cruises",
			Index = 0
		});

		// Validate that a page title exists.
		Assert.IsTrue(aboutTitle.Exists());
	}
	catch (AssertionException e)
	// Add a log message to the results report on failure.
	{
		Reporter.ReportEvent("Verify_AboutOpensCorrectly", "Failed during validation", Status.Failed, e);
		throw;
	}
	finally
	{
		browser.Close();
	}
}

Back to top

Locate an object by its XPath

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.

See an example below.

[Test] public void verify_CurrentDateIsPresented() { // Open the Chrome browser. var 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. var dateLabel = browser.Describe<IWebElement>(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 .NET object. var presentedDate = DateTime.Parse(dateLabel.InnerText); // Verify that today's date matches the date displayed. Assert.AreEqual(DateTime.Now.Date, presentedDate.Date); } catch (AssertionException e) // Use a ReportEvent step to add details to the results report if the validation fails. { Reporter.ReportEvent("verify_CurrentDateIsPresented", "Failed during validation", Status.Failed, e); throw; } finally { browser.Close(); } }

Back to top

Use Assert to validate 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(){
   
	// Navigate to the New Tours website.
	var 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.
		var userName = browser.Describe<IEditField>(new EditFieldDescription
		{
			Name = @"userName"
		});
		var password = browser.Describe<IEditField>(new EditFieldDescription
		{
			Type = @"password",
			Name = @"password"
		});

		userName.SetValue("mercury");
		password.SetSecure("55940fd62c96a30a62b4ab4d3db57c430de69cde");
		browser.Describe<IImage>(new ImageDescription
		{
			Alt = @"Sign-In",
			Type = HP.LFT.SDK.Web.ImageType.Button,
			TagName = @"INPUT"
		}).Click();

		// Log off.
		browser.Describe<ILink>(new LinkDescription
		{
			InnerText = @"SIGN-OFF"
		}).Click();

		// Verify that user name and password fields are writable after logging off.
		Assert.IsFalse(userName.IsReadOnly);
		Assert.IsFalse(password.IsReadOnly);
	}
	catch (AssertionException e)
	// Use a ReportEvent step to add details to the run report if the validation fails.
	{

		Reporter.ReportEvent("Verify_UserCanEnterCredentialsAfterSignOff", "Validation failed.", Status.Failed, e);
		throw;
	}
	finally
	{
		browser.Close();
	}
}

Back to top

Synchronize objects using WaitUntil

The following example shows how to verify that a suggestion box contains suggestions. It contains a WaitUntil step to give the objects in the application time to load fully before continuing to the next step.

The test navigates to the AUT, opens the suggestion box from the search box, waits until the suggestion box opens, and verifies that the suggestion box contains at least one suggestion.

[Test] public void Verify_SearchSuggestionsArePresentedAndMoreThan0() { // Launch the Chrome browser and navigate to the web site. var 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. var search = browser.Describe<IEditField>(new EditFieldDescription { Name = "q" }); 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. var suggestions = browser.Describe<IWebElement>(new WebElementDescription { CSSSelector = @".sbsb_a", }); suggestions.WaitUntil(suggestionsBox => suggestionsBox.Exists() && suggestionsBox.IsVisible); var suggestionList = suggestions.FindChildren<IWebElement>(new WebElementDescription { TagName = "LI" }); // Verify that the suggestion box exists and contains content. Assert.IsTrue(suggestions.IsVisible); Assert.Greater(suggestionList.Length, 0); } catch (AssertionException e) // Use a ReportEvent step to add details to the run report if the validation fails. { Reporter.ReportEvent("Verify_SearchSuggestionsAreOpenUponUserInput", "Failed during validation", HP.LFT.Report.Status.Failed, e); browser.Close(); throw; } }

Back to top

Retrieve and sort list items

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

The test will sign in to the AUT, retrieve the list of departure cities, and sort the list. Then it will sort the list by the city name and verify that both the original list and the sorted one are identical.

[Test] public void verify_CitiesAreSorted() { // Open the Chrome browser. var 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. var departureCombo = browser.Describe<IListBox>(new ListBoxDescription { TagName = @"SELECT", Name = @"fromPort" }); // Sort the list of cities. var departureCities = departureCombo.Items; var sortedList = departureCities.OrderBy(item => item.Text); // Compare the two lists to verify that the data is identical. Assert.AreEqual(sortedList, departureCities); } catch (AssertionException e) // Use a ReportEvent step to add details to the run report if the validation fails. { Reporter.ReportEvent("verify_CitiesAreSorted", "Validation Failed", HP.LFT.Report.Status.Failed, e); throw; } finally { browser.Close(); } } public void SignIn(IBrowser browser) { // Sign in for the New Tours web site. var userName = browser.Describe<IEditField>(new EditFieldDescription { Name = @"userName" }); var password = browser.Describe<IEditField>(new EditFieldDescription { Type = @"password", Name = @"password" }); userName.SetValue("mercury"); password.SetSecure("55940fd62c96a30a62b4ab4d3db57c430de69cde"); browser.Describe<IImage>(new ImageDescription { Alt = @"Sign-In", Type = HP.LFT.SDK.Web.ImageType.Button, TagName = @"INPUT" }).Click(); }

Back to top

Identify an edit box via a CSS selector

Suppose you want to verify that when entering a value in a search box, a suggestion box opens. The only way to identify the suggestion box is via a CSS selector.

The example below shows how to:

  • fire an event that triggers the opening of a suggestion box
  • identify the suggestion box using a CSS selector
[Test]
public void Verify_SearchSuggestionsAreOpenUponUserInput()
{
	// Launch the Chrome browser and navigate to the web site.
	var 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.
		var search = browser.Describe<IEditField>(new EditFieldDescription
		{
			Name = "q"
		});
		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.
		var suggestions = browser.Describe<IWebElement>(new CSSDescription(".sbsb_a"));
		suggestions.WaitUntil(suggestionsBox => suggestionsBox.Exists() && suggestionsBox.IsVisible);

		// Use Assert to verify that the suggestion box exists.
		Assert.IsTrue(suggestions.IsVisible);
	}
	catch (AssertionException e)
	// Use a ReportEvent step to add details to the report if the validation fails.
	{
		Reporter.ReportEvent("Verify_SearchSuggestionsAreOpenUponUserInput", "Failed during validation", Status.Failed, e);
		throw;
	}
	finally
	{
		browser.Close();
	}
}

Back to top

Verify that a suggestion box contains content

The following example shows how to verify that a suggestion box contains suggestions.

It contains a WaitUntil step to give the objects in the application time to load fully before continuing to the next step.

The test navigates to the AUT, opens the suggestion box from the search box, waits until the suggestion box opens, and verifies that the suggestion box contains at least one suggestion.

[Test]
public void Verify_SearchSuggestionsArePresentedAndMoreThan0()
{
    
	// Launch the Chrome browser and navigate to the web site.
	var 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.
		var search = browser.Describe<IEditField>(new EditFieldDescription
		{
			Name = "q"
		});
		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.
		var suggestions = browser.Describe<IWebElement>(new WebElementDescription
		{
			CSSSelector = @".sbsb_a",
		});
		suggestions.WaitUntil(suggestionsBox => suggestionsBox.Exists() && suggestionsBox.IsVisible);

		var suggestionList = suggestions.FindChildren<IWebElement>(new WebElementDescription
		{
			TagName = "LI"
		});


		// Verify that the suggestion box exists and contains content.
		Assert.IsTrue(suggestions.IsVisible);
		Assert.Greater(suggestionList.Length, 0);

	}
	catch (AssertionException e)
	// Use a ReportEvent step to add details to the run report if the validation fails.
	{
		Reporter.ReportEvent("Verify_SearchSuggestionsAreOpenUponUserInput", "Failed during validation", HP.LFT.Report.Status.Failed, e);
		browser.Close();
		throw;
	}

}

Back to top

Verify that a tip is displayed on the Home page

This example verifies that a tip is displayed on an application's Home page.

[Test]
public void Verify_TipIsPresentedInAUTHomePage()
{
						
	//Navigate to the application homepage using the application's Brower control.
	var addressBar =
		Desktop.Describe<StdWin.IWindow>(new StdWin.WindowDescription
		{
			IsOwnedWindow = false,
			IsChildWindow = false,
			WindowClassRegExp = @"Afx:",
			WindowTitleRegExp = @"JSCall"
		}).Describe<StdWin.IWindow>(new StdWin.WindowDescription
		{
			IsOwnedWindow = false,
			IsChildWindow = true,
			WindowClassRegExp = @"Afx:",
			WindowTitleRegExp = @"http://localhost/t112.html"
		}).Describe<StdWin.IEditField>(new StdWin.EditFieldDescription
		{
			AttachedText = @"URL:",
			NativeClass = @"Edit"
		});

	addressBar.SetText("http://newtours.demoaut.com/");
	addressBar.Click();
	addressBar.SendKeys(Keys.Return);


	//Describes the tip image.
	//We can use a regular expression to find the tip number.
	var tipImage = Desktop.Describe<StdWin.IWindow>(new StdWin.WindowDescription
	{
		IsOwnedWindow = false,
		IsChildWindow = false,
		WindowClassRegExp = @"Afx:",
		WindowTitleRegExp = @"JSCall"
	}).Describe<StdWin.IWindow>(new StdWin.WindowDescription
	{
		IsOwnedWindow = false,
		IsChildWindow = true,
		WindowClassRegExp = @"Afx:",
		WindowTitleRegExp = @"http://newtours.demoaut.com/"
	}).Describe<IPage>(new PageDescription()).Describe<IImage>(new ImageDescription
	{
		Alt = As.RegExp(@"Tip.*"),
		Type = HP.LFT.SDK.Web.ImageType.Normal,
		TagName = @"IMG"
	});

	//Verify that the tip is found.
	Verify.IsTrue(tipImage.Exists(), "verify that tips is found", "tipImage.Exists()");
}

Back to top

Verify Fields Using Their Labels

This example shows how to use the labels next to fields to identify the fields instead of field properties.

This is helpful for fields that have automatically generated IDs, making it impossible to use the field properties for identification.

[Test]
public void Verify_SignInIsAvailable()
{
						
	//Navigate to the web site.
	var browser = BrowserFactory.Launch(BrowserType.InternetExplorer);
	browser.Navigate("http://newtours.demoaut.com/");

	//Define the labels you want to use to define the fields.
	var usernameLabel = browser.Describe<IWebElement>(new WebElementDescription
	{
		TagName = @"TD",
		InnerText = @"User Name:"
	});
	var passwordLAbel = browser.Describe<IWebElement>(new WebElementDescription
	{
		TagName = @"TD",
		InnerText = @"Password:"
	});

	//Sign in using the field labels.
	browser.Describe<IEditField>(new EditFieldDescription
	{
		Vri =
		{
			new VisualRelation
			{
				TestObject = usernameLabel,
				HorizontalRelation = HorizontalVisualRelation.LeftAndInline
			}
		}
	}).SetValue("mercury");

	browser.Describe<IEditField>(new EditFieldDescription
	{
		Vri =
		{
			new VisualRelation
			{
				TestObject = passwordLAbel,
				HorizontalRelation = HorizontalVisualRelation.LeftAndInline
			}
		}
	}).SetSecure("55940fd62c96a30a62b4ab4d3db57c430de69cde");

	browser.Describe<IImage>(new ImageDescription
	{
		Alt = @"Sign-In",
		Type = HP.LFT.SDK.Web.ImageType.Button,
		TagName = @"INPUT"
	}).Click();

	//Verify that the sign-out link is displayed.
	Verify.IsTrue(browser.Describe<ILink>(new LinkDescription
	{
		TagName = @"A",
		InnerText = @"SIGN-OFF"
		}).Exists(), "Verify that a Sign out link is available");

	browser.Close();
}

Back to top

Inject JavaScript into your Webpage

This example shows how to inject JavaScript code into your webpage.

In this case, we use the JavaScript SpellCheck property to determine whether spell check is enabled.

[Test] public void VerifySpellCheckIsEnabledOnSuggestionBox() { var browser = BrowserFactory.Launch(BrowserType.InternetExplorer); browser.Navigate("http://www.google.com"); // Determine whether spell check is enabled using the JavaScript SpellCheck property. var performSpellCheck = browser.Page.RunJavaScript<bool>(@"document.querySelectorAll('.sbdd_b')[0].spellcheck"); Verify.IsTrue(performSpellCheck, "Verify that spell check is enabled"); browser.Close(); }

Back to top