Monday, April 13, 2020

Interview Questions

How to extract date values in a string
-          How to use Listeners in framework. Ex: in order to insert test results in DB during runtime, what is the best way to do so
-          Tell me about collections
-          What are diff ways of passing parameters in feature file
-          Have you used TestNG, and why do we use it
-          There are date and timestamp(AM and PM format) values in a data table, how do you sort table rows while reading the cells
-          What are the challenges you have faced in project for selenium programming
-          What are mostly used OOPS concepts In your project

Apple interview:
1. Hashmap vs Hashtable
2. How to access or store data from excel employee records to java collections
3. Reflection in java
4. Different status codes  --- 401 unatuth, 403 -- forbidden, 415 - media format not supported
5. Runtime Exceptions vs compile time exceptions   -- file not found is what exception?
6. why main is public, static   -- So that jvm can access it. 
6.1 why main has String args[] parameters --- because when you create jar java application, you could pass parameters when running the jar file ex: java -jar myapplication.jar "a" "b". When you print args[0] and args[1] in main method, you will get a and b respecitively when main method is executed.
7. jar vs war. How to create Jar file, and what it contains. How to say where is main method if you have multiple class files when you create jar files. ...
jar --- is zip of java classes and resources. Java archive. Command used to create (go to the directory where you have java files): > jar -cf name.jar *.java 
7.1 How to use jar file
8. importance of maven  -- command like mvn clean verify
9. Desired capabilities
10. Browser profiling
11.Errors vs Exception  -- Errors caused by other than application-- like outofmemory, stackoverflow etc. Exception is due to application
12. Using Testng we add respective class which we wanted to test. But when we have new classes that are getting added instead of keep adding classes to testng is there a way to run entire suite
13.  mvn clean install vs mvn clean verify
14. What does final mean for a method   --- methods will final keyword cannot be overriden by subclasses
A class with final keyword means it cannot be extended.

role of JavaScript in selenium web automation testing

We use JavaScript to at two places as of now in web automation testing with selenium:

Interface JavaScriptExecutor in java will help to use execute javascript code in selenium

Scenarios where we use JavaScript:

1. To enter value in input field without using .sendkeys  method

2. To use arguments[0].ScrollToView   -- which scrolls to the element on the webpage

public void ScrollclickJS(WebElement we) {
              JavascriptExecutor executor = (JavascriptExecutor) driver.getWebDriver();
              executor.executeScript("arguments[0].scrollIntoView();"we);
              executor.executeScript("arguments[0].click();"we);
       }

Tuesday, October 22, 2019

Testng test report

1. Testng execute the class which has @test annotation before the method
2. Testng test results report will be created as soon as you run any class with annotation @test in it
3. Since we have @test annotation, we need not have main method
4. Once java class is written with @test annotation method run it with by right clicking class file -> select run as testng test. It will run the method and test ng report will be generated based on number of @test methods
5. You could run test suites by creating test ng XML file.
6. Test XML file created manually by selecting java project-> create file-> xml-> name.xml.
7. Once name.xml is created 
5. 

Tuesday, February 5, 2019

Need expertise on

- Eclipse set up and java program exec
- Reading&Undeestanding Eclipse errors and fixing
- Know all about Maven, bitbucket and Pom XML
-

Monday, September 17, 2018

Handle app authenticatication pop up

Scenario:
Authentication pop up comes when ever app URL is hit or navigated through diff pages. Where user has to provide his valid user ID and pwd to proceed . How to handle the pop up as it is window pop up.

Monday, January 8, 2018

Inbuilt Interface for taking Screenshots

Selenium jars have inbuilt interface that could help us take screenshots with less effort.

Sunday, January 7, 2018

Framework - Multiple classes

Framework1: Below mentioned as packages 
- Business Components:
1. Multiple java files in each
- Pages --- xpath and actions

Play with objects and variables

- Do you know we can create variable of type WebElement and WebObject. And we can make use of that variable to do some actions on the elements.

WebElement a;

