/// <summary> /// Capture a screenshot during execution and associate to the testObject /// </summary> /// <param name="webDriver">The WebDriver</param> /// <param name="testObject">The test object to associate and log to</param> /// <param name="appendName">Appends a name to the end of a filename</param> /// <returns>Boolean if the save of the image was successful</returns> public static bool CaptureScreenshot(this IWebDriver webDriver, SeleniumTestObject testObject, string appendName = "") { try { string path = string.Empty; // Check if we are using a file logger if (!(testObject.Log is FileLogger)) { // Since this is not a file logger we will need to use a generic file name path = CaptureScreenshot(webDriver, testObject, LoggingConfig.GetLogDirectory(), "ScreenCap" + appendName, GetScreenShotFormat()); } else { // Calculate the file name string fullpath = ((FileLogger)testObject.Log).FilePath; string directory = Path.GetDirectoryName(fullpath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fullpath) + appendName; path = CaptureScreenshot(webDriver, testObject, directory, fileNameWithoutExtension, GetScreenShotFormat()); } testObject.Log.LogMessage(MessageType.INFORMATION, "Screenshot saved: " + path); return(true); } catch (Exception exception) { testObject.Log.LogMessage(MessageType.ERROR, "Screenshot error: {0}", exception.ToString()); return(false); } }
/// <summary> /// To capture a page source during execution /// </summary> /// <param name="webDriver">The WebDriver</param> /// <param name="testObject">The TestObject to associate the file with</param> /// <param name="appendName">Appends a name to the end of a filename</param> /// <returns>Boolean if the save of the page source was successful</returns> public static bool SavePageSource(this IWebDriver webDriver, SeleniumTestObject testObject, string appendName = "") { try { string path = string.Empty; // Check if we are using a file logger if (!(testObject.Log is FileLogger)) { // Since this is not a file logger we will need to use a generic file name path = SavePageSource(webDriver, testObject, LoggingConfig.GetLogDirectory(), $"PageSource{appendName}"); } else { // Calculate the file name string fullpath = ((FileLogger)testObject.Log).FilePath; string directory = Path.GetDirectoryName(fullpath); string fileNameWithoutExtension = $"{Path.GetFileNameWithoutExtension(fullpath)}_PS{ appendName}"; path = SavePageSource(webDriver, testObject, directory, fileNameWithoutExtension); } testObject.Log.LogMessage(MessageType.INFORMATION, $"Page Source saved: {path}"); return(true); } catch (Exception exception) { testObject.Log.LogMessage(MessageType.ERROR, $"Page Source error: {exception.ToString()}"); return(false); } }
/// <summary> /// To capture Page Source during execution /// </summary> /// <param name="webDriver">The WebDriver</param> /// <param name="testObject">The TestObject to associate the file with</param> /// <param name="directory">The directory file path</param> /// <param name="fileNameWithoutExtension">Filename without extension</param> /// <returns>Path to the log file</returns> public static string SavePageSource(this IWebDriver webDriver, SeleniumTestObject testObject, string directory, string fileNameWithoutExtension) { // Save the current page source into a string string pageSource = webDriver.PageSource; // Make sure the directory exists if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } // Calculate the file name string path = Path.Combine(directory, fileNameWithoutExtension + ".txt"); // Create new instance of Streamwriter and Auto Flush after each call StreamWriter writer = new StreamWriter(path, false) { AutoFlush = true }; // Write page source to a new file writer.Write(pageSource); writer.Close(); testObject.AddAssociatedFile(path); return(path); }
/// <summary> /// Create a HTML accessibility report for a specific web element and all of it's children /// </summary> /// <param name="webDriver">The WebDriver</param> /// <param name="testObject">The TestObject to associate the report with</param> /// <param name="element">The WebElement you want to use as the root for your accessibility scan</param> /// <param name="throwOnViolation">Should violations cause and exception to be thrown</param> public static void CreateAccessibilityHtmlReport(this IWebDriver webDriver, SeleniumTestObject testObject, IWebElement element, bool throwOnViolation = false) { // If we are using a lazy element go get the raw element instead LazyElement raw = element as LazyElement; if (raw != null) { element = ((LazyElement)element).GetRawExistingElement(); } CreateAccessibilityHtmlReport(element, testObject, () => webDriver.Analyze(element), throwOnViolation); }
/// <summary> /// Get a unique file name that we can user for the accessibility HTML report /// </summary> /// <param name="testObject">The TestObject to associate the report with</param> /// <returns>A unique HTML file name, includes full path</returns> private static string GetAccessibilityReportPath(SeleniumTestObject testObject) { string logDirectory = testObject.Log is FileLogger?Path.GetDirectoryName(((FileLogger)testObject.Log).FilePath) : LoggingConfig.GetLogDirectory(); string reportBaseName = testObject.Log is FileLogger ? $"{Path.GetFileNameWithoutExtension(((FileLogger)testObject.Log).FilePath)}_Axe" : "AxeReport"; string reportFile = Path.Combine(logDirectory, $"{reportBaseName}.html"); int reportNumber = 0; while (File.Exists(reportFile)) { reportFile = Path.Combine(logDirectory, $"{reportBaseName}{reportNumber++}.html"); } return(reportFile); }
/// <summary> /// To capture a screenshot during execution /// </summary> /// <param name="webDriver">The WebDriver</param> /// <param name="testObject">The test object to associate the screenshot with</param> /// <param name="directory">The directory file path</param> /// <param name="fileNameWithoutExtension">Filename without extension</param> /// <param name="imageFormat">Optional Screenshot Image format parameter; Default imageFormat is PNG</param> /// <returns>Path to the log file</returns> public static string CaptureScreenshot(this IWebDriver webDriver, SeleniumTestObject testObject, string directory, string fileNameWithoutExtension, ScreenshotImageFormat imageFormat = ScreenshotImageFormat.Png) { Screenshot screenShot = ((ITakesScreenshot)webDriver).GetScreenshot(); // Make sure the directory exists if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } // Calculate the file name string path = Path.Combine(directory, fileNameWithoutExtension + "." + imageFormat.ToString()); // Save the screenshot screenShot.SaveAsFile(path, imageFormat); testObject.AddAssociatedFile(path); return(path); }
/// <summary> /// Capture a screenshot during execution and associate to the testObject /// </summary> /// <param name="webDriver">The WebDriver</param> /// <param name="testObject">The test object to associate and log to</param> /// <param name="appendName">Appends a name to the end of a filename</param> /// <returns>Boolean if the save of the image was successful</returns> public static bool CaptureScreenshot(this IWebDriver webDriver, SeleniumTestObject testObject, string appendName = "") { try { string path = string.Empty; var htmlLogger = testObject.Log as HtmlFileLogger; var fileLogger = testObject.Log as FileLogger; // Check if we are using an HTMl logger if (htmlLogger != null) { var writer = new StreamWriter(htmlLogger.FilePath, true); // Since this is a HTML File logger we need to add a card with the image in it writer.WriteLine(StringProcessor.SafeFormatter( "<div class='collapse col-12 show' data-logtype='IMAGE'><div class='card'><div class='card-body'><h6 class='card-subtitle mb-1'>2020-01-16 18:57:47.184-05:00</h6></div><a class='pop'><img class='card-img-top rounded' src='data:image/png;base64, {0}'style='width: 200px;'></a></div></div>", ((ITakesScreenshot)webDriver).GetScreenshot().AsBase64EncodedString)); writer.Flush(); writer.Close(); } // Check if we are using a file logger else if (fileLogger != null) { // Calculate the file name string fullpath = ((FileLogger)testObject.Log).FilePath; string directory = Path.GetDirectoryName(fullpath); string fileNameWithoutExtension = $"{Path.GetFileNameWithoutExtension(fullpath)}{appendName}"; path = CaptureScreenshot(webDriver, testObject, directory, fileNameWithoutExtension, GetScreenShotFormat()); } else { // Since this is not a file logger we will need to use a generic file name path = CaptureScreenshot(webDriver, testObject, LoggingConfig.GetLogDirectory(), $"ScreenCap{appendName}", GetScreenShotFormat()); } testObject.Log.LogMessage(MessageType.INFORMATION, $"Screenshot saved: {path}"); return(true); } catch (Exception exception) { testObject.Log.LogMessage(MessageType.ERROR, $"Screenshot error: {exception.ToString()}"); return(false); } }
/// <summary> /// Run axe accessibility and log the results /// </summary> /// <param name="testObject">The test object which contains the web driver and logger you wish to use</param> /// <param name="throwOnViolation">Should violations cause and exception to be thrown</param> public static void CheckAccessibility(this SeleniumTestObject testObject, bool throwOnViolation = false) { CheckAccessibility(testObject.WebDriver, testObject.Log, throwOnViolation); }
/// <summary> /// Initializes a new instance of the <see cref="BaseSeleniumPageModel"/> class. /// </summary> /// <param name="testObject">The Selenium test object</param> protected BaseSeleniumPageModel(SeleniumTestObject testObject) { this.TestObject = testObject; this.WebDriver = testObject.WebDriver; this.lazyElementStore = new Dictionary <string, LazyElement>(); }
/// <summary> /// Initializes a new instance of the SeleniumSoftAssert class /// </summary> /// <param name="seleniumTestObject">The related Selenium test object</param> public SeleniumSoftAssert(SeleniumTestObject seleniumTestObject) : base(seleniumTestObject.Log) { this.testObject = seleniumTestObject; }
/// <summary> /// Create a HTML accessibility report /// </summary> /// <param name="context">The scan context, this is either a web driver or web element</param> /// <param name="testObject">The TestObject to associate the report with</param> /// <param name="getResults">Function for getting the accessibility scan results</param> /// <param name="throwOnViolation">Should violations cause and exception to be thrown</param> public static void CreateAccessibilityHtmlReport(this ISearchContext context, SeleniumTestObject testObject, Func <AxeResult> getResults, bool throwOnViolation = false) { // If we are using a lazy element go get the raw element instead LazyElement raw = context as LazyElement; if (raw != null) { context = ((LazyElement)context).GetRawExistingElement(); } // Check to see if the logger is not verbose and not already suspended bool restoreLogging = testObject.Log.GetLoggingLevel() != MessageType.VERBOSE && testObject.Log.GetLoggingLevel() != MessageType.SUSPENDED; AxeResult results; string report = GetAccessibilityReportPath(testObject); testObject.Log.LogMessage(MessageType.INFORMATION, "Running accessibility check"); try { // Suspend logging if we are not verbose or already suspended if (restoreLogging) { testObject.Log.SuspendLogging(); } results = getResults(); context.CreateAxeHtmlReport(results, report); } finally { // Restore logging if we suspended it if (restoreLogging) { testObject.Log.ContinueLogging(); } } // Add the report testObject.AddAssociatedFile(report); testObject.Log.LogMessage(MessageType.INFORMATION, $"Ran accessibility check and created HTML report: {report} "); // Throw exception if we found violations and we want that to cause an error if (throwOnViolation && results.Violations.Length > 0) { throw new ApplicationException($"Accessibility violations, see: {report} for more details."); } // Throw exception if the accessibility check had any errors if (results.Error.Length > 0) { throw new ApplicationException($"Accessibility check failure, see: {report} for more details."); } }
/// <summary> /// Create a HTML accessibility report for an entire web page /// </summary> /// <param name="webDriver">The WebDriver</param> /// <param name="testObject">The TestObject to associate the report with</param> /// <param name="throwOnViolation">Should violations cause and exception to be thrown</param> public static void CreateAccessibilityHtmlReport(this IWebDriver webDriver, SeleniumTestObject testObject, bool throwOnViolation = false) { CreateAccessibilityHtmlReport(webDriver, testObject, () => webDriver.Analyze(), throwOnViolation); }