Powered By Blogger

Search Here!

Sunday, October 12, 2014

Download File In Firefox and Chrome Driver !

Firefox Driver -

private static IWebDriver FireFoxWebDriver()
        {
            // create profile object
            var profile = new FirefoxProfile();
            // get Log Execution Path
            String getExecutingPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
            // set profile preferences
            profile.SetPreference("FireFox" + DateTime.Now.Ticks + ".log", getExecutingPath);
            profile.SetPreference("browser.download.folderList", 2);
            profile.SetPreference("browser.download.dir", DownloadFilePath);
            profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream doc docx xls xlsx pdf txt zip");
            IWebDriver webDriver = new FirefoxDriver(new FirefoxBinary(), profile, TimeSpan.FromMinutes(3));
            // set page load duration
            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(TimeOut));
            // set cursor position center of the screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return webDriver;
        }

Chrome Driver -

private static IWebDriver ChromeWebDriver()
        {
            // chrome preferences
            var chromeOptions = new ChromeOptionsWithPrefs
            {
                Prefs = new Dictionary
                {
                    {"download.default_directory", DownloadFilePath},
                    {"download.prompt_for_download", false},
                    {"profile.default_content_settings.popups", 0},
                    {"intl.accept_languages", "nl"}
                }
            };

            // chrome capabilities
            var desiredCapabilities = DesiredCapabilities.Chrome();
            desiredCapabilities.SetCapability(ChromeOptions.Capability, chromeOptions);
            // chrome driver path
            string chromeDriverPath = (Path.GetDirectoryName
                (Assembly.GetExecutingAssembly().GetName().CodeBase)
                + "\\..\\..\\..\\..\\ExternalAssemblies").Replace("file:\\", "");
            // create chrome browser instance
            IWebDriver webDriver = new ChromeDriver(chromeDriverPath, chromeOptions, TimeSpan.FromMinutes(3));
            return webDriver;
        }

Jenkins Selenium Grid Configuration !

Integrate Selenium WebDriver (or RC) with Jenkins, in order to run full end-to-end / UI automation testing as part of your build process.

{
  "capabilities":
      [
        {
          "browserName": "*firefox",
          "maxInstances": 1,
          "seleniumProtocol": "Selenium"
        },
        {
          "browserName": "*googlechrome",
          "maxInstances": 1,
          "seleniumProtocol": "Selenium"
        },
        {
          "browserName": "*iexplore",
          "maxInstances": 1,
          "seleniumProtocol": "Selenium"
        },
        {
          "browserName": "firefox",
          "maxInstances": 1,
          "seleniumProtocol": "WebDriver"
        },
        {
          "browserName": "chrome",
          "maxInstances": 1,
          "seleniumProtocol": "WebDriver"
        },
        {
          "browserName": "internet explorer",
          "maxInstances": 1,
          "seleniumProtocol": "WebDriver"
        }
      ],
    "configuration":
        {
         "host": null,
         "port": 4444,
         "newSessionWaitTimeout": -1,
         "servlets" : [],
         "prioritizer": null,
         "capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
         "throwOnCapabilityNotPresent": true,
         "nodePolling": 5000,
         "cleanUpCycle": 5000,
         "timeout": 300000,
         "browserTimeout": 0,
         "maxSession": 5,
         "jettyMaxThreads":-1,
         "url":"http://10.52.132.38:4444/wd/hub"
        }
}

Example: How To Handle Page Synchronization and Loading In Angular JS Site using Webdriver !

This method helps you to wait till Progress bar still on page.

public void HoldTillPageSynchronizationCompletes()
        {
            bool isPageInProgress = HoldTillElementIsVisible(By.CssSelector("div[class=Progress]"), 5);
            if (isPageInProgress)
            {
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                while (stopWatch.Elapsed.TotalMinutes < _waitTimeOut)
                {
                    string isPageStillInProgress = WebDriver.FindElement(By.CssSelector("table[id=mydivimg]")).GetAttribute("style");
                    if (isPageStillInProgress.Contains("display: none;"))
                    {
                        stopWatch.Stop(); break;
                    }
                }
            }
        }


