Auto Scale Selenium Hub with Zalenium

Selenium-Hub Autoscale Issue —

  • – Selenium Grid is resource consuming & Not container based.
  • – Running multiple test creates issue with scaling or increased Test Cases.
  • – Can’t auto scale.
  • – Scaling with docker alone with cloud testing provider.

Zalenium : –
A flexible and scalable container based Selenium Grid with video recording, live preview, basic auth & dashboard.

3,148 total views, 3 views today

 

Step by Step Selenium With Python – Part 1

In this series, We going to learn about the create a Test Suite in the Python. Let’s not waste much of the time lets start as quickly as possible.


Things you know before.

1. Selenium – Testing Framework
2. Python – Basic Python Syntax. – Please install it before proceeding.
3. Brain 😛

About Selenium :

Running selenium server

If you have no clue what is selenium is,Read about Selenium in my other tutorials or you can have a look here for the more http://www.seleniumhq.org, Just for the quick reference, Selenium is Automation framework written in the java that allows you to automate the web application with the different languages support e.g Python,Javascript, Java, Ruby.You can write functional/acceptance tests using Selenium WebDriver.

 

Installing Python bindings for Selenium

Running selenium serverGo to Command prompt or Terminal in the Mac and Type.
Make sure pip is installed on your system.(If not you can install it using this link here)

It will install the python binding for the selenium  to your system.

Step 1 : Running Selenium Server and Install Python Selenium bindings

Let’s run the Selenium Server that listens to our command/Test cases written python and execute them in the browser. Make sure java is installed on your system and its available in the path. If not follow this tutorial. And set up to path here
Download – Selenium server here.

You will see something like this on the command line.

Running selenium server

Selenium Server is up and Running.

Step 2 : Creating a Basic Test in the Selenium with Python and Run it.

Create a File in the Pycharm ( Python Editor) e.g I have made a Folder structure for the upcoming  tutorials also. So This part is Part 1 and I have one file HelloWorld.py that will have the code for the First Test case in python.

In the File, we are going

1. Import the selenium web driver.
2. Create a driver object from FirefoxDriver Class and Open the Borwser.
3. Use get method to go to the URL.
4. Assert the title and Close the Brower.

Run the Test by

File run using python:

Python test running using Pycharm

Python test running using Pycharm

So we have successfully run our first Test, Let’s move to the other Tutorial in the Next Part2.
Hope to see you guys in the next part.

 

Using Appium with Python : Introduction

In this series of blogs, I will discuss about the appium (test automation framework  for mobile apps). We will discuss about how you can
automate your android mobile apps and save your testing hours. I will cover appium with python client and for android only.

Appium is an open source test automation framework for use with native, hybrid and mobile web apps.It drives iOS and Android apps using the WebDriver protocol.

Here is the basic architecture of Appium , How it interact with Android / ios client.

System Installation


Requirements

On Windows Appium Installation :
Please install these basic requirements that are import run Python client in Appium.
  1. PyCharm( python editor)
  2. Appium.exe
  3. Python 2.7 or 3.0 (Pip configured)
  4. Python client Appium
  5. Android SDK install latest(Added to Path).
  6. Java – Added to Path(Optional)
  7. Selenium module of python
  8. unittest /nose module of python.

Make sure you set up environment variables correctly before executing any script. All these variables should be set under ‘System variables’ not in ‘User variables’.

  • JAVA_HOME
  • C:\Program Files\Java\jdk1.8.0_25
  • ANDROID_HOME
  • D:\Android_Development\android_sd
  • PATH variable (this contain System32 , platform-tools , tools ,jdk bin set) –
    • C:\Windows\System32;D:\Android_Development\android_sdk\platform-tools;%JAVA_HOME%\bin;D:\Android_Development\android_sdk\tools;

Installing Selenium and Python Appium client.

Make sure you have pip install on windows(Check out my other post how you can do this).

Now you are ready to write your first Test case using python client in Appium. In the next blog We will write a basic test program that open a  App and Do certain task and close it after. Please comment down if you face any issue or need help.

 

Selenium TestCases with Holmium in Python

