Monday, December 26, 2016

Selenium FAQ

Selenium FAQ
Interview Questions asked by CLIENT; hope this will helps you a bit.

Interview Questions:-
---------------------
1. Tell me about your project.: 5 mins
2. Tell me about framework: I took 30 Mins to explain
3. My sony projects explanation: 15 mins
4. Lead Questions:
      a) How you pick automation test cases from existing manual test cases: 15 mins
      b) How you categorize test cases: 15 mins
3. Normal basic selenium web driver questions: 20 mins
4. Write a sample program using selenium Webdriver
5. Explain about Jenkins integration CI\CD: 15 mins

* This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window
String parentWindow = driver.getWindowHandle();
Set<String> handles =  driver.getWindowHandles();
   for(String windowHandle  : handles)
       {
       if(!windowHandle.equals(parentWindow))
          {
          driver.switchTo().window(windowHandle);
         <!--Perform your operation here for new window-->
         driver.close(); //closing child window
         driver.switchTo().window(parentWindow); //cntrl to parent window
          }
       }
This is to switch from one window to the other, and there is a check as well.


* 1. Tell me about your project.: 5 mins
ANSWER: Refer to you Handbook and read.

* 2. Tell me about framework: I took 30 Mins to explain
ANSWER:
1. Creating Keyword & Hybrid Frameworks with Selenium

* http://www.guru99.com/creating-keyword-hybrid-frameworks-with-selenium.html

Frameworks help to structure our code and make maintenance easy. Without frameworks we will place all our code and data in same place which
is neither re-usable nor readable. Using Frameworks, produce beneficial outcomes like increase code re-usage , higher portability,
reduced script maintenance cost etc.

There are mainly three type of frameworks created by Selenium WebDriver to automate manual testcases

Data Driven Test Framework
Keyword Driven Test Framework
Hybrid Test Framework

*  Hybrid Test Framework
Hybrid Test framework is a concept where we are using advantage of both Keyword and Data driven framework.
Here for keywords we will use excel files to maintain test cases and for test data we can use data provider of TestNG framework.

*  Summary:-
o We can create three types of test framework using selenium WebDriver.
o These are Data Driven, Keyword driven and Hybrid test framework.
o We can achieve Data driven framework using TestNG's data provider.
o In Keyword driven framework , keywords are written in some external files like excel file and java code will call this file
and execute test cases.
o Hybrid framework is a mix of keyword driven and data driven framework.

2.
Create Data Driven Framework For Selenium WebDriver Using POI, TestNG And ANT
http://www.software-testing-tutorials-automation.com/2014/07/create-data-driven-framework-for.html

Selenium WebDriver data driven Framework key features
It will support only .xls files as Input data feed.
It will use Apache POI API to read data from .xls files and write results In .xls files.
It will use TestNG-XSLT Reports to generate results reports In HTML format.
You can feed multiple combinations of test data for executing single test case. Example : Validating Log in form's username and password
fields with different sets of data.
You can set Test suite execution mode (Test Suite To Be Executed or Not) In .xls file.
Reporting test case execution results (Pass, Fail or Skip) In .xls file after test case execution.

It will use Log4j - Apache Logging Services to generate execution log In applog.log file.
Easy to maintain software web application's web page elements as It will use object repository to fetch web page element.
Easy to understand, maintain and integrate with any software web application's test process.

Note:
------
Apache POI is the most commonly used API for Selenium data driven tests. POI is a set of library files that gives an API to
manipulate Microsoft documents like .xls and .xlsx. It lets you create, modify, read and write data into Excel.
http://www.guru99.com/all-about-excel-in-selenium-poi-jxl.html

* Selenium Automation Framework Example
http://www.seleniumeasy.com/selenium-tutorials/selenium-automation-framework-example

Benefits of using automated testing are the following:
Reduction of tests’ time execution and human resources required
Complete control over the tests’ results (“actual results” vs “expected results”)
Possibility to quickly change test’s preconditions and input data, and re-run the tests dynamically with multiple sets of data
Automation workflow for the application can be presented as follows:

First of all it is required to identify tasks that an application has to accomplish.
Second, a set of necessary input data has to be created.
Third, expected results have to be defined in order one can judge that an application (a requested feature) works correspondingly.
Fourth, Executes a test.
Finally, Compares expected results with actual results, and decides whether the test has been passed successfully.
Environment Specifications:

Selenium Webdriver (Supports all major browsers, we use Mozilla, chrome and IE)
Eclipse IDE
Java
TestNG
AutoIT Tool (Used to handle Windows popups for Document Uploads and Downloads.)
JExcel or Apache POI to perform operations with excel like read, write and update the excel sheet

This Framework has the following tools:
1. Selenium - Selenium is a well know open source testing framework, which is widely used for testing Web-based applications.
It has different components and in that Webdriver has rendered the Selenium Remote Control obsolete, and is commonly referred
to as Selenium 2.0.

