Search

Just Another Tech Blog

A mind is like a parachute. It doesn't work if it is not open.

Category

Automation

How To Add Host Entry In Android Virtual Device (AVD)


Pre-requirements:

  1. You need to have installed Android SDK and an Android Virtual Device (AVD)
  2. I did this on Ubuntu 16.04 LTS, it should work for other OS as well but I did not tested

Go for the action:

  1. We are assuming you have android installed in ~/Android location
  2. We are assuming you have an AVD named Nexus-4-API-22

Open a terminal and run the following command:

cd ~/Android/Sdk/tools && ./emulator -avd Nexus-4-API-22
cd ~/Android/Sdk/tools
emulator -avd Nexus-4-API-22 -partition-size 2048 -writable-system

Open another terminal and type the following commands one by one:

It will run the AVD

cd ~/Android/Sdk/platform-tools/
adb devices

If this shows any error run again, it should show the output as below:

abqu@dhaabquubu:~/Android/Sdk/platform-tools$ adb devices
abqu@dhaabquubu:~/Android/Sdk/platform-tools$ adb devicesadb: /home/abqu/.linuxbrew/lib/libcrypto.so.1.0.0: no version information available (required by adb)
List of devices attached 
emulator-5554 device

Now note the device name, here the device name is emulator-5554

adb root
adb -s emulator-5554 remount
adb -s emulator-5554 pull /system/etc/hosts hosts
ll

Here, the hosts file should appear in the file list.
Now, open the hosts file in a text editor and add the host entry into the file the save the hosts file.

sublime-text hosts

After editing the hosts file run the below command:

adb -s emulator-5554 push hosts /system/etc/hosts
adb reboot

It will reboot the AVD and we should now be able to browse your website in AVD with host entry.

Happy testing!!!

 

 

Advertisements

Mobile Automation With Appium, Robot Framework and Android SDK in Ubuntu


Automation becomes an essential part of software testing. For the frequent changes/updates in any software it is necessary to have an fully automated process to test the software to ensure it’s functionalities are working properly. Robot Framework is one of the most handy choice for a well structured automation process of any kind of software or web-application. Mostly, because of it’s built in keywords and reporting features. It’s also highly customizable.

On the other hand, in the era of smart phones and tabs the mobile phone users are increasing dramatically. Therefore, the developers and QA’s need to focus on mobile phone support and testing. So, mobile automation is becoming more important unlike desktop automation. So. here’s the start up article about how can initiate mobile automation.

As the title says we are going to use Robot framework for writing automation scripts and Appium as the server to communicate with the mobile devices. For this tutorial I have used Android virtual Device (AVD) which comes with Android SDK. You can also use real devices as well by making some very minor changes. We have Ubuntu 16.04 LTS for our test environment. You can also setup the test environment on any Windows or MAC OS as well.

Step 1: Installing dependencies

Install Java JDK:

For installing Java JDK there is good instructions in the oracle site, besides that, there are  numbers of tutorial you will find in google search. Here’s what I did to install,

Please note: The JDK version may vary time to time so this might not always right steps for you.

sudo add-apt-repository ppa:webupd8team/java

sudo apt-get update

sudo apt-get install oracle-java8-installer

sudo update-alternatives --config java

The output will look something like the following. In this case, this is what the output will look like with all Java versions mentioned above installed.

Output:
There are 5 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      auto mode
  1            /usr/lib/jvm/java-6-oracle/jre/bin/java          1         manual mode
  2            /usr/lib/jvm/java-7-oracle/jre/bin/java          2         manual mode
  3            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode
  4            /usr/lib/jvm/java-8-oracle/jre/bin/java          3         manual mode
  5            /usr/lib/jvm/java-9-oracle/bin/java              4         manual mode

Press <enter> to keep the current choice[*], or type selection number:

You can now choose the number to use as a default.

Now verify Java installation:

abqu@dhaabquubu:~$ java -version
openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-2ubuntu1.16.04.3-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Set JAVA_HOME:

For setting JAVA_HOME open your ~/.bashrc file in any text editor and add the following 2 lines at the end of the file:

nano ~/.bashrc

Add these 2 lines:

Please note: your JAVA_HOME path should be exactly as the output for the sudo update-alternatives –config java command

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
export PATH=${JAVA_HOME}/bin:$PATH

Install Selenium:

Please follow this post for the Selenium installation tutorial: How to Install Python, PIP, Selenium, Chrome and Firefox Driver

Install Robot Framework:

Please follow this post for the Robot Framework installation tutorial: Python Robot Framework Install

Install Robot framework Appium library:

pip install robotframework-appiumlibrary --user

Install Sublime-text-2 editor (Optional):