Holmium core is nose plugin that provides utilities for simplifying the creation and maintenance of tests that rely on Selenium. Holmium introduce concept of Page Objects reduces the coupling and allow test authors to separate the layout of the page under test and the functional behaviour being tested.This separation also results in more maintainable test code.

Installation of the Holmium:
Assuming you have Nose module installed on the Machine. If not check out my Nose installation post.

[code]pip install holmium.core[/code]

Importing Holmium in Project:
First you have to Import the the TestCase, Page , Element and Locators.

[python]from holmium.core import TestCase, Page, Element, Locators, ElementMap
import unittest[/python]

Adding Test Cases:
Lets add Login Test Cases into the project with the Login functionality. Create a class LoginPage ( A Page object class) with inherit the Page of the Holmium.core and will be used to get the elements on the that page and sending keys to them.

[python]class LoginPage(Page):
userNameText = Element(Locators.NAME, ‘userName’)
passwordText = Element(Locators.NAME, ‘password’)
submitButton = Element(Locators.NAME, ‘login’)</pre>
def login(self):
self.userNameText.send_keys("techdutta")
self.passwordText.send_keys("test123")
self.submitButton.submit()[/python]

Lets add another class LoginTest which inherit the Test Case from the Holmium.core and only be used to assert the desired functionality.

[python]class LoginTest(TestCase):
def setUp(self):
self.page = LoginPage(self.driver,
"http://demoaut.com/")

def test_Login(self):
self.page.login()
self.assertEqual(self.driver.title,
"Find a Flight: Mercury Tours:")

def tearDown(self):
self.driver.close()[/python]

Running the Code with the nose:

Final code with Running Test results.

Source Code Here.

 

How to Handle Alerts & Select with Selenium in Python

While Testing web application, We generally encounter Alert box , Select drop downs. Lets see How we can handle them with selenium web driver in python.Generally JavaScript popups are generated by web application and hence they can be easily controlled by the browser.

Case1: Handling the Alert/Pops:

Create a Selenium Project and in the test Method write the below code to handle the Alert box/Pop. Just get the element using the
”find element by xpath method” and use

[python]
alertObj = driver.switch_to.alert
alertObj.accept()
# To dismiss
alertObj.dismiss()
[/python]


Case2: Handling the (Select)DropDown:

Create a Selenium Project and in the test Method write the below code to handle the select dropdown. Just get the element using the
”find element by xpath or id method” and use

[python]

def test_waitForCheckOutPhotosButton(self):
dropDownId= "wsite-com-product-option-Quantity"
dropDownElement = WebDriverWait(driver, 10).
until(lambda driver : driver.find_element_by_id(dropDownId))
Select(dropDownElement).select_by_value("2")”
[/python]

Case3: Handling the Window Frame:

Lets assume that, When you click on button1(id=’button1’) on the main window a new window pop opens and you have switch to that window and click the button(id=’window1_button2’) on it.

[python]

def test_waitForCheckOutPhotosButton(self):
button1 = WebDriverWait(driver,10)
.until(lambda driver: driver.find_element_by_id("button1"))

#Getting the Main Window Handle
mainHanlde = driver.window_handles

button1.click()

#Getting all windows Main and Window 1 handle in All Handle
allHandle = driver.window_handles

for c in allHandle:
if c !=mainHanlde[0]:
driver.switch_to_window(c)
break

button2= button1 = WebDriverWait(driver,10)
.until(lambda driver: driver.find_element_by_id("window1_button2"))
[/python]

We will learn about how to use Action chain with Selenium in Python.

 

Selenium Test case using Data Driven Testing in Python

In data-driven testing approach, we can use a single test to verify different sets of test cases or test data by driving the test with input and expected values from an external data source instead of using the hard coded values every time a test is run. Its very useful when we have similar tests that consist of the same steps but differ in the input data and expected value or the application state.

We need to install DDT in python to work with Data driven Testing

Installing ddt
We can download and install ddt using the following command line:

[code]
pip install ddt[/code]

Assuming that you have unittest,selenium and nose installed. If not go here.

Steps to Create the DDT using unittest , nose with external data sources(Excel):
1.  Use the @ddt decorator for the test class.
2.  Use the @data decorator on the data-driven test methods.
3.  Use the @unpack decorator, which unpacks tuples or lists into multiple arguments.

