Wednesday, 21 September 2016

C#: How can I get my Selemium test to log into Azure?

I have been writing some entry level Selenium tests for my Azure website that authenticates using Azure AD. The biggest issue is trying to get the WebDriver to authenticate into the solution.

After a lot of learning (read: failed attempts) I have the following solution (read: hack) that seems to work.

1. In my [TestInitialize] method, I load JQuery to the created page

public static class Common
    {
        public static string GetEval(IWebDriver driver, string script)
        {
            IJavaScriptExecutor js = driver as IJavaScriptExecutor;
            return (string)js.ExecuteScript(script);
        }

        public static string GetFile(string path)
        {
            using (var reader = new StreamReader(path))
            {
                return reader.ReadToEnd();
            }
        }
}

Common.GetEval(driver, Common.GetFile("Lib\\jquery.js"));

NOTE: I created a folder called 'lib' and added the jquery.js file. Most importantly, I set the property 'Copy to Output Directory' to 'Copy Always'

2. When I create my connection to the target site, I use JQuery to manipulate the DOM and insert the login credentials. The problem occurs when trying to press 'Enter'. The code simulates pressing 'Enter', waits 5 seconds and then does it again.

 Driver.Navigate().GoToUrl(ConfigurationManager.AppSettings["SiteUrl"]);

            // If we are in the login page, then login
            if (driver.Url.Contains(@"https://login.microsoftonline.com"))
            {
               // set the credentails
                Common.GetEval(driver, "$('#cred_userid_inputtext').val('me@mytenant.onmicrosoft.com')");
                Common.GetEval(driver, "$('#cred_password_inputtext').val('MyPassword123')");

                // press enter
                Common.GetEval(driver, "var e = jQuery.Event('keypress'); e.which = 13; e.keyCode = 13; $('#cred_password_inputtext').trigger(e);");

                System.Threading.Thread.Sleep(5000);

                // press enter again
                Common.GetEval(driver, "var e = jQuery.Event('keypress'); e.which = 13; e.keyCode = 13; $('#cred_password_inputtext').trigger(e);");
            }

3. In the test method, wait 1 second and the DOM should be available.

System.Threading.Thread.Sleep(1000);

var elements = driver.FindElements(By.CssSelector(".myclass"));


No comments:

Post a Comment