Powered By Blogger

Search Here!

Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Friday, July 31, 2015

Handling ! Page Load Events In Python Selenium !

Handling ! Page Load Events In Python Selenium.

from selenium.common.exceptions import InvalidElementStateException, StaleElementReferenceException
from selenium.webdriver import ActionChains as Action_Chains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as Expected_Conditions
from selenium.webdriver.support.ui import WebDriverWait

from time import sleep

def __init__(self, webdriver, TIMEOUT=120):

# An implementation of the Wait interface that may have its timeout and polling interval configured on the fly. Configure the wait to ignore specific types of exceptions whilst waiting.

self.wait = WebDriverWait(self.webdriver, self.TIMEOUT, poll_frequency=2, ignored_exceptions=[InvalidElementStateException, StaleElementReferenceException])

def wait_for_page_to_load(self, find_element_by, element_value, expected_element_text=None, polling_duration=0):
"""
# Helper method to wait for page load. Target to find the element which renders last on the page.
#
# - find_element_by: strategies to use with "locate_value" to locate value of web element.
# - element_value: value of the web element that is looked by the strategy defined in "find_element_by".
# - expected_element_text: (Default: None) will compare the element text from the UI if (any) text given else just find that element on the page.
# - polling_duration:  Sleep interval before verify page is in ready state. (Default) is 0.
# - return: web element which responsible for page load in case there is no spinner on the page.
 """
self.wait_for_page_in_ready_state(polling_duration)
presence_of_element_located = self.webdriver.find_element(by=find_element_by, value=element_value)
Action_Chains(self.webdriver).move_to_element(presence_of_element_located).perform()
        if not expected_element_text is None:
            if expected_element_text in presence_of_element_located.text:
                return presence_of_element_located
        else:
            return presence_of_element_located
           
def wait_for_page_in_ready_state(self, polling_duration=0):
"""
# Helper method to wait for page is in ready state. Ready state here verify there is no load spinner is 
# present on the page. This modular method can be use in any point of time.
# - polling_duration:  Sleep interval before verify page is in ready state. In some scenarios page load starts after some duration(seconds) delay. (Default) is 0, in such scenarios need to pass custom polling duration. 
"""
sleep(polling_duration)
self.wait.until(Expected_Conditions.invisibility_of_element_located((By.CSS_SELECTOR, Ele)))     self.wait.until(Expected_Conditions.invisibility_of_element_located((By.CSS_SELECTOR,Ele )))     self.wait.until(Expected_Conditions.invisibility_of_element_located((By.CSS_SELECTOR, Ele)))
        

Thursday, September 26, 2013

A Case Study on the Building a 21st Century Test Automation Framework!

A Case Study on the Building a 21st Century Test Automation Framework!

Abstract
Re-usable test automation frameworks coupled with open-source tools and technologies is a key solution to shrink test cycle times and related costs. This paper covers an approach for creating a script based web application automation framework around Selenium2 which is robust, flexible, and extensible. Our experimental results on this framework show increased productivity and ROI, reduced learning curve and dependency on skilled resources, eliminated usage of commercial tools and manual configuration. The framework provides ease of script generation & management, page object model, method level logging with screenshots, concurrent and remote execution using continuous integration environment, test data generation and customized reports. Preliminary statistics indicate that the automation framework reduces ~ 40% of total test execution effort per release cycle under a given scenario.

Biography
Frameworks are built at each level of the testing phase/cycle viz. unit, integration, and system testing. Each framework is built on a set of rules which are derived based on need analysis. This paper describes the methodology used in developing a robust web based automation framework.
This paper describes the “Plug and Play” data driven framework architecture in .Net on top of Behavior Driven layer as a best practice this architecture. As per the current design and implementation this framework is scalable because the controller and the execution scripts are designed as individual modules / utilities which give extensibility and ease of maintenance provides the best scalable solution to run tests in parallel.

Architecture and Design Approach


Basic components of an automation framework consist of selenium singleton class, in memory database, object repository, test data, execution engine, reporting and error logging.
Selenium singleton class is the core of the framework which is used to govern the execution work flow and modules listed below-