set a = obj1.findElementByid("ssds");   'check if 'set' could be used or not
a.set "abc"    ' 'a' could be used like alias name for web element

Wednesday, July 26, 2017

F12 Console : Console.log

You could access elements in Console by enter command: Console.log(<element name>) in the console tab(after F12 is hit). Mostly applicable for Chrome Browser.



Scenario: Access calendar using Selenium Webdriver


Generally Calendar elements have common attribute values(no unique values to consider) even if there are more than one in a web page, So it makes these elements too complex to access and work on them.

So here we use siblings in the xpath. Means we go to the previou or next sibling of this item and create xpath for that item. Once we are able to access that element, write sibling to the xpath to access calendar element.

Testing website: https://www.goibibo.com

code:
<a href="/accounting.html">yyy</a>
<h4>zzz</h4>



<h4>  could be accessed using below code:


"//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4"

Tuesday, July 18, 2017

Headless Driver

https://www.guru99.com/selenium-with-htmlunit-driver-phantomjs.html


package  htmldriver;
import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.htmlunit.HtmlUnitDriver;  
public class htmlUnitYest {    
  public static void main(String[] args) {
                     // Creating a new instance of the HTML unit driver
                      
                     WebDriver driver = new HtmlUnitDriver();   //could use any browser here
                //And it will not pop browser instead it will run in the background. so majorly HtmlUnitDriver is used for Load Testing.      
                  // Navigate to Google  
                     driver.get("http://www.google.com");     
          
      // Locate the searchbox using its name  
                     WebElement element = driver.findElement(By.name("q")); 
                     
                    // Enter a search query  
                    element.sendKeys("Guru99"); 
                   
              // Submit the query. Webdriver searches for the form using the text input element automatically  
                    // No need to locate/find the submit button  
                    element.submit();   
                    
              // This code will print the page title  
                    System.out.println("Page title is: " + driver.getTitle());  
                    
                    driver.quit();   
         }  
} 

Tuesday, March 15, 2016

Finding Text among the multiple
tags , that have same attributes around the page.


  • How to locate the element in web page that has common children and no unique attribute to identify.
    • Date: 3/15/2016
    • Ex: <div class="wrapper">Hi I am here</div> <div class ="Wrapper"> Hi I am there </div>.
      • Like this if we have multiple <div> in the page with same attribute class value Wrapper, how will you identify specific text from it. I know you could use [1] or [2].... based on the nth number of <div> tag but sometimes even that one will not work.
    • Have same scenario here:
      • Source: http://stackoverflow.com/questions/36018524/selenium-get-a-text-node-using-xpath-and-use-it-as-a-string-in-java/36020432#36020432
      • I have a section of code like this:
<div id='wrapper'>
  <span>*</span>   
  Question 1
</div>

      • I want to store the Question 1 as a string in Java so when I use the xpath //div/text() to get the text "Question 1." However when I try to print the value, I am getting the error Invalid Selector Exception Xpath //div/text() is: [object Text]. It should be an element.
String text = driver.findElement(By.xpath("//div")).getText();
//returns *Question 1
String text = driver.findElement(By.xpath("//div/text()")).getText();
//returns error

      • How am I supposed to store just the Question 1. I can replace the * once I get it using the first method above but I don't want to do that.
Ex1:


    • This is MSN website, here I would like to find out the text : Todd Palin in intensive care after snowmobile accident. How to find it, looks similar to the above scenario right because even this has code as below:
      • <img alt="In this file photo, former Alaska Gov. Sarah Palin of Alaska, Republican vice pr..." data-src="{&quot;default&quot;:&quot;//img-s-msn-com.akamaized.net/tenant/amp/entityid/BBqu9TY.img?h=75&amp;w=100&amp;m=6&amp;q=60&amp;u=t&amp;o=t&amp;l=f&amp;f=jpg&amp;x=524&amp;y=269&quot;}" src="http://img-s-msn-com.akamaized.net/tenant/amp/entityid/BBqu9TY.img?h=75&amp;w=100&amp;m=6&amp;q=60&amp;u=t&amp;o=t&amp;l=f&amp;f=jpg&amp;x=524&amp;y=269" title="todd palin - Andrew Harrer/Bloomberg News" class =" loaded" data-initial-set="true" width="100">
      • <span class="title">Todd Palin in intensive care after snowmobile accident</span>
      • Solution:
        • I’m not sure I know the best way to do this but this is a way. The issue is that you are looking for specific text within a group of elements that are children of the wrapper DIV. The only thing I can see in the example that you provided is that the text you want is outside of a containing tag. We can use that to our advantage. Basically the approach is to grab the entirety of the text inside wrapper and then loop through all child elements of wrapper removing the text contained within each from the original string. That should leave the text that you want. I have tested the code below using the example you provided.
