Powered By Blogger

Search Here!

Friday, April 27, 2012

Selenium RC: Android Testing using C# !

We can use Selenium RC for Android Testing in C# code, here below how to use this :)


 public static ISelenium GetSeleniumInstance()
        {
            return Thread.GetData(Thread.GetNamedDataSlot("SeleniumInstance")) as ISelenium;
        }


public static IWebDriver GetWebDriverInstance()
        {
            return Thread.GetData(Thread.GetNamedDataSlot("WebDriverInstance")) as IWebDriver;
        }       
-------------------------------
        IWebDriver _webDriver;
        protected IWebDriver WebDriver { get { return GetWebDriverInstance(); } }
        ISelenium _selenium;
        protected ISelenium Selenium { get { return GetSeleniumInstance(); } } 
------------------------------
const BrowserUrl = ConfigurationManager.AppSettings["browserUrl"]; // Defined in app. config


            _webDriver = new AndroidDriver();
            _webDriver.Navigate().GoToUrl(browserUrl);
            _selenium = new WebDriverBackedSelenium(_webDriver, BrowserUrl);
            _selenium.Start();
            Thread.SetData(Thread.GetNamedDataSlot("WebDriverInstance"), _webDriver);
            Thread.SetData(Thread.GetNamedDataSlot("SeleniumInstance"), _selenium);

Note: I am using all Dll's of version 2.6.0.0 

Thursday, April 26, 2012

Selenium RC: Search Text using Pagination !

Sometimes, we want to search a value in absence of search function due to it's not implemented. There is a problem through Selenium to get the value in a table that contains pagination. This method helps you to find search value from the table using pagination.  tableName is the Table locator and searchText is the name of the text that you want to search.


        public static int SearchTextFromPaginationGrid(string tableName, string searchText)
        {
            ISelenium Selenium = GetSeleniumInstance();
            int table_employee;
            string gridID = string.Empty; ;
            bool value = true;
            do
            {
                string get_text = Selenium.GetText(gridIDLoc);
                 table_employee  = get_text.IndexOf(searchText);
                if (gridIDLoc.Contains("'"))
                {
                    string[] SplittedLoc = gridIDLoc.Split('\'');
                    gridID = SplittedLoc[1];
                }
                value = Selenium.IsElementPresent("id=" + gridID + "$next");
                if (value == true)
                {
                    Selenium.Click("id=" + gridID + "$next");
                    Thread.Sleep(2000);
                }
                WaitUntilElement(gridID);
            } while (value && table_txt < 0);
            return  table_employee;
        }

Tuesday, April 24, 2012

Selenium Android Testing : Using the remote WebDriver server in C# !

Following are the steps to setup environment : ANDROID TESTING using c#

1. Install SDK and install 4.0.3 Android API's.

2. Install AVD Manager and create AVD using 4.0.3 Android API'.

3. Start AVD by clicking on Start button and launch virtual device.

4. Open command prompt and browse the path of SDK directory under platform-tools folder to run the adb commands for example I had set the path D:\android-sdk-windows\platform-tools

5. Every device or emulator has a serial ID. Run this command to get the serial ID of the device or emulator you want to use and check whether to check the active state:
> adb devices

6. Download the Android server apk file 'android-server-2.0b3-patched2.apk' from http://code.google.com/p/selenium/downloads/list. To install the application do:
> adb -s emulator-5554 -e install -r D:\android-sdk-windows\platform-tools\android-server-2.0b3-patched2.apk

7. Start the Android WebDriver application through the UI of the device, click on WebDriver link button,

or by running this command: 

> adb -s emulator-5554 shell am start -a android.intent.action.MAIN -n org.openqa.selenium.android.app/.MainActivity

 

and confirm Jetty Server started, if this confirmation fails on the emulator UI then run these commands,
> adb kill-server

> adb start-server
then re-start from step 3 again till then you would not get confirmation.

8. Now we need to setup the port forwarding in order to forward traffic from the host machine to the emulator. In a terminal type:
> adb forward tcp:8080 tcp:8080

 9. Start Selenium Server on the machine :
> java -jar selenium-server-standalone-2.0b2.jar -proxyInjectionMode -trustAllSSLCertificates -log selenium.log

10. Now, execute the C# code for this built setup:

[TestClass] 

public class AndroidApp 
{
private IWebDriver WebDriver; 


[TestInitialize] 
public void TestInitializeAttribute() 

try 

WebDriver = new AndroidDriver(); 
WebDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30)); WebDriver.Manage().Cookies.DeleteAllCookies(); WebDriver.Navigate().GoToUrl("http://google.co.in");
} catch (Exception) { throw; } }


Now, you have done successfully and ready to start testing:)
 

Note: Always use the correct version of Android API with *.apk file.

Selenium : Coded UI Upload File !

This Coded UI method helps you to upload file through Browse button and handles with Window Componet to 'Select File' , the Coded UI record and play actions need to integrate with C#.


