Wednesday, 29 August 2018

Java Concepts -4

Loop Statements/Iterative statements:
-------------------------------------
Loop Statements/Iterative statements are used to execute some portion of the script multiple times/iterations
a. While Loop:
b. Do while Loop:
c. For loop:

a. While Loop:
It will allow script to execute multiple iterations until given condition is true

Syntax:
while (condition){
----------
----------//Repeatable statements
}
Exp:
int n=1;
while (n <= 5){
System.out.println(n);
n++;
}

b. Do While Loop:
It will allow atleast one time to execute the block of statements irrespective of condition true/false

Syntax:
do{
    ----------
    ----------//statements
[break]
}


NOTE: [break] is used to terminate the iterations

Exp:
int n=1;

do {
System.out.println(n);
n++;
    }while (n <= 5);


Ex:
int n=1;

do {
System.out.println(n);
if(n==3){
break;
}
n++;
}while (n <= 5);

ex:
int n=6;
do {
System.out.println(n);
n++;
}while (n <= 5);

c. For Loop:
For Loop is used to execute a block of statement fixed number times/itersations

Syntax:
for(initialization; condition; increment/decrement){
------------
-----------//Repeatable statements
[break]
}

Exp:
for(int i=1; i <= 5; i++){
System.out.println(i);
  }


Array Declaration:
----------------------
Array is used to store multiple values with same data types

Syntax:
datatype[] array_name= new datatype[size];

size--> number of values to store
array index starts with zero
to find number of values in an Array we can use array.length

Exp: Create an array to store 3 values

//Array Declaration
String[] myCars= new String[3];
//to assign values
myCars[0]="Audi";
myCars[1]="Benz";
myCars[2]="BMW";

//to find size of an array
System.out.println("Number of values are: "+myCars.length);

//to read values from array using index
System.out.println(myCars[0]);
System.out.println(myCars[1]);
System.out.println(myCars[2]);