Project Structure:

Importing ddt in the  test

[code]
from ddt import ddt, data, unpack[/code]

Lets write code for the Searching a Text on the “http://demo.magentocommerce.com” site and getting expected results. I have written a search test, which accepts a pair of arguments for different search value and expected value.

[python]

from selenium import webdriver
import unittest
import nose
from ddt import ddt, data, unpack
import xlrd

def getData(fileName):
     myrows = []
     book = xlrd.open_workbook(fileName)
     sheet = book.sheet_by_index(0)
     for row_index in range(1, sheet.nrows):
         myrows.append(list(sheet.row_values(row_index, 0, sheet.ncols)))
     return myrows

@ddt
class SearchResultDDT(unittest.TestCase):
     @classmethod
     def setUpClass(cls):
         cls.driver = webdriver.Firefox()
         cls.driver.implicitly_wait(10)
         cls.driver.maximize_window()

    @data(*getData("TestData.xlsx"))
     @unpack
     def test_SearchResults(self, search_values, expected_value):
         self.driver.get("<a href="http://demo.magentocommerce.com/%22)">http://demo.magentocommerce.com/")</a>
         self.search_field = self.driver.find_element_by_name("q")
         self.search_field.clear()
         self.search_field.send_keys(search_values)
         self.search_field.submit()
         products = self.driver.find_elements_by_xpath("//h2[@class=’product-name’]/a")
         if expected_value > 0:
             self.assertEqual(expected_value, len(products))
         else:
             msg = self.driver.find_element_by_class_name("note-msg")
             self.assertEqual("Your search returns no results.", msg.text)

@classmethod
def tearDownClass(cls):
     cls.driver.quit()

if __name__=="__main__":
     nose.main()

[/python]

Running the test case with Nose

DDT will generate new test methods giving them meaningful names by converting the data values to valid Python identifier.
Final Code Here

 

The Ultimate Cheat Sheet on XPath in Python

XPath aka XML path language defined by W3C is used to traverse through the elements in the XML document.
Its like a query language to search element(nodes) by a variety of criteria in XML document.

XPath is widely used by Testers in Selenium framework with Python to find the elements in the HTML document.

Lets see  what all the things we can do with XPath to find elements in a HTML document.In the below table, I have added column Type, Searched Element with thier respective XPath at the end. Assuming the “x” is the tag. e.g <input name=”text value” />, So x=input and A=name.

 

Type Search for Web Element XPath
Tag Web Element <x> by relative reference //x
Web Element <x> with attribute A value ‘t’ //x[@A=’t’]
Web Element <x> with attribute A containing text ‘t’ //x[contains(@A, ‘t’)]
Web Element <x> whose attribute A begins with ‘t’ //x[starts=with(@A, ‘t’)]
Web Element <x> whose attribute A ends with ‘t’ //x[ends—with(@A, ‘t’)]
Web Element <x> with attribute A containing exactly text ‘t’ and attribute B containing exactly text ‘v’ //x[contains(@A, ‘t’) and contains(@B,‘v’)]

In the above Image
I have used //x[@A=’t’] as //input[@name=’firstName’] as XPath.You can try above mentioned XPath in the Firefox with FirePath’s console installed. Now, lets see how we can implement this Web Element XPath’s in Selenium test case with Python to enter the value in it(input text box).

[python]
__author__ = ‘WP8Dev’
import unittest
from selenium import webdriver

class SearchTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.driver = webdriver.Firefox()
cls.driver.implicitly_wait(20)
cls.driver.maximize_window()
cls.driver.get("http://demoaut.com/mercuryregister.php")

def test_1(self):
self.driver.find_element_by_xpath("//input[@name=’firstName’]").send_keys("Pramod")
self.assertTrue(self.driver.find_element_by_xpath("//input[@name=’firstName’]").is_displayed())

@classmethod
def tearDownClass(cls):
cls.driver.quit()

if __name__ == "__main__":
unittest.main(verbosity=2)

[/python]

 

ID & Name

Web Element <E> with id ‘I’,
All Web Elements with id ‘I’
Web Element <X> with name‘N’
All Web Elements with name‘N’
All Web Elements with id ‘I’ or name ‘N’
//X[@id=’I’]
//*[@id=’I’]
//X[@name=’N’]
//*[@name=’N’]
//*[@id=’I’ or @name=’N’]

Class

Web Element <X> with a class C

//X[@class=’C’]

Text

All Elements with text ‘t’ exactly

//*[.=’t’]

Child or subChild

Element <F> which is a child or a subchild of Element <X>

//X//F

 

Ref. : Gabiste Akoua thanks for being my mentor

Let me know your thoughts regarding post by commenting below.

 

Selenium Test Cases in Java with TestNG

TestNG is next generation testing framework like JUnit & NUnit but with extra features(Read keywords, Generate Test Reports, Generate logs) and easy to use. TestNG framework can cover different type of the tests like Integration, Unit, end-to-end, etc.

  Installing TestNG in Eclispe:

  • Open Eclipse , Select Help / Software updates / Find and Install.
  • Search for new features to install.
  • New remote site.
  • For Eclipse 3.4 and above, enter http://beust.com/eclipse.
  • For Eclipse 3.3 and below, enter http://beust.com/eclipse1.
  • Make sure the check box next to URL is checked and click Next.
  • Eclipse will then guide you through the process.

We are going to Test a Demo website “http://demoaut.com/mercuryregister.php” and will write a Test case
to Do a Registration in it.

Project Structure:

Step1:
Create a project in the eclispe. Add the Selenium StandAlone jar and TestNG jar into a new libs  folder.
Make sure you add them to Build Path by Right Click – Build Path –> Add to Build Path.

Step2:
Create a Base Class with Test Fixture methods e.g. Setup and Tear Down. Note: I have added function name
as JUnit you can name them as you want), Add annotations as Before Method and After Method.