Application Configuration File: This file will load the required test script execution environment to govern the execution work flow.
BDD Layer: The feature files that are used by SpecFlow to store the acceptance criteria of the features (use cases, user stories) of your application are described in a format that is called Gherkin. Each feature file is associated with its definition file to drive the test scripts written in the page class.
In Memory Database: No physical database needed to avoid the extra burden for installing; all the created data through scripts primarily relies on main memory for computer data storage to efficiently used the created data for dependent scripts.           
Test Data Module: Test data stored in XML format and this will provide input for the automation test scripts. Each test data is picked based on the Test Environment defined in Application Configuration File.
Object Repository Module: Web elements / objects stored in resource file and this will provide the same as input to the automation test scripts.
Page Object Pattern: By using the page object model we can make non-brittle test code and reduce or eliminate duplicate test code. Beside of that it improves the readability and allows us to create interactive documentation. Last but not least, we can create tests with less keystroke. An implementation of the page object model can be achieved by separating the abstraction of the test object and the test scripts.
Libraries: This is used to load generic and application specific methods, reusable components grouped as a method calls in the page object model.
Logging Module: This module manages method logging along with screenshot handling across the work flow, Log4net can be used for debugging and error handling.
Reporting Module: Custom SpecFlow reports to produce some reports giving information about the features and steps after a test run has finished. The test execution report contains details about the SpecFlow test features, scenarios and steps. The step definition report shows the steps and their statuses, including unused steps and steps with no implementation.
Error Handling: Selenium2 and MS Test have mechanisms to capture the error logs. In case of a failure or crash, the error log stored in the root project folder along with screen shot.
Continuous Integration Environment: Through CI we execute automated tests after each commit in concurrent manner with different environment setup and send feedback with results to developers.

Test Environment Initialization
This module will set all the required parameters for a test run. The central framework engine will read the application configuration file and will set the environment required for the application under test (AUT)
Framework user has the flexibility to update the configuration file to select and execute tests by customizing the following parameters:
  • Base URL of the AUT
  • Type of Browser
  • Remote or Local machine
  • Wait For Element Time Limit
  • Test Environment Setup       

Reporting Engine
The default report of MSTest is comprehensive, but it's not easy to understand at-a-glance; as a result Continuous Integration is integrated with a batch process which converts the MSTest report in a SpecFlow HTML report. After the test run is completed an email alert will be sent to the stake holders and report published on the common web portal.

The Benefits
As a result of the current implementation Excelsoft is now able to ensure more comprehensive test coverage in a shorter period of time, including instant results of post-build basic tests. Allowing team members to easily develop and maintain reusable testing scenarios through the developed BDD layer on top of Selenium and also execute testing tasks with a unified and standardized approach has important positive implications on the overall efficiency and cost effectiveness of the operations. Also, it has made it possible to use convenient scheduled times, such as nightly run tests. As an example of how automation was effective in this case it was possible to reduce the average time for validating an important product feature from 8 hours to 3-4 hours.
  1. Total test cycle reduction from 2 weeks to 8h after automation.
  2. Shorter release cycles with increase from 1 build every 2 weeks to 2 builds per week.
  3. 60% overall cost reduction through the near shore model.
  4. Increased reusability of testing cases.
  5. Low maintenance costs of testing cases and processes.
  6. Possibility of implementing test metrics to guide decision-making.
  7. Introduction of benchmarks to increase software quality.
  8. Cost Reduction of software tools.

Remarks:

Thus we successfully developed a framework that helped us to exceed preset framework/automation objectives and could execute test scripts concurrently, reducing the execution time from 2 Man days to 60 minutes, bringing in 70% productivity improvement using framework on a continuous basis. We believe this approach can be carried across companies to significantly reduce the automation execution cost without compromising on quality. 

Saturday, June 8, 2013

Internet Explorer Options : Selenium !

org.openqa.selenium.ie.InternetExplorerDriver

Capabilities [{platform=WINDOWS, elementScrollBehavior=0, javascriptEnabled=true, enablePersistentHover=true, ignoreZoomSetting=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=9, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, allowAsynchronousJavaScript=true, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=, nativeEvents=true, takesScreenshot=true}]