Selenium Webdriver supports most of all browsers to run your test cases and many programming languages like C#, Java, Python, Ruby,
.Net, Perl, PHP, etc.. to create and modify your test scripts.

2. Eclipse IDE: Eclipse is an integrated development environment (IDE) for Java. The Eclipse IDE is the most known product of
the Eclipse Open Source project.

3. TestNG - Is a testing framework inspired from JUnit and NUnit. It has extended new functionalities which made it more powerful
and easier than the other testing frameworks.

It supports ReportNG (simple HTML reporting plug-in) and XLST (Graphical / Pictorial reports) plug-ins to customize or extend the
default TestNG reporting style.

TestNG also provides ability to implement 'IReporter' an interface which can be implemented to generate a Customized TestNG report
by users. It has 'generateReport()' method which will be invoked after all the suite has completed its execution and gives the report
into the specified output directory.

4. AutoIT - AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting.
It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks which is
not possible with selenium.

You can also refer the other frameworks available here Keyword Driven Framework and Page Object Model Framework

File Formats Used in the Framework:

Properties file – We use properties file to store and retrieve the UI elements of an application or a website and data set file paths.
It contains id of the elements, name, xpath or Css selector etc.

Excel files – Excel files are used to pass multiple sets of data to the application.
Xml file – Is used to execute the test scripts. Based on the package or classes or Tests mentioned in the xml file scripts will be executed.
The following figure explains physical structure of files required for Test Automation Framework

Project Structure

The Project Folder Structure: All the basic required folders are created with the sub folders and classes under each folder:--

Automation Project Folder structure

The Following explains the structure in detail:-

1. UI Map / Object Repository

UIMap is a concept for defining, storing, and serving UI elements of an application or a website. The UIMap properties file contains a
set of ‘key-value’ pairs, where key is an alias of the UI element, and a value is the locator. Click here for more..

2. Data Set / Test Data

Data set stores the data files, Script reads test data from external data sources and executes test based on it. Data sets increases test
coverage by performing testing with various inputs and reduce the number of overall test scripts needed to implement all the test cases.
Click here for more..

3. Test Automation Scripts

A test is considered as a single action or a sequence of actions, that defines whether a specific feature meets functional requirements.
It has multiple test files / packages / class files which will be executed based on the configurations defined in testng.xml. Click here
for more..

4. Reports / Executed Results

Test report/results is a document which contains summary of test activities. After execution is completed, it is very important to
communicate the test results and findings to the project manager along with the screenshots for failed tests and with that decisions
can be made for the release. Click here for More..

5. TestNG xml file

In order to create a test suite and run separate test cases, we need framework which drives the automation. Here testng.xml can be called
as "driver" which drives several test cases automated using selenium code. Advantage of using TestNG with Selenium is of running multiple
test cases from multiple classes using xml configuration file

* Page Object Model Framework -
http://www.seleniumeasy.com/selenium-tutorials/page-object-model-framework-introduction

Page Object Model (POM) & Page Factory in Selenium: Ultimate Guide
http://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html

Why POM ?
Starting a UI Automation in Selenium WebDriver is NOT a tough task. You just need to find elements, perform operations on it .

Consider this simple script to login into a website

--------------------------------
Selenium :-
* http://www.softwaretestinghelp.com/selenium-tutorial-1/
UDEMY :
* https://www.udemy.com/selenium-webdriver-with-java-testng-and-log4j/learn/v4/overview
aeiouMyUdemy2016123


* What is Fluent wait and how it is different from implicit wait and explicit wait?
ANSWER:

* Thread.sleep(2000);

Implicit wait:
Implicit wait tells web driver to wait on every instance when try to find element. It is like global wait for all driver.
findelement instance. It will <<force web driver to wait until >> element is appeared on page or defined time whatever is
earliest. Drawback is it throws exception when element is not loaded on page even in defined time span.


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

Explicit wait: Explicit wait is of two types:
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));

1) WebDriverWait
2) FluentWait
both are classes and implements Wait interface.

WebDriverWait is applied on certain element with defined expected condition and time. This wait is only applied to the specified element.
This wait can also throw exception when element is not found.

