public void FindByAccessibilityIdTest() { By byAccessibilityId = new ByAccessibilityId("Graphics"); Assert.AreNotEqual(_driver.FindElement(byAccessibilityId).Text, null); Assert.GreaterOrEqual(_driver.FindElements(byAccessibilityId).Count, 1); }
public void FindElementTestCase() { By byAccessibilityId = new ByAccessibilityId("Graphics"); Assert.AreNotEqual(driver.FindElement(byAccessibilityId).Text, null); Assert.GreaterOrEqual(driver.FindElements(byAccessibilityId).Count, 1); driver.FindElementByAccessibilityId("Graphics").Click(); Assert.IsNotNull(driver.FindElementByAccessibilityId("Arcs")); driver.Navigate().Back(); Assert.IsNotNull(driver.FindElementByName("App")); Assert.IsNotNull(driver.FindElement(new ByAndroidUIAutomator("new UiSelector().clickable(true)")).Text); var els = driver.FindElementsByAndroidUIAutomator("new UiSelector().clickable(true)"); Assert.GreaterOrEqual(els.Count, 12); var els2 = driver.FindElements(new ByAndroidUIAutomator("new UiSelector().enabled(true)")); Assert.GreaterOrEqual(els2.Count, 20); els = driver.FindElementsByAndroidUIAutomator("new UiSelector().enabled(true)"); Assert.GreaterOrEqual(els.Count, 20); Assert.IsNotNull(driver.FindElementByXPath("//android.widget.TextView[@text='API Demos']")); }
static void ScrollDown(Size screenSize, By targetBy = null) { var touch = new TouchAction(_driver); if (targetBy == null) { touch.Press(50, screenSize.Height * 0.9) .Wait(300) .MoveTo(50, screenSize.Height * 0.1) .Wait(500) .Release() .Perform(); } else { var targetEle = _driver.FindElements(targetBy).Last(); touch.Press(targetEle, 50, screenSize.Height * 0.9) .Wait(300) .MoveTo(targetEle, 50, screenSize.Height * 0.1) .Wait(500) .Release() .Perform(); } }
public void ReadTestCases() { Methods.Methods.OpenPage(_driver, Constants.LOGIN_URL, 5); Methods.Methods.InputOnElement(_driver, Constants.NAME, "email", "*****@*****.**", 1); Methods.Methods.InputOnElement(_driver, Constants.NAME, "password", "kovcakis88", 1); Methods.Methods.ClickOnElement(_driver, Constants.CSS_SELECTOR, "button.btn.btn-primary.btn-block.mt-4", 2); Methods.Methods.GoToPage(_driver, Constants.USE_CASE_URL); IList <AppiumWebElement> all = _driver.FindElements(By.CssSelector("a.list-group-item.list-group-item-action")); String[] allText = new String[all.Count]; int i = 0; foreach (IWebElement element in all) { allText[i++] = element.Text; } for (i = 0; i < allText.Length; i++) { string elementName = allText[i]; Methods.Methods.ClickOnElement(_driver, Constants.LINK_TEXT, elementName, 1); Methods.Methods.MoveToElement(_driver, "button.btn.btn-primary.mt-4.float-right", 1); Methods.Methods.ClickOnElement(_driver, Constants.CSS_SELECTOR, "button.btn.btn-primary.mt-4.float-right", 1); Thread.Sleep(2000); } Assert.Pass(); }
private ReadOnlyCollection <AppiumWebElement> FindElements(By by) { var elements = _driver.FindElements(by); _logger.LogTrace($"Find elements (element={by}, count={elements.Count})"); return(elements); }
// Implement this method public void Execute(Arguments arguments) { AndroidDriver <AndroidElement> driver = OpenCommand._driver; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(1)); if (arguments.Name.Value != "") { By myElement; if (arguments.By.Value.ToLower() == "classname") { myElement = By.ClassName(arguments.Name.Value); } else { myElement = By.Id(arguments.Name.Value); } List <AndroidElement> elements = new List <AndroidElement>(); for (int i = 0; i < arguments.WaitTimeout.Value; i++) { elements.AddRange(driver.FindElements(myElement)); if (elements.Count > 0) { return; } driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1)); } throw new ArgumentException($"Element with id or class name {arguments.Name.Value} did not show up."); } else { throw new ArgumentException($"The id and content-desc are not defined. You should provide one of them."); } }
private AndroidElement SrollToElement(AndroidDriver <AndroidElement> driver, Arguments arguments) { Boolean isFoundElement = false; By myElement; if (arguments.Id.Value != "" && arguments.PartialID.Value == "") { myElement = By.Id(arguments.Id.Value); } else if (arguments.PartialID.Value != "" && arguments.Id.Value == "") { myElement = By.XPath("//*[contains(@content-desc,\"" + arguments.PartialID.Value + "\")]"); } else { throw new ArgumentException($"No ID was provided or it is invalid."); } while (isFoundElement == false) { SwipeVertical((AppiumDriver <AndroidElement>)driver, 0.9, 0.1, 0.5, 2000, arguments.SwipeDir.Value); List <AndroidElement> elements = new List <AndroidElement>(); elements.AddRange(driver.FindElements(myElement)); isFoundElement = driver.FindElements(myElement).Count > 0; if (arguments.Text.Value != "" && isFoundElement) { foreach (AndroidElement element in elements) { if (element.Text == arguments.Text.Value) { return(element); } } } else if (arguments.Text.Value == "" && isFoundElement) { return(elements[0]); } elements.Clear(); isFoundElement = false; } throw new ArgumentException($"No elements with specified id or text could be found."); }
public EvernoteMainPage NotesListMainPageContainsElements() { List <AndroidElement> Notes = _driver.FindElements(By.XPath("//android.widget.LinearLayout[@class='android.widget.LinearLayout']//android.widget.LinearLayout[@id='snippet_container']")).ToList(); for (int i = 0; i < Notes.Count; i++) { } return(new EvernoteMainPage(_driver)); }
public void TestCreateSimpleTask() { driver.FindElement(By.Id("btn_welcome_log_in")).Click(); // *** Google Play Services Activity *** driver.FindElement(By.Id("button1")).Click(); // *** Login Activity **** driver.FindElement(By.Id("log_in_email")).SendKeys(EMAIL); driver.FindElementById("log_in_password").SendKeys(PASSWORD); driver.FindElementById("btn_log_in").Click(); // *** Google Play Services Activity *** driver.FindElementById("button1").Click(); // *** Goolge Play services in not supported *** //driver.FindElementById("button1").Click(); // Clicking on the Today menu item driver.FindElement(By.XPath("//android.widget.TextView[@text='Today']")).Click(); // Creating a new task driver.FindElementById("fab").Click(); String taskName = "Automated task" + DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; AppiumWebElement message = driver.FindElementById("message"); message.SendKeys(taskName + " #work"); driver.FindElementById("button1").Click(); // Going back driver.FindElementById("action_mode_close_button").Click(); // Searching for the newly created item ReadOnlyCollection <AppiumWebElement> items = driver.FindElements(By.XPath("//android.widget.RelativeLayout[@resource-id='com.todoist:id/item']/android.widget.TextView")); Boolean found = false; foreach (AppiumWebElement item in items) { Console.Write("Item: " + item.Text); if (item.Text.Equals(taskName)) { found = true; break; } } Assert.IsTrue(found, "Item was not created"); Thread.Sleep(1000); }
public new WebElement FindElement(By elementLocator) { try { var element = _appiumDriver.FindElements(elementLocator); if (element.Count > 0) { return(new WebElement(this, elementLocator)); } else { throw new Exception(string.Format("Element not found : {0}", elementLocator)); } } catch (Exception) { throw new Exception(string.Format("Element not found : {0}", elementLocator)); } }
public void ByAndroidUIAutomatorTestCase() { AndroidDriver driver = new AndroidDriver(defaultUri, capabilities); server.respondTo("POST", "/element", new Dictionary <string, object> { { "ELEMENT", '5' } }); driver.FindElement(new ByAndroidUIAutomator(".elements()")); (new ByAndroidUIAutomator(".elements()")).FindElement(driver); server.clear(); List <object> results = new List <object>(); results.Add(new Dictionary <string, object> { { "ELEMENT", "4" } }); server.respondTo("POST", "/elements", results); driver.FindElements(new ByAndroidUIAutomator(".elements()")); (new ByAndroidUIAutomator(".elements()")).FindElements(driver); }
static void Main(string[] args) { caps = new AppiumOptions(); caps.AddAdditionalCapability("platformName", "Android"); // caps.AddAdditionalCapability("platformVersion", "7.0"); caps.AddAdditionalCapability("deviceName", "Android Emulator"); caps.AddAdditionalCapability("automationName", "UIAutomator2"); caps.AddAdditionalCapability("noReset", true); caps.AddAdditionalCapability("appPackage", Const.AppPackage); caps.AddAdditionalCapability("appActivity", Const.LauncherUi); try { _serverUri = new Uri("http://127.0.0.1:4723/wd/hub"); _driver = new AndroidDriver <AppiumWebElement>(_serverUri, caps, TimeSpan.FromSeconds(180)); _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); _screenSize = _driver.Manage().Window.Size; var isFlashPage = IsFlashPage(); while (isFlashPage) { Thread.Sleep(TimeSpan.FromSeconds(3)); isFlashPage = IsFlashPage(); } _driver.FindElements(Const.TabAddressBookId)[1].Click(); ClickElement(Const.PublicId); var previousBottom = 0; var publicList = _driver.FindElement(Const.PublicLvId); _x = (int)(_screenSize.Width * 0.5); _fromY = (int)(_screenSize.Height * 0.9); _toY = (int)(_screenSize.Height * 0.1); var scrollDistance = _fromY - _toY; var isLastTime = false; while (true) { var elements = FetchPublicItems(publicList); foreach (var element in elements) { if (element.Rect.Top > previousBottom - scrollDistance) { OperatePublicItem(element); } } previousBottom = elements.Last().Rect.Bottom; Swipe(new Point(_x, _fromY), new Point(_x, _toY), TimeSpan.FromSeconds(1)); if (!IsPublicBottom()) { continue; } if (isLastTime) { break; } isLastTime = true; } } catch (Exception e) { Console.WriteLine(e); } finally { _driver?.Quit(); } }
private IWebElement GetElement(string id) { IWebElement element = null; string[] index = null; if (id.Contains('[') && id.Contains(']')) { string[] idParts = id.Split(new[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries); id = idParts[0]; index = idParts.Skip(1).ToArray(); } string signature = GetSignature(id); string[] byParams = new string[2]; int pos = signature.IndexOf(':'); byParams[0] = signature.Substring(0, pos); byParams[1] = signature.Substring(pos + 1); //Get all contexts of the driver,try to locate the elemnt in different context; IList <string> driverContexts = _driver.Contexts; int triedTimes = 0; foreach (string context in driverContexts) { triedTimes++; _driver.Context = context; //_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); _javaScript = (IJavaScriptExecutor)_driver; try { #region js, but not implement rightnow for android in appium if (byParams[0].Equals("js", StringComparison.CurrentCultureIgnoreCase)) { //1. try to get element by js directly object elementObj = _javaScript.ExecuteScript(byParams[1]); if (elementObj == null) { //2. try to return element by js elementObj = _javaScript.ExecuteScript("return " + byParams[1]); } if (elementObj == null) { //3. try to get element from collections by js string indexString = "[" + string.Join("][", index) + "]"; if (byParams[1].Contains("return")) { elementObj = _javaScript.ExecuteScript(string.Format("{0}{1};", byParams[1], indexString)); } else { elementObj = _javaScript.ExecuteScript(string.Format("return {0}{1};", byParams[1], indexString)); } } if (elementObj == null) { throw new Exception(string.Format("Cannot found element {0}", id)); } //if target is a collections, to get the one matched index if (elementObj is System.Collections.IList) { elementObj = index.Aggregate(elementObj, (current, i) => ((System.Collections.IList)current)[int.Parse(i)]); } if (elementObj is IWebElement) { element = elementObj as IWebElement; } //else // element = new TextWebElement(elementObj.ToString()); } #endregion //other locate function but javascript. else { By by = null; if (byParams[0].Equals("AccessibilityId", StringComparison.CurrentCultureIgnoreCase)) { by = new ByAccessibilityId(byParams[1].ToString()); } else { by = typeof(By).InvokeMember(byParams[0], BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new object[] { byParams[1] }) as By; } if (index != null) { bool optionIsIndex = false; int optionIndex = -1; optionIsIndex = int.TryParse(index[0], out optionIndex); if (!optionIsIndex) { if (index[0].StartsWith("\"") && index[0].EndsWith("\"")) { index[0] = index[0].Substring(1, index[0].Length - 2); } } IList <IWebElement> foundList = _driver.FindElements(by); //check the found element is list view if (foundList.Count == 1 && foundList[0].TagName.ToLower().Contains("listview")) { IWebElement e = foundList[0]; string tagname = e.TagName; string resource_id = e.GetAttribute("resourceId"); string xpath = string.Empty; //if option is index, just search child, otherwise descendant. if (optionIsIndex) { xpath = string.Format("//{0}[@resource-id='{1}']/child::*", tagname, resource_id); } else { xpath = string.Format("//{0}[@resource-id='{1}']/descendant::*", tagname, resource_id); } //get all children of the listview IList <IWebElement> childElementList = _driver.FindElements(By.XPath(xpath)); if (childElementList.Count == 0) { throw new OpenQA.Selenium.NoSuchElementException("There is not options for the element: " + id); } if (optionIndex >= childElementList.Count) { throw new OpenQA.Selenium.NoSuchElementException("There is not option " + optionIndex + " in the element: " + id); } //check the option is index or content. if (optionIsIndex) { element = childElementList[optionIndex]; } else { element = childElementList.First(item => CommonHelper.IsMatchRegex(index[0], item.Text)); } if (element == null) { throw new OpenQA.Selenium.NoSuchElementException("There is not option " + index[0] + " in the element: " + id); } } //if the result is collection, just get the item in the collection else { //check the option is index or content. if (optionIsIndex) { element = foundList[optionIndex]; } else { element = foundList.First(item => CommonHelper.IsMatchRegex(index[0], item.Text)); } } } //if there is [#], will return the element directly. else { element = _driver.FindElement(by); } } } catch { if (triedTimes == driverContexts.Count) { throw new Exception(string.Format("Cannot found element {0}", id)); } } //If found the element in one context, quit the foreach if (element != null) { break; } } return(element); }
//For Scrolling down directly to the button //public void PressEnter(string locator) //{ // waitDriver.Until(ExpectedConditions.ElementExists(By.Id(locator))); // { // IWebElement elementbutton = waitDriver.Until(ExpectedConditions.ElementExists(By.Id(locator))); // IJavaScriptExecutor js = (IJavaScriptExecutor)driver; // js.ExecuteScript("arguments[0].scrollIntoView();", elementbutton); // // var elmnt = document.getElementById("content"); // // elmnt.scrollIntoView(); // IWebElement button = waitDriver.Until(ExpectedConditions.ElementToBeClickable(By.Id(locator))); // { // //button.SendKeys(OpenQA.Selenium.Keys.Enter); // button.Click(); // } // // js.executeScript("arguments[0].scrollIntoView();", locator); // } //} //public void ScrollToElement(string locator) //{ // waitDriver.Until(ExpectedConditions.ElementExists(By.Id(locator))); // { // IWebElement elementbutton = waitDriver.Until(ExpectedConditions.ElementExists(By.Id(locator))); // IJavaScriptExecutor js = (IJavaScriptExecutor)driver; // js.ExecuteScript("arguments[0].scrollIntoView();", elementbutton); // // var elmnt = document.getElementById("content"); // // elmnt.scrollIntoView(); // //IWebElement button = waitDriver.Until(ExpectedConditions.ElementToBeClickable(By.Id(locator))); // //{ // // //button.SendKeys(OpenQA.Selenium.Keys.Enter); // // button.Click(); // //} // // js.executeScript("arguments[0].scrollIntoView();", locator); // } //} //public void verification(string message, string locator) //{ // try // { // IWebElement Control = waitDriver.Until(ExpectedConditions.ElementIsVisible(By.Id(locator))); // Assert.AreEqual(message, Control.Text); // } // catch (ElementNotVisibleException ex) // { // throw new AssertFailedException(string.Format("The element provided {0} is invalid", locator)); // } // catch (Exception ex) // { // throw new Exception(ex.Message); // } //} //For returning the value from the web page of the keyword given using xpath public void date_wheel(string year, string month) { try { month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Convert.ToInt32(month)).Substring(0, 3); scroll_to_element_text(month); var pickerChildren = driver.FindElements(By.Id("android:id/numberpicker_input")); string check = pickerChildren[0].GetAttribute("text"); if (check != month) { ITouchAction tc = new TouchAction(driver); var element = driver.FindElements(By.ClassName("android.widget.Button")); string value = element[0].GetAttribute("text"); string value2 = element[1].GetAttribute("text"); if (value == month) { Thread.Sleep(2000); tc.Press(pickerChildren[0]).Wait(1000).MoveTo(element[1]).Release().Perform(); } else if (value2 == month) { Thread.Sleep(2000); tc.Press(pickerChildren[0]).Wait(1000).MoveTo(element[0]).Release().Perform(); } } scroll_to_element_text_instance(year, "2"); check = pickerChildren[1].GetAttribute("text"); if (check != month) { ITouchAction tc = new TouchAction(driver); var element = driver.FindElements(By.ClassName("android.widget.Button")); string value = element[2].GetAttribute("text"); string value2 = element[3].GetAttribute("text"); if (value == year) { Thread.Sleep(2000); tc.Press(pickerChildren[1]).Wait(1000).MoveTo(element[3]).Release().Perform(); } else if (value2 == year) { Thread.Sleep(2000); tc.Press(pickerChildren[1]).Wait(1000).MoveTo(element[2]).Release().Perform(); } } } catch (Exception ex) { throw new Exception(ex.Message); } }