using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Diagnostics;
using System.Linq;
using OpenQA.Selenium.Chrome;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
/*
// The source code was generated by cSharpSeleniumGenerator.js
// Copyright: Tricentis
// Website: https://www.tricentis.com
// C# plugin version: 1.3.4
*/
namespace MyNamespace1
{
[TestClass]
public class MyTestCase1
{
private IWebDriver _driver;
private const int MOUSE_LEFT = 0;
private const int MOUSE_RIGHT = 2;
private const bool alwaysExecuteActionInLatestWindow = true;
[TestInitialize]
public void TestInit()
{
_driver = new ChromeDriver();
_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
_driver.Manage().Window.Maximize();
_driver.Navigate().GoToUrl("https://www.flybuys.co.nz/");
}
[TestMethod]
public void Test()
{
Click(null, By.XPath("html/body/div[4]/div[2]/section[1]/div[1]/div/div/div/div[2]/div/div/h3/a"), MOUSE_LEFT,1);
SendKeys(null, By.Id("autocomplete-0-input"),"umbrella", true, 6);
Click(null, By.XPath(".//*[@id='autocomplete-0-label']/button"), MOUSE_LEFT,6);
Click(null, By.XPath(".//*[@id='instant-search-results-container']/div/div/ol/li[1]/div/div/a/div[1]/div[1]/div[1]/img"), MOUSE_LEFT,8);
SelectItemByVisibleText(null, By.Id("attribute234"), 6, "Choose an Option..." );
SelectItemByVisibleText(null, By.Id("attribute234"), 6, "Mint" );
Click(null, By.XPath("html"), MOUSE_LEFT,5);
Click(null, By.XPath(".//*[@id='product-addtocart-button']/span"), MOUSE_LEFT,3);
}
///
/// Switches to an iframe.
///
///
/// The json frames. ex: [{"value":"child2","type":"id_or_name"}]
/// "type" should be "id or value" or "index"
///
private void SwitchToFrames(string framesJson)
{
try
{
_driver.SwitchTo().DefaultContent();
var array = JsonConvert.DeserializeObject(framesJson);
var children = array.Children();
foreach (var obj in children)
{
var type = obj.GetValue("type").ToString();
var value = obj.GetValue("value").ToString();
// switch to desired frame/iframe
if (type.ToLower() == "index")
{
_driver.SwitchTo().Frame(int.Parse(value));
}
else
{
_driver.SwitchTo().Frame(value);
}
}
}
catch
{
throw;
}
}
///
/// Sends the keys to the UI element
///
/// The element locator
/// The keys to send to the element
/// if true, clear the text field before sending keys to it, otherwise, false
/// The time out, in seconds, to find element
public void SendKeys(String frames, By locator, string keys, bool clearTextBeforeSendingKeys, int timeOutInSeconds)
{
if (alwaysExecuteActionInLatestWindow) SwitchToLastWindow(frames);
IWebElement elm = FindElement(locator, timeOutInSeconds);
if (clearTextBeforeSendingKeys) elm.Clear();
elm.SendKeys(keys);
}
///
/// Clicks the specified UI element.
///
/// The element locator.
/// The mouse button, e.g. MOUSE_LEFT, MOUSE_RIGHT.
/// The timeout in seconds.
public void Click(String frames, By locator, int mouseButton, int timeoutInSeconds)
{
Click(frames, locator, mouseButton, null, timeoutInSeconds);
}
///
/// Clicks on the specified UI element.
///
/// The element locator.
/// The mouse button.
/// The modifier keys.
/// The timeout in seconds.
/// Element not found.
/// Failed to click on the element
public void Click(String frames, By locator, int mouseButton, string modifierKeys, int timeoutInSeconds)
{
if (alwaysExecuteActionInLatestWindow) SwitchToLastWindow(frames);
bool success = false;
long timeoutInMillies = timeoutInSeconds * 1000;
IWebElement elm = null;
// time spent counters
long timeSpentInMillis = 0;
// try to click on the element until wait timout reached
while ((success == false) && (timeSpentInMillis <= timeoutInMillies))
{
try
{
Stopwatch stopWatch = Stopwatch.StartNew();
// find the element and calculate time spent
elm = FindElement(locator, 1);
stopWatch.Stop();
timeSpentInMillis += stopWatch.ElapsedMilliseconds;
if (elm != null)
{
PerformClick(elm, mouseButton, modifierKeys);
// successfully clicked on element, turn on the flag to escape the loop
success = true;
}
}
catch (Exception e)
{
// probably the element is not present yet or it is non-clickable
Console.WriteLine(e.Message);
// if element is found and we reached to the timeout, try to click on it with JavaScript
if ((elm != null) && (timeSpentInMillis > timeoutInMillies))
{
IJavaScriptExecutor js = (IJavaScriptExecutor)this._driver;
js.ExecuteScript("arguments[0].click();", elm);
// successfully clicked on element, turn on the flag to escape the loop
success = true;
}
}
}
if (!success)
{
if (elm == null)
{
throw new NoSuchElementException("Element not found.");
}
else
{
throw new Exception("Failed to click on the element");
}
}
}
private void PerformClick(IWebElement element, int mouseButton, string modifierKeys)
{
modifierKeys = modifierKeys ?? string.Empty;
if (string.IsNullOrEmpty(modifierKeys) && (mouseButton == MOUSE_LEFT))
{
element.Click();
return;
}
var actions = new Actions(_driver);
if (modifierKeys.IndexOf("Ctrl") > -1)
{
actions = actions.KeyDown(Keys.Control);
}
if (modifierKeys.IndexOf("Alt") > -1)
{
actions = actions.KeyDown(Keys.Alt);
}
if (modifierKeys.IndexOf("Shift") > -1)
{
actions = actions.KeyDown(Keys.Shift);
}
if (mouseButton == MOUSE_LEFT)
{
actions = actions.Click(element);
}
else
{
actions = actions.ContextClick(element);
}
if (modifierKeys.IndexOf("Ctrl") > -1)
{
actions = actions.KeyUp(Keys.Control);
}
if (modifierKeys.IndexOf("Alt") > -1)
{
actions = actions.KeyUp(Keys.Alt);
}
if (modifierKeys.IndexOf("Shift") > -1)
{
actions = actions.KeyUp(Keys.Shift);
}
actions.Perform();
}
///
/// Finds the element by a locator
///
/// The element locator.
/// The timeout, in seconds, to wait for element.
///
private IWebElement FindElement(By locator, int waitForElementTimeoutInSeconds)
{
while (true)
{
try
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(waitForElementTimeoutInSeconds));
return wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(locator));
}
catch (WebDriverTimeoutException)
{
// sometimes WebDriverWait falied to find elements, e.g. Dojo checkboxs, and we need to fall back to use WebDriver itself
return _driver.FindElement(locator);
}
catch (UnhandledAlertException)
{
// Alert dialog is about to be closed, wait a moment and retry
System.Threading.Thread.Sleep(500);
}
}
}
///
/// Select an option in a select element
///
/// frame list, where select tag belong to
/// locator of select element
/// wait time out
/// text to select
public void SelectItemByVisibleText(String frames, By selectElementLocator, int waitForElementTimeout, String text)
{
if (alwaysExecuteActionInLatestWindow) SwitchToLastWindow(frames);
SelectElement sel = new SelectElement(FindElement(selectElementLocator, waitForElementTimeout));
sel.SelectByText(text);
}
///
/// Switch to lastest window and frames
///
/// List of frame to switch or null
private void SwitchToLastWindow(String frameList)
{
_driver.SwitchTo().Window(_driver.WindowHandles.Last());
if (null != frameList) SwitchToFrames(frameList);
}
[TestCleanup]
public void TestCleanup()
{
_driver.Close();
_driver.Quit();
}
}
}