WebDriverWait wait = new WebDriverWait (driver, 20);
wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(""//button[@value='Save Changes']"")));

Fluent wait:
Fluent wait is another type of Explicit wait and you can define polling ( Interval it try) and ignore the exception to continue with
script execution in case element is not found.

new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS).pollingevery(10, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Wait wait = new FluentWait(driver)

    .withTimeout(30, SECONDS)

    .pollingEvery(5, SECONDS)

    .ignoring(NoSuchElementException.class);


* What is Absolute and relative path?
ANSWER:

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Always Relative Xpaths are preferred as they are not the complete paths from the Root element. (//html//body) ..
Beacuse in future any of the webelement when added/Removed then Absolute Xpath changes. So Always use Relative Xpaths in your Automation.


// Absolute Path starts from root path, Relative Path starts from current path
//Selenium WebDriver - Absolute and Relative Path Examples
//Example Absolute and Relative Paths for Selenium WebDriver

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class AbsoluteRelativePaths {

@Test
public void absolutePath() throws InterruptedException {

System.setProperty("webdriver.chrome.driver", "E:\\Selenium\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.get("E:\\Selenium\\absolute.html");

  // Absolute Path starts from root path
  WebElement link1 = driver.findElement(By.xpath("/html/body/li[@id='test']/a"));

  // Relative Path starts from current path
  WebElement link2 = driver.findElement(By.xpath(".//*[@id='test']/a"));

  driver.quit();

}

}

* How to scroll the scroll ball in window with selenium - Java script
ANSWER:
EventFiringWebDriver eventFiringWebDriver = newEventFiringWebDriver(webDriver);
eventFiringWebDriver.executeScript("scroll(0,4000)",args);

* How will you handle dynamic object - runtime objects in Selenium,
we can do through ID's, index and other CSS locators
ANSWER:Xpath
http://www.testerlogic.com/handling-dynamic-elements-in-selenium-webdriver/
Code :
// Dynamic Element Locators
<button id="Submit-901" />
<button id="Submit-902" />
<button id="Submit-903" />

1. Absolute XPath
web_element_name=html/body/div[30]/div[2]/div[2]/div/div/div/div[1]/table/tbody/tr/td[2]/table/tbody/tr/td[1]/table/tbody/tr/td[1]/table/tbody/tr[2]/td[2]/em/button
//p[6]/label[2]/div/ins

2. Identify Element by starting Text
XPath: //button[starts-with(@id, 'Submit-')]

3. Identify Element by containing Text
<input class="new-userfield-001">
<input class="old-userfield-002">
XPath: //input[contains(@class, '-userfield-')].

4. Identify Element by Index
driver.findElements(By.xpath(“//*submit”)).get(0).click();

5. Identify Element with reference of a closest stable element
XPATH: //span1/../following-sibling::div//button1

6. Identify Element by stable preceding Text
//label2/following::input


* Exception handling can be done through try catch

* Window popups are handled through Robot scripting in selenium
  http://www.softwaretestinghelp.com/handle-alerts-popups-selenium-webdriver-selenium-tutorial-16/
  There are two types of alerts that we would be focusing on majorly:
   1.Windows based alert pop ups
   2.Web based alert pop ups

* http://www.softwaretestinghelp.com/selenium-select-class-selenium-tutorial-13/

* Java :-
Download and install - Java SE Development Kid ( JDK 8.0)
http://www.javatpoint.com/corejava-interview-questions
At command prompt
Check for JDK
javac -version

C:\Users\acerpraveen>javac -version
javac 1.8.0_112

If error: Set the JDK path : -
C:\Program Files\Java\jdk1.8.0_112\bin
Type Env and go the environment variables and do the settings;
Control Panel\System and Security\System - ( Edit environment variable - path)

For JRE :-
C:\Users\acerpraveen>java -version
java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b15, mixed mode)

<<<<Eclipse IDE for Java Developer>>>>
https://www.udemy.com/selenium-webdriver-with-java-testng-and-log4j/learn/v4/t/lecture/1344972
https://eclipse.org/downloads/

* FAQ
ANSWER:

Could you please share your thought about the below interview questions.

1: If you were unable to automate a test because you could not find a selector for an element, what would you do?
Ans.> 1. This reason is almost not possible. There are many ways to find an element and we can find almost every element
using one or the other way. If the interviewer still insist on this question, then the best you would do is,
simply contact the developers and collaborate with them to add a unique attribute like "id" to it and then you
can use it to find an element.
I think the interviewer just wants to see if you can collaborate with developers to make automation smart.

Ans.> 1. - Look for alternate navigation paths to achieve same functionality
- see if API tests can cover the required acceptance criteria
- collaborate with developers (as Anil mentioned)
- switch to manual ( last option - but sometimes questions are tricky and answer could be a simple one)

Ans.> 1. I would not suggest the 1.a Look for alternate navigation paths.
The reason is all paths should be tested and automated. It is easily possible that one path works and other might not work.
It is a good idea to see if API tests cover that functionality but again the break can happen between GUI and API connection.
It depends on how important the functionality is from GUI stand point.

If it is not very important then we can rely on API tests, but if it is important to test a particular feature from GUI
then we must find a way to test and automate it.

2: What process do you go through before writing an automated test suite?
Ans.> 2. You first need to execute the test cases manually, so that you understand the flow and then cover
all the scenarios. This will help you in automating and not miss small details.

3: When you have a fairly straightforward story you need to write acceptance criteria for (or a test script), what
approach would you take to ensure that you have covered every possible angle which could produce evidence of a bug?
Ans.> 3. Again, you need to cover all the scenario, execute the story manually and cover all the scenarios.
This will help you in designing better automation suite.

* Release Testing
ANSWER:
After build release some of the companies do engineering prequal before giving the build to qa there are different terms like,
BVT, BFT, smoke test, We call it as RFB.

CUSTOMER SERVICE   Service Requests  Generate Debit Card PIN

* How to selecet the application for testing?
----------------------------------------------
ANSWER:

https://www.tutorialspoint.com/qtp/qtp_test_automation_process.htm
Answer:
Automated Testing Process:
For any automated tool implementation, the following are the phases/stages of it. Each one of the stages corresponds to a particular activity
and each phase has a definite outcome.

 1. Test Automation Feasibility Analysis - First step is to check if the application can be automated or not. Not all applications can be
automated due to its limitations.

 2. Appropriate Tool Selection - The Next most important step is the selection of tools. It depends on the technology in which the
application is built, its features and usage.

 3. Evaluate the suitable framework - Upon selecting the tool the next activity is to select a suitable framework. There are various kinds
 of frameworks and each framework has its own significance. We will deal with frameworks in detail later this chapter.

 4. Build the Proof of Concept - Proof of Concept(POC) is developed with an end to end scenario to evaluate if the tool can support the
automation of the application. As it is performed with an end to end scenario which will ensure that the major functionalities can be
automated.

 5. Develop Automation Framework - After building the POC, framework development is carried out, which is a crucial step for the success of
any test automation project. Framework should be build after diligent analysis of the technology used by the application and also its key
features.

 6. Develop Test Script, Execute and Analyze - Once Script development is completed, the scripts are executed, results are analyzed
and defects are logged, if any. The Test Scripts are usually version controlled.


FAQ.
* What is this? Is it in TestNG
What is the threadpoolsize and invocation count?
ANSWER
@Test(threadPoolSize = 2, invocationCount = 10)
The method will be run a total of 10 times using 2 threads

For example, we are trying to run 100 threads with invocation count set to 1000 (10 times the thread count) in order to simulate 100
simultaneous users.

Suppose there are 2 thread a and b. each thread ll run 10 times?

And if there are 5 threads and the code remains same "@Test(threadPoolSize = 2, invocationCount = 10)". what would happen?

* Selenium Page Object Model framework Video-1
https://www.youtube.com/watch?v=xQXGuWacdQE&index=2&list=PL5NG-eEzvTth6B0bvVRDcU8Wa8Z-_oiDI

* Reporting:-
-------------
Testng and Junit are the framework; used for reproting.No goog reporting
Junit we do unit testing, extensive support for Qa testing
Log4j configure xml file is used fr the results convertion & Xtent reporting is the jar file used for detail reporting with chart.

* How to scroll the scroll ball in window with selenium - Java script
EventFiringWebDriver eventFiringWebDriver = newEventFiringWebDriver(webDriver);
eventFiringWebDriver.executeScript("scroll(0,4000)",args);

* How will you handle dynamic object - runtime objects in Selenium, we can do through ID's, index and other CSS locators
* Exception handling can be done through try catch
* Window popups are handled through Robot scripting in selenium
  http://www.softwaretestinghelp.com/handle-alerts-popups-selenium-webdriver-selenium-tutorial-16/
  There are two types of alerts that we would be focusing on majorly:
   1.Windows based alert pop ups
   2.Web based alert pop ups

* http://www.softwaretestinghelp.com/selenium-select-class-selenium-tutorial-13/


* Headless browser Testing using Selenium
http://learn-automation.com/headless-browser-testing-using-selenium-htmlunitdriver/

* TCS - Upcasting and downcasting in Java
http://javainsimpleway.com/upcasting-and-downcasting-in-java/

Casting : taking an object of one type and assigning it to reference variable of another type.

Upcasting : Object of child class is assigned to reference varibale of parent type.

Ex: class A{}
class B extend A{}

A a1 = new B();
this operation is a upcasting. and it happens automatically.no need to do anything explicitly.

package com.kb.casting;

class Parent{
    int x=10;
    void show(){
        System.out.println("parent-show");
    }
 
    void OnlyParentShow(){
        System.out.println("OnlyParentShow");
    }
}

class Child extends Parent{
    int x=20;
    void show(){
        System.out.println("child-show");
    }
    void OnlyChildShow(){
        System.out.println("OnlyChildShow");
    }
}

public class ParentChild {

    public static void main(String[] args) {
        Parent p = new Child();
        p.show();
        p.OnlyParentShow();
        System.out.println(p.x);
    }
}
Output is
---------
child-show
OnlyParentShow

show() is a method and overridden in child so child’s method is called.
OnlyParentShow() is a method not overridden but inherited to child and called as it is.

* Multiple buttons with same type and id (3 Button) - Dynamic
Normal code : <input type="submit" id="button" value="Edit"/>
Code 1. selenium.click("xpath=//input[1][@id='button' and @value='Edit']"); i have tried this is not working.
Code 2. selenium.click("//input[@id='button' and @value='Edit'][1]");
Code 3.
String cssSelectorOfSameElements="input[type='submit'][id='button']";
 List<WebElement> a=driver.findElements(By.cssSelector(cssSelectorOfSameElements)) ;
 a.get(0).click();
//a.get(1).click();
//a.get(2).click();

* Sendkey() Replacement\ Alternate
Code - Way default \ 0
public void loginTestCase() {
      driver.navigate().to(URL);
      driver.findElement(By.name("signIn")).click();
      driver.findElement(By.id("username")).sendKeys("testuser");
      driver.findElement(By.id("password")).sendKeys("testpassword");
      driver.findElement(By.name("loginbtn")).click();

Ex2:
System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-2.35.0\\chromedriver_win32_2.2\\chromedriver.exe");

         WebDriver driver = new ChromeDriver();
         driver.get("http://www.google.com");
         WebElement element = driver.findElement(By.name("q"));
         element.sendKeys("Cheese!");
         element.submit();

* Code - Way 1 to Execute Script
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
myExecutor.executeScript("document.getElementsByName('q')[0].value='Kirtesh'", searchbox);
driver.quit();

* Code - Way 2 to Execute Script
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement searchbox = driver.findElement(By.xpath("//input[@name='q']"));
JavascriptExecutor myExecutor = ((JavascriptExecutor) driver);
myExecutor.executeScript("arguments[0].value='Kirtesh';", searchbox);
driver.quit();

* When does finally block execute? ( try.... catch...)
Yes, it will. No matter what happens in your try or catch block unless otherwise System.exit()
called or JVM crashed. if there is any return statement in the block(s),finally will be
executed prior to that return statement. finally block execute always, no matter exception
object occur or not.

* What is Page Facotry?
Page Object Model is an Object repository design pattern in Selenium WebDriver. POM creates our
testing code maintainable, reusable. Page Factory is an optimized way to create object
repository in POM concept.
http://www.guru99.com/page-object-model-pom-page-factory-in-selenium-ultimate-guide.html

* What is Data Provider?
TestNG Data Providers. When you need to pass complex parameters or parameters that need to be
created from Java (complex objects, objects read from a property file or a database, etc…), in
such cases parameters can be passed using Dataproviders. A Data Provider is a method annotated
with @DataProvider.

* Parameterization using XML and DataProviders: Selenium
As we create software we always wish it should work differently with a different set of data.
When it comes to testing the same piece of software, we can't be unfair to test it with just
one set of data. Here again, we need to verify that our system is taking all set of combinations
which it expected to support.

Type of Parameterization in TestNG-
To make parameterization more clear, we will go through the parameterization options in one the
most popular framework for Selenium Webdriver - TestNG.

There are two ways by which we can achieve parameterization in TestNG

1. With the help of Parameters annotation and TestNG XML file.
                      @Parameters({"name","searchKey"})

2. With the help of DataProvider annotation.
                      @DataProvider(name="SearchProvider")


* Sikuli is user to test Adope / Compare Images. ( Instead of Selenium validations)

-------------------------------------------------------------------------------------------------------------------------------------
Selenium with java course



Check the Maven and GITs add ins \ already install software in Eclipse IDE \ Help\install new s/w.



Session 1:
* Java :-

Download and install - Java SE Development Kid ( JDK 8.0)

http://www.javatpoint.com/corejava-interview-questions

At command prompt

Check for JDK
javac -version

C:\Users\acerpraveen>javac -version
javac 1.8.0_112

If error: Set the JDK path : -

C:\Program Files\Java\jdk1.8.0_112\bin

Type Env and go the environment variables and do the settings;

Control Panel\System and Security\System - ( Edit environment variable - path)

For JRE :-
C:\Users\acerpraveen>java -version

java version "1.8.0_112"

Java(TM) SE Run time Environment (build 1.8.0_112-b15)

Java HotSpot(TM) 64-Bit Server VM (build 25.112-b15, mixed mode)

<<<<Eclipse IDE for Java Developer>>>>
https://www.udemy.com/selenium-webdriver-with-java-testng-and-log4j/learn/v4/t/lecture/1344972

Session 2:
https://eclipse.org/downloads/

Selenium IDE ( For Firefox )


How to do record and play back and SLOW the Script execution :



Selenium IDE Record and play back:


How to access the Selenium IDE:


Selenium IDE - Setup as Add-On to Mozilla Firefox

Fire bug and fire path installation:


Install fire path:


Installing Maven : ( Build automation Tool )
Session 2 -14


Go to Install new software in Eclipse:-

http://download.eclipse.org/technology/m2e/releases

org.openqa.selenium download at google.com





Session 2 – 15.
Hello world


  1. Setup Eclipse IDE – https://eclipse.org/downloads
  2. * 5. selenium web driver configuration with eclipse – http://docs.seleniumhq.org/download

Configure Build path:







Selenium is the compilation of each jar files and each has seperate packages.

Sample Java Code:
Download Code driver :
Driver code:
package BestPck;

import org.openqa.selenium.*;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class FB {
public static void main(String[] args) throws InterruptedException {
// System.setProperty("webdriver.chrome.driver", "C:/Selenium Trainig/chromedriver_win32/chromedriver.exe");
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
InternetExplorerDriver driver = new InternetExplorerDriver();

// WebDriver driver = new ChromeDriver();
driver.get("http://facebook.com/login/");
driver.manage().window().maximize();
driver.findElement(By.name("email")).sendKeys("myemail@yahoo.com");
driver.findElement(By.name("pass")).sendKeys("myPassword");
driver.findElement(By.id("loginbutton")).click();
driver.findElement(By.name("mercurymessages")).click();
driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();
// This has worked randomly. Sometimes the driver will work and open the chat box. Sometimes it will say element not found. I didn't include the full link of the conversation because apparently you don't have to. And it has worked like this in the past.
}
}
Variables and Data Type:
Session 2 – 16.
8 primitive data type & String is one reference type.

package bestpk;

//8 primitive data type

public class VariableTypes {
int myglobalint =100;
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* Byte
* Min: -128
* Max: 127
* Default : 0
*/
byte mybyte =100;
System.out.println("Byte Value : "+mybyte);
/*
* Short
* Min: -32.768
* Max: 32.767
* Default : 0
*/
short myshort =10000;
System.out.println("Short Value : "+myshort);
/*
* Int
* Min: -2,347,483,648
* Max: 2,347,483,647
* Default : 0
*/
int myint =1000000;
System.out.println("Int Value : "+myint);

/*
* Long
* Min: -2^63
* Max: 2^63-1
* Default : 0
*/
long mylong =1000000000;
System.out.println("Long Value : "+mylong);
/*
* Float
* Default : 0.0f
*/
float myfloat =02.0f;
System.out.println("Float Value : "+myfloat);

/*
* Double
* Default : 0.0d
*/
double mydouble = 21.0;
System.out.println("Double Value : "+mydouble);
/*
* Boolean
* false and true
* Default : false
*/
boolean myboolean = true;
System.out.println("Boolean Value : "+myboolean);

/*
* char
* Min :0
* Min : 65,535
*/
char mychar = 'S';
System.out.println("Char Value : "+mychar);
}
public void test(){
myglobalint =101;
}
}

OUTPUT:
Byte Value : 100
Short Value : 10000
Int Value : 1000000
Long Value : 1000000000
Float Value : 2.0
Double Value : 21.0
Boolean Value : true
Char Value : S
* Reference data type – String example
String methods – Part 3 – Session 17
package bestpk;

public class BestClassPlusStringDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello This is the BEST");
//String Literal - string constant pool
String str1 = "Hello 1";
String str3 = "Hello 3";
System.out.println("String Literal - string constant pool "+ str1 );

//String Object - Heap
String str2 = new String("Welcome 2");
String str4 = new String("Welcome 4");
System.out.println("String Object - Heap "+ str2 );

//Strings
str1 = "More Hello";
String stradd1 = str1+str2;
System.out.println("String Addition : "+ stradd1 );


String stradd2 = str3+" " +str4;
System.out.println("String Addition : "+ stradd2 );

}

}
OUTPUT:
Hello This is the BEST
String Literal - string constant pool Hello 1
String Object - Heap Welcome 2
String Addition : More HelloWelcome 2
String Addition : Hello 3 Welcome 4
SAMPLE CODE :
package bestpk;
public class BestCallingMethodsInSameClass {

public static void main(String[] args) {
// TODO Auto-generated method stub
printOne();
printOne();
printTwo();
}
public static void printOne() {
System.out.println("HI This is the BEST - HELLO");
}

public static void printTwo() {
printOne();
printOne();
}

}
OUTPUT :
HI This is the BEST - HELLO
HI This is the BEST - HELLO
HI This is the BEST - HELLO
HI This is the BEST – HELLO
Palindrome program :
SAMPLE CODE:
import java.util.*;
 
class Palindrome
{
   public static void main(String args[])
   {
      String original, reverse = "";

      Scanner in = new Scanner(System.in); 
      System.out.println("Enter a string to check if it is a palindrome");

      original = in.nextLine();
 
      int length = original.length();
 
      for ( int i = length - 1; i >= 0; i-- )

         reverse = reverse + original.charAt(i);

       if (original.equals(reverse))
         System.out.println("Entered string is a palindrome.");
 
     else
         System.out.println("Entered string is not a palindrome.");
 
   }
}
OUTPUT
Malayalam
AMMA
ANNA
Entered string is a palindrome.
* String Demo :
String methods – Part 3 – Session 18

FAQ


Code for Gmail:
---------------------
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

import org.openqa.selenium.firefox.*;

import java.util.concurrent.*;
public class myclass {
public static void main(String[] args) {

//initialize Chrome driver

System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-

2.35.0\\chromedriver_win32_2.2\\chromedriver.exe");



WebDriver driver = new ChromeDriver();
//Open gmail

driver.get("http://www.gmail.com");
// Enter userd id

WebElement element = driver.findElement(By.id("Email"));

element.sendKeys("xyz@gmail.com");

//wait 5 secs for userid to be entered

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

//Enter Password

WebElement element1 = driver.findElement(By.id("Passwd"));

element1.sendKeys("Password");

//Submit button
element.submit();

WebElement myDynamicElement = (new WebDriverWait(driver, 

15)).until(ExpectedConditions.presenceOfElementLocated(By.id("gbg4")));

driver.findElement(By.id("gbg4")).click();

//press signout button

driver.findElement(By.id("gb_71")).click();

}
}

--------------------------------------------------------------------------------------------------------------------------------

"DA-RUM" "DUM-DUM"
https://www.hackerrank.com/challenges/30-hello-world
Day1:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
public static void main(String[] args) {
        // Create a Scanner object to read input from stdin.
Scanner scan = new Scanner(System.in); 
// Read a full line of input from stdin and save it to our variable, inputString.
String inputString = scan.nextLine(); 

// Close the scanner object, because we've finished reading 
        // all of the input from stdin needed for this challenge.
scan.close(); 
      
// Print a string literal saying "Hello, World." to stdout.
        //System.out.println("Welcome to 30 Days of Code!");
        System.out.println("Hello, World.");
        System.out.print(inputString);

   // TODO: Write a line of code here that prints the contents of inputString to stdout.
}
}

OUTPUT:
-------
Input (stdin)
Welcome to 30 Days of Code!
Your Output (stdout)
Hello, World.
Welcome to 30 Days of Code!
Expected Output
Hello, World.
Welcome to 30 Days of Code!

Code Reference :- https://codearvilyn.wordpress.com/2016/04/14/hacker-rank-day-0-hello-world/

----------------
Day 1:
mport java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        int i = 4;

        double d = 4.0;

        String s = "HackerRank ";
        Scanner scan = new Scanner(System.in);
/* Declare second integer, double, and String variables. */

      int myInt = 0;

      double myDouble = 0.0;

      String myString = "";

      /* Read and save an integer, double, and String to your variables.*/

      myInt = scan.nextInt();

      myDouble = scan.nextDouble();

      scan.nextLine();

      myString = scan.nextLine();

      /* Print the sum of both integer variables on a new line. */

      System.out.println(i + myInt);

      /* Print the sum of the double variables on a new line. */

      System.out.println(d + myDouble);

      /* Concatenate and print the String variables on a new line; 

      the ‘s’ variable above should be printed first. */

      System.out.print(s + myString);
scan.close();
    }
}

