Skip to content

Instantly share code, notes, and snippets.

@kensykora
Last active August 29, 2015 14:06
Show Gist options
  • Save kensykora/e0b07e2dcaae19442bff to your computer and use it in GitHub Desktop.
Save kensykora/e0b07e2dcaae19442bff to your computer and use it in GitHub Desktop.
UI Unit Testing with SauceLabs while allowing local testing
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Messaging;
namespace Website.Tests.UI
{
public static class Config
{
public static string SauceLabsAccountName
{
get { return ConfigurationManager.AppSettings["SauceLabsAccountName"]; }
}
public static string SauceLabsAccountKey
{
get { return ConfigurationManager.AppSettings["SauceLabsAccountKey"]; }
}
public static string StartingUrl
{
get { return string.IsNullOrEmpty(SeleniumStartingUrl) ? "http://localhost:51206/" : SeleniumStartingUrl; }
}
public static string SeleniumStartingUrl
{
get { return Environment.GetEnvironmentVariable("SELENIUM_STARTING_URL") ?? string.Empty; }
}
public enum TestTypes
{
Local,
Remote
}
public static TestTypes TestType
{
get
{
return string.IsNullOrEmpty(SeleniumStartingUrl) ? TestTypes.Local : TestTypes.Remote;
}
}
public static string Platform
{
get { return Environment.GetEnvironmentVariable("TEST_PLATFORM") ?? "WIN8_1"; }
}
public static string OperatingSystem
{
get { return Environment.GetEnvironmentVariable("TEST_OS") ?? "Windows 2012 R2"; }
}
public static string Browser
{
get { return Environment.GetEnvironmentVariable("TEST_BROWSER") ?? "chrome"; }
}
public static string BrowserVersion
{
get { return Environment.GetEnvironmentVariable("TEST_BROWSER_VERSION") ?? "37"; }
}
public static string SeleniumHost
{
get { return Environment.GetEnvironmentVariable("SELENIUM_HOST") ?? "ondemand.saucelabs.com"; }
}
public static string SeleniumPort
{
get { return Environment.GetEnvironmentVariable("SELENIUM_PORT") ?? "4444"; }
}
public static string BuildNumber
{
get { return Environment.GetEnvironmentVariable("SAUCE_BAMBOO_BUILDNUMBER") ?? string.Empty; }
}
public static int SeleniumIdleTimeout
{
get
{
int result;
if (!int.TryParse(Environment.GetEnvironmentVariable("SELENIUM_IDLE_TIMEOUT"), out result))
{
result = 300;
}
return result;
}
}
public static int SeleniumMaxDuration
{
get
{
int result;
if (!int.TryParse(Environment.GetEnvironmentVariable("SELENIUM_MAX_DURATION"), out result))
{
result = 300;
}
return result;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
namespace Website.Tests.UI
{
[TestClass]
public class HomepageTests : UITestBase
{
public override TestContext TestContext { get; set; }
[TestMethod]
[TestCategory("UI")]
public void can_visit_homepage()
{
Assert.AreEqual("ASP.NET", _driver.FindElement(By.XPath("//h1")).Text);
}
[TestMethod]
[TestCategory("UI")]
public void can_browse_to_about_page()
{
_driver.FindElement(By.LinkText("About")).Click();
Assert.AreEqual("About.", _driver.FindElement(By.XPath("//h2")).Text);
}
[TestMethod]
[TestCategory("UI")]
public void can_browse_to_contact_page()
{
_driver.FindElement(By.LinkText("Contact")).Click();
Assert.AreEqual("Contact.", _driver.FindElement(By.XPath("//h2")).Text);
}
[TestMethod]
[TestCategory("UI")]
public void can_browse_to_login()
{
_driver.FindElement(By.LinkText("Log in")).Click();
Assert.AreEqual("Log in.", _driver.FindElement(By.XPath("//h2")).Text);
}
[TestMethod]
[TestCategory("UI")]
public void can_browse_to_registration()
{
_driver.FindElement(By.LinkText("Register")).Click();
Assert.AreEqual("Register.", _driver.FindElement(By.XPath("//h2")).Text);
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
namespace Website.Tests.UI
{
[TestClass]
public abstract class UITestBase
{
protected IWebDriver _driver;
public abstract TestContext TestContext { get; set; }
[TestInitialize]
public void Init()
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
if (Config.TestType == Config.TestTypes.Remote)
{
_driver = _GetRemoteDriver(Config.Browser, Config.BrowserVersion, Config.OperatingSystem);
}
else
{
_driver = _GetLocalChromeDriver();
}
_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(Config.SeleniumIdleTimeout));
_driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Config.SeleniumMaxDuration));
_driver.Navigate().GoToUrl(Config.StartingUrl);
}
private IWebDriver _GetLocalChromeDriver()
{
var result = new ChromeDriver();
return result;
}
private IWebDriver _GetRemoteDriver(string browser, string version, string platform)
{
// construct the url to sauce labs
Uri commandExecutorUri = new Uri("http://ondemand.saucelabs.com/wd/hub");
// set up the desired capabilities
DesiredCapabilities desiredCapabilites = new DesiredCapabilities(browser, version, Platform.CurrentPlatform); // set the desired browser
desiredCapabilites.SetCapability("platform", platform); // operating system to use
desiredCapabilites.SetCapability("username", Config.SauceLabsAccountName); // supply sauce labs username
desiredCapabilites.SetCapability("accessKey", Config.SauceLabsAccountKey); // supply sauce labs account key
desiredCapabilites.SetCapability("name", CurrentTestName); // give the test a name
// start a new remote web driver session on sauce labs
var result = new RemoteWebDriverWithSessionId(commandExecutorUri, desiredCapabilites);
Trace.WriteLine(string.Format("\nSauceOnDemandSessionID={0} job-name={1}",
((RemoteWebDriverWithSessionId)result).SessionId, CurrentTestName
));
return result;
}
/// <summary>called at the end of each test to tear it down</summary>
[TestCleanup]
public void CleanUp()
{
// get the status of the current test
bool passed = TestContext.CurrentTestOutcome == UnitTestOutcome.Passed;
try
{
if (_driver is RemoteWebDriverWithSessionId)
{
// log the result to sauce labs
((IJavaScriptExecutor)_driver).ExecuteScript("sauce:job-result=" + (passed ? "passed" : "failed"));
}
}
finally
{
// terminate the remote webdriver session
_driver.Quit();
}
}
private string CurrentTestName
{
get { return Config.BuildNumber + "-" + TestContext.TestName; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment