public void CheckMenuFontUS(IWebDriver driver) { driver.Url = "http://us.kantar.stage.guardianprofessional.co.uk/"; IWebElement home; home = driver.FindElement(By.CssSelector("html body.us form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a.selected")); string actualfont = home.GetCssValue("font-family"); Assert.IsTrue(actualfont.Contains("dinotregular")); String expectedfontsize; if ((driver.GetType().Name == "FirefoxDriver")) { expectedfontsize = "15.95px"; } else if ((driver.GetType().Name == "ChromeDriver")) { expectedfontsize = "16px"; } else { expectedfontsize = "10pt"; } string actfontsize = home.GetCssValue("font-size"); Assert.AreEqual(expectedfontsize, actfontsize); }
public static void TakeScreenShot(IWebDriver webDriver, string screenShotFileNameWithoutExtension, ImageFormat imageFormat, string screenShotDirectoryPath) { Screenshot screenShot = null; var browserName = string.Empty; if (webDriver.GetType() == typeof(InternetExplorerDriver)) { screenShot = ((InternetExplorerDriver)webDriver).GetScreenshot(); browserName = "IE"; } if (webDriver.GetType() == typeof(FirefoxDriver)) { screenShot = ((FirefoxDriver)webDriver).GetScreenshot(); browserName = "Firefox"; } if (webDriver.GetType() == typeof(ChromeDriver)) { screenShot = ((ChromeDriver)webDriver).GetScreenshot(); browserName = "Chrome"; } var screenShotFileName = screenShotFileNameWithoutExtension + "." + imageFormat.ToString().ToLower(); if (screenShot != null) { if (!string.IsNullOrEmpty(screenShotDirectoryPath)) { Directory.CreateDirectory(screenShotDirectoryPath).CreateSubdirectory(browserName); var browserScreenShotDirectoryPath = Path.Combine(screenShotDirectoryPath, browserName); Directory.CreateDirectory(browserScreenShotDirectoryPath); var screenShotFileFullPath = Path.Combine(browserScreenShotDirectoryPath, screenShotFileName); screenShot.SaveAsFile(screenShotFileFullPath, imageFormat); } } }
public void CheckMenuFontCN(IWebDriver driver) { driver.Url = "http://cn.kantar.stage.guardianprofessional.co.uk/"; IWebElement home; home = driver.FindElement(By.CssSelector("html body.cn form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a")); //html body.cn form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a.selected CSS path for actual homepage above is the login page string actualfont = home.GetCssValue("font-family"); Assert.IsTrue(actualfont.Contains("Microsoft Yahei")); String expectedfontsize; if ((driver.GetType().Name == "FirefoxDriver")) { expectedfontsize = "15.95px"; } else if ((driver.GetType().Name == "ChromeDriver")) { expectedfontsize = "16px"; } else { expectedfontsize = "10pt"; } string actfontsize = home.GetCssValue("font-size"); Assert.AreEqual(expectedfontsize, actfontsize); }
public void Initialize() { _driver = new ChromeDriver(); driverName = _driver.GetType().Name; wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)); _driver.Navigate().Refresh(); }
public void GetFirefoxBrowser64() { Assume.That(_driver.DownloadGeckoDriver()); _driver = WebDriverFactory.GetBrowser<FirefoxDriver>("http://rickcasady.blogspot.com/"); Assert.AreEqual(typeof(FirefoxDriver), _driver.GetType()); }
/// <summary> /// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen. /// </summary> /// <param name="driver">The driver instance to extend.</param> /// <returns>A <see cref="Screenshot"/> object containing the image.</returns> /// <exception cref="WebDriverException">Thrown if this <see cref="IWebDriver"/> instance /// does not implement <see cref="ITakesScreenshot"/>, or the capabilities of the driver /// indicate that it cannot take screenshots.</exception> public static Screenshot TakeScreenshot(this IWebDriver driver) { ITakesScreenshot screenshotDriver = driver as ITakesScreenshot; if (screenshotDriver == null) { IHasCapabilities capabilitiesDriver = driver as IHasCapabilities; if (capabilitiesDriver == null) { throw new WebDriverException("Driver does not implement ITakesScreenshot or IHasCapabilities"); } if (!capabilitiesDriver.Capabilities.HasCapability(CapabilityType.TakesScreenshot) || !(bool)capabilitiesDriver.Capabilities.GetCapability(CapabilityType.TakesScreenshot)) { throw new WebDriverException("Driver capabilities do not support taking screenshots"); } MethodInfo executeMethod = driver.GetType().GetMethod("Execute", BindingFlags.Instance | BindingFlags.NonPublic); Response screenshotResponse = executeMethod.Invoke(driver, new object[] { DriverCommand.Screenshot, null }) as Response; if (screenshotResponse == null) { throw new WebDriverException("Unexpected failure getting screenshot; response was not in the proper format."); } string screenshotResult = screenshotResponse.Value.ToString(); return(new Screenshot(screenshotResult)); } return(screenshotDriver.GetScreenshot()); }
public void Initialize() { _driver = new ChromeDriver(); _driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(3)); _wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(3)); driverName = _driver.GetType().Name; }
public override ISnapshot TakeSnapshot() { ITakesScreenshot takesScreenshot = WebDriver as ITakesScreenshot; if (takesScreenshot != null) { var shot = takesScreenshot.GetScreenshot(); return(new SeleniumSnapshot(shot)); } IHasCapabilities hasCapability = WebDriver as IHasCapabilities; if (hasCapability == null) { throw new WebDriverException("Driver does not implement ITakesScreenshot or IHasCapabilities"); } if (!hasCapability.Capabilities.HasCapability(CapabilityType.TakesScreenshot) || !(bool)hasCapability.Capabilities.GetCapability(CapabilityType.TakesScreenshot)) { throw new WebDriverException("Driver capabilities do not support taking screenshots"); } MethodInfo method = WebDriver.GetType().GetMethod("Execute", BindingFlags.Instance | BindingFlags.NonPublic); object[] screenshot = new object[] { DriverCommand.Screenshot, null }; Response response = method.Invoke(WebDriver, screenshot) as Response; if (response == null) { throw new WebDriverException("Unexpected failure getting screenshot; response was not in the proper format."); } return(new SeleniumSnapshot(new Screenshot(response.Value.ToString()))); }
/// <summary> /// Take snapshot when error accured /// </summary> /// <param name="driver"></param> /// <param name="folderName"></param> /// <returns></returns> public string ScreenShot(IWebDriver driver, string folderName) { Screenshot ss; // Create Screenshot folder string createdFolderLocation = folderName; // Take the screenshot driver.Manage().Window.Maximize(); if (driver.GetType().Name.IndexOf("RemoteWebDriver", StringComparison.Ordinal) >= 0) { ss = ((ScreenShotRemoteWebDriver)driver).GetScreenshot(); } else { ss = ((ITakesScreenshot)driver).GetScreenshot(); } string time = DateTime.Now.ToString(CultureInfo.InvariantCulture).Replace(":", "_").Replace("/", "_").Replace(" ", "_") + DateTime.Now.Millisecond.ToString(); // Save the screenshot ss.SaveAsFile((string.Format("{0}\\{1}", createdFolderLocation, time + ".png")), ImageFormat.Png); return(string.Format("{0}\\{1}", createdFolderLocation, time + ".png")); }
public PageObject(IWebDriver driver, string pageExpectedTitle) { //set the driver this.driver = driver; this.Pause(1); //set focus to opened window this.driver.SwitchTo().Window(this.driver.CurrentWindowHandle); //wait for the page to be loaded and contain the correct title if (pageExpectedTitle != null) { int timeToWaitForPage = defaultTimeoutGroupElement; timeToWaitForPage = timeToWaitForPage * 2; //Click on Login page to load - for IE only if ((driver.GetType() == typeof(InternetExplorerDriver)) && (pageExpectedTitle.Contains("Login"))) { timeToWaitForPage = timeToWaitForPage * 5; driver.FindElement(By.XPath("//body")).Click(); TestsLogger.Log("[IEDriver] Click on <body> tag was made"); } string titleLocator = string.Format(universalPageTitle, pageExpectedTitle); this.WaitForElementToBePresent(By.XPath(titleLocator), timeToWaitForPage); } }
/// <summary> /// Log that the web driver setup /// </summary> /// <param name="webDriver">The web driver</param> private void LoggingStartup(IWebDriver webDriver) { try { IWebDriver driver = Extend.GetLowLevelDriver(webDriver); string browserType; // Get info on what type of browser we are using if (driver is RemoteWebDriver remoteDrive) { browserType = remoteDrive.Capabilities.ToString(); } else { browserType = driver.GetType().ToString(); } if (SeleniumConfig.GetBrowserName().Equals("Remote", StringComparison.CurrentCultureIgnoreCase)) { Log.LogMessage(MessageType.INFORMATION, $"Remote driver: {browserType}"); } else { Log.LogMessage(MessageType.INFORMATION, $"Local driver: {browserType}"); } webDriver.SetWaitDriver(SeleniumConfig.GetWaitDriver(webDriver)); } catch (Exception e) { Log.LogMessage(MessageType.ERROR, $"Failed to start driver because: {e.Message}"); Console.WriteLine($"Failed to start driver because: {e.Message}"); } }
/// <summary> /// Tries to get PID and kill it. /// </summary> /// <param name="webDriver">Driver to kill.</param> internal void TryToKill(IWebDriver webDriver) { var commandExecutor = webDriver.GetType() .GetProperty("CommandExecutor", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(webDriver) as ICommandExecutor; var fields = commandExecutor.GetType().GetRuntimeFields(); var driverService = fields.FirstOrDefault(s => s.Name == "service")?.GetValue(commandExecutor) as DriverService; if (driverService != null) { var id = driverService.ProcessId; KillProcess(id); return; } var commandServer = fields.FirstOrDefault(s => s.Name == "server")?.GetValue(commandExecutor); if (commandServer != null) { var firefoxBinary = commandServer.GetType().GetRuntimeFields().FirstOrDefault(a => a.Name == "process").GetValue(commandServer); if (firefoxBinary == null) { var firefoxProcess = firefoxBinary.GetType().GetRuntimeFields().FirstOrDefault(a => a.Name == "process").GetValue(commandServer) as Process; KillProcess(firefoxProcess.Id); } } }
private static string GetAutomation(ISearchContext context) { IWebDriver driver = WebDriverUnpackUtility. UnpackWebdriver(context); if (driver == null) { return(null); } if (typeof(IHasCapabilities).IsAssignableFrom(driver.GetType())) { IHasCapabilities hasCapabilities = (IHasCapabilities)driver; object automation = hasCapabilities. Capabilities.GetCapability(MobileCapabilityType.AutomationName); if (automation == null || String.IsNullOrEmpty(Convert.ToString(automation))) { automation = hasCapabilities.Capabilities.GetCapability(CapabilityType.BrowserName); } string convertedAutomation = Convert.ToString(automation); if (automation != null && !String.IsNullOrEmpty(convertedAutomation)) { return(convertedAutomation); } } return(null); }
public void ClearCache() { CoreHelpers.LogMessage("Clearing Cache..."); //http://automationoverflow.blogspot.in/2013/07/clean-session-in-internet-explorer.html if (selDriver.GetType() == typeof(OpenQA.Selenium.IE.InternetExplorerDriver)) { ProcessStartInfo psInfo = new ProcessStartInfo(); psInfo.FileName = Path.Combine(Environment.SystemDirectory, "RunDll32.exe"); psInfo.Arguments = "InetCpl.cpl,ClearMyTracksByProcess 2"; psInfo.CreateNoWindow = true; psInfo.UseShellExecute = false; psInfo.RedirectStandardError = true; psInfo.RedirectStandardOutput = true; Process p = new Process { StartInfo = psInfo }; p.Start(); p.WaitForExit(10000); } else { //TBD } }
public static string CheckDOMForErrors(IWebDriver driver, int timeoutInSeconds) { if (driver.GetType() == typeof(InternetExplorerDriver)) { throw new UnsupportedDriverTypeException(typeof(InternetExplorerDriver), "This extension is incompatible with Internet Explorer, please use another driver."); } if (timeoutInSeconds > 0) { var errorStrings = new List <string> { "SyntaxError", "EvalError", "InternalError", "ReferenceError", "RangeError", "TypeError", "URIError" }; var jsErrors = driver.Manage().Logs.GetLog(LogType.Browser).Where(x => errorStrings.Any(e => x.Message.Contains(e))); if (jsErrors.Any()) { return("JavaScript error(s):" + "\n" + jsErrors.Aggregate("", (s, entry) => s + entry.Message + "\n")); } return(null); } throw new ArgumentException("timeoutInSeconds must be greater than 0"); }
private string CreateTheoryDisplayName(IMethodInfo method, string displayName, object[] convertedDataRow, ITypeInfo[] resolvedTypes) { string returnString = displayName; if (convertedDataRow.Length == 1) { IWebDriver driver = convertedDataRow[0] as IWebDriver; if (driver == null && convertedDataRow[0] is Fixture) { driver = ((Fixture)convertedDataRow[0]).Driver; } if (driver != null) { var property = driver.GetType().GetProperty("Capabilities"); if (property != null) { ICapabilities capabilities = property.GetValue(driver) as ICapabilities; if (capabilities != null) { returnString += string.Format(" {0} {1}", capabilities.BrowserName, capabilities.Version); } } } } return(returnString); }
private static void RunDriver() { driver = new TWebDriver(); Log.Info($"{driver.GetType().ToString()} the driver is initialized"); driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(baseUrl); }
/// <summary>Overrides the security warning.</summary> /// <returns>true if override was successful</returns> protected static bool OverrideSecurityWarning() { switch (driver.GetType().Name) { case "InternetExplorerDriver": case "ChromeDriver": if (driver.FindElement(By.XPath(@"//a[@id='overridelink']")).Displayed) { driver.Navigate().GoToUrl("javascript:document.getElementById('overridelink').click()"); //Log.WriteLine("Overrode security warning"); } else { //Log.WriteLine("Did not find 'Override Security Warning' Link", Log.LogType.ERROR); return(false); } break; case "FirefoxDriver": DesiredCapabilities cap = (DesiredCapabilities)((RemoteWebDriver)driver).Capabilities; cap.SetCapability("acceptSslCerts", true); //driver = new FirefoxDriver(cap); //Log.WriteLine("Restarted Firefox driver with override security warning capability"); break; default: break; } return(true); }
public void TakeScreenshot() { if (!IsInitialized()) { return; } if (!(driverInstance is RemoteWebDriver)) { Console.WriteLine("Unsupported driver type: " + driverInstance.GetType()); return; } string screenshotName = $"screenshot_{DateTime.Now:yyyy-MM-ddTHH-mm-ss.fff}.jpeg"; string relativeScreenshotPath = Constants.ATTACHMENTS_DIR + "\\" + screenshotName; string fullScreenshotPath = FileUtils.Solution_dir + relativeScreenshotPath; FileUtils.CheckOrCreateDir(Path.GetDirectoryName(fullScreenshotPath)); var screenshot = ((ITakesScreenshot)driverInstance).GetScreenshot(); screenshot.SaveAsFile(fullScreenshotPath, ScreenshotImageFormat.Jpeg); string issueKey = GetIssue(); IssueManager.SetAttachments(issueKey, relativeScreenshotPath); }
public static Screenshot TakeScreenshot(this IWebDriver driver) { ITakesScreenshot takesScreenshot = driver as ITakesScreenshot; if (takesScreenshot != null) { return(takesScreenshot.GetScreenshot()); } IHasCapabilities hasCapabilities = driver as IHasCapabilities; if (hasCapabilities == null) { throw new WebDriverException("Driver does not implement ITakesScreenshot or IHasCapabilities"); } if (!hasCapabilities.Capabilities.HasCapability(CapabilityType.TakesScreenshot) || !(bool)hasCapabilities.Capabilities.GetCapability(CapabilityType.TakesScreenshot)) { throw new WebDriverException("Driver capabilities do not support taking screenshots"); } MethodInfo method = driver.GetType().GetMethod("Execute", BindingFlags.Instance | BindingFlags.NonPublic); MethodBase arg_7E_0 = method; object[] array = new object[2]; array[0] = DriverCommand.Screenshot; Response response = arg_7E_0.Invoke(driver, array) as Response; if (response == null) { throw new WebDriverException("Unexpected failure getting screenshot; response was not in the proper format."); } string base64EncodedScreenshot = response.Value.ToString(); return(new Screenshot(base64EncodedScreenshot)); }
public static void KillDriverProcesses() { var driverName = driver.GetType().Name.ToLower(); string processName = String.Empty; switch (driverName) { case INTERNET_EXPLORER_DRIVER: processName = INTERNET_EXPLORER_DRIVER_SERVER; break; case CHROME_DRIVER: processName = CHROME_DRIVER; break; case FIREFOX_DRIVER: processName = FIREFOX_DRIVER; break; } if (!String.IsNullOrEmpty(processName)) { var processes = Process.GetProcesses().Where(p => p.ProcessName.ToLower() == processName); foreach (var process in processes) { if (!process.HasExited) { process.Kill(); } } } }
/// <summary> /// Create a NeoLoad instance to the webDriver. /// In Design mode, project in parameter will be opened and the userPath in parameter will be created or updated if it is already present in opened project. /// In EndUserExperience mode, the userPath in parameter will be added to the path of entries sent to NeoLoad. /// </summary> /// <param name="webDriver">an instance of a WebDriver as ChromeDriver or FirefoxDriver.</param> /// <param name="userPath">the name of the UserPath.</param> /// <param name="projectPath">the path of the project to open in NeoLoad.</param> /// <param name="paramBuilderProvider">ParamBuilderProvider class can be overridden in order to update parameters.</param> public static NLWebDriver NewNLWebDriver(IWebDriver webDriver, string userPath, string projectPath, ParamBuilderProvider paramBuilderProvider) { Mode mode = ModeHelper.getMode(); INeoLoadInterceptor interceptor; switch (mode) { case Mode.END_USER_EXPERIENCE: ICapabilities capabilitites = null; if (webDriver is IHasCapabilities) { capabilitites = (webDriver as IHasCapabilities).Capabilities; } var eueConf = ConfigurationHelper.newEUEConfiguration(webDriver.GetType().Name, userPath, capabilitites); interceptor = new WebDriverEUEInterceptor(webDriver, eueConf); break; case Mode.DESIGN: var designConf = ConfigurationHelper.newDesignConfiguration(userPath, projectPath); interceptor = new WebDriverDesignInterceptor(designConf, paramBuilderProvider); break; case Mode.NO_API: default: interceptor = new NoOpInterceptor(); break; } interceptor.DoOnStart(); return(new NLWebDriver(webDriver, interceptor)); }
public void WindowMaximize() { if (!_driver.GetType().Name.Equals("ChromeDriver")) { _driver.Manage().Window.Maximize(); } }
public void OneTimeTearDown() { if ((_driver != null) && (_driver.GetType().GetMethod("Close") != null)) { _driver.Quit(); } }
public static void TakeScreenshot(this IWebDriver driver, string screenshotFileName) { Log.Info($"{driver.GetType().Name}: TakeScreenshot(): {screenshotFileName}"); if (string.IsNullOrEmpty(screenshotFileName)) { var msg = "Cannot specify a Screenshot Filename that is NULL or empty"; Log.Error(msg); throw new Exception(msg); } var screenshotPath = Path.GetDirectoryName(new Uri(typeof(WebDriverExtensions).Assembly.CodeBase).LocalPath) + @"\Screenshots"; var camera = (ITakesScreenshot)driver; var screenshot = camera.GetScreenshot(); if (!Directory.Exists(screenshotPath)) { Directory.CreateDirectory(screenshotPath); } var outputPath = Path.Combine(screenshotPath, screenshotFileName); var pathChars = Path.GetInvalidPathChars(); var stringBuilder = new StringBuilder(outputPath); foreach (var item in pathChars) { stringBuilder.Replace(item, '.'); } var screenShotPath = stringBuilder.ToString(); screenshot.SaveAsFile(screenShotPath, ScreenshotImageFormat.Jpeg); }
private static bool ContainsCookies(IWebDriver driver) { Log.Info($"{driver.GetType().Name}: ContainsCookies()"); if (!driver.Manage().Cookies.AllCookies.Any()) { return(false); } return(true); }
private void ReleaseInternal(IWebDriver webDriver) { if (!acquired.TryRemove(webDriver, out var key)) { throw new Exception($"WebDriver {webDriver.GetType().Name} was not taken from the pool or already released"); } GetPool(key).Release(webDriver); }
public void SetUpSelenium() { _driver = new FirefoxDriver(); if (_driver.GetType() == typeof (FirefoxDriver)) { _driver.Manage().Window.Maximize(); } if (_driver.GetType() == typeof (ChromeDriver)) { var options = new ChromeOptions(); options.AddArgument("--start-maximized"); _driver = new ChromeDriver(options); } _driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 0, 5)); _actions = new Actions(_driver); }
public void WebElementToWebDriverUnwrappedDriver() { WebDriver.Navigate().GoToUrl(TestSiteAutomationUrl); IWebDriver driver = ((IWrapsDriver)WebDriver).WrappedDriver; IWebElement element = driver.FindElement(AutomationShowDialog1); IWebDriver basedriver = SeleniumUtilities.WebElementToWebDriver(element); Assert.AreEqual("OpenQA.Selenium.Chrome.ChromeDriver", basedriver.GetType().ToString()); }
public void LazyWebElementToWebDriverUnwrappedDriver() { WebDriver.Navigate().GoToUrl(TestSiteAutomationUrl); IWebDriver driver = this.WebDriver.GetLowLevelDriver(); LazyElement lazy = new LazyElement(this.TestObject, driver, AutomationShowDialog1); IWebDriver basedriver = SeleniumUtilities.WebElementToWebDriver(lazy); Assert.AreEqual("OpenQA.Selenium.Chrome.ChromeDriver", basedriver.GetType().ToString()); }
public void Setup() { log("starting driver"); driver = new ChromeDriver(); log(driver.GetType().Name); log("opening url"); driver.Url = "https://whatismyviewport.com/"; log(driver.Url); }
protected void SetUp(IWebDriver driver) { driver.Url = BaseURL; IsIE = driver.GetType() == typeof(InternetExplorerDriver); if (IsIE) { driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); } Driver = driver; }
public static void ClearCookies(this IWebDriver driver) { Log.Info($"{driver.GetType().Name}: ClearCookies()"); if (!ContainsCookies(driver)) { return; } driver.Manage().Cookies.DeleteAllCookies(); }
public static string TakeScreenshot(IWebDriver driver, string screenshotPath, string fileName = "") { ITakesScreenshot ss = driver as ITakesScreenshot; if (ss == null) { throw new Exception(string.Format( "Can't take screenshot - driver {0} is null or doesn't implement ITakesScreenshot", (driver == null) ? "null" : driver.GetType().Name)); } DirectoryInfo outputPath = new DirectoryInfo(Path.Combine( screenshotPath, DateTime.Now.ToString("yyyy-MM-dd"))); if (!outputPath.Exists) { outputPath.Create(); } var driverName = driver.GetType().Name.Replace("Driver", string.Empty); if (String.IsNullOrEmpty(fileName)) { var now = DateTime.Now.ToString("HHmmss"); fileName = now; } foreach (var handle in driver.WindowHandles) { driver.SwitchTo().Window(handle); Uri u = new Uri(driver.Url); ss .GetScreenshot() .SaveAsFile(Path.Combine(outputPath.FullName, string.Format("{0}.jpeg", fileName)), System.Drawing.Imaging.ImageFormat.Jpeg); } return Path.Combine(outputPath.FullName, fileName); }
public void CheckMenuFontUK(IWebDriver driver) { //if((driver.GetType().Name == "FirefoxDriver")) //{ // driver.Url = "http://uk.kantar.stage.guardianprofessional.co.uk/"; // var ActualFont = ((FirefoxDriver)driver).ExecuteScript("var elem=document.querySelector('html body.uk form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a.selected'); return getComputedStyle(elem, null).getPropertyValue('font-family')"); // Assert.IsTrue(ActualFont.ToString().Contains("dinotregular")); // var ActualFontsize = ((FirefoxDriver)driver).ExecuteScript("var elem=document.querySelector('html body.uk form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a.selected'); return getComputedStyle(elem, null).getPropertyValue('font-size')"); // String ExpectedFont = "15.95px"; // Assert.AreEqual(ActualFontsize.ToString(), ExpectedFont); //} driver.Url = "http://uk.kantar.stage.guardianprofessional.co.uk/"; IWebElement home; home = driver.FindElement(By.CssSelector("html body.uk form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a.selected")); string actualfont = home.GetCssValue("font-family"); Assert.IsTrue(actualfont.Contains("dinotregular")); String expectedfontsize; if ((driver.GetType().Name == "FirefoxDriver")) { expectedfontsize = "15.95px"; } else if ((driver.GetType().Name == "ChromeDriver")) { expectedfontsize = "16px"; } else { expectedfontsize = "10pt"; } string actfontsize = home.GetCssValue("font-size"); Assert.AreEqual(expectedfontsize, actfontsize); }
public void GetInternetExplorerBrowser() { Assume.That(_driver.GetNuGetIEDriver()); _driver = WebDriverFactory.GetBrowser<InternetExplorerDriver>("http://rickcasady.blogspot.com/"); Assert.AreEqual(typeof(InternetExplorerDriver), _driver.GetType()); }
public void GetChromeBrowser() { Assume.That(_driver.GetNuGetChromeDriver()); _driver = WebDriverFactory.GetBrowser<ChromeDriver>("http://rickcasady.blogspot.com/"); Assert.AreEqual(typeof(ChromeDriver), _driver.GetType()); }
public void TestMethod1() { //testTarget = targ; //testID = "UI-" + tclass + "-" + tsubclass + "-" + tID; //testClass = tclass; //testSubClass = tsubclass; testRegressionCandidate = false; testStatus = states[0]; testClass = "TIT"; testSubClass = "IE"; testTarget = "visitor"; testUrl = "http://10.141.10.20:8080/Account/Login?ReturnUrl=%2f"; switch (this.testSubClass) { case "FF": // Create a new instance of the Firefox driver. //driver = new FirefoxDriver(); driver = new FirefoxDriver(new FirefoxProfile("")); break; case "IE": // Create a new instance of the Firefox driver. driver = new InternetExplorerDriver(); break; case "AS": // Create a new instance of the Firefox driver. driver = new SafariDriver(); break; case "GC": // Create a new instance of the Firefox driver. driver = new ChromeDriver(); break; default: System.Console.Error.WriteLine("ERROR: Invalid test subclass"); Environment.Exit(-1); break; } switch (this.testClass) { case ("TIT"): try { //driver.Navigate().GoToUrl("http://www.google.com/"); driver.Navigate().GoToUrl(testUrl); // Find the text input element by its name //IWebElement query = driver.FindElement(By.Name("q")); IWebElement loginF = driver.FindElement(By.ClassName("form-hideLabels")); IWebElement uName = driver.FindElement(By.Id("UserName")); IWebElement uPass = driver.FindElement(By.Id("Password")); System.Console.WriteLine(driver.GetType()); System.Console.WriteLine(driver.GetHashCode()); int wdr = driver.Manage().GetHashCode(); // Enter something to search for uName.SendKeys("admin"); uPass.SendKeys("1234"); // Now submit the form. WebDriver will find the form for us from the element loginF.Submit(); } catch (OpenQA.Selenium.NoSuchElementException nsee) { driver.Quit(); System.Console.Error.WriteLine("ERROR: Exception trying to reach a page element"); System.Console.Error.WriteLine(nsee.Message); Thread.Sleep(5000); response = null; Environment.Exit(-2); } catch (OpenQA.Selenium.NoSuchWindowException nswe) { driver.Quit(); System.Console.Error.WriteLine("ERROR: Exception trying to reach a window"); System.Console.Error.WriteLine(nswe.Message); Thread.Sleep(5000); response = null; Environment.Exit(-2); } catch { driver.Quit(); System.Console.Error.WriteLine("ERROR: Other error"); Thread.Sleep(5000); response = null; Environment.Exit(-2); } string theTitle; // Google's search is rendered dynamically with JavaScript. // Wait for the page to load, timeout after 10 seconds WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); try { wait.Until((d) => { return d.Title.ToLower().StartsWith(testTarget.Split(' ')[0]); }); } catch(Exception e) { theTitle = "PROBLEM!"; driver.Quit(); System.Console.Error.WriteLine("ERROR: Exception trying to reach the page title"); //response = null; //Environment.Exit(-3); response = "problem"; result = false; } if (result) { // Should see: "Cheese - Google Search" //System.Console.WriteLine("Page title is: " + driver.Title); theTitle = driver.Title; //Close the browser driver.Quit(); response = theTitle; } break; case ("PNF"): driver.Navigate().GoToUrl(this.testTarget); //driver.FindElement(By.ClassName,). //wait.Until((d) => { return d.}); break; default: response = null; break; } Assert.AreEqual("Visitor Management Kendo UI Demo", response); //Assert.AreEqual("Not this page, man!", response); }
/// <summary> /// Click on a desired element within a document (with reference to Internet Explorer). /// </summary> /// <param name="element"></param> /// <param name="browser">Current webdriver instance.</param> public static void ForceClick(this IWebElement element, IWebDriver browser) { if (typeof(InternetExplorerDriver) == browser.GetType()) { element.SendKeys(Keys.Enter); } else { element.Click(); } }
public void GetSauceTest() { _driver = WebDriverFactory.GetSauceDriver(TestContext.CurrentContext.Test.Name, url: "http://rickcasady.blogspot.com/"); Assert.AreEqual(typeof(RemoteWebDriver), _driver.GetType()); }
public void CheckTitleUK(IWebDriver driver) { if ((driver.GetType().Name == "internetexplorerdriver")) { //driver.Navigate().GoToUrl("http://uk.kantar.stage.guardianprofessional.co.uk/"); //System.Threading.Thread.Sleep(60000); //WebDriverWait wait = new WebDriverWait(ied, TimeSpan.FromSeconds(10)); //String actualText = driver.FindElement(By.CssSelector("html body.uk form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a.selected")).Text; //wait.Until(a => actualText = "HOME"); IWebElement we = FindElement(driver, By.CssSelector("html body.uk form#Form1 div#whiteBackground div#mainContainer div#mainNavigationContainer ul.firstLevelMenu li.first a.selected"), 10); } else { driver.Url = "http://uk.kantar.stage.guardianprofessional.co.uk/"; } String StrExpectedTitle = "Home - Kantar"; String actualtitle = driver.Title; Assert.AreEqual(StrExpectedTitle, actualtitle); }
/// <summary> /// Record details of an error that was detected during testing /// </summary> protected void RecordError(IWebDriver driver, string failingTest, Exception ex) { if (!NareshScalerSettings.Default.LoggingEnabled) return; if (!Directory.Exists(LogFileDirectory)) Directory.CreateDirectory(LogFileDirectory); var screenshotsDir = LogFileDirectory + @"\screenshots"; if (!Directory.Exists(screenshotsDir)) Directory.CreateDirectory(screenshotsDir); var screenshotFilename = string.Format(screenshotsDir + @"\{0}-{1}.png", failingTest, DateTime.Now.ToString("MMdd-HHmm")); dynamic error = new ExpandoObject(); error.Browser = driver.GetType().Name; error.TestName = failingTest; error.Description = ex.Message; error.Screenshot = screenshotFilename; TakeScreenshot(driver, screenshotFilename); ErrorList.Add(driver.GetType().Name + "_" + failingTest, error); // once we've logged the error, throw it on to allow nunit etc to handle it throw ex; }