OUTPUT:
-------
Input (stdin)
12
4.0
is the best place to learn and practice coding!
Your Output (stdout)
16
8.0
HackerRank is the best place to learn and practice coding!
Expected Output
16
8.0
HackerRank is the best place to learn and practice coding!
      
Day2:
-----

public class Arithmetic {

    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);

        double mealCost = scan.nextDouble(); // original meal price


        int tipPercent = scan.nextInt(); // tip percentage

        int taxPercent = scan.nextInt(); // tax percentage

        scan.close();

        // Write your calculation code here.

        double tip = mealCost * tipPercent/100;

        double tax = mealCost * taxPercent/100;

        double cost = mealCost + tip + tax;

        // cast the result of the rounding operation to an int and save it as totalCost

        int totalCost = (int) Math.round(cost);

        // Print your result
        System.out.println("The total meal cost is " + totalCost + " dollars.");
      
    }
}

*OUTPUT:
-------

Input (stdin)

12.00

20

8

Your Output (stdout)

The total meal cost is 15 dollars.

Expected Output

The total meal cost is 15 dollars.



----------------------


Summary - Locator Usage:-


-------------------------

By ID                        id= id_of_the_element                                id=email

By Name                        name=name_of_the_element                        name=username

By Name Using Filters        name=name_of_the_element filter=value_of_filter
\
name=tripType value=oneway


 Link Text link=link_text link=REGISTER