InternetExplorerOptions options = new InternetExplorerOptions
                                                  {
                                                      IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                                                      UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Ignore,
                                                      IgnoreZoomLevel = true,
                                                      EnableNativeEvents = true,
                                                      RequireWindowFocus = true,
                                                      EnablePersistentHover = true,
                                                      ElementScrollBehavior = InternetExplorerElementScrollBehavior.Top,
                                                      BrowserAttachTimeout = TimeSpan.FromSeconds(timeOut),
                                                  };
 IWebDriver webDriver = new InternetExplorerDriver(ieDriverPath, options, TimeSpan.FromMinutes(20));

Properties Description

Name
Description
ElementScrollBehavior
Gets or sets the value for describing how elements are scrolled into view in the IE driver. Defaults to scrolling the element to the top of the viewport.
EnableNativeEvents
Gets or sets a value indicating whether to use native events in interacting with elements.
EnablePersistentHover
Gets or sets a value indicating whether to enable persistently sending WM_MOUSEMOVE messages to the IE window during a mouse hover.
IgnoreZoomLevel
Gets or sets a value indicating whether to ignore the zoom level of Internet Explorer .
InitialBrowserUrl
Gets or sets the initial URL displayed when IE is launched. If not set, the browser launches with the internal startup page for the WebDriver server.
IntroduceInstabilityByIgnoringProtectedModeSettings
Gets or sets a value indicating whether to ignore the settings of the Internet Explorer Protected Mode.
RequireWindowFocus
Gets or sets a value indicating whether to require the browser window to have focus before interacting with elements.
UnexpectedAlertBehavior
Gets or sets the value for describing how unexpected alerts are to be handled in the IE driver. Defaults to Default.

Sunday, June 24, 2012

Getting Started With HTMLUnitDriver: A Silent Simulator !

HTMLUnitDriver

This is currently the fastest and most lightweight implementation of WebDriver. As the name suggests, this is based on HtmlUnit. HtmlUnitDriver is a class of Interface WebDriver using namespace as OpenQA.Selenium.Remote; 

HtmlUnitDriver, a pure Java driver based on HtmlUnit browser simulator (all Java-capable OS).When running, you won’t see any window opening because it doesn’t render any page like Firefox would. You can’t use it to get size or position of pages' elements
It is very fast but does not provides JavaScript yet: this feature is still a WIP. If you want to use it anyway, use  desiredCapabilities.IsJavaScriptEnabled = true;
FirefoxDriver: supports Firefox (2.x and 3.x, all OS)
InternetExplorerDriver: supports InternetExplorer (tested on IE6, 7 and 8, should work on IE5.5 and on Windows XP and Vista)
ChromeDriver: drives Google’s browser (>= 4.0, all OS)


To use HtmlUnit you need to use the RemoteWebDriver and pass in the desired capabilities for it. Beloe code will help you to run application using HTMLUnitDriver using .Net. Note that you’ll need to run the remote WebDriver server to useHtmlUnit from C#

1. There is no Class HtmlUnit  in C# (dlls for Selenium)
2.  HtmlUnit  is really fast
We can walk through in this method:
1. Install  Selenium Server and start it using java -jar selenium server path
2.  To get an instance of the HtmlUnit Driver.
IWebDriver drive = new RemoteWebDriver(DesiredCapabilities.HtmlUnit());

---------------------------------------------------
using System;
using System.Configuration;
using OpenQA.Selenium.Remote;

               public static IWebDriver WebDriver;

               var remoteServer = new Uri("http://localhost:4444/wd/hub/");
               DesiredCapabilities desiredCapabilities = DesiredCapabilities.HtmlUnit();
               WebDriver = new RemoteWebDriver(remoteServer, desiredCapabilities);
               desiredCapabilities.IsJavaScriptEnabled = true;
               WebDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
               //go to url 
               WebDriver.Navigate().GoToUrl("http://google.co.in");


Tuesday, April 24, 2012

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);
            }

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'