sudo add-apt-repository ppa:webupd8team/sublime-text-2
sudo apt-get update
sudo apt-get install sublime-text

Install homebrew (for linux):

Please follow this post for homebrew installation tutorial: Install Homebrew In Ubuntu 16.04

Install Nodejs (NOT AS ROOT USER), Appium, WD and appium-doctor:

brew update
brew install node
brew link node
npm install -g appium
npm install wd
npm install -g appium-doctor

Now, run appium command to check the appium server is running properly:

abqu@dhaabquubu:~$ appium
[Appium] Welcome to Appium v1.7.1 (REV ce9a10fa47b486859e53c0991c0672c0c2aa8bba)
[Appium] Appium REST http interface listener started on 0.0.0.0:4723

Also, run appium-doctor command to check the missing configuration:

abqu@dhaabquubu:~$ appium-doctor
info AppiumDoctor Appium Doctor v.1.4.3
info AppiumDoctor ### Diagnostic starting ###
info AppiumDoctor ✔ The Node.js binary was found at: /home/abqu/.linuxbrew/bin/node
info AppiumDoctor ✔ Node version is 8.7.0
info AppiumDoctor ✔ ANDROID_HOME is set to: /home/abqu/Android/Sdk
info AppiumDoctor ✔ JAVA_HOME is set to: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
info AppiumDoctor ✔ adb exists at: /home/abqu/Android/Sdk/platform-tools/adb
info AppiumDoctor ✔ android exists at: /home/abqu/Android/Sdk/tools/android
info AppiumDoctor ✔ emulator exists at: /home/abqu/Android/Sdk/tools/emulator
info AppiumDoctor ✔ Bin directory of $JAVA_HOME is set
info AppiumDoctor ### Diagnostic completed, no fix needed. ###
info AppiumDoctor 
info AppiumDoctor Everything looks good, bye!
info AppiumDoctor

Please note: At this point you may find some ‘x’ sign in the appium-doctor output, it should all be ✔ at the end of this tutorial.

Install Android SDK:

sudo add-apt-repository ppa:maarten-fonville/android-studio

sudo apt update

sudo apt install android-studio

During the installation, the latest Android Studio zip file will be downloaded from Google server. Once the installation is finished, you can open Android Studio from Unity Dash or your preferred app launcher.

android-studio-ubuntu

If the icon didn’t load, then please log out and log back in or use the following command to start Android Studio.

/opt/android-studio/bin/studio.sh

Select whether you want to import previous Android Studio settings or not, then click OK.

ubuntu-android-studio

Then follow the setup wizard. You will prompted to install Android SDK Tools, Android platform tools, Android support library, etc.

android-studio-ubuntu-16.04

Set ANDROID_HOME:

Unlike setting up JAVA_HOME, open the ~/.bashrc file and add the following 2 lines at the bottom of the file then save the file:

export ANDROID_HOME=/home/abqu/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Create Android Virtual Device(AVD)/Emulator:

Please Note: I recommend to use the same device and system image version to use for the first time which has been show in this tutorial. If you use some other device or system image version then you need to change the open application string accordingly in the demo.txt robot script which has been used at the end of this tutorial. Therefore, I suggest, when you gain enough knowledge about appium then you can go for any device and system image.

For creating an AVD open the Android studio, then click on the AVD Manager button.

Selection_043

The AVD manager window will open. Now, follow next button and choose your desire android device and OS version.

Selection_044

Please note: At the very first time the device list will be empty, so click Create Virtual Device… button

First you need to choose a device, here in this tutorial I used Nexus 4.

Selection_045

Now, you need to download the system image/OS, if there is no system image in the Recommended tab then click other two tabs and download them. It will take time to download the system image, so keep patient.

Selection_046

Then follow the Next button and complete the AVD creation.

See the list of AVDs:

Go to ~/Android/Sdk/emulators and run the following commands:

abqu@dhaabquubu:~/Android/Sdk/emulator$ emulator -list-avds
Nexus-4-API-22
Nexus-5X-API-25

The list of AVDs will appear.

The name of the AVDs are very important, so, keep it.

Run the AVDs:

Now run the AVD using following command:

cd ~/Android/Sdk/tools && ./emulator -avd Nexus-4-API-22

Note: Here, you need to replace the Nexus-4-API-22 part with your AVD name.

Install Python six package:

pip install six --user

Run the appium server using appium command.

Now run the appium-doctor command again to check if everything is good.

The output should be like below:

abqu@dhaabquubu:~$ appium-doctor
info AppiumDoctor Appium Doctor v.1.4.3
info AppiumDoctor ### Diagnostic starting ###
info AppiumDoctor ✔ The Node.js binary was found at: /home/abqu/.linuxbrew/bin/node
info AppiumDoctor ✔ Node version is 8.7.0
info AppiumDoctor ✔ ANDROID_HOME is set to: /home/abqu/Android/Sdk
info AppiumDoctor ✔ JAVA_HOME is set to: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
info AppiumDoctor ✔ adb exists at: /home/abqu/Android/Sdk/platform-tools/adb
info AppiumDoctor ✔ android exists at: /home/abqu/Android/Sdk/tools/android
info AppiumDoctor ✔ emulator exists at: /home/abqu/Android/Sdk/tools/emulator
info AppiumDoctor ✔ Bin directory of $JAVA_HOME is set
info AppiumDoctor ### Diagnostic completed, no fix needed. ###
info AppiumDoctor 
info AppiumDoctor Everything looks good, bye!
info AppiumDoctor

 

Write Robot scripts and run:

Now, all set up so you can write the automation scripts and run it.

Here is a demo robot file for testing:

*** Settings ***

Library AppiumLibrary

Documentation demo for appium library

Force Tags demo


*** Test Cases ***

test_demo

[Tags] regression

Open Application http://localhost:4723/wd/hub platformName=Android platformVersion=5.1.1 deviceName=Nexus-4-API-22 app=com.android.browser browserName=Browser

Go To Url http://facebook.com
 Wait Until Page Contains Element xpath=//input[@type='email']
 Input Text xpath=//input[@type='email'] test@gmail.com
 Sleep 5

For testing you can save the above code into a file called demo.txt and make it executable then run it from terminal using pybot demo.txt command:

chmod +x demo.txt

pybot demo.txt

Note: You must have the AVD and Appium server running before executing the pybot demo.txt command.

You will see the script will create a browser instance and open the Facebook login page then in the email field it will input ‘test@gmail.com’ email.

If everything goes well you should see the following output in the terminal:

abqu@dhaabquubu:~/Documents/appium-rnd$ pybot demo3.txt 
==============================================================================
Demo3 :: demo for appium library 
==============================================================================
test_demo | PASS |
------------------------------------------------------------------------------
Demo3 :: demo for appium library | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
Output: /home/abqu/Documents/appium-rnd/output.xml
Log: /home/abqu/Documents/appium-rnd/log.html
Report: /home/abqu/Documents/appium-rnd/report.html

That’s it!! Happy testing!!!

Create Current Date Time Stamp in Robot Framework


Background:

Recently I had to write some automation test scripts where I needed to create a date time stamps and use those to schedule a test content to be published and unpublished. For this purpose I created a keyword which will generate the desired date time stamp and enter the value to the date and time field. Therefore, this example might not be very useful for a generic purpose, however if someone need this type of date time stamp for scheduling something it might be little helpful.

The Test Scenario:

The basic test scenario was like, there was 2 sections called Publish-on and Un-publish-on in a content creation page, and both sections have 2 separate fields called date and time.

Selection_002

So, here what needed to do the following 2 steps:

  1. get the current date and paste it the Publish on date field.
  2. get the current time and add 2 minutes with it and paste it to the time field.

Then there was some additional test cases, like, save the content and check if the content properly published on the scheduled time.

After that I needed to do the same 2 steps for the Un-publish on fields.

The keyword I created for the achieving the above 2 steps are as below:

Enter Time Date To Scheduler [Arguments] ${field-label}

# THE ARGUMENTS ${FIELD-LEBEL} SHOULD BE EITHER "ACTIVATEDATEFIELD" OR "EXPIRYDATEFIELD"
 # HERE, "EXPIRYDATEFIELD" SHOULD BE USED FOR UN-PUBLISH FIELD AND "ACTIVATEDATEFIELD" SHOULD BE USED FOR PUBLISH FIELD.
 # IT WILL ONLY CREATE THE DATE TIME FORMAT AND ENTER INTO THE FIELD, USER NEED TO CLICK SAVE, SCHEDULE OR PUBLISH BUTTON ADDITIONALLY AFTER THIS KEYWORD.

Wait Until Page Contains Element xpath=//div[@field='vm.${field-label}']//input[@placeholder='No date']
 # GET THE CURRENT DATE AND TIME FROM THE SYSTEM AND RE-FORMAT FOR SCHEDULING A CONTENT
 ${date}= Get Current Date result_format=%m/%d/%Y

# SPECIAL CASE IS TO HANDLE WHEN THE MINUTE VALUE WILL EXCEED 60
 ${special_case}= Set Variable 0
 ${hour}= Get Current Date result_format=%H
 ${hour}= Convert To Integer ${hour}
 ${min}= Get Current Date result_format=%M
 ${min}= Convert To Integer ${min}
 ${new_min}= Evaluate ${min}+2

${min_special}= Evaluate ${new_min}-60
 ${special_case}= Set Variable if ${new_min}>=60
 ... 1 0