Tag and ID css=tag#id css=input#email


Tag and Class css=tag.class css=input.inputtext


Tag and Attribute css=tag[attribute=value] css=input[name=lastName]

Tag, Class, and Attribute css=tag.class[attribute=value]

css=input.inputtext[tabindex=1]




Locators tell Selenium IDE which GUI elements ( say Text Box, Buttons, Check Boxes etc) its needs

to operate on.

I dentification of correct GUI elements is a prerequisite to create an automation script. But accurate

identification of

 GUI elements is more difficult than it sounds. Sometimes, you end up working with incorrect GUI

elements or no elements at all!

Hence, Selenium provides a number of Locators to precisely locate a GUI element





The different types of locator are:

 ID

 Name

 Link Text

 CSS Selector


  Tag and ID

  Tag and class

  Tag and attribute

 Tag, class, and attribute


 Inner text


  DOM (Document Object Model)

  getElementById


  getElementsByName

  dom:name


  dom: index


 XPath

Close VS Quit :

---------------

webDriver.Close() - Close the browser window that the driver has focus of

webDriver.Quit() - Calls Dispose()

webDriver.Dispose() Closes all browser windows and safely ends the session


The code below will dispose the driver object, ends the session and closes all browsers opened

during

a test whether the test fails or passes.



----------------