This method helps you to wait till search records visible on page.

public void HoldTillRecordLoadInPageCompletes()
        {
            bool isLoadRecordInProgress = HoldTillElementIsVisible(By.CssSelector("div[style='display: block;']"), 5);
            if (isLoadRecordInProgress)
            {
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                while (stopWatch.Elapsed.TotalMinutes < _waitTimeOut)
                {
                    string isLoadRecordStillInProgress = WebDriver.FindElement(By.CssSelector("div[id=load_Summary]")).GetAttribute("style");
                    if (isLoadRecordStillInProgress.Contains("display: none;"))
                    {
                        stopWatch.Stop(); break;
                    }
                }
            }
        }

This is a common method helps you to hold for finding the element. In this element surely visible on the page but after sometime.

protected bool HoldTillElementIsVisible(By by, int timeOut = -1)
        {
            //Wait For Element
            if (timeOut == -1)
            {
                timeOut = this._waitTimeOut;
            }
            try
            {
                WebDriverWait wait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(timeOut));
                wait.Until(ExpectedConditions.ElementIsVisible(@by));
                return true;
            }
            //Exception Handling
            catch (Exception)
            {
                return false;
            }
        }

Thursday, June 19, 2014

How to fix Internet explorer has stopped working !

If you get this error message Internet explorer has sopped working‘. That means, must be a 3rd party “.dll” file is conflicting with iexplore.exe, also Internet explorer getting lots of load of unwanted toolbars, BHO’s, addon’s, extensions, and some internet explorer security settings. When you open Internet explorer you got a message ‘Internet explorer has sopped working’.
Anyway, we have the proper solution to fix that error message ”Internet explorer has stopped working”. We are give you 9 methods to fix that issue. please follow below method one by one.
__________________________________________________________________________________________

Method 1 : Reset Internet Explorer

  • Open Internet Explorer.
  • Click on Tools menu (Press “alt” key to active menu bar).
  • Click on “Internet Options“. a configuration window you will appear
  • Click on advanced tab.
  • Click on “Reset” Button. You’ll get an another box, here check a box named as “Delete Personal Settings“, then click on Reset button on it.
internet-explorer-reset
If doesn’t fix,  follow next method.
__________________________________________________________________________________________

Method 2 : Disable Software Rendering.

Disable Hardware Acceleration option in IE 9 & IE10
  • Open Internet Explorer.
  • Click on Tools menu (Press “alt” key to active menu bar).
  • Click on “Internet Options”. a configuration window you will appear
  • Click on advanced tab.
  • Un-check a option named as “use software rendering instead of GPU rendering”. it is located under “accelerated graphics”.
gpu-render-option-disable
If doesn’t fix, follow next method.
__________________________________________________________________________________________

Method 3 : Disable 3d in “NVIDIA Graphics driver”

Disable “stereoscopic 3D” option into “NVIDIA Graphic driver” application.(If you have Nvidia Graphics Drivers & Software, If you don’t have the you can leave that step)
  • Open Nvidia software from system tray.
  • Disable the option named as “stereoscopic 3D” from NVIDIA Drivers (NVIDIA driver is a computer Graphics drivers their software runs on system tray. )
nvidia-on-systemtray
nvidia-disable-option
If doesn’t fix, follow next method.
__________________________________________________________________________________________

Method 4 : Uninstall Unwanted Toolbars

  • Remove Unwanted Toolbars from Control Panel.
uninstall-unwated-toolbars
If doesn’t fix, so please follow next method.
__________________________________________________________________________________________

Method 5 : Disable Unwanted Addons

  • Disable Unwanted Add-ons from Internet Explorer.
disable-unwanted-addons
If doesn’t fix, so please follow next method.
__________________________________________________________________________________________