${new_min}= Set Variable if ${special_case}==1
 ... ${min_special} ${new_min}

${hour_special}= Evaluate ${hour}+1
 ${hour}= Set Variable if ${special_case}==1
 ... ${hour_special} ${hour}

${time}= Set Variable ${hour}:${new_min}

# ENTER THE FORMATTED DATE AND TIME
 Clear Element Text xpath=//div[@field='vm.${field-label}']//input[@placeholder='No date']
 Input Text xpath=//div[@field='vm.${field-label}']//input[@placeholder='No date'] ${date}
 Clear Element Text xpath=//div[@field='vm.${field-label}']//input[@placeholder='No time']
 Input Text xpath=//div[@field='vm.${field-label}']//input[@placeholder='No time'] ${time}

Here, I needed to converted the date-time to specific format which will support by the web app.

I hope the code is pretty self-explained. If you have any question or suggestions please fell free to comment.

How To Add Robot Framework Syntax in Sublime Text and VIM editor


By default, files for the Robot Framework do not show any syntax on Sublime Text or VIM, with some tweaks we can add Robot Framework syntax.

For Sublime Text 2:

Open Sublime Text 2 and click Preferences -> Browse Packages to open the packages directory. Then create a directory named Robot Framework containing the contents of the following repository:

https://github.com/seeamkhan/sublime-robot-plugin

Note: The contents of the repository should be directly under the Robot Framework directory.

Now close the Sublime Text 2 editor if it’s already been opened and then open a file with Robot Framework syntax, the syntax should be now visible like below:

Selection_012

For VIM Text Editor:

Clone the git repository in any place:

git clone https://github.com/seeamkhan/robotframework-vim

Go to the content directory:

cd robotframework-vim

Make sure the directory ~/.vim/ already exist for the current user, if not then create the directory:

mkdir ~/.vim

Now copy all the contents to ~/.vim/ location:

cp -R * ~/.vim/

Now open any files with Robot Framework syntax in the VIM editor, the syntax should be visible like below:

Selection_014

Prepare CentOS 6.x or 7.x Server for Selenium


We need to install the following things in the server to run the Python test scripts after WordPress auto update:

  1. Need to be installed Python 2.6.x or 2.7.x
  2. Install WP CLI, see detail: http://wp-cli.org/
  3. Install pip:For RHEL 6.x and CentOS 6.x (x86_64)
    rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

    For RHEL 6.x and CentOS 6.x (i386)

    rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

    Now install pip with yum command:

    yum install -y python-pip

    If you can not install pip be following the above steps then try the below steps:

    curl "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
    python get-pip.py
    
  4. Install Selenium:
    pip install selenium
    
  5. Install python-detenv:
    pip install python-dotenv
    
  6. Install python requests library:

    pip install requests
  7. Download Phantomjsfrom:http://phantomjs.org/download.html
  8. Copy Phantomjs to /usr/local/share/:
    cp -f phantomjs /usr/local/share/phantomjs

    Note: Keep the phantomjs nonexecutable while the wp-auto-update will run the script will make it executable and make it nonexecutable once it’s done.

  9. Make symlinks of Phantomjs:
    ln -s /usr/local/share/phantomjs /usr/local/bin/phantomjs
    ln -s /usr/local/share/phantomjs /usr/bin/phantomjs
    
  10. Install additional dependency for Phantomjs:
    yum install freetype
    yum install fontconfig

XPath in Selenium WebDriver: Complete Tutorial


In Selenium automation, if the elements are not found by the general locators like id, class, name, etc. then XPath is used to find an element on the web page .

In this tutorial, we will learn about the xpath and different XPath expression to find the complex or dynamic elements, whose attributes changes dynamically on refresh or any operations.

What is XPath

XPath is defined as XML path. It is a syntax or language for finding any element on the web page using XML path expression. XPath is used to find the location of any element on a webpage using HTML DOM structure. The basic format of XPath is explained below with screen shot.

XPath in Selenium WebDriver: Complete Tutorial

Syntax for XPath:

XPath contains the path of the element situated at the web page. Standard syntax for creating XPath is.

Xpath=//tagname[@attribute='value']
  • // : Select current node.
  • Tagname: Tagname of the particular node.
  • @: Select attribute.
  • Attribute: Attribute name of the node.
  • Value: Value of the attribute.

To find the element on web pages accurately there are different types of locators:

XPath Locators Find different elements on web page
ID To find the element by ID of the element
Classname To find the element by Classname of the element
Name To find the element by name of the element
Link text To find the element by text of the link
XPath XPath required for finding the dynamic element and traverse between various elements of the web page
CSS path CSS path also locates elements having no name, class or ID.

Types of X-path

There are two types of XPath:

1) Absolute XPath .

2) Relative XPath .

Absolute XPath :

It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.

The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.

Below is the example of an absolute xpath expression of the element shown in the below screen.

Absolute xpath:

html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[1]/b

XPath in Selenium WebDriver: Complete Tutorial

Relative xpath:

For Relative Xpath the path starts from the middle of the HTML DOM structure. It starts with the double forward slash (//), which means it can search the element anywhere at the webpage.

You can starts from the middle of the HTML DOM structure and no need to write long xpath.

Below is the example of a relative XPath expression of the same element shown in the below screen. This is the common format used to find element through a relative XPath.

Relative xpath: //*[@class='featured-box']//*[text()='Testing']

XPath in Selenium WebDriver: Complete Tutorial

What are XPath axes.

XPath axes search different nodes in XML document from current context node. XPath Axes are the methods used to find dynamic elements, which otherwise not possible by normal XPath method having no ID , Classname, Name, etc.

Axes methods are used to find those elements, which dynamically change on refresh or any other operations. There are few axes methods commonly used in Selenium Webdriver like child, parent, ancestor, sibling, preceding, self, etc.

Using XPath Handling complex & Dynamic elements in Selenium

1) Basic XPath:

XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, etc. from the XML document as illustrated below.

Xpath=//input[@name='uid']

Here is a link to access the page http://demo.guru99.com/v1/

XPath in Selenium WebDriver: Complete Tutorial

Some more basic xpath expressions:

Xpath=//input[@type='text']				
Xpath=	//label[@id='message23']
Xpath=	//input[@value='RESET']
Xpath=//*[@class='barone']
Xpath=//a[@href='http://demo.guru99.com/']
Xpath= //img[@src='//cdn.guru99.com/images/home/java.png']

2) Contains() : Contains() is a method used in XPath expression. It is used when the value of any attribute changes dynamically, for example, login information.

The contain feature has an ability to find the element with partial text as shown in below example.

In this example, we tried to identify the element by just using partial text value of the attribute. In the below XPath expression partial value ‘sub’ is used in place of submit button. It can be observed that the element is found successfully.

Complete value of ‘Type’ is ‘submit’ but using only partial value ‘sub’.

Xpath=//*[contains(@type,'sub')]

Complete value of ‘name’ is ‘btnLogin’ but using only partial value ‘btn’.

Xpath=.//*[contains(@name,'btn')]

In the above expression, we have taken the ‘name’ as an attribute and ‘btn’ as an partial value as shown in the below screenshot. This will find 2 elements (LOGIN & RESET) as their ‘name’ attribute begins with ‘btn’.

XPath in Selenium WebDriver: Complete Tutorial

Similarly, in the below expression, we have taken the ‘id’ as an attribute and ‘message’ as a partial value. This will find 2 elements (‘User-ID must not be blank’ & ‘Password must not be blank’) as its ‘name’ attribute begins with ‘message’.

Xpath=//*[contains(@id,'message')]

XPath in Selenium WebDriver: Complete Tutorial

In the below expression, we have taken the “text” of the link as an attribute and ‘here’ as a partial value as shown in the below screenshot. This will find the link (‘here’) as it displays the text ‘here’.

Xpath=//*[contains(text(),'here')]
Xpath=//*[contains(@href,'guru99.com')]

XPath in Selenium WebDriver: Complete Tutorial

3) Using OR & AND:

Note: For Google Chrome you need to use small letter ‘and’ and ‘or’.

In OR expression, two conditions are used, whether 1st condition OR 2nd condition should be true. It is also applicable if any one condition is true or maybe both. Means any one condition should be true to find the element.

In the below XPath expression, it identifies the elements whose single or both conditions are true.

Xpath=//*[@type='submit' or @name='btnReset']

Highlighting both elements as “LOGIN ” element having attribute ‘type’ and “RESET” element having attribute ‘name’.

XPath in Selenium WebDriver: Complete Tutorial

In AND expression, two conditions are used, both conditions should be true to find the element. It fails to find element if any one condition is false.

Xpath=//input[@type='submit' and @name='btnLogin']

In below expression, highlighting ‘LOGIN’ element as it having both attribute ‘type’ and ‘name’.

XPath in Selenium WebDriver: Complete Tutorial

4) Start-with function: Start-with function finds the element whose attribute value changes on refresh or any operation on the webpage. In this expression, match the starting text of the attribute is used to find the element whose attribute changes dynamically. You can also find the element whose attribute value is static (not changes).

For example -: Suppose the ID of particular element changes dynamically like:

Id=” message12″

Id=” message345″

Id=” message8769″

and so on.. but the initial text is same. In this case, we use Start-with expression.

