Skip to content

Commit

Permalink
Merge pull request #96 from ObjectivityLtd/3.1.10
Browse files Browse the repository at this point in the history
3.1.10
  • Loading branch information
raczeja authored Mar 28, 2019
2 parents c75b412 + 894f8ad commit 7d6b39d
Show file tree
Hide file tree
Showing 9 changed files with 426 additions and 290 deletions.
283 changes: 2 additions & 281 deletions Objectivity.Test.Automation.Common/DriverContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ namespace Objectivity.Test.Automation.Common
/// Contains handle to driver and methods for web browser
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Driver is disposed on test end")]
public class DriverContext
public partial class DriverContext
{
private static readonly NLog.Logger Logger = LogManager.GetLogger("DRIVER");
private readonly Collection<ErrorDetail> verifyMessages = new Collection<ErrorDetail>();
Expand Down Expand Up @@ -82,11 +82,6 @@ public class DriverContext
/// </value>
public string TestTitle { get; set; }

/// <summary>
/// Gets or sets the CrossBrowserProfile from App.config
/// </summary>
public string CrossBrowserProfile { get; set; }

/// <summary>
/// Gets or sets the Environment Browsers from App.config
/// </summary>
Expand Down Expand Up @@ -422,23 +417,7 @@ private InternetExplorerOptions InternetExplorerOptions
return options;
}

// loop through all of them
for (var i = 0; i < internetExplorerPreferences.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Set custom preference '{0},{1}'", internetExplorerPreferences.GetKey(i), internetExplorerPreferences[i]);

// and verify all of them
switch (internetExplorerPreferences.GetKey(i))
{
case "EnsureCleanSession":
options.EnsureCleanSession = Convert.ToBoolean(internetExplorerPreferences[i], CultureInfo.CurrentCulture);
break;

case "IgnoreZoomLevel":
options.IgnoreZoomLevel = Convert.ToBoolean(internetExplorerPreferences[i], CultureInfo.CurrentCulture);
break;
}
}
this.GetInternetExplorerPreferences(internetExplorerPreferences, options);

return options;
}
Expand Down Expand Up @@ -603,263 +582,5 @@ public void Stop()
this.driver.Quit();
}
}

/// <summary>
/// Saves the screenshot.
/// </summary>
/// <param name="errorDetail">The error detail.</param>
/// <param name="folder">The folder.</param>
/// <param name="title">The title.</param>
/// <returns>Path to the screenshot</returns>
public string SaveScreenshot(ErrorDetail errorDetail, string folder, string title)
{
var fileName = string.Format(CultureInfo.CurrentCulture, "{0}_{1}_{2}.png", title, errorDetail.DateTime.ToString("yyyy-MM-dd HH-mm-ss-fff", CultureInfo.CurrentCulture), "browser");
var correctFileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(CultureInfo.CurrentCulture), string.Empty));
correctFileName = Regex.Replace(correctFileName, "[^0-9a-zA-Z._]+", "_");
correctFileName = NameHelper.ShortenFileName(folder, correctFileName, "_", 255);

var filePath = Path.Combine(folder, correctFileName);

try
{
errorDetail.Screenshot.SaveAsFile(filePath, ScreenshotImageFormat.Png);
FilesHelper.WaitForFileOfGivenName(BaseConfiguration.ShortTimeout, correctFileName, folder);
Logger.Error(CultureInfo.CurrentCulture, "Test failed: screenshot saved to {0}.", filePath);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "##teamcity[publishArtifacts '{0}']", filePath));
return filePath;
}
catch (NullReferenceException)
{
Logger.Error("Test failed but was unable to get webdriver screenshot.");
}

return null;
}

/// <summary>
/// Saves the page source.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns>The saved source file</returns>
public string SavePageSource(string fileName)
{
if (BaseConfiguration.GetPageSourceEnabled)
{
var fileNameShort = Regex.Replace(fileName, "[^0-9a-zA-Z._]+", "_");
fileNameShort = NameHelper.ShortenFileName(this.PageSourceFolder, fileNameShort, "_", 255);
var fileNameWithExtension = string.Format(CultureInfo.CurrentCulture, "{0}{1}", fileNameShort, ".html");
var path = Path.Combine(this.PageSourceFolder, fileNameWithExtension);
if (File.Exists(path))
{
File.Delete(path);
}

var pageSource = this.driver.PageSource;
pageSource = pageSource.Replace("<head>", string.Format(CultureInfo.CurrentCulture, "<head><base href=\"http://{0}\" target=\"_blank\">", BaseConfiguration.Host));
File.WriteAllText(path, pageSource);
FilesHelper.WaitForFileOfGivenName(BaseConfiguration.LongTimeout, fileNameWithExtension, this.PageSourceFolder);
Logger.Error(CultureInfo.CurrentCulture, "Test failed: page Source saved to {0}.", path);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, "##teamcity[publishArtifacts '{0}']", path));
return path;
}

return null;
}

/// <summary>
/// Takes and saves screen shot
/// </summary>
/// <returns>Array of filepaths</returns>
public string[] TakeAndSaveScreenshot()
{
List<string> filePaths = new List<string>();
if (BaseConfiguration.FullDesktopScreenShotEnabled)
{
filePaths.Add(TakeScreenShot.Save(TakeScreenShot.DoIt(), ImageFormat.Png, this.ScreenShotFolder, this.TestTitle));
}

if (BaseConfiguration.SeleniumScreenShotEnabled)
{
filePaths.Add(this.SaveScreenshot(new ErrorDetail(this.TakeScreenshot(), DateTime.Now, null), this.ScreenShotFolder, this.TestTitle));
}

return filePaths.ToArray();
}