public IWebDriver Driver;



[SetUp]

public void SetupTest()

{

    Driver = WebDriverFactory.GetDriver();
\}



[TearDown]

public void TearDown()

{

    if (Driver != null)

      Driver.Quit();

}

In summary ensure that Quit() or Dispose() is called before exiting the program, and don't use the

Close() method unless you're sure of what you're doing.



-------------------


* Windows Alert
-----------------

Sample 1:
----------
import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.NoAlertPresentException;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class Alert_Demo {
       
        public static void main(String[] args) throws NoAlertPresentException {
            WebDriver driver = new FirefoxDriver();
           
            // Alert Message handling
                       
            driver.get("http://demo.guru99.com/V4/");
                               

            driver.findElement(By.name("uid")).sendKeys("mngr30127");

            driver.findElement(By.name("password")).sendKeys("EzAtAqy");

            driver.findElement(By.name("btnLogin")).submit();

            driver.findElement(By.linkText("Delete Customer")).click();

            driver.findElement(By.name("cusid")).sendKeys("53920");

            driver.findElement(By.name("AccSubmit")).submit();

           

                // Switching to Alert      

            Alert alert=driver.switchTo().alert();

           

            // Capturing alert message.  

            String alertMessage=driver.switchTo().alert().getText();

           


            // Displaying alert message

            System.out.println(alertMessage);

           

            // Accepting alert

            alert.accept();

               
        }
}



