예제 #1
0
        public override bool IsFalse(bool condition, string softAssertName, string failureMessage = "")
        {
            bool didPass = base.IsFalse(condition, softAssertName, failureMessage);

            if (!didPass && this.testObject.GetDriverManager <SeleniumDriverManager>().IsDriverIntialized())
            {
                if (SeleniumConfig.GetSoftAssertScreenshot())
                {
                    SeleniumUtilities.CaptureScreenshot(this.testObject.WebDriver, this.testObject, this.TextToAppend(softAssertName));
                }

                if (SeleniumConfig.GetSavePagesourceOnFail())
                {
                    SeleniumUtilities.SavePageSource(this.testObject.WebDriver, this.testObject, StringProcessor.SafeFormatter($" ({this.NumberOfAsserts})"));
                }

                return(false);
            }
            else if (!didPass)
            {
                return(false);
            }

            return(true);
        }
예제 #2
0
        /// <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}");
            }
        }
예제 #3
0
        /// <summary>
        /// Soft assert method to check if the strings are equal
        /// </summary>
        /// <param name="expectedText">Expected text</param>
        /// <param name="actualText">Actual text</param>
        /// <param name="softAssertName">Soft assert name to use</param>
        /// <param name="message">Exception message if desired</param>
        /// <returns>Boolean if the assert is true</returns>
        /// <example>
        /// <code source = "../SeleniumUnitTesting/SeleniumUnitTest.cs" region="SoftAssertAreEqual" lang="C#" />
        /// </example>
        public override bool AreEqual(string expectedText, string actualText, string softAssertName, string message = "")
        {
            bool didPass = base.AreEqual(expectedText, actualText, softAssertName, message);

            if (!didPass && this.testObject.GetDriverManager <SeleniumDriverManager>().IsDriverIntialized())
            {
                if (SeleniumConfig.GetSoftAssertScreenshot())
                {
                    SeleniumUtilities.CaptureScreenshot(this.testObject.WebDriver, this.testObject, this.TextToAppend(softAssertName));
                }

                if (SeleniumConfig.GetSavePagesourceOnFail())
                {
                    SeleniumUtilities.SavePageSource(this.testObject.WebDriver, this.testObject, StringProcessor.SafeFormatter(" ({0})", this.NumberOfAsserts));
                }

                return(false);
            }
            else if (!didPass)
            {
                return(false);
            }

            return(true);
        }
예제 #4
0
 /// <summary>
 /// Sets the proxy settings for the driver options (if configured)
 /// </summary>
 /// <param name="options">The driver options</param>
 public static void SetProxySettings(this DriverOptions options)
 {
     if (SeleniumConfig.GetUseProxy())
     {
         SetProxySettings(options, SeleniumConfig.GetProxyAddress());
     }
 }
예제 #5
0
        /// <summary>
        /// Get the web driver location
        /// </summary>
        /// <param name="driverFile">The web drive file, including extension</param>
        /// <param name="defaultHintPath">The default location for the specific driver</param>
        /// <param name="mustExist">Do we need to know where this drive is located, if this is true and the file is not found an error will be thrown</param>
        /// <returns>The path to the web driver</returns>
        private static string GetDriverLocation(string driverFile, string defaultHintPath = "", bool mustExist = true)
        {
            // Get the hint path from the app.config
            string hintPath = SeleniumConfig.GetDriverHintPath();

            // Try the hintpath first
            if (!string.IsNullOrEmpty(hintPath) && File.Exists(Path.Combine(hintPath, driverFile)))
            {
                return(hintPath);
            }

            // Try the default hit path next
            if (!string.IsNullOrEmpty(defaultHintPath) && File.Exists(Path.Combine(defaultHintPath, driverFile)))
            {
                return(Path.Combine(defaultHintPath).ToString());
            }

            // Get the test dll location
            UriBuilder uri          = new UriBuilder(Assembly.GetExecutingAssembly().Location);
            string     testLocation = Path.GetDirectoryName(Uri.UnescapeDataString(uri.Path));

            // Try the test dll location
            if (File.Exists(Path.Combine(testLocation, driverFile)))
            {
                return(testLocation);
            }

            // We didn't find the web driver so throw an error if we need to know where it is
            if (mustExist)
            {
                throw new FileNotFoundException(StringProcessor.SafeFormatter("Unable to find driver for '{0}'", driverFile));
            }

            return(string.Empty);
        }