Method 6 : Re-install Java, Flash player, Silverlight.

  • Uninstall and then Re-install Add-ons program Like: Java, Flash player, Silverlight from control panel.
__________________________________________________________________________________________

Method 7 : Reset Security Zone.

  • Reset Internet Explorer Security Settings zone.
disable-security-zone
If doesn’t fix, so please follow next method.
__________________________________________________________________________________________

Method 7 : Run Microsoft Fixit’s

If doesn’t fix, so please follow next method.
__________________________________________________________________________________________

Method 8 : Get “.dll” file name which one makes conflicting.

If your issue has not fixed yet by following above method, that means must a “.dll” file which have making conflicting with iexplore.exe. we have to find that “.dll” file name with the help of system logs. please follow below steps.
  • Right click on MyComputer and then click on Manage. You’ll get an another window.
  • Click on allow of the “Event Viewer” (Expand it).
  • Click on allow of the “Windows Logs” (Expand it).
  • Click on “Application” under windows Logs.
  • Now look on the right side pane, it have listed all the system LOGS.
  • Now scroll down and find a error(Red Cross Error) related to iexplore.exe, anddouble click on it get the details (that log was created when you get error message on internet Explorer, so please find by the “Time”).
  • Now you have the Error Message details. Find the name of “.dll” on that detail.
  • Now you have the particular “.dll” file name which one is doing conflicting with iexplore.exe. Now Stop the conflicting via repair, rename, delete that file. you have to do research on it, what to do with that file (I can’t help you any more, because I don’t know “.dll” file name), so please do it carefully.
eventlogs

Monday, June 9, 2014

Jenkins for Selenium !

  • Jenkins is an open source continuous integration tool written in Java
  • Jenkins was originally developed as the Hudson project. Hudson's creation started in summer of 2004 at Sun Microsystems. It was first released in java.net in Feb. 2005.
                                                       Know more about Jenkins
What is the use of Jenkins in Selenium
  • Using Jenkins we can create build (Build - set of Testcase combined together) and we can run easily using batch file or Git or build.xml or SVN etc
  • Jenkins- can schedule the build periodically 
         for Example- You want to run 100 Testcase daily at 10 pm
  • Email-Notification- Jenkins provide notification mails too once build passed or failed to respective recipients (Depends of configuration)
 Lets have a look How Jenkins works

1- Download Jenkins - refer the below url

    Download Jenkins

2- Configure Jenkins for Running Build - Refer the below url

    Configure Jenkins

3- Finally run build using Jenkins

     Testcase running through Jenkins

Wednesday, April 2, 2014

Get random string, email string and number in Protractor JS !

Get random string, email string and number in Protractor JS.

/**
* Usage: Return Random Email Id.
*/
exports.getRandomEmail = function () {
    var strValues = "abcdefghijk123456789";
    var strEmail = "";
    for (var i = 0; i < strValues.length; i++) {
        strEmail = strEmail + strValues.charAt(Math.round(strValues.length * Math.random()));
    }
    return strEmail + "@mymail.test";
};

/**
* Usage: Generate random string.
* characterLength :  Length of string.
* Returns : Random string.
*/
exports.getRandomString = function (characterLength) {
    var randomText = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < characterLength; i++)
        randomText += possible.charAt(Math.floor(Math.random() * possible.length));
    return randomText;
};

/**
* Usage: Generate random number.
* characterLength :  Length of number.
* Returns : Random number.
*/
exports.getRandomNumber = function (numberLength) {
    var randomNumber = "";
    var possible = "0123456789";
    for (var i = 0; i < numberLength; i++)
        randomNumber += possible.charAt(Math.floor(Math.random() * possible.length));
    return randomNumber;
};

Select Dropdown Value in Protractor JS !

Select value from drop down in Protractor JS using Index, Text and Random Text.

