/// <summary> /// Try to log a message - Do not fail if the message is not logged /// </summary> /// <param name="messageType">The type of message</param> /// <param name="message">The message text</param> /// <param name="args">String format arguments</param> protected void TryToLog(MessageType messageType, string message, params object[] args) { // Get the formatted message string formattedMessage = StringProcessor.SafeFormatter(message, args); try { // Write to the log this.Log.LogMessage(messageType, formattedMessage); // If this was an error and written to a file, add it to the console output as well if (messageType == MessageType.ERROR && !(this.Log is ConsoleLogger)) { Console.WriteLine(formattedMessage); } } catch (Exception e) { Console.WriteLine(formattedMessage); Console.WriteLine("Logging failed because: " + e); } }
/// <summary> /// Deserialize the body of a HTTP response /// </summary> /// <typeparam name="T">The expected response type</typeparam> /// <param name="response">The HTTP response</param> /// <param name="supportedFormatters">List of supported media formats</param> /// <returns>The deserialized HTTP body</returns> public static T DeserializeResponse <T>(HttpResponseMessage response, List <MediaTypeFormatter> supportedFormatters) { try { // Save off a new list of formats List <MediaTypeFormatter> tempList = new List <MediaTypeFormatter>(supportedFormatters); // Check to see if formatters are provided, if not try to provide now if (tempList.Count == 0 && response.Content.Headers.ContentType != null) { string mediaType = response.Content.Headers.ContentType.MediaType.ToLower(); if (mediaType.Contains("xml")) { tempList.Add(new CustomXmlMediaTypeFormatter(response.Content.Headers.ContentType.MediaType, typeof(T))); } else if (mediaType.Contains("json")) { tempList.Add(new JsonMediaTypeFormatter()); } } return(response.Content.ReadAsAsync <T>(tempList).Result); } catch (Exception e) { // Create a useful error message string body = response.Content.ReadAsStringAsync().Result; throw new InvalidOperationException( StringProcessor.SafeFormatter( "Response could not be deserialized to a {0} object.{1}Body:{1}{2}{1}Because:{3}", typeof(T).FullName, Environment.NewLine, body, e.Message), e); } }
/// <summary> /// Setup logging data /// </summary> protected void SetupLogging() { this.LoggedExceptionList = new List <string>(); this.LoggingEnabledSetting = LoggingConfig.GetLoggingEnabledSetting(); // Setup the exception listener AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.FirstChanceException += this.FirstChanceHandler; if (this.LoggingEnabledSetting != LoggingEnabled.NO) { this.Log = LoggingConfig.GetLogger( StringProcessor.SafeFormatter( "{0} - {1}", this.GetFullyQualifiedTestClassName(), DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm-ss-ffff", CultureInfo.InvariantCulture))); } else { this.Log = new ConsoleLogger(); } }
/// <summary> /// Raise an action message for a response /// </summary> /// <param name="actionType">The action type - Get, Post, etc.</param> /// <param name="response">The response</param> private void RaiseEvent(string actionType, HttpResponseMessage response) { try { StringBuilder message = new StringBuilder(); HttpRequestMessage responseMessage = response.RequestMessage; message.AppendLine(StringProcessor.SafeFormatter("Received {0} response from {1}", actionType, responseMessage.RequestUri)); message.AppendLine(StringProcessor.SafeFormatter("Returned {0}({1})", response.ReasonPhrase, (int)response.StatusCode)); // Only pull content if we are returned content if (response.Content.Headers.ContentType != null) { string mediaType = response.Content.Headers.ContentType.MediaType; BuildContentMessage(message, mediaType, response.Content); } OnEvent(message.ToString()); } catch (Exception e) { OnErrorEvent(StringProcessor.SafeFormatter("Failed to log event because: {0}", e.ToString())); } }
/// <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())); } }
/// <summary> /// Have the driver cleanup after itself /// </summary> protected override void DriverDispose() { Log.LogMessage(MessageType.VERBOSE, "Start dispose driver"); // If we never created the driver we don't have any cleanup to do if (!this.IsDriverIntialized()) { return; } try { IWebDriver driver = this.GetWebDriver(); driver?.KillDriver(); } catch (Exception e) { Log.LogMessage(MessageType.ERROR, StringProcessor.SafeFormatter("Failed to close web driver because: {0}", e.Message)); } this.BaseDriver = null; Log.LogMessage(MessageType.VERBOSE, "End dispose driver"); }
/// <summary> /// Method to determine the text to be appended to the screenshot file names /// </summary> /// <param name="softAssertName">Soft assert name</param> /// <returns>String to be appended</returns> private string TextToAppend(string softAssertName) { string appendToFileName = string.Empty; // If softAssertName name is not provided only append the AssertNumber if (softAssertName == string.Empty) { appendToFileName = StringProcessor.SafeFormatter(" ({0})", this.NumberOfAsserts); } else { // Make sure that softAssertName has valid file name characters only foreach (char invalidChar in System.IO.Path.GetInvalidFileNameChars()) { softAssertName = softAssertName.Replace(invalidChar, '~'); } // If softAssertName is provided, use combination of softAssertName and AssertNumber appendToFileName = " " + softAssertName + StringProcessor.SafeFormatter(" ({0})", this.NumberOfAsserts); } return(appendToFileName); }
/// <summary> /// Change the console color to match the message type, write the message and restore the previous console colors /// </summary> /// <param name="type">The type of message</param> /// <param name="line">Is this a write-line command, else it is just a write</param> /// <param name="message">The log message</param> /// <param name="args">Message string format arguments</param> private void SetColorWriteAndRestore(MessageType type, bool line, string message, params object[] args) { // Just return if there is no message or this type of message should not be logged if (string.IsNullOrEmpty(message) || !this.ShouldMessageBeLogged(type)) { return; } // Save the original console colors ConsoleColor originalBack = Console.BackgroundColor; ConsoleColor originalFore = Console.ForegroundColor; // Update console colors SetConsoleColor(type); string result = StringProcessor.SafeFormatter(message, args); try { // If this a write-line command if (line) { Console.WriteLine(result); } else { Console.Write(result); } } catch (Exception e) { Console.WriteLine(StringProcessor.SafeFormatter("Failed to write to the console because: {0}", e.Message)); } // Cleanup after yourself SetConsoleColor(originalFore, originalBack); }
/// <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 RemoteWebDriver remoteDrive = driver as RemoteWebDriver; if (remoteDrive != null) { 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: {0}", e.Message); Console.WriteLine(StringProcessor.SafeFormatter("Failed to start driver because: {0}", e.Message)); } }
public void StringFormatterThrowException() { string message = StringProcessor.SafeFormatter("This {0} should return {5}", "Test", "Test", "Test"); Assert.IsTrue(message.Contains("This {0} should return {5}")); }
public void StringFormatterCheckForStringFormat() { string message = StringProcessor.SafeFormatter("This {0} should return {1}", "Test", "Test"); Assert.AreEqual("This Test should return Test", message); }
public void StringFormatterCheckForJson() { string message = StringProcessor.SafeFormatter("{This is a test for JSON}"); Assert.AreEqual("{This is a test for JSON}\r\n", message); }
/// <summary> /// Raise an action message without content /// </summary> /// <param name="actionType">The action type - Get, Post, etc.</param> /// <param name="requestUri">The request uri</param> /// <param name="mediaType">The type of media being requested</param> private void RaiseEvent(string actionType, string requestUri, string mediaType) { this.OnEvent(StringProcessor.SafeFormatter("Sending {0} request to base: '{1}' endpoint: '{2}' with the media type: '{3}'", actionType, this.HttpClient.BaseAddress, requestUri, mediaType)); }
/// <summary> /// Raise an exception message /// </summary> /// <param name="e">The exception</param> private void RaiseErrorMessage(Exception e) { this.OnErrorEvent(StringProcessor.SafeFormatter($"Failed because: {e.Message}{Environment.NewLine}{e.ToString()}")); }
/// <summary> /// Initializes a new instance of the <see cref="EventFiringEmailDriver" /> class /// </summary> /// <param name="host">The email server host</param> /// <param name="username">Email user name</param> /// <param name="password">Email user password</param> /// <param name="port">Email server port</param> /// <param name="serverTimeout">Timeout for the email server</param> /// <param name="isSSL">Should SSL be used</param> /// <param name="skipSslCheck">Skip the SSL check</param> public EventFiringEmailDriver(string host, string username, string password, int port, int serverTimeout = 10000, bool isSSL = true, bool skipSslCheck = false) : base(host, username, password, port, serverTimeout, isSSL, skipSslCheck) { this.OnActionEvent(StringProcessor.SafeFormatter($"Connect to email with user '{username}' on host '{host}', port '{port}'")); }
/// <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.appiumTestObject.GetDriverManager <MobileDriverManager>().IsDriverIntialized()) { if (AppiumConfig.GetSoftAssertScreenshot()) { AppiumUtilities.CaptureScreenshot(this.appiumTestObject.AppiumDriver, this.appiumTestObject, this.TextToAppend(assertName)); } if (AppiumConfig.GetSavePagesourceOnFail()) { AppiumUtilities.SavePageSource(this.appiumTestObject.AppiumDriver, this.appiumTestObject, StringProcessor.SafeFormatter($" ({ this.NumberOfAsserts})")); } return(false); } return(didPass); }
/// <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); } }
/// <summary> /// Soft assert method to check if the files are equal /// </summary> /// <param name="expectedText">Expected text</param> /// <param name="actualText">Actual text</param> /// <param name="softAssertName">Soft assert name</param> /// <param name="message">Exception message if desired</param> /// <returns>Boolean if the assert is true</returns> public override bool AreEqual(string expectedText, string actualText, string softAssertName, string message = "") { bool didPass = base.AreEqual(expectedText, actualText, softAssertName, message); if (!didPass && this.appiumTestObject.GetDriverManager <MobileDriverManager>().IsDriverIntialized()) { if (AppiumConfig.GetSoftAssertScreenshot()) { AppiumUtilities.CaptureScreenshot(this.appiumTestObject.AppiumDriver, this.appiumTestObject, this.TextToAppend(softAssertName)); } if (AppiumConfig.GetSavePagesourceOnFail()) { AppiumUtilities.SavePageSource(this.appiumTestObject.AppiumDriver, this.appiumTestObject, StringProcessor.SafeFormatter(" ({0})", this.NumberOfAsserts)); } return(false); } else if (!didPass) { return(false); } return(true); }
/// <summary> /// Get the message for an unknown message type /// </summary> /// <param name="type">The message type</param> /// <returns>The unknown message type message</returns> protected string UnknownMessageTypeMessage(MessageType type) { return(StringProcessor.SafeFormatter($"Unknown MessageType: {Enum.GetName(typeof(MessageType), type)}{Environment.NewLine}Message will be displayed with the MessageType of: {Enum.GetName(typeof(MessageType), MessageType.GENERIC)}")); }
public void StringFormatterCheckForJson() { string message = StringProcessor.SafeFormatter("{This is a test for JSON}"); Assert.AreEqual("{This is a test for JSON}" + Environment.NewLine, message); }
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); }
/// <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) { 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); }
/// <summary> /// Get the webdriver based for the provided browser /// <para>Browser are maximized by default</para> /// </summary> /// <param name="browser">The browser type we want to use</param> /// <returns>An IWebDriver</returns> /// <example> /// <code source = "../SeleniumUnitTesting/SeleniumConfigTests.cs" region="GetBrowserWithString" lang="C#" /> /// </example> public static IWebDriver Browser(string browser) { IWebDriver webDriver = null; try { switch (browser.ToUpper()) { case "INTERNET EXPLORER": case "INTERNETEXPLORER": case "IE": webDriver = InitializeIEDriver(); break; case "FIREFOX": webDriver = InitializeFirefoxDriver(); break; case "CHROME": webDriver = InitializeChromeDriver(); break; case "HEADLESSCHROME": webDriver = InitializeHeadlessChromeDriver(); break; case "EDGE": webDriver = InitializeEdgeDriver(); break; case "PHANTOMJS": throw new ArgumentException(StringProcessor.SafeFormatter("Selenium no longer supports PhantomJS", browser)); case "REMOTE": webDriver = new RemoteWebDriver(new Uri(Config.GetValueForSection(SELENIUMSECTION, "HubUrl")), GetRemoteCapabilities(), GetCommandTimeout()); break; default: throw new ArgumentException(StringProcessor.SafeFormatter("Browser type '{0}' is not supported", browser)); } SetBrowserSize(webDriver); 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); } }
/// <summary> /// Get the message for an unknown message type /// </summary> /// <param name="type">The message type</param> /// <returns>The unknown message type message</returns> protected string UnknownMessageTypeMessage(MessageType type) { return(StringProcessor.SafeFormatter("Unknown MessageType: {0}{1}{2}{3}", Enum.GetName(typeof(MessageType), type), Environment.NewLine, "Message will be displayed with the MessageType of: ", Enum.GetName(typeof(MessageType), MessageType.GENERIC))); }
/// <summary> /// Initializes a new instance of the <see cref="EventFiringEmailDriver" /> class /// </summary> /// <param name="setupEmailBaseConnectionOverride">A function that returns the email connection</param> public EventFiringEmailDriver(Func <ImapClient> setupEmailBaseConnectionOverride) : base(setupEmailBaseConnectionOverride) { this.OnActionEvent(StringProcessor.SafeFormatter($"Connect to email with function '{setupEmailBaseConnectionOverride.Method.Name}'")); }
/// <summary> /// Write the formatted message (one line) to the console as a generic message /// </summary> /// <param name="messageType">The type of message</param> /// <param name="message">The message text</param> /// <param name="args">String format arguments</param> public override void LogMessage(MessageType messageType, string message, params object[] args) { // If the message level is greater that the current log level then do not log it. if (this.ShouldMessageBeLogged(messageType)) { InsertHtml($"<div class='collapse col-12 show' data-logtype='{messageType}'><div class='card'><div class='card-body {GetTextWithColorFlag(messageType)}'><h5 class='card-title mb-1'>{messageType}</h5><h6 class='card-subtitle mb-1'>{CurrentDateTime()}</h6><p class='card-text'>{HttpUtility.HtmlEncode(StringProcessor.SafeFormatter(message, args))}</p></div></div></div>"); } }
/// <summary> /// Get the fully qualified test name /// </summary> /// <returns>The test name including class</returns> private string GetFullyQualifiedTestClassNameVS() { return(StringProcessor.SafeFormatter("{0}.{1}", this.TestContext.FullyQualifiedTestClassName, this.TestContext.TestName)); }
/// <summary> /// Get a unique file name /// </summary> /// <param name="testName">Prepend text</param> /// <param name="extension">The file extension</param> /// <returns>A unique file name</returns> private string GetFileName(string testName, string extension) { return(StringProcessor.SafeFormatter("UtilitiesUnitTesting.{0}-{1}.{2}", testName, Guid.NewGuid(), extension)); }
/// <summary> /// Raise an exception message /// </summary> /// <param name="e">The exception</param> private void RaiseErrorMessage(Exception e) { this.OnErrorEvent(StringProcessor.SafeFormatter("Failed because: {0}{1}{2}", e.Message, Environment.NewLine, e.ToString())); }
/// <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); }