[java]
package com.scrolltest.testng;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

public class BaseClass {

WebDriver driver;

@BeforeMethod
public void setUp() {
driver = new FirefoxDriver();

}

@AfterMethod
public void tearDown() {
// driver.close();
driver.quit();
}

}
[/java]

Step3 :
Create a Separate Class with Name Registration .java to write a Test case for Registration of the
Demo: Website http://demoaut.com/mercuryregister.php

[java]
package com.scrolltest.testng;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import org.testng.Reporter;

public class RegisterationPageObect {

private WebDriver driver;

public RegisterationPageObect(WebDriver driver) {
this.driver = driver;
}

public void RegisterUser() {
driver.findElement(By.name("firstName")).sendKeys("Pramod");
driver.findElement(By.name("lastName")).sendKeys("Dutta");
driver.findElement(By.name("phone")).sendKeys("981457452");
WebElement t = driver.findElement(By.id("userName"));

driver.findElement(By.id("userName")).sendKeys("a@c.com");
Reporter.log(""+t.getAttribute("maxlength"));
// #Drop Down
new Select(driver.findElement(By.name("country")))
.selectByVisibleText("ANGUILLA");
// register
driver.findElement(By.name("register")).click();
}

}[/java]

Step4: Now Lets create a Final class and TestNG xml file.

MainClass.java

[java]
package com.scrolltest.testng;

import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class MainClass extends BaseClass {

@Test
public void testRegisterationInDemoAUT() throws InterruptedException {

RegistrationPageObect pageOject = new RegistrationPageObect(driver);
driver.get("http://demoaut.com/mercuryregister.php");
pageOject.RegisterUser();

assert driver
.findElement(By.tagName("body"))
.getText()
.contains(
"Thank you for registering. You may now sign-in using the user name and password you’ve just entered.");

assert driver.findElement(By.tagName("body")).getText()
.contains("Dear Pramod Dutta,");

}

}
[/java]

Step5:
Now Run the Test by Creating new TestNG configuration by Clicking on the Project->Run Configuration, Select
the TestSuite and browse the XML file(testng.xml). and Now Run the Project.

Step6:
After run successfully, If you refresh you project you will see the test-output folder , Open “index.html” and see that You Test Suite Results. Click on the Report output link you can see max length also.(Used as Logging)

Source code Github