/**
* Usage: selectDropdownByNumber ( element, index)
* element : select element
* index : index in the dropdown, 1 base.
*/
exports.selectDropdownByNumber = function (element, index, milliseconds) {
    element.findElements(by.tagName('option'))
        .then(function (options) {
            options[index].click();
        });
    if (typeof milliseconds != 'undefined') {
        browser.sleep(milliseconds);
    }
};


/**
* Usage: selectDropdownByText (selector, item)
* selector : select element
* item : option(s) in the dropdown.
*/
exports.selectDropdownByText = function selectOption(element, item, milliseconds) {
    var desiredOption;
    element.findElements(by.tagName('option'))
    .then(function findMatchingOption(options) {
        options.some(function (option) {
            option.getText().then(function doesOptionMatch(text) {
                if (text.indexOf(item) != -1) {
                    desiredOption = option;
                    return true;
                }
            });
        });
    })
    .then(function clickOption() {
        if (desiredOption) {
            desiredOption.click();
        }
    });
    if (typeof milliseconds != 'undefined') {
        browser.sleep(milliseconds);
    }
};

/**
* Usage: selectRandomDropdownReturnText ( element, milliseconds)
* element : select random element
* index : wait time to select value for drop down.
*/
exports.selectRandomDropdownReturnText = function (element, milliseconds) {
    return element.findElements(by.tagName('option')).then(function (options) {
        var randomNumber = Math.floor((Math.random() * options.length
        ));
        options[randomNumber].click();
        return options[randomNumber].getText().then(function (text) {
            return text;
        })
    })
    if (typeof milliseconds != 'undefined') {
        browser.sleep(milliseconds);
    }
};

WebDriver Wait Commands !

Wait commands in WebDriver

Listing out the different WebDriver Wait statements that can be useful for an effective scripting and can avoid using the Thread.sleep() comamnds
After few searches and digging into the WebDriver Java doc, I managed to design a mindmap of the different WebDriver commands available



WebDriver.manage().timeouts()

implicitlyWait

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement =
driver.findElement(By.id("myDynamicElement"));


The Implicit Wait will tell the webDriver to poll the DOM for certain duration when trying to find the element, this will be useful when certain elements on the webpage will not be available immediately and needs some time to load.
By default it will take the value to 0, for the life of the WebDriver object instance throughout the test script.

pageLoadTimeout

driver.manage().timeouts().pageLoadTimeout(100, SECONDS);

Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.

setScriptTimeout


driver.manage().timeouts().setScriptTimeout(100, SECONDS);

Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.
Support.ui
FluentWait
   // Waiting 30 seconds for an element to be present on the page, checking
   // for its presence once every 5 seconds.
   Wait wait = new FluentWait(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

   WebElement foo = wait.until(new Function() {
     public WebElement apply(WebDriver driver) {
       return driver.findElement(By.id("foo"));
     }
   });


Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.

ExpectedConditions
 
WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(>someid>)));

Models a condition that might reasonably be expected to eventually evaluate to something that is neither null nor false.
Examples : Would include determining if a web page has loaded or that an element is visible.
Note that it is expected that ExpectedConditions are idempotent. They will be called in a loop by the WebDriverWait and any modification of the state of the application under test may have unexpected side-effects.
WebDriverWait will be used as we used in the Expected conditions code snippet as above.
Sleeper is something same as the Thread.sleep() method, but this with an Abstraction around the thread.sleep() for better testability.

AngularJS Wait for element to come into view !

Wait for element in protrator JS.

helper.js

/**
* Usage: wait(element, label)
* element : It will wait for this element to come into view
* label : just used for the error message
*/
exports.wait = function (element, label) {
    browser.wait(function () {
        return element.isPresent().then(function (state) {
            if (state == true) {
                return element.isDisplayed().then(function (state2) {
                    return state2 == true;
                });
            } else {
                return false;
            }
        });
    }, 10000, label + " did not appear");
    browser.sleep(250);
};


Call This Function

Test.js

this.bookContextMenuIcon = $('.context-info-icon');

helper.wait(this.bookContextMenuIcon, "book context menu icon");