/// <summary> /// Test all links on the Krossover home page /// </summary> public void testHomePage(FirefoxDriver driver) { string homePage = "http://www.krossover.com/"; driver.Navigate().GoToUrl(homePage); Thread.Sleep(1000); //find all links on the page IList<IWebElement> links = driver.FindElementsByTagName("a"); //loop through all of the links on the page foreach (IWebElement link in links) { try { //check if any of the links return a 404 link.SendKeys(Keys.Control + Keys.Enter); driver.SwitchTo().Window(driver.WindowHandles.Last()); driver.FindElementByXPath("//div[contains(@class, '404')]"); log(link.GetAttribute("href") + " is broken. Returned 404"); driver.SwitchTo().Window(driver.WindowHandles.First()); } catch { //continue to the next link continue; } } driver.Quit(); //kill the driver }
public void Test2() { var driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://tourism.51book.com/adminLogin.htm"); driver.FindElement(By.Id("userName")).SendKeys("ZLBGYCS"); driver.FindElement(By.Id("password")).SendKeys("123456"); driver.FindElement(By.Id("submit")).Submit(); driver.FindElement(By.XPath("/html/body/table/tbody/tr/td[1]/div/a[1]")).Click(); driver.FindElement(By.Id("nextSteps")).Click(); driver.SwitchTo().DefaultContent(); driver.SwitchTo().Frame(""); }
static void Main(string[] args) { IWebDriver driver; driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://www.javascriptsandmore.com/javascript-alert-box.html"); IAlert alert = driver.SwitchTo().Alert(); Console.WriteLine(alert.Text); alert.Accept(); IAlert next_alert = driver.SwitchTo().Alert(); Console.WriteLine(next_alert.Text); next_alert.Accept(); driver.Quit(); Console.Read(); }
public void WindowProcess_Demo2() { var articleName = "[小北De编程手记] : Lesson 02 - Selenium For C# 之 核心对象"; _output.WriteLine("Step 01 : 启动浏览器并打开Lesson 01 - Selenium For C#"); IWebDriver driver = new FirefoxDriver(); driver.Url = "http://www.cnblogs.com/NorthAlan/p/5155915.html"; _output.WriteLine("Step 02 : 点击链接打开新页面。"); var lnkArticle02 = driver.FindElement(By.LinkText(articleName)); lnkArticle02.Click(); _output.WriteLine("Step 03 : 根据标题获取新页面的句柄。"); var oldWinHandle = driver.CurrentWindowHandle; foreach (var winHandle in driver.WindowHandles) { driver.SwitchTo().Window(winHandle); if (driver.Title.Contains(articleName)) { break; } } _output.WriteLine("Step 04 : 验证新页面标题是否正确。"); var articleTitle = driver.FindElement(By.Id("cb_post_title_url")); Assert.Equal<string>(articleName, articleTitle.Text); _output.WriteLine("Step 05 : 关闭浏览器。"); driver.Quit(); }
public void WindowProcess_Demo1() { // 1. 获取窗口定位对象 IWebDriver driver = new FirefoxDriver(); //省略部分代码... ... ITargetLocator locator = driver.SwitchTo(); driver = locator.Window("windowName"); //后续操作... ... driver.Quit(); }
public void shouldAllLinkLeadSomewhere() { IWebDriver driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://www.theguardian.com"); var mainPage = new MainEntryPage(driver); listoflinks = mainPage.GetLinks (driver); for (int n = 0; n < listoflinks.Count; n++) { Console.WriteLine(listoflinks[n].Text); var beforeWindow = driver.CurrentWindowHandle; if (driver.FindElement(By.LinkText(listoflinks[n].Text)).Displayed && listoflinks[n].Text != "Sign in"){ Console.WriteLine("Found link: " + listoflinks[n].Text); driver.FindElement(By.LinkText(listoflinks[n].Text)).SendKeys(Keys.Shift + Keys.Return); foreach (string handle in driver.WindowHandles) { if (handle != beforeWindow) { driver.SwitchTo().Window(handle); break; } } Console.WriteLine("UJ: " + driver.Url); driver.Close(); driver.SwitchTo().Window(beforeWindow); Console.WriteLine("REGI: " + driver.Url); } else { Console.WriteLine("NotFound link: " + listoflinks[n].Text); } //driver.Navigate().Back(); } }
public void Test2() { //var driver = new InternetExplorerDriver(@"D:\test file\selenium\IEDriverServer"); //FirefoxProfile firfoxProfile = new FirefoxProfile(@"D:\install\Mozilla Firefox"); var driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://tourism.51book.com/adminLogin.htm"); driver.FindElement(By.Id("userName")).SendKeys("ZLBGYCS"); driver.FindElement(By.Id("password")).SendKeys("123456"); driver.FindElement(By.Id("submit")).Submit(); driver.FindElement(By.XPath("/html/body/table/tbody/tr/td[1]/div/a[1]")).Click(); System.Collections.Generic.IList<string> handls=driver.WindowHandles; IWebDriver childeDriver = driver.SwitchTo().Window(handls[1]); childeDriver.FindElement(By.Id("nextSteps")).Click(); //////childeDriver.SwitchTo().DefaultContent(); //////childeDriver.SwitchTo().Frame(1); var iframe = childeDriver.FindElement(By.CssSelector("iframe.ke-edit-iframe")); childeDriver.SwitchTo().Frame(iframe);//进入iframe childeDriver.FindElement(By.XPath("/html/body")).SendKeys("12345678");//进入body输入数据 }
public void Test() { string testTime = DateTime.Now.ToString("t"); var driver=new FirefoxDriver(); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl("http://www.51aqy.com/"); driver.FindElement(By.CssSelector("a.xs2-link")).Click(); System.Collections.Generic.IList<string> handles = driver.WindowHandles;//获取窗口数量 IWebDriver chilWindow = driver.SwitchTo().Window(handles[1]);//调转到当前窗口 // chilWindow.Close();//关闭当前窗口 chilWindow.FindElement(By.CssSelector("a.app-data > span.text")).Click();//对当前窗口操作 System.Collections.Generic.IList<string> handles1 = chilWindow.WindowHandles; IWebDriver TwoWindow = chilWindow.SwitchTo().Window(handles1[1]); TwoWindow.FindElement(By.Id("input1")).SendKeys("880082993370"); TwoWindow.FindElement(By.Id("input2")).SendKeys("15015015050"); TwoWindow.FindElement(By.CssSelector("button.open-client")).Click(); TwoWindow.FindElement(By.CssSelector("#myModal-no-bangding > div.modal-header > button.close")).Click(); string actualResult = TwoWindow.FindElement(By.CssSelector("div.info > span.info-name ")).Text; string expectedResult = "尊敬的用户"; Assert.AreEqual(expectedResult, actualResult); //Console.WriteLine(actualResult); //将测试结果写入excel // Helper.NPOIHelper(testTime,expectedResult,actualResult); log4net.ILog iLog = log4net.LogManager.GetLogger("message"); if (iLog.IsDebugEnabled) { iLog.Debug("debug"); } if (iLog.IsInfoEnabled) { iLog.Info("message"); } driver.Quit(); }
public void WindowProcess_Demo3() { IWebDriver driver = new FirefoxDriver(); //省略部分代码... ... var oldWinHandle = driver.CurrentWindowHandle; ITargetLocator locator = driver.SwitchTo(); IAlert winAlert = locator.Alert(); winAlert.Accept(); //确定:Alert , Confirm, Prompt winAlert.Dismiss(); //取消:Confirm, Prompt var text = winAlert.Text; //获取提示内容:Alert , Confirm, Prompt winAlert.SendKeys("input text."); //输入提示文本:Prompt //后续操作... ... driver.Quit(); }
static void Main(string[] args) { Console.WriteLine("Please enter the URL (Like :- https://qa-playdays.lego.com )\n\t"); var url = Console.ReadLine(); //var url = "http://google.com"; var path = AppDomain.CurrentDomain.BaseDirectory + "\\Result"; string subject = "Regress Test for " + url; string str = "<center><table border=1 ><caption><b>Site Tracking : " + subject + "</b></caption>"; str += "<tr><th style='width:700px'>Test Case </th><th style='width:150px;'>Result</th></tr>"; Proxy proxy = new Proxy(); proxy.IsAutoDetect = true; DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.SetCapability(CapabilityType.Proxy, proxy); IWebDriver driver = new FirefoxDriver(capabilities); driver.Manage().Cookies.DeleteAllCookies(); driver.Navigate().GoToUrl(url); driver.Manage().Window.Maximize(); driver.SwitchTo().ParentFrame(); IWebElement scriptTag = null; try { var updatedURL = driver.Url; var words = updatedURL.Split('/'); var local = words[3].ToLower(); var environment = words[2].ToLower(); try { Console.WriteLine("Test Case 1 : Verify the site tracking implementation by checking presence of ‘data-tracking-script’ tag in DOM "); scriptTag = driver.FindElement(By.CssSelector("script[data-tracking-script]")); Console.WriteLine("Test Case 1 : Pass - Verify the site tracking implementation by checking presence of ‘data-tracking-script’ tag in DOM"); str += "<tr><td>Test Case 1 : Verify the site tracking implementation by checking presence of ‘data-tracking-script’ tag in DOM </td><td> Pass" + "</td></tr>"; } catch (Exception) { Console.WriteLine("Test Case 1 : Fail - 1. Site tracking implementation by checking presence of ‘data-tracking-script’ tag in DOM"); str += "<tr><td>Test Case 1 : Verify the site tracking implementation by checking presence of ‘data-tracking-script’ tag in DOM </td><td> Fail" + "</td></tr>"; } if (scriptTag != null) { Console.WriteLine("Test Case 2 : Verify URL locale (ex. da-dk) should match with site tracking script tag i.e. cultural-info attribute (da-dk) "); try { var cultureInfo = scriptTag.GetAttribute("culture-info").ToLower(); Console.WriteLine("Locale mention in 'Culture-Info' attribute : " + cultureInfo); try { //Assert.Equals(local, cultureInfo); if (cultureInfo.Equals(local)) { Console.WriteLine("Test Case 2 : Pass - Verify URL locale should match with site tracking script tag i.e. cultural-info attribute : " + cultureInfo); str += "<tr><td>Test Case 2 : Verify URL locale (ex. da-dk) should match with site tracking script tag i.e. cultural-info attribute (da-dk) </td><td> Pass" + "</td></tr>"; } else if (cultureInfo.Equals("en-us")) // check with Dev End for better implementation { Console.WriteLine("Test Case 2 : Pass - Verify URL locale should match with site tracking script tag i.e. cultural-info attribute : " + cultureInfo); str += "<tr><td>Test Case 2 : Verify URL locale should match with site tracking script tag i.e. cultural-info attribute :" + cultureInfo + " </td><td> Pass" + "</td></tr>"; } else { Console.WriteLine("Test Case 2 : Fail - URL locale should not match with site tracking script tag i.e. cultural-info attribute : " + cultureInfo); str += "<tr><td>Test Case 2 : Verify URL locale should not match with site tracking script tag i.e. cultural-info attribute :" + cultureInfo + " </td><td> Fail" + "</td></tr>"; } } catch (Exception) { Console.WriteLine("Test Case 2 : Fail - URL locale should not match with site tracking script tag i.e. cultural-info attribute : " + cultureInfo); str += "<tr><td>Test Case 2 : URL locale should not match with site tracking script tag i.e. cultural-info attribute :" + cultureInfo + " </td><td> Fail" + "</td></tr>"; } } catch (Exception) { Console.WriteLine("Test Case 2 : Fail - Because Culture-info Attribute Tag is Missing "); str += "<tr><td>Test Case 2 : URL locale should not match with site tracking script tag i.e. cultural-info attribute (da-dk) </td><td> Fail" + "</td></tr>"; } } if (scriptTag != null) { Console.WriteLine("Test Case 3 : Verify ‘Report Suite’ should be as per expectation i.e. for QA it should be 'LegoGlobalQA' and Live it should be 'Global' "); if (environment.Contains("qa-")) { try { var dataReportSuite = scriptTag.GetAttribute("data-reportsuite").ToLower(); Console.WriteLine("Report Suite is in 'dataReportSuite' attribute : " + dataReportSuite); if (dataReportSuite.Equals("legoglobalqa") || dataReportSuite.Contains("qa")) { Console.WriteLine("Test Case 3 : Pass - Verify ‘Report Suite’ should be as per expectation i.e. for QA it should be 'LegoGlobalQA' "); str += "<tr><td>Test Case 3 : Verify ‘Report Suite’ should be as per expectation for QA i.e. " + dataReportSuite + "</td><td> Pass" + "</td></tr>"; } else { Console.WriteLine("Test Case 3 : Fail - ‘Report Suite’ should npt be as per expectation "); str += "<tr><td>Test Case 3 : ‘Report Suite’ should not be as per expectation i.e. for QA it should not be 'LegoGlobalQA' </td><td> Fail" + "</td></tr>"; } } catch (Exception) { Console.WriteLine("Test Case 3 : Fail Because data-reportsuite Attribute Tag is Missing in QA env"); str += "<tr><td>Test Case 3 :‘Report Suite’ should not be as per expectation i.e. for QA it should not be 'LegoGlobalQA' </td><td> Fail" + "</td></tr>"; } } else { try { var dataReportSuite = scriptTag.GetAttribute("data-reportsuite").ToLower(); Console.WriteLine("Report Suite is in 'dataReportSuite' attribute : " + dataReportSuite); if (dataReportSuite.Equals("")) { Console.WriteLine("Test Case 3 : Pass - ‘Report Suite’ should be as per expectation i.e. for Live it should be 'Global' "); str += "<tr><td>Test Case 3 : ‘Report Suite’ should be as per expectation for Live i.e. " + dataReportSuite + " empty in script tag </td><td> Pass" + "</td></tr>"; } else { Console.WriteLine("Test Case 3 : Fail - ‘Report Suite’ should not be as per expectation for Live "); str += "<tr><td>Test Case 3 : ‘Report Suite’ should not be as per expectation for live " + dataReportSuite + "</td><td> Fail" + "</td></tr>"; } } catch (Exception) { Console.WriteLine("Test Case 3 : Pass - Because if data-reportsuite Attribute Tag is Missing in Live env than it points to Global"); str += "<tr><td>Test Case 3 : ‘Report Suite’ should be as per expectation for Live </td><td> Pass" + "</td></tr>"; } } } if (scriptTag != null) { Console.WriteLine("Test Case 4 : Verify ‘Page Name’(ex. playdays:homepage:overview) should be as per expectation i.e. data-initial-page attribute should not be empty and should contains two :(colons) like - playdays:homepage:overview"); try { var dataInitialPage = scriptTag.GetAttribute("data-initial-page"); Assert.DoesNotThrow(() => dataInitialPage.ToLower()); var count = dataInitialPage.Count(f => f == ':'); Assert.AreEqual(count, 2); Console.WriteLine("Test Case 4 : Pass - Verify ‘Page Name’(ex. playdays:homepage:overview) should be as per expectation i.e. data-initial-page attribute should not be empty and should contains two :(colons) like - playdays:homepage:overview"); str += "<tr><td>Test Case 4 : Verify ‘Page Name’(ex. playdays:homepage:overview) should be as per expectation i.e. data-initial-page attribute should not be empty and should contains two :(colons) and Page Name is : " + dataInitialPage + " </td><td> Pass" + "</td></tr>"; } catch (Exception) { Console.WriteLine("Test Case 4 : Fail, Because Either Page Name is missing or Not In Proper Format"); str += "<tr><td>Test Case 4 : Verify Page Name Should as Per Expectation : Because Either Page Name is missing or Not In Proper Format </td><td> Fail" + "</td></tr>"; } } if (scriptTag != null) { Console.WriteLine("Test Case 5 : Verify site tracking ‘src’ attribute should contain Trackmanapi"); try { var src = scriptTag.GetAttribute("src"); Assert.IsTrue(src.Contains("TrackManApi")); Console.WriteLine("Test Case 5 : Pass, Verify site tracking ‘src’ attribute should contain Trackmanapi"); str += "<tr><td>Test Case 5 : Verify site tracking ‘src’ attribute should contain Trackmanapi : " + src + " </td><td> Pass" + "</td></tr>"; } catch (Exception) { Console.WriteLine("Test Case 5 : Fail, site tracking ‘src’ attribute should not contain Trackmanapi"); str += "<tr><td>Test Case 5 : Site tracking ‘src’ attribute should not contain Trackmanapi </td><td> Fail" + "</td></tr>"; } } } catch (Exception) { Console.WriteLine("Please check URL "); str += "<tr><td>Please check URL or Site not loaded. Please Try Again.. </td><td> Fail" + "</td></tr>"; } //------------------------------------------------- sticky footer test script------------------------------------------------------------------- Console.WriteLine("-----------------------The script to test sticky footer------------------------- "); str += "<tr><td colspan=\"2\"><center><B> The script to test sticky footer" + "</B></center></td></tr>"; driver.Manage().Window.Maximize(); //driver.FindElement(By.CssSelector("#closing")).Click(); try { bool present; try { driver.FindElement(By.CssSelector("#closing")); driver.FindElement(By.CssSelector("#closing")).Click(); } catch (NoSuchElementException) { Console.WriteLine("No one time sticky footer"); } } catch (NUnit.Framework.AssertionException) { } // Checking the visibility of sticky footer string b = "#GFSticky"; try { try { driver.FindElement(By.CssSelector(b)); Assert.AreEqual(true, driver.FindElement(By.CssSelector(b)).Displayed); str += "<tr><td>Test Case 1 : Pass- Verify the visibility of sticky footer </td><td> Pass" + "</td></tr>"; Console.WriteLine("Test Case 1 : Pass- Verify the visibility of sticky footer"); } catch (NoSuchElementException) { Console.WriteLine("Testcase 1: Fail- Verify the visibility of sticky footer"); str += "<tr><td>Testcase 1: Fail- Verify the visibility of sticky footer</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } //check the visibility of privacy string c = "#GFSpplink"; try { try { driver.FindElement(By.CssSelector(c)); Console.WriteLine("Testcase 2: Pass- Verify the visibility of privacy"); Assert.AreEqual(true, driver.FindElement(By.CssSelector(c)) != null); str += "<tr><td>Test Case 2 :Verify the visibility of privacy </td><td> Pass" + "</td></tr>"; } catch (NoSuchElementException) { Console.WriteLine("Testcase 2: Fail- Verify the visibility of privacy "); str += "<tr><td>Testcase 2: Fail- Verify the visibility of privacy</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } //check the visibility of cookies string d = "#GFScilink"; try { try { driver.FindElement(By.CssSelector(d)); Console.WriteLine("Testcase 3: Pass- Verify the visibility of cookies"); Assert.AreEqual(true, driver.FindElement(By.CssSelector(d)) != null); str += "<tr><td>Test Case 3:Verify the visibility of cookies </td><td> Pass" + "</td></tr>"; } catch (NoSuchElementException) { Console.WriteLine("Testcase 3: Fail- Verify the visibility of cookies"); str += "<tr><td>Testcase 3: Fail- Verify the visibility of cookies</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } //checking if the sticky footer is present string z = "#GFSticky"; try { try { driver.FindElement(By.CssSelector(z)); Console.WriteLine("Testcase 4: Pass- Verify the presence of sticky footer"); Assert.AreEqual(true, driver.FindElement(By.CssSelector(z)) != null); str += "<tr><td>Test Case 4 :Verify the presence of sticky footer </td><td> Pass" + "</td></tr>"; } catch (NoSuchElementException) { Console.WriteLine("Testcase 4: Fail-Verify the presence of sticky footer"); str += "<tr><td>Testcase 4: Fail- Verify the presence of sticky footer</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } //checking if the privacy is present string y = "#GFSpplink"; try { try { driver.FindElement(By.CssSelector(y)); Console.WriteLine("Testcase 5: Pass- Verify the presence of privacy"); Assert.AreEqual(true, driver.FindElement(By.CssSelector(y)) != null); str += "<tr><td>Test Case 5 :Verify the presence of privacy </td><td> Pass" + "</td></tr>"; } catch (NoSuchElementException) { Console.WriteLine("Testcase 5: Fail-Verify the presence of privacy"); str += "<tr><td>Testcase 5: Fail- Verify the presence of privacy</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } //checking if the cookies is present string g = "#GFScilink"; try { try { driver.FindElement(By.CssSelector(g)); Console.WriteLine("Testcase 6: Pass- Verify the presence of cookies"); Assert.AreEqual(true, driver.FindElement(By.CssSelector(g)) != null); str += "<tr><td>Test Case 6 :Verify the presence of cookies</td><td> Pass" + "</td></tr>"; } catch (NoSuchElementException) { Console.WriteLine("Testcase 6: Fail-Verify the presence of cookies"); str += "<tr><td>Testcase 6: Fail- Verify the presence of cookies</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } driver.Manage().Cookies.DeleteAllCookies(); //Switching to iframe of sticky footer driver.SwitchTo().ParentFrame(); Console.WriteLine("Checking if there exist any text in the privacy popup"); try { try { IWebElement privacy_text = driver.FindElement(By.TagName("body")); driver.FindElement(By.CssSelector("#GFSpplink")); driver.FindElement(By.CssSelector("#GFSpplink")).Click(); Console.WriteLine("Testcase 7: Text exists in the privacy popup"); Assert.IsNotNullOrEmpty(privacy_text.Text); str += "<tr><td>Test Case 7 :Text exists in the privacy popup</td><td> Pass" + "</td></tr>"; driver.FindElement(By.CssSelector(".lego-modal-wrapper.lego-modal-close-trigger.lego-in")).Click(); } catch (NoSuchElementException) { Console.WriteLine("Testcase 7: Fail-Text exists in the privacy popup"); str += "<tr><td>Testcase 7: Fail- Text exists in the privacy popup</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } driver.Manage().Cookies.DeleteAllCookies(); //Checking if there exist any text in the cookies popup try { try { IWebElement cookie_text = driver.FindElement(By.TagName("body")); driver.FindElement(By.CssSelector("#GFScilink")); driver.FindElement(By.CssSelector("#GFScilink")).Click(); Console.WriteLine("Testcase 8: Text exists in the cookies popup"); Assert.IsNullOrEmpty(cookie_text.Text); str += "<tr><td>Test Case 8 :Text exists in the cookies popup</td><td> Pass" + "</td></tr>"; } catch (NoSuchElementException) { Console.WriteLine("Testcase 8: Fail-Text exists in the cookies popup"); str += "<tr><td>Testcase 8: Fail- Text exists in the cookies popup</td><td> Fail" + "</td></tr>"; } } catch (NUnit.Framework.AssertionException) { } //-------------------------------------------------------------------------------------------------legoid------------------------- driver.Navigate().GoToUrl(url); LoginPage obj = new LoginPage(); Console.WriteLine("\n\tPlease Enter the Username : "******"\n\tPlease Enter the Password : "******"</table></center></body><html>"; //string Res = AppDomain.CurrentDomain.BaseDirectory + "\\TestReport.html"; //FileStream fs = new FileStream(Res, FileMode.Create); //StreamWriter sw = new StreamWriter(fs); //sw.WriteLine(str); //sw.Close(); //fs.Close(); //Lego Header----------------------------------------------------------------------------------------------------------------------------- string str_result = "<tr><td colspan=\"2\"> <center><b>Lego header test</b></center></td>"; IWebElement main_logo = null; String title_page = null; driver.Navigate().GoToUrl(url); driver.Manage().Window.Maximize(); try { IJavaScriptExecutor js1 = driver as IJavaScriptExecutor; string title1 = (string)js1.ExecuteScript("return window.getComputedStyle( document.querySelector('.lego-global-header-wrap .lego-brand a'), ':after' ).getPropertyValue('box-sizing')"); IWebElement header = driver.FindElement(By.CssSelector(".lego-global-navigation")); string header_postion = header.GetCssValue("position"); Console.WriteLine(title1); string p = "absolute"; if (header_postion == p) { Console.WriteLine("mobile view"); } else { Console.WriteLine("desk view"); throw new Exception(); } } catch (Exception) { Console.WriteLine("Inside desktop view"); } try { main_logo = driver.FindElement(By.ClassName("logo")); if (main_logo.Enabled && main_logo.Displayed) { Console.WriteLine("Main logo is present"); str_result += "<tr><td>Main Logo</td> <td>Present</td></tr>"; try { main_logo.Click(); str_result += "<tr><td>Main Logo</td> <td>Is Clickable</td></tr>"; driver.Navigate().Back(); } catch { str_result += "<tr><td>Main Logo</td> <td>Is Not Clickable</td></tr>"; Console.WriteLine("Main logo is not clickable"); } } else { str_result = str_result + "<tr><td>Main Logo</td> <td>IS Not Present</td></tr>"; } } catch (Exception e) { str_result = str_result + "<tr><td>Lego header</td> <td>IS Not Present</td></tr>"; } //code according to desktop view try { IWebElement brandingsection = driver.FindElement(By.XPath("//div[@class='lego-global-navigation']/ul")); List<string> anchor_list = new List<string>(); IList<IWebElement> totallogos = brandingsection.FindElements(By.TagName("a")); IJavaScriptExecutor js = driver as IJavaScriptExecutor; string title = (string)js.ExecuteScript("return window.getComputedStyle( document.querySelector('.lego-global-navigation .global-links a'), ':before' ).getPropertyValue('background-image')"); int ifirstindx = title.IndexOf("url"); int start = ifirstindx + 5; string s = title.Substring(start); int l = s.Length; string final_url = s.Substring(0, l - 2); Console.WriteLine("Total logos present are" + ":" + totallogos.Count); HttpWebRequest request_url = (HttpWebRequest)WebRequest.Create(final_url); request_url.Method = "GET"; try { using (var response_url = request_url.GetResponse()) { Thread.Sleep(2000); HttpStatusCode statusCode_url = ((HttpWebResponse)response_url).StatusCode; Console.WriteLine("Lego Header Images Url status" + ":" + statusCode_url); str_result += "<tr><td>Status of All Images in Navigation</td> <td>" + statusCode_url + "</td></tr>"; } } catch { str_result += "<tr><td>Status of All Images in Navigation</td> <td> Not Found </td></tr>"; } try { for (int i = 0; i < totallogos.Count; i++) { brandingsection = driver.FindElement(By.XPath("//div[@class='lego-global-navigation']/ul")); totallogos = brandingsection.FindElements(By.TagName("a")); NUnit.Framework.Assert.IsTrue(driver.FindElement(By.TagName("a")).Enabled); anchor_list.Add(totallogos[i].GetAttribute("href")); Console.WriteLine(anchor_list.Count); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(anchor_list[i]); request.Method = "GET"; Thread.Sleep(2000); using (var response = request.GetResponse()) { HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode; Console.WriteLine(anchor_list[i]); Console.WriteLine(statusCode); str_result += "<tr><td>" + anchor_list[i] + "</td> <td>" + statusCode + "</td></tr>"; } } catch { Console.WriteLine("No response for : " + anchor_list[i]); str_result += "<tr><td>" + anchor_list[i] + "</td> <td> Not Clickable </td></tr>"; } IWebElement main_logo2 = driver.FindElement(By.ClassName("logo")); main_logo2.Click(); //if (totallogos[i].Enabled && totallogos[i].Displayed) //{ try { Thread.Sleep(2000); totallogos[i].Click(); title_page = driver.Title; Console.WriteLine((title_page)); str_result += "<tr><td>" + title_page + "</td> <td>Clickable</td></tr>"; driver.Navigate().Refresh(); driver.Navigate().Back(); driver.Navigate().Refresh(); Thread.Sleep(500); IWebElement main_logo1 = driver.FindElement(By.ClassName("logo")); main_logo1.Click(); Thread.Sleep(1000); } catch (Exception ex) { Console.WriteLine("Item is not clickable" + ":" + title_page + ex.ToString()); // str_result += "<tr><td>" + title_page + "</td> <td>Not Clickable</td></tr>"; } } } catch (Exception e) { } } catch ( Exception e) { } str = str + str_result; str = str + "</table></center></body><html>"; string Res = AppDomain.CurrentDomain.BaseDirectory + "\\TestReport.html"; FileStream fs = new FileStream(Res, FileMode.Create); StreamWriter sw = new StreamWriter(fs); sw.WriteLine(str); sw.Close(); fs.Close(); //Console.WriteLine("The end"); //string Res = AppDomain.CurrentDomain.BaseDirectory + "\\TestReport.html"; //FileStream fs = new FileStream(Res, FileMode.Create); //StreamWriter sw = new StreamWriter(fs); //sw.WriteLine(str_result); ; //str_result = str_result + "<tr><td>End of Prog</td> <td>The End</td></tr><table></body> </html>"; //StreamWriter sw = new StreamWriter("D:/Lego_Automate/LegoHeader/LegoHeader/Result/res.html", false); //FileStream fs = new FileStream(str_result, FileMode.Create); //StreamWriter sw = new StreamWriter(fs); // sw.WriteLine(DateTime.Now.ToString() + str_result); //sw.Flush(); sw.Close(); driver.Navigate().GoToUrl(Res); /* IList<IWebElement> footer_section = driver.FindElements(By.CssSelector(".lego-global-footer-wrap > ul"));//(By.XPath("//div[@class='lego-global-footer-wrap']/ul")); Console.WriteLine(footer_section.Count); Console.WriteLine(footer_section[0].Text); Console.WriteLine(footer_section[1].Text); Console.WriteLine(footer_section[2].Text); List<string> anchor_list_footer = new List<string>(); foreach (var v in footer_section) { IList<IWebElement> total_sub_sections = v.FindElements(By.TagName("li")); Console.WriteLine(total_sub_sections.Count); // Console.WriteLine(v.Text); for (int i = 0; i < total_sub_sections.Count; i++) { // Console.WriteLine(total_sub_sections[i].Text + " index" + i); if (total_sub_sections[i].Enabled && total_sub_sections[i].Displayed) { Console.WriteLine(total_sub_sections[i].Text + "is present "); } } } driver.Navigate().GoToUrl(Res);*/ }
private void EnterDummyPaymentOptions(FirefoxDriver seleniumInstance,StripeCardDetails cardDetails) { seleniumInstance.SwitchTo().Frame(seleniumInstance.FindElementByCssSelector(".stripe_checkout_app")); var emailEl = seleniumInstance.FindElementByName("email"); emailEl.SendKeys("*****@*****.**"); var cardEl = seleniumInstance.FindElementByName("card_number"); cardEl.SendKeys(cardDetails.CardNumber); var expiresEl = seleniumInstance.FindElementByName("cc-exp"); expiresEl.SendKeys(cardDetails.Expiry); //var nameOnCard = seleniumInstance.FindElementById("paymentName"); //nameOnCard.SendKeys(cardDetails.CardHolderName); var cvc = seleniumInstance.FindElementByName("cc-csc"); cvc.SendKeys(cardDetails.CVC); var submitButton = seleniumInstance.FindElementByCssSelector(".button button"); submitButton.ClickWithJavascript(seleniumInstance); }
public void CorrectUserLogInTest() { IWebDriver driver = new FirefoxDriver(); string baseURL = "http://www.google.com/ "; StringBuilder verificationErrors = new StringBuilder(); driver.Navigate().GoToUrl(baseURL); try { Assert.AreEqual("Google", driver.Title); } catch (Exception e) { verificationErrors.Append(e.Message); } driver.FindElement(By.Id("gb_70")).Click(); driver.FindElement(By.Id("Email")).Clear(); driver.FindElement(By.Id("Email")).SendKeys("testqaexam"); driver.FindElement(By.Id("Passwd")).Clear(); driver.FindElement(By.Id("Passwd")).SendKeys("TestPass"); driver.FindElement(By.Id("signIn")).Click(); for (int second = 0; ; second++) { if (second >= 60) Assert.Fail("timeout"); try { if ("*****@*****.**" == driver.FindElement(By.LinkText("*****@*****.**")).Text) break; } catch (Exception) { } Thread.Sleep(1000); } try { Assert.AreEqual("*****@*****.**", driver.FindElement(By.LinkText("*****@*****.**")).Text); } catch (Exception e) { verificationErrors.Append(e.Message); } // command [selectWindow | null | ] string currentWindowHadle = driver.CurrentWindowHandle; driver.SwitchTo().Window(currentWindowHadle); for (int second = 0; ; second++) { if (second >= 60) Assert.Fail("timeout"); try { if ("*****@*****.**" == driver.FindElement(By.LinkText("*****@*****.**")).Text) break; } catch (Exception) { } Thread.Sleep(1000); } try { Assert.AreEqual("*****@*****.**", driver.FindElement(By.LinkText("*****@*****.**")).Text); } catch (Exception e) { verificationErrors.Append(e.Message); } driver.FindElement(By.LinkText("*****@*****.**")).Click(); for (int second = 0; ; second++) { if (second >= 60) Assert.Fail("timeout"); try { if ("Изход" == driver.FindElement(By.Id("gb_71")).Text) break; } catch (Exception) { } Thread.Sleep(1000); } try { Assert.AreEqual("Изход", driver.FindElement(By.Id("gb_71")).Text); } catch (Exception e) { verificationErrors.Append(e.Message); } driver.FindElement(By.Id("gb_71")).Click(); for (int second = 0; ; second++) { if (second >= 60) Assert.Fail("timeout"); try { if ("Вход" == driver.FindElement(By.Id("gb_70")).Text) break; } catch (Exception) { } Thread.Sleep(1000); } try { Assert.AreEqual("Вход", driver.FindElement(By.Id("gb_70")).Text); } catch (Exception e) { verificationErrors.Append(e.Message); } driver.Quit(); }
public void baiduTest() { var mainWindow = new FirefoxDriver(); INavigation navigation = mainWindow.Navigate(); navigation.GoToUrl("http://www.baidu.com/"); IWebElement btnMainWindow = mainWindow.FindElement(By.Name("tj_reg")); btnMainWindow.Click(); System.Collections.Generic.IList<string> handles = mainWindow.WindowHandles; //for (int i=0;i<handles.Count;i++) //{ // Console.WriteLine(handles[i]); //} //Console.ReadKey(); IWebDriver childWindow = mainWindow.SwitchTo().Window(handles[1]); IWebElement txchildWindow = childWindow.FindElement(By.Id("TANGRAM__PSP_4__account")); txchildWindow.SendKeys("1234567"); }
public void WindowHandleTest() { var mainWindow = new FirefoxDriver(); INavigation navigation = mainWindow.Navigate(); navigation.GoToUrl("http://www.hao123.com"); IWebElement btnMainWindow = mainWindow.FindElement(By.XPath("//*[@id='site']/div/ul/li[1]/a")); btnMainWindow.Click(); System.Collections.Generic.IList<string> handles = mainWindow.WindowHandles; //获取窗口的数量 IWebDriver childWindow = mainWindow.SwitchTo().Window(handles[1]); //定位到第一个窗口 IWebElement textchildWindow = childWindow.FindElement(By.Id("kw")); textchildWindow.SendKeys("selenium"); IWebElement buttonElement = childWindow.FindElement(By.Id("su")); buttonElement.Click(); mainWindow.SwitchTo().Window(handles[0]); //回到主窗口 }
public void QTest() { var driver = new FirefoxDriver(); driver.Navigate().GoToUrl("http://17186.cn/business/business_detail.3.jsp?columnId=92470&resourceCode=208654&version=3&unikey=ea1dd33180794db683bd17868ce4de7a"); var js_displayBlock = string.Format("document.querySelector('#slide_nav').style.display=' block'"); ((IJavaScriptExecutor)driver).ExecuteScript(js_displayBlock); driver.FindElement(By.XPath("//*[@id='slide_nav']/ul/li[2]/div/a/span")).Click(); System.Collections.Generic.IList<string> handles = driver.WindowHandles; IWebDriver OneHandle = driver.SwitchTo().Window(handles[1]); }
public void makeTest() { var mainWindow = new FirefoxDriver(); mainWindow.Manage().Window.Maximize(); mainWindow.Navigate() .GoToUrl( "http://my.b2b.makepolo.com/ucenter/login/login.php?gotourl=http%3A%2F%2Fmy.b2b.makepolo.com%2Fucenter%2F"); mainWindow.FindElement(By.Id("new_username")).SendKeys("*****@*****.**"); mainWindow.FindElement(By.Id("new_passwd")).SendKeys("123456"); mainWindow.FindElement(By.CssSelector("#new_submitBtn > a")).Click(); Thread.Sleep(5000); var js_displayBlock = string.Format("document.querySelector('div.d-titleBar > a.d-close').style.display=' block'"); ((IJavaScriptExecutor) mainWindow).ExecuteScript(js_displayBlock); mainWindow.FindElement(By.CssSelector("div.d-titleBar > a.d-close")).Click(); //mainWindow.FindElement(By.XPath("div[@class='menu']/dl[4]/dd[1]/a")).Click(); mainWindow.FindElement(By.LinkText("发布产品")).Click(); mainWindow.FindElement(By.CssSelector("div.product_post_one > a.product_post_btn")).Click(); //mainWindow.FindElement(By.CssSelector("div.i_freepost > a.i_freepost_supply")).Click(); System.Collections.Generic.IList<string> handles = mainWindow.WindowHandles; IWebDriver oneWindow = mainWindow.SwitchTo().Window(handles[1]); IWebElement textchildWindow = oneWindow.FindElement(By.CssSelector("div.postProduct_textBox > input.postProduct_textBox_text")); textchildWindow.SendKeys("手机"); IWebElement btnWindow = oneWindow.FindElement(By.CssSelector("div.postProduct_textBox > input.postProduct_textBox_btn")); btnWindow.Click(); Thread.Sleep(5000); IWebElement radioElement = oneWindow.FindElement(By.XPath("//*[@id='tj_cat']/li[1]/label/span")); radioElement.Text.Equals("家电、手机、数码 > 手机、通讯及配件 > 手机保护套/保护壳"); IWebElement btn2Element = oneWindow.FindElement(By.CssSelector("input.postProduct_nextstep")); btn2Element.Click(); //tyr{ // // Loop throgh all products till get "iPhone 4S" name // for (int i = 1; i < 9; i++) { // if(myTestDriver.findElement(By.xpath("//*[@id='product_list']/li["+i+"]/div[2]/h3/a")).getText().equals("iPhone 4S")){ // // click on "iPhone 4S" named product // myTestDriver.findElement(By.xpath("//*[@id='product_list']/li["+i+"]/div[3]/a")).click(); // } // } //} catch (Exception e) { // } // } // } //radioElement.FindElement(By.TagName("18,550")); ////var radioElement = // oneWindow.FindElement( // By.CssSelector("ul[value='18,550']")); //var mouseOverAction = new OpenQA.Selenium.Interactions.Actions(oneWindow); //mouseOverAction.MoveToElement(radioElement); //mouseOverAction.Perform(); radioElement.Click(); IWebElement nextElement = oneWindow.FindElement(By.CssSelector("p.postProduct_btn > input.postProduct_nextstep")); nextElement.Click(); }
static void Main(string[] args) { RemoteWebDriver browser = new FirefoxDriver(); try { browser.Navigate().GoToUrl("http://alitrack.ru/"); #region Login if (browser.FindElementByName("login") != null) { browser.FindElementByName("login").SendKeys(cabinet.alitrack.ru.Properties.Settings.Default.UserName); browser.FindElementByName("pass").SendKeys(cabinet.alitrack.ru.Properties.Settings.Default.Password); browser.FindElementByXPath("//input[@type='submit']").Click(); } #endregion WaitForCompleteXPath(browser, "//a[contains(@href,'tracking')]"); browser.Navigate().GoToUrl("http://cabinet.alitrack.ru/tracking/"); WaitForCompleteXPath(browser, "//a[contains(@href,'tracking')]"); if (browser.PageSource.Contains("trackingCheckAllItems")) { #region update browser.FindElementById("trackingCheckAllItems").Click(); var alert = browser.SwitchTo().Alert(); alert.Accept(); WaitForCompleteXPath(browser, "//div[@id='processingWindow' and contains(@style,'display: none;')]"); var trackingRows = browser.FindElementsByClassName("tracking-row"); foreach (var trackingRow in trackingRows) { Console.WriteLine(trackingRow.FindElement(By.ClassName("name")).Text); string number = trackingRow.GetAttribute("id").Replace("trow", string.Empty); if (browser.PageSource.Contains(string.Format("id=\"refresh-button{0}\"", number))) { browser.FindElementById("refresh-button" + number).Click(); WaitForCompleteXPath(browser, "//div[@id='processingWindow' and contains(@style,'display: none;')]"); } } #endregion #region find new browser.Navigate().GoToUrl("http://cabinet.alitrack.ru/tracking/"); WaitForCompleteXPath(browser, "//a[contains(@href,'tracking')]"); var trackingNewRows = browser.FindElementsByClassName("tracking-row"); Regex regexButtons = new Regex("<div[^>]*class=\"buttons\"[^>]*>(.*?)</div>", RegexOptions.Compiled | RegexOptions.IgnoreCase); Regex regexFull = new Regex("<div[^>]*class=\"fullinfo\"[^>]*>(.*?)</div>", RegexOptions.Compiled | RegexOptions.IgnoreCase); int newCount = 0; StringBuilder newItems = new StringBuilder(); foreach (var trackingRow in trackingNewRows) { Console.WriteLine(trackingRow.FindElement(By.ClassName("name")).Text); if (!string.IsNullOrEmpty(trackingRow.FindElement(By.ClassName("newSteps")).Text)) { newCount++; newItems.AppendLine(regexFull.Replace(regexButtons.Replace(trackingRow.GetAttribute("outerHTML"), string.Empty), string.Empty)); } } #endregion if (newCount > 0) { #region Processing newItems.Replace("class=\"clear\"", "style=\"clear: both;\""); newItems.Replace("class=\"newSteps\"", "style=\"font-size: 11px;font-weight: normal;color: #a00;display: inline-block;padding: 0 0 0 4px;margin: -5px 0 0 0;vertical-align: top;\""); newItems.Replace("class=\"info\"", "style=\"padding: 0; overflow: hidden; white-space: nowrap;color: #50749b;\""); newItems.Replace("class=\"meta\"", "style=\"padding: 3px 0 0 0; display:inline-block;overflow: hidden;color: #97adc3;white-space: nowrap;\""); newItems.Replace("class=\"name\"", "style=\"font-size: 18px; padding: 9px 0 5px 0; overflow: hidden; color: #50749b; cursor: pointer; white-space: nowrap;\""); newItems.Replace("class=\"tracking-row hasmoves\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #d0e7ff; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row hasexport\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #bad2ff; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row haslong\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #c0b4ff; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row hascustom\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #e6ff8c; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row hasnotrace\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #ffc994; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row hasnative\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #b3fab3; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row hasarrive\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #161; color: #b3fab3; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row haswarning\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #ffd0d0; color: #50749B; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row hasrecieved\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #DDD; border-radius: 5px;\""); newItems.Replace("class=\"tracking-row\"", "style=\"font-family: Arial, Verdana, Tahoma; font-size: 12px; line-height: 1em; margin: 0 0 2px 0; background-color: #ebeff3; border-radius: 5px;\""); newItems.Replace("class=\"main\"", "style=\"padding: 0 0 8px 8px; float: left; background-color: #ebeff3; border-radius: 0 5px 5px 0; cursor: pointer; position: relative;\""); newItems.Replace("class=\"time\"", "style=\"font-size: 10px; line-height: 10px; color: #50749b; text-align: center; padding: 35px 0 0;\""); newItems.Replace("class=\"icon\" style=\"", "style=\"float: left;width: 60px;height: 60px;border-radius: 5px 0 0 5px; overflow: hidden; cursor: default;background: url(trackicons/0.png) 14px 5px no-repeat;"); newItems.Replace(" class=\"infopos\"", string.Empty); #endregion #region Send report string report = cabinet.alitrack.ru.Properties.Resources.Template.Replace("{NEW}", newItems.ToString()); SmtpClient client = new SmtpClient(cabinet.alitrack.ru.Properties.Settings.Default.SMTP); MailAddress from = new MailAddress(cabinet.alitrack.ru.Properties.Settings.Default.EmailFrom); MailAddress to = new MailAddress(cabinet.alitrack.ru.Properties.Settings.Default.EmailTo); MailMessage message = new MailMessage(from, to); message.Subject = string.Format("{0} new update from alitrack", newCount); message.IsBodyHtml = true; message.Body = report; client.Send(message); #endregion } } } catch(Exception e) { SmtpClient client = new SmtpClient(cabinet.alitrack.ru.Properties.Settings.Default.SMTP); MailAddress from = new MailAddress(cabinet.alitrack.ru.Properties.Settings.Default.EmailFrom); MailAddress to = new MailAddress(cabinet.alitrack.ru.Properties.Settings.Default.EmailTo); MailMessage message = new MailMessage(from, to); message.Subject = "new update from alitrack Exception"; message.Body = e.ToString(); client.Send(message); } finally { browser.Quit(); } }