using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;
using Microsoft.VisualStudio.TestTools.UITesting.WinControls;
using System.Threading;

public void ImportScoMetadataFile()
        {
            BrowserWindow bwindow;
            bwindow = BrowserWindow.Locate("Browse Window Name");
            UITestControl Browse = new UITestControl(bwindow);
            Browse.TechnologyName = "Web";
            Browse.FilterProperties.Add(HtmlDocument.PropertyNames.Title, "Browse Window Name");
            Browse.SearchProperties.Add(HtmlFileInput.PropertyNames.Id, "txtSpreadsheetFile");
            Browse.SearchProperties.Add(HtmlFileInput.PropertyNames.Name, "txtSpreadsheetFile");
            Browse.FilterProperties.Add(HtmlFileInput.PropertyNames.ControlDefinition, "onkeydown=\"return false;\" id=txtSpreadsh");
            Mouse.DoubleClick(Browse);
            WinWindow popup = new WinWindow();
            popup.TechnologyName = "MSAA";
            popup.SearchProperties.Add(WinWindow.PropertyNames.Name, "Choose", PropertyExpressionOperator.Contains);
            popup.SearchProperties.Add(WinWindow.PropertyNames.ClassName, "#32770");
            Thread.Sleep(2000);
            if (popup.Exists)
            {
                WinEdit choose_Edit = new WinEdit(popup);
                choose_Edit.SearchProperties.Add(WinEdit.PropertyNames.Name, "File name:", PropertyExpressionOperator.Contains);
                choose_Edit.Text = ConfigurationManager.AppSettings["UploadFilePath"]; // Provide file path from app.config
                WinButton Browsebutton = new WinButton(popup);
                Browsebutton.SearchProperties[WinButton.PropertyNames.Name] = "Open";
                Mouse.Click(Browsebutton);
            }

Coded UI Test : BOON To Selenium for Handling Hectic Scenarios

Using Visual Studio Premium or Visual Studio Ultimate, you can create a coded UI test that can test that the user interface for an application functions correctly. The coded UI test performs actions on the user interface controls for an application and verifies that the correct controls are displayed with the correct values. For more information about which platforms and configurations are supported by coded UI tests, see Supported Configurations and Platforms for Coded UI Tests and Action Recordings.


In major scenarios Selenium not able to perform actions like File Upload, Multiple iFrame Handling having same ID's for the elements, pop up handling even more. There is a mechanism where you can record the action in steps and the same Coded UI class methods integrate in to C# library.


For more information please see http://channel9.msdn.com/Blogs/kmcgrath/Introduction-to-Creating-Coded-UI-Tests-with-Visual-Studio-2010

Selenium: Generate Unique variable

This C# method helps to generate unique variable, you can use with element to maintain it's uniqueness.


public static string Generate_Unique_variable(string value)
        {
            string[] clCourse = new string[10];
            string fun_inter_org;
            clCourse[0] = inter_org;
            clCourse[1] = DateTime.Now.Year.ToString();
            clCourse[2] = DateTime.Now.Month.ToString();
            clCourse[3] = DateTime.Now.Day.ToString();
            clCourse[4] = DateTime.Now.Hour.ToString();
            clCourse[5] = DateTime.Now.Minute.ToString();
            clCourse[6] = DateTime.Now.Second.ToString();
            fun_inter_org = String.Concat(clCourse);
            return value;
        }
Generic.Generate_Unique_variable("myinputvalue");
It would input like 'myinputvalue42420121137'

Selenium RC: Create Log Files

This C# method provides you to create verification results log in HTML format, you can change the format according to your need also it would take the screen shots of the FAILED log(s) and saves in a drive.


public static void Logs(string Logtext, string Status)
        {
            ISelenium Selenium = GetSeleniumInstance();
            string LogMessage;
            string StatusTest = Status.ToUpper();
            string time = Time_Stamp();
            String DriveName = ConfigurationManager.AppSettings["LogDriveName"]; //  in app.config file.
            String ErrorFileName = String.Concat(DriveName, ":\\Error_History.html");
            try
            {               
                String logsFileName = string.Empty;
                switch (StatusTest)
                {
                    case "PASSED":
                        logsFileName = String.Concat(DriveName, ":\\Passed_Results.html");
                        LogMessage = string.Format("{0},\"  \"{1},\"  \"{2}", Logtext, time, StatusTest);
                        break;
                    case "FAILED":
                        logsFileName = String.Concat(DriveName, ":\\Failed_Results.html");
                        string error = Generate_Unique_variable("Error") + ".png";
                        Selenium.CaptureScreenshot(DriveName + ":\\Selenium_Screenshots\\" + error);
                        LogMessage = string.Format("{0},\"  \"{1},\"  \"{2}", Logtext, time, StatusTest);
                        break;
                    default:
                        logsFileName = String.Concat(DriveName, ":\\Failed_Results.html");
                        LogMessage = string.Format("{0},\"  \"{1},\"  \"{2}", Logtext, time, StatusTest);
                        break;
                }
                WriteLogs(logsFileName, LogMessage);//write logs to appropriate log file.
                WriteLogs(ErrorFileName, LogMessage);// write all the logs to error history
            }
            catch (Exception ex)
            {
               WriteLogs(string.Concat(DriveName, ":\\Failed_Results.html"),String.Concat(ex.Message,"FAILED"));
            }              
        }


//  WriteLogs Method

private static void WriteLogs(string FileName, String LogMessage)
        {
            //Delete if the file is old
            if (File.GetLastAccessTime(FileName) < DateTime.Now.Subtract(new TimeSpan(24, 0, 0)))
            //if the file does not exist, GetLastAccessTime returns minimum datetime value
            {
                File.Delete(FileName);                
            };
            LogMessage = String.Concat(LogMessage, "\r\n");
            //Append The Message To The File
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(FileName, true))
            {
                file.WriteLine(LogMessage);
                file.Close();
            }
        }