In the below expression, there are two elements with an id starting “message”(i.e., ‘User-ID must not be blank’ & ‘Password must not be blank’). In below example, XPath finds those element whose ‘ID’ starting with ‘message’.

Xpath=//label[starts-with(@id,'message')]

XPath in Selenium WebDriver: Complete Tutorial

5) Text(): In this expression, with text function, we find the element with exact text match as shown below. In our case, we find the element with text “UserID”.

Xpath=//td[text()='UserID']

XPath in Selenium WebDriver: Complete Tutorial

6) XPath axes methods: These XPath axes methods are used to find the complex or dynamic elements. Below we will see some of these methods.

For illustrating these XPath axes method, we will use the Guru99 bank demo site.

a) Following: Selects all elements in the document of the current node( ) [ UserID input box is the current node] as shown in the below screen.

Xpath=//*[@type='text']//following::input

XPath in Selenium WebDriver: Complete Tutorial

There are 3 “input” nodes matching by using “following” axis- password, login and reset button. If you want to focus on any particular element then you can use the below XPath method:

Xpath=//*[@type='text']//following::input[1]

You can change the XPath according to the requirement by putting [1],[2]…………and so on.

With the input as ‘1’, the below screen shot finds the particular node that is ‘Password’ input box element.

XPath in Selenium WebDriver: Complete Tutorial

b) Ancestor: The ancestor axis selects all ancestors element (grandparent, parent, etc.) of the current node as shown in the below screen.

In the below expression, we are finding ancestors element of the current node(“ENTERPRISE TESTING” node).

Xpath=//*[text()='Enterprise Testing']//ancestor::div

XPath in Selenium WebDriver: Complete Tutorial

There are 13 “div” nodes matching by using “ancestor” axis. If you want to focus on any particular element then you can use the below XPath, where you change the number 1, 2 as per your requirement:

Xpath=//*[text()='Enterprise Testing']//ancestor::div[1]

You can change the XPath according to the requirement by putting [1], [2]…………and so on.

c) Child : Selects all children elements of the current node (Java) as shown in the below screen.

Xpath=//*[@id='java_technologies']/child::li

XPath in Selenium WebDriver: Complete Tutorial

There are 71 “li” nodes matching by using “child” axis. If you want to focus on any particular element then you can use the below xpath:

Xpath=//*[@id='java_technologies']/child::li[1]

You can change the xpath according to the requirement by putting [1],[2]…………and so on.

d) Preceding: Select all nodes that come before the current node as shown in the below screen.

In the below expression, it identifies all the input elements before “LOGIN” button that is Userid and password input element.

Xpath=//*[@type='submit']//preceding::input

XPath in Selenium WebDriver: Complete Tutorial

There are 2 “input” nodes matching by using “preceding” axis. If you want to focus on any particular element then you can use the below XPath:

Xpath=//*[@type='submit']//preceding::input[1]

You can change the xpath according to the requirement by putting [1],[2]…………and so on.

e) Following-sibling: Select the following siblings of the context node. Siblings are at the same level of the current node as shown in the below screen. It will find the element after the current node.

 xpath=//*[@type='submit']//following-sibling::input

XPath in Selenium WebDriver: Complete Tutorial

One input nodes matching by using “following-sibling” axis.

f) Parent: Selects the parent of the current node as shown in the below screen.

Xpath=//*[@id='rt-feature']//parent::div

XPath in Selenium WebDriver: Complete Tutorial

There are 65 “div” nodes matching by using “parent” axis. If you want to focus on any particular element then you can use the below XPath:

Xpath=//*[@id='rt-feature']//parent::div[1]

You can change the XPath according to the requirement by putting [1],[2]…………and so on.

g) Self: Selects the current node or ‘self’ means it indicates the node itself as shown in the below screen.

XPath in Selenium WebDriver: Complete Tutorial

One node matching by using “self ” axis. It always finds only one node as it represents self-element.

Xpath =//*[@type='password']//self::input

h) Descendant: Selects the descendants of the current node as shown in the below screen.

In the below expression, it identifies all the element descendants to current element ( ‘Main body surround’ frame element) which means down under the node (child node , grandchild node, etc.).

Xpath=//*[@id='rt-feature']//descendant::a

XPath in Selenium WebDriver: Complete Tutorial

There are 12 “link” nodes matching by using “descendant” axis. If you want to focus on any particular element then you can use the below XPath:

Xpath=//*[@id='rt-feature']//descendant::a[1]

You can change the XPath according to the requirement by putting [1],[2]…………and so on.

Summary:

XPath is required to find an element on the web page as to do an operation on that particular element.

  • There are two types of XPath:
    • Absolute XPath
    • Relative XPath
  • XPath Axes are the methods used to find dynamic elements, which otherwise not possible to find by normal XPath method
  • XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, etc. from the XML document .