System.out.println("*******************");
//to read values from array using for loop
for(int i=0; i <= myCars.length-1; i++){
System.out.println(myCars[i]);

For-each:
Used to read each value from an array/collections

Syntax:
for( datatype variableName: array/collectionname)

//to read values from array using For -each
for(String myCar: myCars)
{
System.out.println(myCar);

}


ArrayList/Dynamic Array:
--------------------------------
When we don't know how many values to store in an Array we can use an ArrayList
Syntax:
ArrayList arrayname= new ArrayList();

//to assign values
Syntax:
arrayname.add(value);

//to find size of an ArrayList we can use ArrayList.size();

Exp: Create ArrayList to assign 3 string values

// ArrayList Declaration
ArrayList myCars= new ArrayList();

//to assign values
myCars.add("Audi");
myCars.add("Benz");
myCars.add("BMW");

//to find number of values
System.out.println("Number of values are: "+myCars.size());

//to read values from an arrayList using For each
for(String myCar: myCars){
System.out.println(myCar);
}


Sunday, 26 August 2018

Java Concepts-3

Java concepts-3
---------------
1. Comparative operators
< -less than
> -greater than
<= less than or equals
>= greaterthan or equals
AND or &&
OR or ||
NOT EQULS TO or !=
.equals() or ==
2. Conditinal statements:
To execute particular block of statement based on given condition true/false
i. If condition
ii. else if condition
iii. Nested if
iv. switch case

i. if Condition:
To execute particular block of statement when given expression is true

Syntax:
if (condition){
------
------//statements
}

ex:
int a= 10;
int b= 20;

if (a < b){
System.out.println("a- is smaller than b");
}





ii. else if condition:
using Else If we can execute different block of statements based on given expression/condition is true or false

syntax:
if (condition)
{
-----------
-----------//statements
}
else
{
-----------
-----------//statements
}

Exp: Write program to find smaller value in given 2 numbers
script:
int a= 30;
int b= 20;


if (a < b){
System.out.println("a- is smaller than b");
}
else{
System.out.println("b-is smaller than a");
}




3. Nested if:
To check more than one condition in a block of statement

Syntax:
if (condition-1){
----------------
----------------//Statements-1
}
else if (condition-2){
-------------
-------------//statements-2
}
else{
-------------
-------------//statements-3
}


Exp: write program to find smaller value in given 3 numbers
script:
int a= 30;
int b= 20;
int c= 10;


if ((a < b) && (a < c)){
System.out.println("smaller value is: "+a);
}
else if (b < c){
System.out.println("smaller value is: "+b);
}
else{
System.out.println("Smaller value is: "+c);
}



Exp: write program to find student grade based on given marks
Script:
int stMarks;
String stGrade;
System.out.println("Enter student marks");
//to read student marks from console
Scanner sc= new Scanner(System.in);
stMarks= sc.nextInt();

if (stMarks >= 90){
stGrade="A";
}
else if (stMarks >= 80){
stGrade ="B";
}
else if(stMarks >= 70){
stGrade ="C";
}
else{
stGrade ="D";
}

System.out.println("Student marks are: "+stMarks);
System.out.println("Student Grade is: "+stGrade);


4. Switch statement:
It is similar to nested if, but it will increase reliability of the script

Syntax:
switch(expression)
{
case (condition-1):
-------
-------//statements-1
break;
case (condition-2):
--------
--------//statements-2
break;
case (condition-3):
--------
--------//statements-3
break;
default:
--------
--------//statements-4
}


Exp: Write program to display color name based on given character from "RGB"
script:
System.out.println("Enter any one character from -RGB");
Scanner sc= new Scanner(System.in);
String myColor=sc.nextLine();
switch(myColor.toUpperCase()){
case "R":
System.out.println("Your choice is: RED");
break;
case "G":
System.out.println("Your choice is: GREEN");
break;
case "B":
System.out.println("Your choice is: BLUE");
break;
default:
System.out.println("Invalid entity");
}

========================================================================

Saturday, 25 August 2018

Multiple Browsers on Selenium

Working on Different Browsers
-------------------------
Selenium WD library provided individual classes to interact with different browser

Exp:  FirefoxDriver(), ChromeDriver(), InternetExplorerDriver()...etc

1. Working on Chrome Browser:
-----------------------------
To work on Chrome browser, we need to run Chromedriver server and
need to create object for ChromeDriver() class

Procedure:
Step 1: Download Chromedriver server
Extract zip file into working folder

Step 2: Provide Chromedriver server path into script to Run chromedriver server

Syntax:
System.setProperty(key, path of server);

Exp:
System.setProperty("webdriver.chrome.driver", "E:\\SeleniumResource\\chromedriver.exe");

Step 3: Create object for ChromeDriver() class

Syntax:
WebDriver obj= new ChromeDriver();

Exp:
Write script to perform login operation in Sales Force application using chrome browser

/*Exercise:
  Launch Chrome Browser
  Open ("http://Salesforce.com")
          Maximize the browser window
  Insert Username
  Insert Password
  Click on Login Button
  */

//To launch Chrome browser
System.setProperty("webdriver.chrome.driver", "E:\\SeleniumResource\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Insert Username
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Insert Password
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To click on Login Button
driver.findElement(By.xpath("//input[@id='Login']")).click();


2. Working on IE Browser
------------------------
To work on IE browser, we need to run IEDriver server and
need to create object for InternetExplorerDriver() class

Procedure:
Step 1: Download IEdriver server
Extract zip file into working folder

Step 2: Provide IEDriver server path into script to Run IE driver server

Syntax:
System.setProperty(key, server path);

Exp:
System.setProperty("webdriver.ie.driver", "E:\\SeleniumResource\\IEDriverServer.exe");

Step 3: Create object for InternetExplorerDriver() class

Syntax:
WebDriver obj= new InternetExplorerDriver();

NOTE:
Set IE browser zoom level to 100%
Set all the 4 zones security settings either ON/OFF

Exp:
/*Exercise:
  Launch IE Browser
  Open ("http://Salesforce.com")
          Maximize the browser window
  Insert Username
  Insert Password
  Click on Login Button
  */

//To launch IE browser
System.setProperty("webdriver.ie.driver", "E:\\SeleniumResource\\IEDriverServer.exe");
WebDriver driver=new InternetExplorerDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Insert Username
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Insert Password
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To click on Login Button
driver.findElement(By.xpath("//input[@id='Login']")).click();

3. Working on Latest version of FF browser
------------------------------------------

NOTE:
We Must use WD 3.0 Jar Files and above verions to support Latest FF Browser

Step 1:
Download geckodriver server
url:https://github.com/mozilla/geckodriver/releases
Extract zip file

Step 2: Provide geckoDriver server path into script to Run geckodriver server

Syntax:
System.setProperty(key, server path);

Exp:
System.setProperty("webdriver.gecko.driver", "E:\\SeleniumResource\\geckodriver.exe");

Step 3: Create object for FirefoxDriver() class

Syntax:
WebDriver obj= new FirefoxDriver();

Exp:
/*Exercise:
  Launch Gheko Browser
  Open ("http://Salesforce.com")
        Maximize the browser window
  Insert Username
  Insert Password
  Click on Login Button
  */

//To launch Latest Firefox browser
System.setProperty("webdriver.gecko.driver", "E:\\SeleniumResource\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Insert Username
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Insert Password
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To click on Login Button
driver.findElement(By.xpath("//input[@id='Login']")).click();










Thursday, 16 August 2018

Locators in WebDriver-Very Imp

Locators
----------
Addressing Webelements in WebDriver

WD will identify webelements in a page using locator values
Locators are the html propeties/attributes values of a webelement

Syntax:
driver.findElement(By.LocatorName("Locator value"));


WD Supports 8 types of locators:
1. id
2. name
3. className
4. tagName
5. linkText
6. partialLinkText
7. xpath
8. cssSelector

1. id:
It is most commonly used locator to address webelement
Syntax:
driver.findElement(By.id(id value));

NOTE:
i. click():
Click method is used to perform mouse click on specifed webElement
Syntax:
webelement.click();

ii. sendKeys():
SendKeys method is used to enter data in input objects
Syntax:
webelement.sendKeys(data);

/*Exercise:
  Launch FireFox Browser
  Open salesforce login Page
        Maximize the browser window
  Enter Username
  Enter Password
  Click on Login Button
  Close browser*/

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To enter Username (Invalid Username)
driver.findElement(By.id("username")).sendKeys("SeleniumClass");
//To enter Password (Invalid Password)
driver.findElement(By.id("password")).sendKeys("Password123");
//To click on Login Button
driver.findElement(By.id("Login")).click();
//To close browser
driver.close();


2. name:
Name is also used as a locator to address webelements
Syntax:
driver.findElement(By.name(name value));

/*Exercise:
  Launch FireFox Browser
  Open ("http://newtours.demoaut.com")
        Maximize the browser window
  Enter Username
  Enter Password
  Click on Login Button
  Close browser*/a

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://newtours.demoaut.com");
//To maximize the browser window
driver.manage().window().maximize();
//To enter Username (Valid Username)
driver.findElement(By.name("userName")).sendKeys("mercury");
//To enter Password (Valid Password)
driver.findElement(By.name("password")).sendKeys("mercury");
//To click on Login Button
driver.findElement(By.name("login")).click();
//To close browser
driver.close();


3. className:
className is also used as a locator to address webelements
However, className may not be unique to identify webelements
Syntax:
driver.findElement(By.className(className value));

/*Exercise:
  Launch FireFox Browser
  Open ("http://facebook.com")
        Maximize the browser window
  Enter value in password edit box using "className" as a locator*/
 

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://facebook.com");
//To maximize the browser window
driver.manage().window().maximize();
//To enter value in password edit box
driver.findElement(By.className("inputtext")).sendKeys("Password");

NOTE:   It will enter value in Email edit box because className"inputtext" not unique,
Email edit box className is also "inputtext" Plz check using Firebug
If similar attribute values exist for webelements on a page,  WD will identify fist webelement from
the root tag, in this case, Email edit box is the first element from the root tag


4. linkText:
Used to locate Hyperlinks on a webpage
Hyperlinks tab will always starts with "a" (Anchor tag)
Syntax:
driver.findElement(By.linkText(visible text of link));

/*Exercise:
  Launch FireFox Browser
  Open ("http://facebook.com")
        Maximize the browser window
  Click on "forgotten account?" using linkText locator*/
 

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://facebook.com");
//To maximize the browser window
driver.manage().window().maximize();
//To click on "forgotten account" link
driver.findElement(By.linkText("Forgotten account?")).click();



5. partialLinkText():
this locator also used to address hyperlinks

syntax:
driver.findElement(By.partialLinkText(partial visible text of link));

/*Exercise:
  Launch FireFox Browser
  Open ("http://facebook.com")
        Maximize the browser window
  Click on "account?" link using partialLinkText locator*/
 

//To launch firefox browser
WebDriver driver=new FirefoxDriver();
//To Open salesforce Login Page
driver.get("http://facebook.com");
//To maximize the browser window
driver.manage().window().maximize();
//To click on link
driver.findElement(By.partialLinkText(" account?")).click();

NOTE:
In general, partialLinkText locator is preferred for dynamic links that constantly change

Exp: 
Your order no. 110150 (the number may change time to time)

6. tagName:
This locator is used to address similar type of objects on a page
Syntax:
driver.findElements(By.tagname(value));


7. xpath:
xpath ("x" stands for XML, extendable markup language)
using expath we can address webelements based on hierarchy of tag names in a page

In General, xpath is used when a webelement doesnt have any proper attribute values,
so as cssSelector

Finding xpath on a webpage:
i. Using "firepath"
firepath is an add-on to firefox browser
download and install firepath from firefox browser
once installed, right click on any element on the webpage
click on "Inspect in Firepath"
you will be able to see xpath correctly

NOTE:  Precondition for firepath, Ensure Firebug is already installed in your machine
       in order for firth path to work

There are two types of xpath:
a. Absolute xpath:
b. Relative xpath:

a. Absolute xpath:
addressing webelement from root tag in a page
absolute xpath can be prefixed with "/"

Exp:  Html code in a webpage

html...
header
body
div...
input...
li...
li...
input...
input id="abcd"

Absolute xpath:
/html/body/input/li[2]/input[2]

Exp:
Find Absolute xpath for "Email" edit box on yahoomail homepage

Manually written xpath:     /html/body/div[2]/div/div/form/div/input
or
Firepath Generated xpath:    html/body/div[2]/div[1]/div[1]/form/div/input

Finding Absolute xpath for a webelement using Firepath

Right click on any element
Click on "Inspect in FirePath"
Ensure "Generate Absolute Xpath" is cheked under FirePath Dropdown
Absolute xpath is generated successfully

NOTE:  Checked "Generate Absolute Xpath" option is used for "Absolute Xpath"
     

Exp:
Find Absolute xpath for "Next" button on yahoomail homepage

Manually written xpath:     /html/body/div[2]/div/div/form/input[3]
or
Firepath Generated xpath:    html/body/div[2]/div[1]/div[1]/form/input[3]


Exp:
Find absolute xpath for "sign in" object in www.amazon.in

Manually written xpath:     /html/body/div/div[3]/div/div/div/div[3]/div/a/span
or
Firepath Generated xpath:    html/body/div[1]/div[3]/div/div[1]/div/div[2]/div[1]/a/span

NOTE:  The Absolute xpath in above example has changed between Manually written and Firepath generated
that is becuase there is two days difference between manually written xpath and
Firepath generated xpath, amazon has made some changes on the webpage in last two days. 
Everytime, there is a change on webpage, the absolute xpath changes,
this is the reason why absolute xpath is NOT a preferred locator

Exp:
Find absolute xpath for "Next" button in Gmail-home page using Firepath

Firepath Generated xpath:    html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/content/span


b. Relative xpath:
Relative xpath is prefered more than Absolute xpath
Relative xpath is a combination of tagname and anyone of the
attribute value of a webelement

Syntax:
//tagname[@attributename='value']

Exp: Write relative xpath for "Email" edit box in Gmail-home page
//input[@id='identifierId']
or
//input[@name='identifier']
or
//input[@type='email']

Different options in Relative xpath:

i. using "*" in Relative xpath
syntax:
//*[@attribute='value']
here "*" represents any tagname
ex:
//*[@name='identifier']

Finding Relative xpath for a webelement using Firepath

Right click on any element
Click on "Inspect in FirePath"
Ensure "Generate Absolute Xpath" is uncheked under FirePath Dropdown
Relative xpath is generated successfully

NOTE: Unchecked "Generate Absolute Xpath" is used to Generate "Relative Xpath"


ii. Providing multiple attribute values using Relative xpath
we can also give more than one attribute values to address a webelement

syntax:
//tagname[@attribute1='value'][@attribute2='value']

Exp:
//input[@name='identifier'][@type='email']
or
//*[@name='identifier'][@type='email']

iii. Using text():
Used to identify a webelement through visibletext
syntax:
//tagname[text()='visibletext']

Exp:
//span[text()='Forgot email?']

iv. **traversing xpath:
It is a combination of relative xpath and absolute xpath
In following scenarios Traversing xpath is prefered
a. When there are similar objects exist in a page
b. When webelement properties are changing during runtime (i.e. Dynamic objects)

Exp: Finding traversing xpath for "signin" object in www.amazon.in"

//div[@id='rhf-container']/div/div[3]/div/a/span

Exp: Finding traversing xpath for "6E senior citizen" webelement in www.goindigo.in

//div[@id='oneWay']/form/div/div/div/ul/li[3]/div/label

Exp: Finding traversing xpath for "New pwd" edit box based on create account section
in a FB-home page

//div[@id='reg_form_box']/div[5]/div/div/input

8. cssSelector:
Cascading Style Sheet
Used to identify the webelements which doesn't have proper attribute values

Syntax:
driver.findElement(By.cssSelector(value));

cssSelector syntax:
tagname[attribute='value']

Exp:
input[id='identifierId']
or
tagname[text()='visibletext']

Exp:
span[text()='Next'] //for "Next" button in "Gmail-home page"

NOTE:   CssSelector identification is much faster than xpath during Runtime,
        but xpath is prefered locator

Exp: Writing script to perform login operation on Salesforce application using xpath

/*Exercise:
  Launch FireFox Browser
  Open ("https://login.salesforce.com")
        Maximize the browser window
  Enter username using xpath
  Enter password using xpath
  Click on Login using xpath*/


//To launch firefox browser
WebDriver driver= new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Enter username using xpath
driver.findElement(By.xpath("//input[@id='username']")).sendKeys("SeleniumClass");
//To Enter password using xpath
driver.findElement(By.xpath("//input[@id='password']")).sendKeys("Password");
//To Click on Login Button using xpath
driver.findElement(By.xpath("//input[@id='Login']")).click();

Exp: Writing script to perform login operation on mercury tours application using cssSelector


/*Exercise:
  Launch FireFox Browser
  Open ("https://login.salesforce.com")
        Maximize the browser window
  Enter username using cssSelector
  Enter password using cssSelector
  Click on Login using cssSelector*/


//To launch firefox browser
WebDriver driver= new FirefoxDriver();
//To Open salesforce Login Page
driver.get("https://login.salesforce.com");
//To maximize the browser window
driver.manage().window().maximize();
//To Enter username using cssSelector
driver.findElement(By.cssSelector("input[name='username']")).sendKeys("SeleniumClass");
//To Enter password using cssSelector
driver.findElement(By.cssSelector("input[name='password']")).sendKeys("Password");
//To Click on Login Button using cssSelector
driver.findElement(By.cssSelector("input[name='Login']")).click();

Monday, 13 August 2018

WebElements in WebDriver


Identifing Webelements In WebDriver During Runtime

Class:
A set of similar objects are called a Class

Class Example:
Animal, Fruit, Birds

Object:
An instance of a class

Object Example:
Tiger, Apple, Parrot

NOTE:  Every object should have some sort of identification properties and behaviors
based on which we can identify the objects correctly

An Example of how HTML code is written for WebElement:



Exp:
Open "www.login.salesforce.com" page
Press F12, Click on Inspector and Check html code for "UserName" edit box

input style="display: block;" class="input r4 wide mb16 mt8 username" value=""
name="username" id="username" type="email"

In above HTML code: Tagname is "input"

Attribute_Name Attribute_value
-------------- ---------------
style display: block;
class input r4 wide mb16 mt8 username
value ""
name username
id         username
type         email


Inspecting WebElement Attribute Values:

There are 2 ways to view webelement html Properties/Attributes
i. Using selenium IDE:
Using Selenium IDE Recording, we can capture webelement attribute values
and these are displayed under "Target" component in "Script Editor"

ii. Using Firebug Add-on on Firefox Browser:
It is used to inspect webelement property values

How to Install FireBug on Firefox Browser:
NOTE:  FireBug only works with Firefox Browser

Open FF browser
Open google search engine
Enter "download Firebug"
Click on "Search" button
Click on the first link
Click on "Add to firefox"
Add on is added to Firefox browser successfully


Finding WebElement Properties using Firebug:

Focus on the webelement that you want to view the properties for,
Right click the webelement
Select "Inspect webelement with firebug" option
Webelement attributes/properties are displayed


NOTE: WD can identify webelements using html properties/attribute values/locator values during runtime

Syntax: {to address webelements}
driver.findElement(By.locatorName(Locator value));

Exp:
Finding Webelement Properties for "username" edit box
driver.findElement(By.id("username"));

NOTE: During Runtime, WD will compare each element by given webelement property value in
the root tag of the html page (ie., DOM, Document Object Model), it will then perform the
given operation on the correct element thats matches based on the values provided. Exp: (By.id("username"))


WD Supports 8 Types Of Element Locators:
----------------------------------------
1. id
2. name
3. className
4. linkText
5. partialLinkText
6. tagName
7. xpath
8. cssSelector

WebDriver Browser Interaction Commands

Launching WebBrowser:
------------------------------
WD library consists of individual classes to interact with different browsers

Exp: Firefox:  FirefoxDriver()
        Chrome:   ChromeDriver()
        IE:   InternetExplorerDriver()

We have to create an "object" to the "browser class" to open a web browser

Syntax:
WebDriver obj=new BrowserDriver class();

Exp:
WebDriver driver=new FirefoxDriver();
It will launch Firefox browser in safe mode
Safe mode means, it will open browser with no history, no bookmarks, no add-ons...etc

Browser Interaction Commands:
---------------------------------------
1. get():
Used to open a specifed url
Syntax:
driver.get(url);

2. maximize():
Used to maximize browser
Syntax:
driver.manage().window().maximize();

3. getPageSource():
Used to read page source code
Syntax:
driver.getPageSource():

Ex: Write a script to open FB page, maximize the window,
read page source code and print source code

/*Launch FireFox Browser
          Open Facebook Page
  Maximize the browser window
  Read source code
  Print source code*/

//To launch Firefox Browser
WebDriver driver=new FirefoxDriver();
//To open Facebook Page
driver.get("https://facebook.com");
//To maximize browser window
driver.manage().window().maximize();
//To create a source code variable and Read source code
String pgSource=driver.getPageSource();
//To print source code in console
System.out.println(pgSource);
//Before running the code make sure all your browsers are closed

4. getTitle():
Used to read page title
Syntax:
driver.getTitle();

5. getCurrentUrl():
Used to read current page url
Syntax:
driver.getCurrentUrl();

6. close():
Used to close focused window in browser
Syntax:
driver.close():

Ex: Write a script to open FB, read page title and print, get page url and print,
and to close browser

/*Launch FireFox Browser
  Open Facebook Page
  Maximize the browser window
  Get page title
  Get page url
  Close browser*/

//To launch Firefox Browser
WebDriver driver=new FirefoxDriver();
//To open Facebook Page
driver.get("https://facebook.com");
//To maximize the browser window
driver.manage().window().maximize();
//To get page title
String pgTitle=driver.getTitle();
//To print page title in console
System.out.println(pgTitle);
//To get current url
String pgUrl=driver.getCurrentUrl();
//To print current url in console
System.out.println(pgUrl);
driver.close();


7. navigate().to():
Also used to open specified url
Syntax:
driver.navigate().to(url);

NOTE:   When we use driver.get(): it will wait until page is loaded, once page is loaded then only it will execute the next step
        When we use navigate().to(): it will NOT wait until the page is loaded, it will attempt to execute the next step


8. navigate().back():
Used to move back by one page in browser history
Syntax:
driver.navigate().back();


9. navigate.()forward():
Used to move forward by one page in browser history
Syntax:
driver.navigate().forward();


10. navigate().refresh():
Used to refresh the page
Syntax:
driver.navigate().refresh();

11. quit():
Used to close all the opened windows in a browser
Syntax:
driver.quit();

// to open FF browser
WebDriver driver= new FirefoxDriver();
//to open FB
driver.get("http://facebook.com");
//to maximize window
driver.manage().window().maximize();
//to open Google
driver.navigate().to("http://google.co.in");
//to move back
driver.navigate().back();
//to refresh the page
driver.navigate().refresh();
//to close browser
driver.quit();





Sunday, 12 August 2018

Java Concepts -2:

Variable Declaration:
---------------------

Variable is a basket of memory where we can store data
Variables are used to store information to be referenced and used by programs

There are Eight Types of Primative DataTypes in Java for Numeric Values

Syntax:  Datatype VariableName=Data

The Following are Eight Types of DataTypes:

1. Byte (Memory 8 bits)
Range: -128 to 127 (2^7)

Exp:
byte myByte = 127;
System.out.println(myByte);
//Console Output Shown: 127

2. Short (Memory 16 bits)
Range: -32768 to 32767 (2^15)

Exp:
short myShort = 32750;
System.out.println(myShort);
//Console Output Shown: 32750


3. Int (Memory 32 bits)
Range: upto 18446744073709551616 (2^64)

Exp:
int myInt = 1000000000
System.out.println(myInt);
//Console Output Shown: 1000000000


4. Long (Memory 64 bits)
Range: Long Values

Exp:
long myLongNumber = 1000000000000000000l //(we have to add L at the end as suffix)
System.out.println(myLongNumber);
//Console Output Shown: 1000000000000000000


5. Float (32 bit) (Used for Decimal values)
Exp: 
float myFloat= 23.45f; //(we have to add F as suffix)
System.out.println(myFloat);
//Console Output Shown: 23.45


6. Double (64 bit) (Used for Decimal values)
Exp: 
double myDouble= 2334.4587;
System.out.println(myDouble);
//Console Output Shown: 2334.4587

7. Char (16 bit)
Exp: 
char myGender='M' //(Single quotes only for single character)
System.out.println(myGender);
//Console Output Shown: M


8. Boolean for true/false
Exp:
boolean myStatus= true;
System.out.println(myStatus);
//Console Output Shown: true

NOTE:  String Class in Java is used for sequence of characters
Exp:
String myVal="SeleniumClass"; //(4* 16 bits)
System.out.println(myVal);
//Console Output Shown: SeleniumClass

-------------------------------------------------------------------------------------
Some of the Important string methods:
------------------------------------
1. length():
To find number of characters in a given string
Exp:
String str1="SeleniumClass";
System.out.println(str1.length());
//Console Output Shown: 13


2. charAt():
To read character from main string based on index
Exp:
String str2="SeleniumClass"; //to read "m"
System.out.println(str2.charAt(7));
//Console Output Shown: m


3. indexOf():
To find index of given character in main string
Exp:
String str3="SeleniumClass"; //to find index of "C"
System.out.println(str3.indexOf("C"));
//Console Output Shown: 8
/*indexing starts from 0,
in the above example S is 0, e is 1, l is 2.....C is 8*/


4. toUpperCase():
It will convert given string into upper case
Exp:
String str4="SeleniumClass";
System.out.println(str4.toUpperCase());
//Console Output Shown: SELENIUMCLASS


5. toLowerCase():
It will convert given string into lower case
Exp:
String str5="SeleniumClass";
System.out.println(str5.toLowerCase());
//Console Output Shown: seleniumclass


6. equals():
To compare the strings
Exp:
String str6="SeleniumClass";
System.out.println(str6.equals("Seleniumclass"));
//Console Output Shown: False

String str7="SeleniumClass";
System.out.println(str7.equals("SeleniumClass"));
//Console Output Shown: True


7. equalsIgnoreCase():
To compare the strings, It is caseinsensitive
Exp:
String str8="SeleniumClass";
System.out.println(str8.equalsIgnoreCase("SeleNiumClass"));
//Console Output Shown: True

String str9="SeleniumClass";
System.out.println(str9.equalsIgnoreCase("Seleniumclass"));
//Console Output Shown: True


8. startsWith():
To compare prefix value of a string(i.e starting characters)
Exp:
String str10="SeleniumClass";
System.out.println(str10.startsWith("Se"));
//Console Output Shown: True

String str11="SeleniumClass";
System.out.println(str11.startsWith("Ae"));
//Console Output Shown: False


9. endsWith():
To check suffix value of a string (i.e. end characters)
Exp:
String str12="SeleniumClass";
System.out.println(str12.endsWith("Class"));
//Console Output Shown: True

String str13="SeleniumClass";
System.out.println(str13.endsWith("Cless"));
//Console Output Shown: False


10. contains():
To check substring availability in a main string
Exp:
String str14="SeleniumClass";
System.out.println(str14.contains("ium"));
//Console Output Shown: True

String str15="SeleniumClass";
System.out.println(str15.contains("mum"));
//Console Output Shown: False


11. concat():
To concat the strings
Exp:
String str16="Selenium";
String str17="Class";
System.out.println(str16.concat(str17));
//Console Output Shown: SeleniumClass

String str18="Selenium";
String str19="Class";
System.out.println(str18+str19);
//Console Output Shown: SeleniumClass


12. trim():
It will remove leading and trailing spaces for a given string

Exp:
String str20=" SeleniumClass ";
System.out.println(str20.length());
//Console Output Shown: 15

String str21=" SeleniumClass ";
System.out.println(str21.trim().length());
//Console Output Shown: 13


13. replace():
To replace substring in a main string
Exp:
String str22="SeleniumClass";
System.out.println(str22.replace("s", "@"));
//Console Output Shown: SeleniumCla@@
//replace is casesensitive so capital S is not replaced

String str23=" Sele nium Cla ss ";
System.out.println(str23.trim());
//Console Output Shown: Sele nium Cla ss
//trim only trims at the beginning and ending spaces

String str24=" Sele nium Cla ss ";
System.out.println(str24.replace(" ", ""));
//Console Output Shown: SeleniumClass

14. subString():
To read substring from mainstring
ex:
String str25="SeleniumClass";
System.out.println(str25.substring(5));
//Console Output Shown: iumClass

String str26="SeleniumClass";
System.out.println(str26.substring(5, 7));
//Console Output Shown: // iu

String str27="SeleniumClass";
System.out.println(str27.substring(5, 8));
//Console Output Shown:// ium

15. isEmpty():
To check value in a variable is Empty or not









Thursday, 9 August 2018

Java Concepts-1:


Java program structure:
----------------------------
Hierarchy in Eclipse:
-------------------------
Workspace (For organizing all your projects at one place)
  --> Java project (A collection of Packages)
--> package (A collection of Classes)
     --> class (A collection of Methods)
  --> Methods
---------------------------------------------------------------------------
Package:
Pacakge organizes a set of classes

How to create a "Package"
Navigation: {To create package}
Select "src" folder under java project in eclipse
Right click and Select "New" then Select "Package"
    Enter a "package name"
Click on "OK" Button

NOTE: Package name must be lower case ONLY
Exp Packages Names:  sample.test, selenium.testcases, org.insightq

---------------------------------------------------------------------------
Class:
Class is a Template using which we can write java programs

How to create a "Class"
Navigation:{To create class}
Select the "Package name" under "src" folder under java project in eclipse
Right click and Select "New" then Select "Class"
    Enter a "Class name"
Click on Check Box "Public Static Void Main (String []args)"
    Click on "Finish" Button

NOTE: Package name must be Camel case ONLY
Exp Packages Names:  SampleTest, SeleniumTestcases, OrgInsightq

Class with main method only
--------------------------
The below structure generated in edit box automatically by doing the above

package packageName;

public class ClassName
{
public static void main(String[] args)
{
---------
---------
}
}
---------------------------------------------------------------------------
How To Make "Comments" in Java:
-------------------------------

Single Line Comment:
Use two forward slashes "//" as prefix to comment a single line

Exp: //To validate login functionality

Multiple Lines Comment:
Use one forward slash and a star "/*" as prefix to open comment, */ as suffix to close comment

Exp: /*This is a
     block of code
for further use*/

Shortcut Keyboard Keys:
Ctrl+Shift+/ used to comment multiple lines
Ctrl+Shift+\ used to uncomment multiple lines
---------------------------------------------------------------------------
Output Functions:
-----------------

To display user messages during runtime, we can use following output functions

i. System.out.print(); It will print user message in console
syntax:
System.out.print(user msg);
Exp:
System.out.print("SeleniumClass1");
System.out.print("SeleniumClass2");

The output will be: SeleniumClass1SeleniumClass2

ii. System.out.println(); It will also print user message in console but line by line
syntax:
System.out.println(user meg);

Exp:
System.out.print("SeleniumClass1");
System.out.print("SeleniumClass2");

The output will be:
SeleniumClass1
SeleniumClass2

Shortcut Keyboard Keys:  //Syso+Ctrl+Spacebar+Enter

---------------------------------------------------------------------------
Scanner class:
--------------

To read user inputs during runtime (i.e. Keyboard inputs) we can use Scanner class
To use scanner class we need to create an obj in scanner class

syntax:

Scanner obj= new Scanner(System.in);
String variable=obj.nextLine(); //This object will provide methods to read data
obj.nextLine();
obj.nextInt();

Exp: Write program to read string value during runtime
System.out.println("Enter any name");
Scanner sc= new Scanner(System.in);
String myVal=sc.nextLine();
System.out.println("Entered value is: "+myVal);


Ex: Write program to read integer value during runtime
System.out.println("Enter any number");
Scanner sc= new Scanner(System.in);
int myVal=sc.nextInt();
System.out.println("Entered number is: "+myVal);

========================================================================



Selenium WebDriver Configuration Step by Step

WebDriver Configuration
===================

Step 1: Download "JDK 1.8" and Install (Based on your machine 32bit/64bit)
Step 2: Specify "JDK and JDK/bin" path into system Environment variables
Go to "C:\Program Files\Java\jdk1.8.0_181"
  "Copy" the above path
    "Right click" on "PC Properties"
      Click on "Advanced System Settings"
        Click on "Environment Variables"
          Click "New" under System Variables
             Variable Name: JAVA_HOME
               Variable Value:  Paste the copied above "C:\Program Files\Java\jdk1.8.0_181"
                 Click on "OK" Button
Go to "System Variables" secton on the same screen
Find "Path" and Click on "Edit"
    Under variable value: do not delete or replace anything, go to the end of the value and
      enter "semicolon" (;), then copy and paste bin path as "C:\Programfiles\Java\jdk1.8.0_181\bin"
then click "OK" Button then click "OK" Button Again

NOTE:  The above process is to let the machine know where the Java Library is available while executing the test scrips


Step 3: Download "Eclipse Mars 2" (Based on your machine 32bit/64bit)
Right click and Extract "Eclipse zip" file from "Downloads" folder
  Open Extracted "Eclipse folder"
    Select "Eclipse Icon" (3rd one from the bottom)
      "Right click" on "Eclipse Icon"
Click on "Send to"
          Select "Desktop (create shortcut)" option
            Eclipse is now ready to use from the Desktop


Step 4: Create "Java Project" in Eclipse
Open "Eclipse" from Desktop
  Provide "Workspace name" (exp: C:\Users\Prasad\Desktop\Selenium\Selenium Workspace)
    Click on "OK"
       Click on "Workbench" from top right corner on Eclipse
Click on "File" from Main Menu
           Hover on "New" and Select "Project"
             Select "Java Project" (the first one)
               Click on "Next" button
Provide a "Project Name" (exp:  "SampleProject01")
                  Click on "Finish" button
                    Click "Yes" on the next window
                       "SampleProject01" is successfully created on Eclipse


Step 5: Download WebDriver 2.53.1 jars (Based on your machine 32bit/64bit)
Right click and Extract "selenium-java-2.53.1" zip file  from "Downloads" folder
  Open "selenium 2.53.1" folder
    Select "selenium-java-2.53.1" and "selenium-java-2.53.1.src" jar files and move them into "libs" folder above
       Now we have all the "jar files" in one folder called "libs"

Step 6: Configure WebDriver jar files to Java project in Eclipse
Go to Eclipse Application
  Select "Java project" that was created previously "SampleProject01"
    Right click on "SampleProject01"
      Hover on "Build path"
Select "configure Build path"
         Click on "Libraries" Tab
           Click on "Add External jars"
             Browse WD jar files location
I kept all my selenium files and softwares in one folder on Desktop,
               In your case it may be "Downloads folder"
                 (MyCase: C:\Users\Prasad\Desktop\Selenium\selenium-java-2.53.1\libs)
                   Select "All jar files" using (Ctrl+A)
Click on "Open"
                     Click on "Apply"
                       Click on "OK"

You will notice jar files are associated to "SampleProject01" as "Referenced Libraries"

Now We Have Successfully Configured WebDriver To Automate Software Testing
===========================================================

Tuesday, 7 August 2018

Introduction to Selenium RC, Grid and WebDriver


Selenium RC:
-----------
RC- Stands for Remote Control
It was introduced in 2004
It supports different Scripting languages like Java/Ruby/Python/Perl/C#...etc.,
It supports different Browsers like Chrome, Firefox, IE...etc
It supports different OS like Windows, Linux, Solaris, Mac (OSX)...etc
*NOTE:  Selenium RC uses JavaScript injections to communicate Web Browsers
        Selenium RC requires Selenium RC server which converts script into JavaScript injections

Disadvantages:
JavaScript injections are blocked on majority of the browsers, hence RC scripts are not able to execute successfully
Hackers mostly use JavaScript injections to hack websites, hence its not secured
There is no further enhancements for Selenium RC (Deprecated)

Selenium Grid:
-------------
It is also called as Grid-1
It is used for parallel execution (i.e. executing multiple scripts simultaneously on different machines)

Disadvantages:
It supports only RC scripts
There is no further enhancements for Selenium Grid (Deprecated)

-----------------------------------------------------------------------------------------------------------
Selenium WebDriver:
==================================
WD was introduced in 2010
The main intension is to overcome challenges faced in Selenium RC
WD does not require RC server/proxy server
JavaScript injections completely removed in WD
WD also supports different languages like Java/Ruby/Python/Perl/C#...etc
WD supports different Browsers like Chrome, Firefox, IE,...etc
it supports different OS like Windows, linux, solaris, Mac (OSX)...etc
WD able to communicate with Browser native code
IE ---> developed using C#
FF ---> developed using Java
Using WD we can also automate mobile applications using Appium add-ons
WD is an interface between scripts and AUT
NOTE: WD doesn't have any user interface



Prerequisites for WD configuration:
----------------------------------
1. JDK 1.8:
Java Development Kit which consists of JDK+JRE library (Java Run Environment is used for WD)
Donwload and Install JDK 1.8 based on your machine specifications

2. Eclipse Mars 2:
Eclipse IDE is an Editor to write java programs
Donwload and Install Eclipse Mars 2 based on your machine specifications

3. WebDriver Jars (2.53.1):
Jars (Java Archive), which consists of library that contains set of classes, methods, properties used to communicate to the browser
Donwload and Install WebDriver Jars (2.53.1) based on your machine specifications

Monday, 6 August 2018

Working with Selenium IDE: Part-2


1. Two ways to Generate Script IDE:
a. Scripting using Recording Option
b. Scripting Manually

Ex:
Requirement: Create script manually for "Login Operation" on http://newtours.demoaut.com
uid="mercury"
pwd="mercury"


Ex:
Requirement: Create script manually for "User Registration" in Mercury
tours application


2. Enhancement in the script:
After creation of basic script, we can enhance the script using following commands:
i. Assertion commands
ii. Verify commands
iii. Stored Commands

i. Assertion commands:
Used to verify actual values on AUT against expected values

If assertion command is passed, then only the script would allow to continue
further execution, otherwise it will stop execution

ex: AssertTitle: Is used to verify page title with against the expected value

Ex:
Requirement: Create script to check login functionality with valid data procedure
open url: http://newtours.demoaut.com
enter "mercury" in "Username" edit box
enter "mercury" in "Password" edit box
click on "Signin" button
verify page title using assertion command
click on "Continue" button

ii. Verify commands:
Used to verify actual values on AUT against expected values

Verify Command will allow to continue script execution irrespective of
the current test status (Pass/Fail)

ex: VerifyTitle: To check page title

Ex:
Requirement: Create script to check login functionality with valid data procedure
open url: http://newtours.demoaut.com
enter "mercury" in "Username" edit box
enter "mercury" in "Password" edit box
click on "Signin"
verify page title using verify command
click on "Continue" button


iii. Stored commands:
User to read actual values from AUT during runtime

ex: StoreTitle: To read page title

Note:
echo: Command used to print user message in log section
syntax: echo ${variable}

Ex:
Requirement: Create script to read "Page Title" before and after click on
"Forgot your password?" link in https://login.salesforce.com


Converting script into other languages to support other browsers testing:
---------------------------------------
To execute script on other browsers using selenium WD/RC,
we have to convert the script into required supported languages

NAVIGATION:
Create required script in Selenium IDE
select "Source view" in script editor
"Options" menu
"Format"
select Required language

If the Languages are not available, Go to "Option Menu"
"Options"
Click on "Enable Experimental Features"

Limitations of Selenium IDE:
---------------------------
-It supports only FF and Chrome browsers
-Using loop statements and conditional statements are not possible
-Using TestData in the script is not possible (i.e. parameterization)
-There is no exception handling
-Cannot customize test reports

When can we prefer selenium IDE:
------------------------------
-To check if the application compatible for test automation using selenium (i.e. POC)
-If there are any issues with scripting using any programming languages on WebDriver
-To find webelement attributes/html property values

When can we prefer Selenium WebDriver?
-To automate an entire project
========================================================================


Wednesday, 1 August 2018

Working with selenium IDE: Part-1



Components in Selenium IDE:
--------------------------


1. Menu bar:
where we have menu options to perform operations on Selenium IDE
2. Base url:
it refer AUT url
3. Test Case Pane:
where we can find list of test cases which are created by us
4. Script Editor:
where we generate automation script using Recording option or manually
there are 2 views in Script Editor
i. Table view:
script geenrates in terms of tabular format
components in Table view
a. Command:
where we can find methods to perform operations on AUT
i. open: to open base url
ii. type: to enter data
iii. select: to select value from dropdown
iv. click: to click on element and to continue
v. clickAndWait: to click on webelement and to wait when application taking sometime to
complete transaction (max. 30 sec)
b. Target:
where it shows webelement attribute/html property values
c. value:
data to be provided for AUT during runtime


ii. Source view:
in this view by default script will be in html format

5. log & Reference:
a. Log:
where we can find script execution result
b. Reference:
where we can find information about Selenium IDE commands
=============================================================
Generating script:
a. using Recording option:
Navigation:
open FF browser
"Tools" menu in FF
select "Selenium IDE"
enter url in FF browser
perform required operations on AUT, which operations do you want to convert
into automation script
click on "Record" icon to stop recording


Excercise:
Create script to perform user registration in http://newtours.demoaut.com

















Introduction to Selenium


-It is an open source tool
-It is also a free tool
-It is used for Functionality testing and Regression testing
-it supports only web application to Automate (Browser Automation tool)
-it supports multiple scripting languages like Java/C#/Ruby/Python/Perl...etc
-It supports multiple browsers like IE, FF, Chrome, Opera...etc
-It supports multiple OS like Windows, Linux, Mac...etc
-Selenium is a suite of tools
Selenium 1.0:
It was firstly introduced in 2004
Components in Selenium 1.0
1. Selenium IDE
2. Selenium RC (Deprecated)
3. Selenium Grid/Grid-1 (Deprecated)
Selenium 2.0 & 3.0:
It was introduced in 2010
Components in Selenium 2.0 & 3.0
1. Selenium WebDriver/WebDriver
2. Remote WebDriver/Grid-2

----------------------------------------------------------------
Selenium IDE
-------------
IDE--> Integrated Development Environment
It is an Add-on for Firefox browser
It is a Record and Playback tool
Recording:
Converting our actions/operations which we perform on AUT into automation script is called REcording
Playback:
While script execution tool will interact with application and perform operations is called Playback

Installation of Selenium IDE:
----------------------------
Prerequisites:
Firefox browser (43.0.1 Version)
open "www.seleniumhq.org"
click on "download previous versions" under "Selenium IDE" section
click on "Add to Firefox"
click on "Install"