Powered By Blogger

Search Here!

Tuesday, August 4, 2015

Change The Download Path For IE using C# !

We can change the download path in IE which helps to verify the download file using Webdriver in IE.

RegistryKey rKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main", true);
            if (rKey != null)

              rKey.SetValue("Default Download Directory", @"E:\E$", RegistryValueKind.String);

For disabling Download Prompt, we can use ESC key by Selenium or change IE settings using RegEdit.

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

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