예제 #6
0
        /// <summary>
        /// Initialize a new headless Chrome driver
        /// </summary>
        /// <param name="commandTimeout">Browser command timeout</param>
        /// <param name="headlessChromeOptions">Browser options</param>
        /// <returns>A new headless Chrome driver</returns>
        public static IWebDriver GetHeadlessChromeDriver(TimeSpan commandTimeout, ChromeOptions headlessChromeOptions)
        {
            return(CreateDriver(() =>
            {
                LazyInitializer.EnsureInitialized(ref ChromeDriverPath, () => new DriverManager().SetUpDriver(new ChromeConfig(), SeleniumConfig.GetChromeVersion()));

                return new ChromeDriver(ChromeDriverService.CreateDefaultService(), headlessChromeOptions, commandTimeout);
            }, SeleniumConfig.GetRetryRefused()));
        }
예제 #7
0
        /// <summary>
        /// Get the default remote driver options - Default values are pulled from the configuration
        /// </summary>
        /// <returns>The remote driver options</returns>
        public static DriverOptions GetDefaultRemoteOptions()
        {
            RemoteBrowserType           remoteBrowser        = SeleniumConfig.GetRemoteBrowserType();
            string                      remotePlatform       = SeleniumConfig.GetRemotePlatform();
            string                      remoteBrowserVersion = SeleniumConfig.GetRemoteBrowserVersion();
            Dictionary <string, object> capabilities         = SeleniumConfig.GetRemoteCapabilitiesAsObjects();

            return(GetRemoteOptions(remoteBrowser, remotePlatform, remoteBrowserVersion, capabilities));
        }
예제 #8
0
        /// <summary>
        /// Initialize a new Chrome driver
        /// </summary>
        /// <param name="commandTimeout">Browser command timeout</param>
        /// <param name="chromeOptions">Browser options</param>
        /// <param name="size">Browser size in the following format: MAXIMIZE, DEFAULT, or #x# (such as 1920x1080)</param>
        /// <returns>A new Chrome driver</returns>
        public static IWebDriver GetChromeDriver(TimeSpan commandTimeout, ChromeOptions chromeOptions, string size = "MAXIMIZE")
        {
            return(CreateDriver(() =>
            {
                LazyInitializer.EnsureInitialized(ref ChromeDriverPath, () => new DriverManager().SetUpDriver(new ChromeConfig(), SeleniumConfig.GetChromeVersion()));

                var driver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), chromeOptions, commandTimeout);
                SetBrowserSize(driver, size);
                return driver;
            }, SeleniumConfig.GetRetryRefused()));
        }
예제 #9
0
        /// <summary>
        /// Initialize a new Edge driver
        /// </summary>
        /// <param name="commandTimeout">Browser command timeout</param>
        /// <param name="edgeOptions">Browser options</param>
        /// <param name="size">Browser size in the following format: MAXIMIZE, DEFAULT, or #x# (such as 1920x1080)</param>
        /// <returns>A new Edge driver</returns>
        public static IWebDriver GetEdgeDriver(TimeSpan commandTimeout, EdgeOptions edgeOptions, string size = "MAXIMIZE")
        {
            return(CreateDriver(() =>
            {
                LazyInitializer.EnsureInitialized(ref EdgeDriverPath, () => new DriverManager().SetUpDriver(new EdgeConfig(), SeleniumConfig.GetEdgeVersion()));

                var driver = new EdgeDriver(Path.GetDirectoryName(EdgeDriverPath), edgeOptions, commandTimeout);
                SetBrowserSize(driver, size);
                return driver;
            }, SeleniumConfig.GetRetryRefused()));
        }
예제 #10
0
        /// <summary>
        /// Initialize a new Firefox driver
        /// </summary>
        /// <param name="commandTimeout">Browser command timeout</param>
        /// <param name="firefoxOptions">Browser options</param>
        /// <param name="size">Browser size in the following format: MAXIMIZE, DEFAULT, or #x# (such as 1920x1080)</param>
        /// <returns>A new Firefox driver</returns>
        public static IWebDriver GetFirefoxDriver(TimeSpan commandTimeout, FirefoxOptions firefoxOptions, string size = "MAXIMIZE")
        {
            return(CreateDriver(() =>
            {
                LazyInitializer.EnsureInitialized(ref FirefoxDriverPath, () => new DriverManager().SetUpDriver(new FirefoxConfig(), SeleniumConfig.GetFirefoxVersion()));

                // Add support for encoding 437 that was removed in .net core
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                var driver = new FirefoxDriver(Path.GetDirectoryName(FirefoxDriverPath), firefoxOptions, commandTimeout);
                SetBrowserSize(driver, size);

                return driver;
            }, SeleniumConfig.GetRetryRefused()));
        }