Source: http://www.guru99.com/xpath-selenium.html

Selenium Grid Step by Step Guide


Install java jar:

1. Add the PPA.

Open terminal (Ctrl+Alt+T) and run the command:

sudo add-apt-repository ppa:webupd8team/java

Type in your password when it asks and hit Enter.

2. Update and install the installer script:

Run commands to update system package index and install Java installer script:

sudo apt update; sudo apt install oracle-java8-installer

You may replace oracle-java8-installer with oracle-java9-installer to install Java 9.

While the install process, you have to accept Java license to continue downloading & installing Java binaries.

3. Check the Java version

To check the Java version after installing the package, run command:

javac -version

4. Set Java environment variables

The PPA also contains a package to automatically set Java environment variables, just run command:

sudo apt install oracle-java8-set-default

For Java 9, install the package oracle-java9-set-default instead.

Setup Selenium Standalone Server

 1. Download Selenium Selenium Standalone Server:

Go to http://www.seleniumhq.org/download/ and then download Selenium Standalone Server by clicking ‘Download version 3.0.1‘ (version number may vary).

You need to download this for both hub and node PCs

2. Now, start the Hub machine:

Open the terminal, CD to the location where the selenium standalone server file is being kept and type:

java -jar selenium-server-standalone-2.30.0.jar -role hub

It will start the hub.

Another way to verify whether the hub is running is by using a browser. Selenium Grid, by default, uses hub’s port 4444 for its web interface. Simply open up a browser and go to http://localhost:4444/grid/console

Also, you can find if the node can access the hub. For this, open a browser in the node machine and type http://192.168.136.130:4444/grid/console as URL. Here ‘192.168.136.130’ should replace with the node machine’s IP address.

3. Now, the hub is up and running. Let’s setup node:

In the node machine, open a terminal, CD to the location where the selenium standalone jar file is located and type the following command:

java -jar selenium-server-standalone-3.0.1.jar -role webdriver -hub http://192.168.136.130:4444/grid/register -port 5566

Here, 192.168.136.130 should be replaced with the hub machine’s IP address.

We also used port 5566 though you may choose any free port number you desire.

If everything went well, the node will up and show it’s status.

You can also verify if the node is connected with hub properly from the web browser.

Refresh the http://192.168.136.130:4444/grid/console URL and it will show the connected nodes.

4. Run the selenium script:

Now, we will run a selenium remote control script from the hub machine and it will execute to the node machines.

Here is a sample python script we are using:

Please Note: To run this script the node pc must have installed the following things:

  1. Python
  2. Python PIP
  3. Selenium
  4. Latest Chrome driver

Remote Control Script:

# -*- coding: utf-8 -*-
from selenium import selenium
import unittest, time, re

class sample-script(unittest.TestCase):
 def setUp(self):
 self.verificationErrors = []
 self.selenium = selenium("localhost", 4444, "*chrome", "http://jaxara.com/")
 self.selenium.start()
 
 def test_sample-script(self):
 sel = self.selenium
 sel.open("/")
 sel.type("id=edit-search-block-form--4", "test")
 sel.click("xpath=.//*[@value='Search']")
 for i in range(60):
 try:
 if sel.is_element_present("xpath=.//*[@id='block-system-main']/div/h2"): break
 except: pass
 time.sleep(1)
 else: self.fail("time out")
 try: self.failUnless(sel.is_element_present("xpath=.//*[@id='block-system-main']/div/h2"))
 except AssertionError as e: self.verificationErrors.append(str(e))
 
 def tearDown(self):
 self.selenium.stop()
 self.assertEqual([], self.verificationErrors)

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

To verify if the above listed items are already been installed, run this script from the terminal. If the following scripts run properly then everything is installed and ready.

Sample Script:

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class SampleWebScriptPy(unittest.TestCase):
 def setUp(self):
 self.driver = webdriver.Chrome()
 self.driver.implicitly_wait(30)
 self.base_url = "http://jaxara.com/"
 self.verificationErrors = []
 self.accept_next_alert = True
 
 def test_sample_web_script_py(self):
 driver = self.driver
 driver.get(self.base_url + "/")
 driver.find_element_by_id("edit-search-block-form--4").clear()
 driver.find_element_by_id("edit-search-block-form--4").send_keys("test")
 driver.find_element_by_xpath(".//*[@value='Search']").click()
 for i in range(60):
 try:
 if self.is_element_present(By.XPATH, ".//*[@id='block-system-main']/div/h2"): break
 except: pass
 time.sleep(1)
 else: self.fail("time out")
 try: self.assertTrue(self.is_element_present(By.XPATH, ".//*[@id='block-system-main']/div/h2"))
 except AssertionError as e: self.verificationErrors.append(str(e))
 
 def is_element_present(self, how, what):
 try: self.driver.find_element(by=how, value=what)
 except NoSuchElementException as e: return False
 return True
 
 def is_alert_present(self):
 try: self.driver.switch_to_alert()
 except NoAlertPresentException as e: return False
 return True
 
 def close_alert_and_get_its_text(self):
 try:
 alert = self.driver.switch_to_alert()
 alert_text = alert.text
 if self.accept_next_alert:
 alert.accept()
 else:
 alert.dismiss()
 return alert_text
 finally: self.accept_next_alert = True
 
 def tearDown(self):
 self.driver.quit()
 self.assertEqual([], self.verificationErrors)

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