/// <summary>
/// Logs JavaScript errors
/// </summary>
/// <returns>True if JavaScript errors found</returns>
public bool LogJavaScriptErrors()
{
IEnumerable<LogEntry> jsErrors = null;
bool javScriptErrors = false;

// Check JavaScript browser logs for errors.
if (BaseConfiguration.JavaScriptErrorLogging)
{
Logger.Debug(CultureInfo.CurrentCulture, "Checking JavaScript error(s) in browser");
try
{
jsErrors =
this.driver.Manage()
.Logs.GetLog(LogType.Browser)
.Where(x => BaseConfiguration.JavaScriptErrorTypes.Any(e => x.Message.Contains(e)));
}
catch (NullReferenceException)
{
Logger.Error(CultureInfo.CurrentCulture, "NullReferenceException while trying to read JavaScript errors from browser.");
return false;
}

if (jsErrors.Any())
{
// Show JavaScript errors if there are any
Logger.Error(CultureInfo.CurrentCulture, "JavaScript error(s): {0}", Environment.NewLine + jsErrors.Aggregate(string.Empty, (s, entry) => s + entry.Message + Environment.NewLine));
javScriptErrors = true;
}
}

return javScriptErrors;
}

/// <summary>
/// Sets the driver options.
/// </summary>
/// <typeparam name="T">The type of DriverOptions for the specific Browser</typeparam>
/// <param name="options">The options.</param>
/// <returns>
/// The Driver Options
/// </returns>
private T SetDriverOptions<T>(T options)
where T : DriverOptions
{
this.DriverOptionsSet?.Invoke(this, new DriverOptionsSetEventArgs(options));
return options;
}

private Proxy CurrentProxy()
{
Proxy proxy = new Proxy
{
HttpProxy = BaseConfiguration.Proxy,
FtpProxy = BaseConfiguration.Proxy,
SslProxy = BaseConfiguration.Proxy,
SocksProxy = BaseConfiguration.Proxy
};
return proxy;
}

private void CheckIfProxySetForSafari()
{
// set browser proxy for Safari
if (!string.IsNullOrEmpty(BaseConfiguration.Proxy))
{
throw new NotSupportedException("Use command line to setup proxy");
}
}

private FirefoxOptions AddFirefoxArguments(FirefoxOptions option)
{
var firefoxArguments = ConfigurationManager.GetSection("FirefoxArguments") as NameValueCollection;

// if there are any arguments
if (firefoxArguments != null)
{
// loop through all of them
for (var i = 0; i < firefoxArguments.Count; i++)
{
Logger.Trace(CultureInfo.CurrentCulture, "Setting FireFox Arguments {0}", firefoxArguments.GetKey(i));
option.AddArgument(firefoxArguments.GetKey(i));
}
}

return option;
}

private T SetRemoteDriverOptions<T>(NameValueCollection driverCapabilitiesConf, NameValueCollection settings, T options)
where T : DriverOptions
{
// if there are any capability
if (driverCapabilitiesConf != null)
{
// loop through all of them
for (var i = 0; i < driverCapabilitiesConf.Count; i++)
{
string value = driverCapabilitiesConf.GetValues(i)[0];
Logger.Trace(CultureInfo.CurrentCulture, "Adding driver capability {0}", driverCapabilitiesConf.GetKey(i));
options.AddAdditionalCapability(driverCapabilitiesConf.GetKey(i), value);
}
}

// if there are any capability
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Logger.Trace(CultureInfo.CurrentCulture, "Adding driver capability {0} from {1}", key, this.CrossBrowserEnvironment);

options.AddAdditionalCapability(key, settings[key]);
}
}

return options;
}

private BrowserType GetBrowserTypeForRemoteDriver(NameValueCollection settings)
{
if (BaseConfiguration.TestBrowserCapabilities != BrowserType.CloudProvider)
{
return BaseConfiguration.TestBrowserCapabilities;
}

BrowserType browserType = BrowserType.None;
bool supportedBrowser = false;
if (settings != null)
{
string browser = settings.GetValues("browser")?[0];
supportedBrowser = Enum.TryParse(browser, true, out browserType);
Logger.Info(CultureInfo.CurrentCulture, "supportedBrowser {0} : {1}", supportedBrowser, browserType);
}

if (!supportedBrowser)
{
if (this.CrossBrowserEnvironment.ToLower(CultureInfo.CurrentCulture).Contains(BrowserType.Android.ToString().ToLower(CultureInfo.CurrentCulture)))
{
browserType = BrowserType.Chrome;
}
else if (this.CrossBrowserEnvironment.ToLower(CultureInfo.CurrentCulture).Contains(BrowserType.Iphone.ToString().ToLower(CultureInfo.CurrentCulture)))
{
browserType = BrowserType.Safari;
}
}

return browserType;
}

private void SetRemoteDriverBrowserOptions(NameValueCollection driverCapabilitiesConf, NameValueCollection settings, dynamic browserOptions)
{
// if there are any capability
if (driverCapabilitiesConf != null)
{
// loop through all of them
for (var i = 0; i < driverCapabilitiesConf.Count; i++)
{
string value = driverCapabilitiesConf.GetValues(i)[0];
Logger.Trace(CultureInfo.CurrentCulture, "Adding driver capability {0}", driverCapabilitiesConf.GetKey(i));
browserOptions.AddAdditionalCapability(driverCapabilitiesConf.GetKey(i), value, true);
}
}

// if there are any capability
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Logger.Trace(CultureInfo.CurrentCulture, "Adding driver capability {0} from {1}", key, this.CrossBrowserEnvironment);
browserOptions.AddAdditionalCapability(key, settings[key], true);
}
}
}
}
}
Loading

0 comments on commit 7d6b39d

Please sign in to comment.