예제 #11
0
        /// <summary>
        /// Take a screen shot if needed and tear down the web driver
        /// </summary>
        /// <param name="resultType">The test result</param>
        protected override void BeforeLoggingTeardown(TestResultType resultType)
        {
            // Try to take a screen shot
            try
            {
                if (this.Log is FileLogger && resultType != TestResultType.PASS && this.LoggingEnabledSetting != LoggingEnabled.NO)
                {
                    SeleniumUtilities.CaptureScreenshot(this.WebDriver, this.Log);

                    if (SeleniumConfig.GetSavePagesourceOnFail())
                    {
                        SeleniumUtilities.SavePageSource(this.WebDriver, this.Log, "FinalPageSource");
                    }
                }
            }
            catch (Exception e)
            {
                this.TryToLog(MessageType.WARNING, "Failed to get screen shot because: {0}", e.Message);
            }
        }
예제 #12
0
        /// <summary>
        /// Soft assert method to check if the Action is false
        /// </summary>
        /// <param name="assertFunction">Function to use</param>
        /// <param name="failureMessage">Message to log</param>
        /// <param name="assertName">Soft assert name or name of expected assert being called.</param>
        /// <returns>Boolean of the assert</returns>
        public override bool Assert(Action assertFunction, string assertName, string failureMessage = "")
        {
            bool didPass = base.Assert(assertFunction, assertName, failureMessage);

            if (!didPass && this.testObject.GetDriverManager <SeleniumDriverManager>().IsDriverIntialized())
            {
                if (SeleniumConfig.GetSoftAssertScreenshot())
                {
                    SeleniumUtilities.CaptureScreenshot(this.testObject.WebDriver, this.testObject, this.TextToAppend(assertName));
                }

                if (SeleniumConfig.GetSavePagesourceOnFail())
                {
                    SeleniumUtilities.SavePageSource(this.testObject.WebDriver, this.testObject, $" ({this.NumberOfAsserts})");
                }

                return(false);
            }
            return(didPass);
        }
예제 #13
0
        /// <summary>
        /// Take a screen shot if needed and tear down the web driver
        /// </summary>
        /// <param name="resultType">The test result</param>
        protected override void BeforeCleanup(TestResultType resultType)
        {
            // Try to take a screen shot
            try
            {
                if (this.TestObject.GetDriverManager <SeleniumDriverManager>().IsDriverIntialized() && this.Log is IFileLogger && resultType != TestResultType.PASS && this.LoggingEnabledSetting != LoggingEnabled.NO)
                {
                    SeleniumUtilities.CaptureScreenshot(this.WebDriver, this.TestObject, " Final");

                    if (SeleniumConfig.GetSavePagesourceOnFail())
                    {
                        SeleniumUtilities.SavePageSource(this.WebDriver, this.TestObject, "FinalPageSource");
                    }
                }
            }
            catch (Exception e)
            {
                this.TryToLog(MessageType.WARNING, $"Failed to get screen shot because: {e.Message}");
            }
        }
예제 #14
0
        /// <summary>
        /// Soft assert method to check if the boolean is false
        /// </summary>
        /// <param name="condition">Boolean condition</param>
        /// <param name="softAssertName">Soft assert name</param>
        /// <param name="failureMessage">Failure message</param>
        /// <returns>Boolean of the assert</returns>
        /// <example>
        /// <code source = "../SeleniumUnitTesting/SeleniumUnitTest.cs" region="SoftAssertIsTrue" lang="C#" />
        /// </example>
        public override bool IsTrue(bool condition, string softAssertName, string failureMessage = "")
        {
            bool didPass = base.IsTrue(condition, softAssertName, failureMessage);

            if (!didPass)
            {
                if (SeleniumConfig.GetSoftAssertScreenshot())
                {
                    SeleniumUtilities.CaptureScreenshot(this.testObject.WebDriver, this.Log, this.TextToAppend(softAssertName));
                }

                if (SeleniumConfig.GetSavePagesourceOnFail())
                {
                    SeleniumUtilities.SavePageSource(this.testObject.WebDriver, this.Log, StringProcessor.SafeFormatter(" ({0})", this.NumberOfAsserts));
                }

                return(false);
            }

            return(true);
        }