Sample2:


--------



Handling web based pop-up box


WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface.



There are the four methods that we would be using along with the Alert interface.



1) void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window



appears.

2) void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window

appears.


3) String getText() – The getText() method returns the text displayed on the alert box.




4) void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern

into the alert box.



Scenario to be automated



Launch the web browser and open the webpage

Click on the “Try it” button

Accept the alert

Click on the “Try it” button again

Reject the alert

WebDriver Code using Select Class




Please take a note that for script creation, we would be using “Learning_Selenium” project created in

the former tutorial.



Step 1: Create a new java class named as “DemoWebAlert” under the “Learning_Selenium” project.

Step 2: Copy and paste the below code in the “DemoWebAlert.java” class.



Below is the test script that is equivalent to the above mentioned scenario.



1

import org.junit.After;

2

import org.junit.Before;


3

import org.junit.Test;

4

import org.openqa.selenium.Alert;

5

import org.openqa.selenium.By;

6

import org.openqa.selenium.WebDriver;

7


import org.openqa.selenium.firefox.FirefoxDriver;

8

9
/**
10

* class description

11
*/
12

13

public class DemoWebAlert {

14

                WebDriver driver;
15
                /**
16
                * Constructor
17
                */
18
                public DemoWebAlert() {                          
19
                }
20

21
                /**
22
                * Set up browser settings and open the application
23
                */
24

25
                @Before
26
                public void setUp() {
27
                                driver=new FirefoxDriver();
28
                                // Opened the application
29
                                driver.get("file:///F:/Work/Selenium/Testing-Presentation/DemoWebPopup.htm");
30
                                driver.manage().window().maximize();
31
                }
32

33
                /**
34
                * Test to check Select functionality
35
                * @throws InterruptedException
36
                */
37

38
                @Test
39
             