Good luck!

Python Robot Framework Install


To install Robot Framework, you need to pre-installed the following items:

  1. Python 2 or 3
  2. Selenium
  3. PIP
  4. PATH setting in Environment Variables

See How to Install Python, PIP, Selenium, Chrome Driver post if you already have not the above things.

Install Robot:

Open CMD as an administrator user.

Type:

pip install robotframework --user
pip install robotframework-selenium2library --user

After completion you can start working on the Robot framework.

You can simply create a .txt file and put the following codes to check the Robot framework is working or not:

*** Settings ***
Library     Selenium2Library
Suite Setup     Go to homepage
Suite Teardown  Close All Browsers

*** Variables ***
${HOMEPAGE}     http://mytestsite/wp-admin
${BROWSER}      chrome
${user}         abc@example.com
${pass}         password

*** Test Cases ***
Open Browser To Login Page
    Input Username    abc@example.com
    Input Password    password
    Submit Credentials

*** Keywords ***
Open Browser To Login Page
    Maximize Browser Window
    Open Browser    ${HOMEPAGE}    ${BROWSER}
    Login Page Should Be Open

Go to homepage
    Open Browser    ${HOMEPAGE}     ${BROWSER}

Input Username
    [Arguments]    ${username}
    Input Text    id=user_login    ${username}

Input Password
    [Arguments]    ${password}
    Input Text    id=user_pass    ${password}

Submit Credentials
    Click Button    xpath=//input[contains(@id, 'wp-submit')]

Save this code in a text file like, demo-robot.txt

Now from CMD or terminal type

pybot demo-robot.txt

It will run the script and generate the detail report, log file and other necessary output.

You can also save the file as robot file like, debo-robot.robot

It that case you need to add “C:\Python27\Lib\site-packages\robot” in your Environment Variable.

Now type the following code to run the robot script:

robot demo-robot.robot

Please Note: If you are using any IDE like Pycharm, some notification will appear after installing Robot framework, which will say that there are some plugins for Robot, do you want to install it or not. In that case you should install it in the IDE.

How to Install Python, PIP, Selenium, Chrome and Firefox Driver


Install Python:

If you are using a Linux machine then you have already installed Python, so only Windows users need to download and install Python. For this, go the following URL, download the latest Python (I am using 2.7.x) and install it:

https://www.python.org/downloads/

Install PIP:

If you already have Python installed in you system, then you have PIP but you need to update it.

To install pip, securely download get-pip.py.

Run the file, it will update PIP.

Make Python Executable via CMD:

Now to make python executable via windows command line, you need to add environment variable, For this go to My Computer Properties > Click Advanced System Settings > click Environment Variables.. > select PATH and click Edit.

Here, add “C:\Python27″ and “C:\Python27\Scripts” by clicking New. If any of them are already exist then no need to add again. Now press OK for everything.

2016-11-20_0-07-242016-11-20_0-08-302016-11-20_0-10-512016-11-20_0-11-152016-11-20_0-13-03

Now close and open the CMD. You can now able to run python files from command prompt by typing ‘python test.py’ where test.py is a python script.

Please Note: Sometimes the PC may need to logoff and then login again to take effect this new installation.

Install Selenium

For installing Selenium first,

Open the CMD.

go to python script directory by typing:

cd C:\Python27\Scripts

Now install Selenium:

pip install -U selenium
or
pip install selenium --user

It will appear like bellow after successful completion:

2016-11-20_0-28-32

Install Chrome Driver:

To install Chrome driver you need to installed the Chrome browser in your system.

Now, download the latest chrome driver from the official page: https://sites.google.com/a/chromium.org/chromedriver/downloads

To download the latest Firefox (Gecko dirver) download the latest form here: http://www.seleniumhq.org/download/

Unzip it and copy the chromedriver.exe file to “C:\Python27” location.

Please Note: While updating any driver (Chromedriver, Firefox Gecko driver) you need to copy the latest driver.exe file to this same location and replace the old one with new one.

Create a free website or blog at WordPress.com.

Up ↑