예제 #15
0
        /// <summary>
        /// Gets the Screenshot Format to save images
        /// </summary>
        /// <returns>Desired ImageFormat Type</returns>
        public static ScreenshotImageFormat GetScreenShotFormat()
        {
            switch (SeleniumConfig.GetImageFormat().ToUpper())
            {
            case "BMP":
                return(ScreenshotImageFormat.Bmp);

            case "GIF":
                return(ScreenshotImageFormat.Gif);

            case "JPEG":
                return(ScreenshotImageFormat.Jpeg);

            case "PNG":
                return(ScreenshotImageFormat.Png);

            case "TIFF":
                return(ScreenshotImageFormat.Tiff);

            default:
                throw new ArgumentException(StringProcessor.SafeFormatter("ImageFormat '{0}' is not a valid option", SeleniumConfig.GetImageFormat()));
            }
        }
예제 #16
0
        /// <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 brower we are using
                RemoteWebDriver asRemoteDrive = driver as RemoteWebDriver;

                if (asRemoteDrive != null)
                {
                    browserType = asRemoteDrive.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: {0}", e.Message);
                Console.WriteLine(StringProcessor.SafeFormatter("Failed to start driver because: {0}", e.Message));
            }
        }
예제 #17
0
 /// <summary>
 /// Get the default web driver based on the test run configuration
 /// </summary>
 /// <returns>A web driver</returns>
 public static IWebDriver GetDefaultBrowser()
 {
     return(GetBrowserWithDefaultConfiguration(SeleniumConfig.GetBrowserType()));
 }
예제 #18
0
        /// <summary>
        /// Get the default web driver (for the specified browser type) based on the test run configuration
        /// </summary>
        /// <param name="browser">The type of browser</param>
        /// <returns>A web driver</returns>
        public static IWebDriver GetBrowserWithDefaultConfiguration(BrowserType browser)
        {
            IWebDriver webDriver = null;
            TimeSpan   timeout   = SeleniumConfig.GetCommandTimeout();
            string     size      = SeleniumConfig.GetBrowserSize();

            try
            {
                switch (browser)
                {
                case BrowserType.IE:
                    webDriver = GetIEDriver(timeout, GetDefaultIEOptions(), size);
                    break;

                case BrowserType.Firefox:
                    webDriver = GetFirefoxDriver(timeout, GetDefaultFirefoxOptions(), size);
                    break;

                case BrowserType.Chrome:
                    webDriver = GetChromeDriver(timeout, GetDefaultChromeOptions(), size);
                    break;

                case BrowserType.HeadlessChrome:
                    webDriver = GetHeadlessChromeDriver(timeout, GetDefaultHeadlessChromeOptions(size));
                    break;

                case BrowserType.Edge:
                    webDriver = GetEdgeDriver(timeout, GetDefaultEdgeOptions(), size);
                    break;

                case BrowserType.Remote:
                    webDriver = new RemoteWebDriver(SeleniumConfig.GetHubUri(), GetDefaultRemoteOptions().ToCapabilities(), SeleniumConfig.GetCommandTimeout());
                    break;

                default:
                    throw new ArgumentException(StringProcessor.SafeFormatter("Browser type '{0}' is not supported", browser));
                }

                return(webDriver);
            }
            catch (Exception e)
            {
                if (e.GetType() == typeof(ArgumentException))
                {
                    throw e;
                }
                else
                {
                    try
                    {
                        // Try to cleanup
                        webDriver?.KillDriver();
                    }
                    catch (Exception quitExecption)
                    {
                        throw new Exception("Web driver setup and teardown failed. Your web driver may be out of date", quitExecption);
                    }
                }

                // Log that something went wrong
                throw new Exception("Your web driver may be out of date or unsupported.", e);
            }
        }
예제 #19
0
 /// <summary>
 /// Set the script and page timeouts using the default configuration timeout
 /// </summary>
 /// <param name="driver">Driver who's timeouts you want set</param>
 public static void SetTimeouts(IWebDriver driver)
 {
     SetTimeouts(driver, SeleniumConfig.GetTimeoutTime());
 }
예제 #20
0
 /// <summary>
 /// The default get web driver function
 /// </summary>
 /// <returns>The web driver</returns>
 protected virtual IWebDriver GetBrowser()
 {
     return(SeleniumConfig.Browser());
 }