You can call this generic method by using:
Logs("The Log generated.", "PASSED"); or
Logs("The Log not generated.", "FAILED");

Selenium RC: Find Row Number of Element

This C# method gives you the table row no.of the element. You need to pass the cloumn no. in which you want to make search, ReferenceText the text you want to find out and table locator, after then you could perform any action that row no.


public static int GetRowWithCellText(string columnnum, string ReferenceText, string TableLocator,int startFromRowNum=0)
        {
            ISelenium Selenium = GetSeleniumInstance();
            for (int i = startFromRowNum; ; i++)
            {
                try
                {
                    string elementPresent = Selenium.GetTable(TableLocator + "." + i.ToString() + "." + columnnum).Trim();
                    if (elementPresent.Contains(ReferenceText))
                    {
                        return i;
                    }
                }
                catch (Exception)
                {
                    break;
                }
            }
            return -1;
        }

Selenium RC: RedirectToPage


There are various scenarios when we need to switch in between different URL's. This C# method helps to redirecting page from one to another in a very generic manner.

public static void RedirectToPage(string url)
        {
            ISelenium Selenium = GetSeleniumInstance();
            Selenium.SelectWindow("");
            Selenium.GetEval("javascript{ (function() { var txt=selenium.browserbot.getCurrentWindow().location ='" + url + "'; return '';})(); }");
        }

Selenium RC: Select and Close Window


This C# method provides you to select the pop-Up window name and close it in a definite interval of time. You need to pass pop-Up window name and time to wait in milliseconds.


public static void SelectAndCloseWindow(string popUpName, int insertDelay)
        {
            ISelenium Selenium = GetSeleniumInstance();
            Selenium.SelectWindow(popUpName);
            Selenium.Close();
            if (insertDelay > 0)
            Thread.Sleep(insertDelay);
        }

Selenium WebDriver: Wait Until Element

How to wait for an element till it comes on the page. C# code to wait for an element in a very generic manner using Selenium WebDriver.

public void WaitUntilElement(By by)
{
Boolean elementFound = false;
Stopwatch sw = new Stopwatch();
sw.Start();
int minutesToWait = Int32.Parse(ConfigurationManager.AppSettings["WaitUntillElementMinutes"]);
while (sw.Elapsed.Minutes < minutesToWait)
{
try
{
var elements = WebDriver.FindElements(by);
if (elements != null && elements.Count > 0)
{
elementFound = true;
break;
}
}
catch (Exception)
{ }
}
if (!elementFound)
{
throw new TimeoutException(string.Format("The expected element '{0}' has not found nder specified time interval of '{1}' minute(s).", by, ConfigurationManager.AppSettings["WaitUntillElementMinutes"]));
}
sw.Stop();
sw = null;
}

Selenium RC: Wait Until Element

How to wait for an element till it comes on the page. C# code to wait for an element in a very generic manner using Selenium RC.


public static void WaitUntilElement(string elementValue)       
 {
ISelenium Selenium = GetSeleniumInstance();            
Boolean ElementFound = false;            
Stopwatch sw = new Stopwatch();            
sw.Start();           
int MinutesToWait = Int32.Parse(ConfigurationManager.AppSettings["WaitUntillElementMinutes"]);            
while (sw.Elapsed.Minutes < MinutesToWait)            
{                
try                
{                    
if (Selenium.IsElementPresent(elementValue))                    
{                    
ElementFound = true;                        
break;                    
}                
}                
catch (Exception)                
{ }            
}            
if (!ElementFound)           
{
throw new TimeoutException(string.Format("The expected element '{0}' has not found under specified time interval of '{1}' minute(s).",elementValue, ConfigurationManager.AppSettings["WaitUntillElementMinutes"]));            
}
sw.Stop();
sw = null;
}