String wrapperText = driver.findElement(By.id("wrapper")).getText().trim(); // get all the text under wrapper
List<WebElement> children = driver.findElements(By.cssSelector("#wrapper > *")); // get all the child elements of wrapper
for (WebElement child : children)
{
    String subText = child.getText(); // get the text from the child element
    wrapperText = wrapperText.replace(subText, "").trim(); // remove the child text from the wrapper text
}
System.out.println(wrapperText);



Jars and Difference between Selenium standalone server and Selenium-Java-Jar


http://stackoverflow.com/questions/36018648/selenium-standalone-server-and-selenium-java-jar-usage-specifics


The selenium standalone server contains everything i need to run my scripts on local machine or remote machine or Grid. I understand that it has both server side and client side bindings'.
If i use Selenium-Java-Jar, i can run scripts on my local machine. It has only client side bindings'. But again for Remote or grid i would need standalone server separately.
Considering all this why would i need to use Selenium-Java-Jar over selenium standalone server? Does it offer any thing good in terms of speed? What points scores over selenium standalone server for people to use Selenium-Java-Jar? Is it something to do with selenium standalone server supporting RC style scripts whereas Selenium-Java-Jar not supporting the same?



What are the Implementations differences between 'Selenium-server-standalone.jar' and 'Selenium Client & WebDriver'. Following is the link from SeleniumHQ.org website [http://www.seleniumhq.org/download/]..
  1. http://selenium-release.storage.googleapis.com/2.44/selenium-server-standalone-2.44.0.jar
  2. "http://selenium-release.storage.googleapis.com/2.44/selenium-java-2.44.0.zip"
I know first one is Formerly known as Selenium RC and second one is Selenium 2.0(Webdriver). But Is the latest version supporting all the jars in Webdriver in Selenium Server. I have only Selenium Server available, Did all the method's in Selenium Webdriver supports in Selenium Server? likewise, what are the differences between the jars in it?
Selenium WebDriver 2.0 - helps to write scripts for automating browsers..this package provides us with classes & methods to achieve automation. After writing scripts we can run them on LOCAL MACHINE and see automation ourselves. WebDriver projects were merged with selenium RC to overcome the drawbacks of selenium RC making it selenium WebDriver 2.0
Selenium Server: Now once i have my scripts (as mentioned above),To run scripts on REMOTE MACHINES (Test Beds) and NOT ON LOCAL MACHINE we do it using selenium server. So in short Selenium Webdriver works together with Selenium Server..they co-exist to help and not to replace each other.

Why importing Jar files:


To access selenium class functions like getTtile(), getText(), getAlert() or getConfirmation() etc.. we might need to import jar files.
We have library files in Jar fiiles that are embeded and put together so that the person who imports jar files, will be able to use the fuctions in the files direclty. Somelines public class files, If you import you could be able to use the methods(functions) of that class.


Scenario:

If you see that your script is not able to detect the inbuilt functions then it means you have not imported proper jar files( here in selenium we have only two already mentioned above jar files).




Friday, March 11, 2016

Selenium notes




1/11/2015:

Java

-        Child cannot have multiple parents. Means we cannot extend multiple classes, one class can extend only one class.

-        But Implementation could be done on multiple classes. This is called multiple inheritances.

-        Even Eclipse needs to have JDK(Java 1.7) installed and environment variable set before running code in java.

-        For Static methods memory is allocated during initialization. So memory gets allocated only once.

-        Passing parameters while creating object, is to call specific constructor (parameterized)

-        Initialize object – means

-        No limit for number of constructors

-        Local variables

-        Instance variable – memory loaded only when it is called not like static.

Can be declared along with static variables, this are the variables declared without static keyword

-        Class variables – cannot be declared inside methods?

-        Final class – cannot be inherited

Final method – cannot be overloaded

Final variable – cannot change the value of the variable

-        Abstract class -

-        Final abstract cannot be together for a class

-        This – keyword

It will pick up the current object value

-        Initialization and Instantiation ??

-        Super keyword – helps you to access  the methods of super class.

-        Override – is using same method names in parent and child, using the super keyword.

-        Adding jar files and importing packages… how are they different from each other.

Selenium

-        Selenium RC – we have to keep the server open - open the command prompt and run java commands to keep the server running

-        Selenium RC– does not interact with Windows application. Very difficult during windows authentication

-        Why do we need diff drivers while running code on diff browsers??

-        Only one limitation with webdriver is --- necessity of drivers(Server.exe) for all browsers except FireFox

-        Explicitwait – can be applied on web element, this is not for all elements but for a specific element. Like load to a button we use Explicit wait instead of Implicit wait.

Implicit wait - for all the components (exist in selenium IDE). It will wait for a mentioned time whatever be the web element.

 

-        Contains method of xpath is used vastly.

Xpath = “//input[contains(@src,’picture1’)]    ‘looks for word ‘picture1’ in the src property of that element, this helps to avoid using entire xpath

-        Why do we need to have two import statements here as they both talk about same thing:

Import org.openqa.selenium.*;

Import org.openqa.selenium.firefox.FirefoxDriver;

-        Why do we have this kind of object creation:

WebDriver obj1= new FirefoxDriver();

 

Instead of

WebDriver obj1 = new WebDriver(); --- which is wrong

              Solution:

              I don’t know why the above code is wrong, but when I looked at Select and List class, you might    understand.

            

-        Selenium does not detect Desktop applications, in this if any authentication error occurs while automating web application from desktop, then we need to use third party tools to continue or handle the desktop error.

-        Mozilla Firefox 41 does not support Selenium web driver

-        Driverobj.get and Driverobj.navigate.to ---- could be used for the same pupose but navigate has additional benefits like navigate used to navigate from the existing web page to other urls, forward or back the browser.

-        Sendkeys:

… here sendkeys could be used in diff ways 1. Enter value using keyword

.Sendkeys(“srikanth”)

2. Clicking enter or space etc  buttons

.Sendkeys(keys.Enter) – this one clicks enter button

 

-         

 

Xpath: 12/24/2013
-        Selenium 1 and Selenium2
-        Primary reason for selenium being so popular: Driving multiple browsers  and open source
-        We have 4 categories in selenium- Selenium IDE ,Selenium Remote Control(RC)(Selenium 1), Selenium Web Driver(Selenium 2) and Selenium Grid.
-        Selenium 2:
Selenium 1 is in intrusive in nature. If the field is not editable or not unable selenium 1 could not recognize (as it is purely javascript)
-        In case of Selenium 2, the handling each browser, each browser has got its own controls with selenium, this feature was not available in selenium 1.
-        Selenium locators:
-        Firefox = Firebug and IDE.
1.      Use Firebug to get the html code(id or class name of element) and IDE to evaluate whether that id or class belongs to the element in the web page. IF you give id value in the IDA and click find, it will highlight the corresponding element in the webpage.(this is one way to test Element locator)
2.      You can also test from console
-        Chrome= click F12 to see console.
Go to Element. Right click on element and select inspect element.
Click Escape or console. Here we can create query to test. Use this only when you are finding complex elements.
Syntax to test xpath: we use 2 functions:
Function1: $x(“<xpath>”) -> press enter. Ex: $x(“//input[…]”) ---here if you see after press enter, you could see the element html code or else o/p is just [].
Note: xpath is slower than id.
$x is the function to test xpath.
Function2:
-        // -anywhere/somewhere  in Html code (Relative path)
/- direct child
-        IE – IE Developer tool bar. Some applications may only open in IE, so lets use IE Developer tab for the same.
-        Id/name/class might be common across various elements, but xpath is not.  So use xpath as element locator in most of the cases.
-        $x(“//input[@id=’searchinput’][@idname=’search’]”)
-        $x(“//input[starts-with(@id=’searchinput’)]”)
-        $x(“//input[substring(@id.2)=’earchinput’]”)
-        $x(“//input[substring(@id. 2. 5)=’earch’]”)             // begin character length is ‘2’ and end character is ‘5’
-        Avoiding spaces:
$x(“//title[text()=’selenium – Google Search’]”)     //text() is used to get inner text
$x(“//title[normalize-space(text()=’selenium – Google Search’]”)       //if you have space at the beginning.
$x(“//title[normalize-space(text()=’selenium – Google Search’]”)      
-        ‘.’
-        $x(“//title[normalize-space(.)=’selenium – Google Search’]”)      
Here ‘.’ Identifies the present node, so you may not need to write text() always.
-        $x(“//title[contains(@id. ’hin’)]”)      
-        Xpath, we can navigate back, but this is not the case with css. So that is the reason css is faster than xpath.
-         

Timeouts:


-        Pageload Timeout = selenium will wait till page loads.
-        setScriptTimeout =
-        Explicit wait = specif point
-        Implicitwait= global value
-         


 

 

 
-        JavascriptExecutor: Specialized form of webdriver, it will let you to execute any javascript on the page.
-        Sometimes if you are not able to find element  you could use JavascriptExecutor.

 
-        Selenium does not allow you to reuse in existing session
-        Use Selenium discussion forum to get more details on selenium.
-        Work on scenarios: Get the details of more scenarios-
-       

-        Keys. Back Space – is used to provide keyboard keys to the selenium code. ‘Enter’ key.
-        driver.switchto() ---iframes, alerst, popus—we use this.
-        Driver.switchTo().frame.
-        selenium does not distinguish b/w new tab and new window.
-        .getwindowhandles()
-       

-       

 
-        Annotations
 
-        Assert text
 
-        Junit
 
-       

 
-       

 

 
-        Dataprovider – class using which we can get data from excel
-         

Selenium Methods Notes:


-        Selenium RC:

1.      Jason Huggins developed a Javascript library that could drive interactions with the page, allowing him to automatically rerun tests against multiple browsers.

2. Selenium tests can be written in any of following language: Java, C#, Python, Ruby, Perl and PHP

3. Selenium interacts with the UI elements of a web site using JavaScript injection

4. Limitation of Selenium RC

o   Restrictive to do different things due to the security limitations browsers apply to JavaScript (Uses JavaScript based automation engine)

o   Webapps became more and more powerful over time with special features and new browser support

-        WebDriver developed by Simon Stewart works by accessing the OS and passing commands to the browser from the OS. Not constrained by the JavaScript Sandbox as Selenium RC is.

-        To overcome limitation offered by Selenium RC and to support broader range of browsers Selenium RC and WebDriver is merged to form Selenium WebDriver.

-        The downside to Selenium WebDriver is that it requires new implementations for each of the browsers that it works against. This is due to each browser having its own access points with the Operating System.

-        WebDriver ’s goal is to provide a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.

-        WebDriver  supports dynamic web pages where elements of a page may change without the page itself being reloaded

-        WebDriver Scripts can be written in any one of following languages: Java, C#, Perl, Python, Ruby, PHP.

-        Different types of WebDrivers: HtmlUnitDriver, FirefoxDriver , InternetExplorerDriver , ChromeDriver  and SafariDriver

-        WebDrivers available for Mobile testing include: AndriodDriver and IPhoneDriver

Name of driver
OS Supported
Class to instantiate
HtmlUnitDriver
All
org.openqa.selenium.htmlunit.HtmlUnitDriver
FirefoxDriver
All
org.openqa.selenium.firefox.FirefoxDriver
InternetExplorerDriver
Windows
org.openqa.selenium.ie.InternetExplorerDriver
ChromeDriver
All
org.openqa.selenium.chrome.ChromeDriver
SafariDriver
MAC
org.openqa.selenium.safari.SafariDriver

 

Name of driver
OS Supported
Class to instantiate
AndroidDriver
All
org.openqa.selenium.android.AndroidDriver
IPhoneDriver
All
org.openqa.selenium.iphone.IPhoneDriver

 

-        Emulating Specific Browser:

o   Using Browser Version

HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);

 

o   Using Capabilities

        HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);

 

-         WebDriver pros and cons:

Pros:

        Fastest implementation of WebDriver

        A pure Java solution and so it is platform independent.

        Supports JavaScript

Cons:

        It's not graphical, which means that you can't watch what's happening

 

-        FireFoxDriver Instantiation process:

WebDriver  driver = new FirefoxDriver()

This will invoke firefox browser and returns an handle in form of WebDriver  object which is used to interact with the browser.

-        InternetExplorerDriver Instantiation process:

To work with IE, first download IEDriverServer.exe file from

http://code.google.com/p/chromedriver/downloads/list  and keep it is your project resources folder.

Set Webdriver.ie.driver  property

        System.setProperty("Webdriver.ie.driver","src/main/resources/drivers/ie/IEDriverServer.exe")

Ex:

System.setProperty("webdriver.chrome.driver", C:\\Users\\Public\\Jars\\ChromeDriver.exe");

WebDriver driver = new ChromeDriver();

      WebDriver  driver = new InternetExplorerDriver ()

 

-        Test can be executed against emulators and real devices for IPhone and Andorid OS.

IPhoneDriver Instantiation process

To work with Iphone, first do the setup as given in following page: http://code.google.com/p/selenium/wiki/IPhoneDriver.

Instantiate a WebDriver  implementation

  WebDriver  WebDriver  = new IPhoneDriver();

Andorid Instantiation process

To work with Andorid, first do the setup as given in following page: http://code.google.com/p/selenium/wiki/AndroidDriver.

Instantiate a WebDriver  implementation

        WebDriver  WebDriver  = new AndoridDriver();

-        Useful WebDriver Methods:

1.      get:

void get(java.lang.String url)

Load a new web page in the current browser window.

Parameters: url - The URL to load. It is best to use a fully qualified URL

Ex - WebDriver .get(“http://ww.google.com”);

2.      getTitle:

java.lang.String getTitle()

The title of the current page.

Returns: The title of the current page, with leading and trailing whitespace stripped, or null if one is not already set

Ex - WebDriver .getTitle( );

3.      close:

void close()

Close the current window, quitting the browser if it's the last window currently open.

Ex - WebDriver .close();

4.      quit:

void quit()

Quits this driver, closing every associated window.

Ex - WebDriver .quit( );

-        WebDriver – Browser Navigation Methods:

Method
Description
example
back()
Move back a single "item" in the browser's history.
Wedriver.navigate().back();
forward()
Move a single "item" forward in the browser's history.
Wedriver.navigate().forward();
refresh()
Refresh the current page
Wedriver.navigate().refresh();
to(java.lang.String url)
Load a new web page in the current browser window.
Wedriver.navigate().to (“http://www.cognizant.com”);

 

-        WebDriver Methods –  To switch between Windows:

Method
Description
example
java.util.Set<java.lang.String> getWindowHandles()
A set of window handles which can be used to iterate over all open windows.
Wedriver.getWindowHandles();
alert()
Switches to the currently active modal dialog for this particular driver instance.
Wedriver. switchTo().alert();
defaultContent()
Selects either the first frame on the page, or the main document when a page contains iframes.
Wedriver. switchTo() .defaultContent();
window(java.lang.String nameOrHandle)
Switch the focus of future commands for this driver to the window with the given name/handle.
Wedriver. switchTo(). window(“id”);

 

-