                                public void testWebAlert() throws InterruptedException {                        
40
                             
                                // clicking on try it button
41
                             
                                 driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
42
                               
                                 Thread.sleep(5000);
43

44
                                // accepting javascript alert
45
                                Alert alert = driver.switchTo().alert();
46
                                alert.accept();
47

48
                                // clicking on try it button
49
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
50
                                Thread.sleep(5000);
51

52
                                // accepting javascript alert
53
                                driver.switchTo().alert().dismiss();
54

55
                                // clicking on try it button
56
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
57
                                Thread.sleep(5000);
58

59
                                // accepting javascript alert
60
                                System.out.println(driver.switchTo().alert().getText());
61
                                driver.switchTo().alert().accept();
62
                }
63

64
                /**
65
                * Tear down the setup after test completes
66
                */
67

68
                @After
69
                public void tearDown() {          
70
                    driver.quit();
71
                }
72
         }




-----------------


Take the screenshot
-------------------

Sample 1 :

----------


WebDriver driver = new FirefoxDriver();


driver.get("http://www.google.com/");



File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);



// Now you can do whatever you need to do with it, for example copy somewhere

FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));





Sample 2: with try catch

-------------------------

public void TestJavaS1()

{

// Open Firefox


 WebDriver driver=new FirefoxDriver();




// Maximize the window


driver.manage().window().maximize();



// Pass the url


driver.get("http://www.google.com");



// Take screenshot and store as a file format



File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);



try {



 // now copy the  screenshot to desired location using copyFile //method



FileUtils.copyFile(src, new File("C:/selenium/error.png"));



}



catch (IOException e)

 {

  System.out.println(e.getMessage());



 }

 }



   
---------------------------------





No comments:

Post a Comment