Friday 2 August 2019

ElementNotInteractableException



ElementNotInteractableException::
is caused when an element is found, but you can not interact with it. For instance, you may not be able to click or send keys.

There could be several reasons for this:

1. Wait until an element is visible / clickable
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.until(ExpectedConditions.visibilityOf(element));
wait.until(ExpectedConditions.elementToBeClickable(element));

2. Add Implicit wait

what is stale element exception - how to fix it


Stale = left over / old

if an element changes its position and then if you are trying to perform some event on top of it then we get stale element exception.

below are the fixes

wait.until(ExpectedConditions.visiblityofElementToBeClickable(By.id(“id”)))

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("id")));

wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf("table")));

Interview qns on final keyword | java

1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).

2) Java final method
If you make any method as final, you cannot override it.

3)Java final class
If you make any class as final, you cannot extend it.

Q)Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:

Q)Can we initialize blank final variable?
Yes, but only in constructor. For example:

Q)static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.   int cube(final int n){ n = n+2; }

Q)Can we declare a constructor final?
No, because constructor is never inherited.

Thursday 1 August 2019

Print your name 10 k time with out for loop

  1. String name = "kranthi";
  2. String str = "X";
  3. str = str.replaceAll("X", "XXXXXXXXXX");
  4. str = str.replaceAll("X", "XXXXXXXXXX");
  5. str = str.replaceAll("X", "XXXXXXXXXX");
  6. str = str.replaceAll("X", name + "\n");
  7. System.out.println(str);

or


@Test(invocationcount=10)
public void main(){
SYstem.out.println("hello")
}

Wednesday 31 July 2019

Linux commands

-------------------- pwd / cd --------------------------------

pwd - print working directory
cd - change directory
cd / - move to root directory
cd ~ - home directory
cd dir1/dir2 - move to said directory
cd .. -fall back one directory

------------------------ LS---------------------------------
ls - displays files and folders in the currect directlory

ls-R - displays files and folders in the currect directlory & sub driectories

ls-a - shows hidden files

------------------------- CAT --------------------------------
cat command:

create file :
cat (enter)
> fileName1
> file content

combining file:
cat fileName1 fileName2 > newFileName

to view file content:
cat newFileName
------------------------ delete ---------------------------------
delete file
rm newFileName
------------------------- move --------------------------------
move a file ( file to a new directory )
mv fileName1 /home/dir1/dir2  --- permission denied

we need super user credentials for this
sudo mv fileName1 /home/dir1/dir2 

---------------------- rename -----------------------------------

rename file name
mv fileName newFileName

--------------------- mkdir ------------------------------------
create directory:
mkdir songs

create sub directories:
mkdir temp/songs

multiple directories:
mkdir  dir1 dir2 dir3

--------------------- rmdir ------------------------------------

deletes directory with contents init
rmdir dir1
---------------------------------------------------------
Help - Man

man ls
help information
---------------------------------------------------------
history
>history
---------------------------------------------------------
clear command
> clear






Monday 22 July 2019

Interview Qns - Core java

Output please

public class Test123 {

static {
System.out.println("first static block");
}
static {
System.out.println("Second static block");
}

public static void main(String[] args) {
System.out.println("Main Method");
Test123 t = new Test123();
}

Test123() {
System.out.println("COnstructor");
}

}


Output:
first static block
Second static block
Main Method
COnstructor



Yes, we can write n number of static blocks 
Main method executes after static blocks
--------------------------------


Can we write Throwable in Catch block??

public void doNotCatchThrowable() {
try {
// do something
} catch (Throwable t) {
// don't do this!
}
}

Throwable is the superclass of all exceptions and errors. You can use it in a catch clause, but you should never do it!

If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application. Typical examples for that are the OutOfMemoryError or the StackOverflowError. Both are caused by situations that are outside of the control of the application and can’t be handled.

So, better don’t catch a Throwable unless you’re absolutely sure that you’re in an exceptional situation in which you’re able or required to handle an error.

-----------------------------------
The task is to write a program to generate the largest number possible using these digits.
Input : arr[] = {8, 6, 0, 4, 6, 4, 2, 7}
Output : Largest number: 87664420


static int findMaxNum(int arr[])
{
    // sort the given array in
    // ascending order and then
    // traverse into descending
    Arrays.sort(arr);
   
    int num = arr[0];
    int n = arr.length;
   
    // generate the number
    for(int i = n - 1; i >= 0; i--)
    {
        num = num * 10 + arr[i];
    }
   
    return num;
}
--------------------------------------
Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
FileReader thows FileNotFoundException is a subclass of IOException - hence am throwing


import java.io.*;

class Main {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
       
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++)
            System.out.println(fileInput.readLine());
       
        fileInput.close();
    }
}

Ex:
ClassNotFoundException,
IOException,
SQLException


Unchecked: are the exceptions that are not checked at compiled time
Ex:
NullPointerException
ArithmeticException,
ArrayStoreException,
ClassCastException
IndexOutofbounds
---------------------------------------

Inheritance - Class casting -  Parent to Child and Child to parent


public class Parent {

public void m1() {
System.out.println("parent method");
}

}

public class Child1 extends Parent {

public void m1() {
System.out.println("Child1 method");
}

public static void main(String[] args) {
Parent p = new Parent();
p.m1();

Child1 c = new Child1();
c.m1();

Parent p1 = new Child1();
p1.m1();

Child1 cer = (Child1) p;// RuntimeError : java.lang.ClassCastException:
// javaProg.Parent cannot be cast
// to
// javaProg.Child1

Child1 cerr1 = (Child1) new Parent();// Runtime error :
// java.lang.ClassCastException: javaProg.Parent cannot be
// cast to javaProg.Child1
}
}

output:
parent method
Child1 method

Child1 method

Note - Only Child to parent casting is possible, Rest all Runtime Exception
--------------------------------------------------
Remove duplicates from array

// NOTE : SORTED ARRAY
public static int removeDuplicateElements(int arr[], int n){
        if (n==0 || n==1){
            return n;
        }
        int[] temp = new int[n]; // lets use temp array
        int j = 0;
        for (int i=0; i<n-1; i++){
            if (arr[i] != arr[i+1]){
                temp[j++] = arr[i];
            }
         }
        temp[j++] = arr[n-1]; // ADD LAST ITEM TO TEMP ARRAY
 
        // Changing original array
        for (int i=0; i<j; i++){
            arr[i] = temp[i];
        }
        return j;
    }
---------------------------------------------------
how to make thread safe

Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is a Java synchronized static method example:

  public static synchronized void add(int value){
      count += value;
  }
Also here the synchronized keyword tells Java that the method is synchronized.

Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.


If the static synchronized methods are located in different classes, then one thread can execute inside the static synchronized methods of each class. One thread per class regardless of which static synchronized method it calls.
--------------------------------------
public vs protected

The protected specifier allows access by all subclasses of the class in a program, whatever package they reside in, as well as to other code in the same package. The default specifier allows access by other code in the same package, but not by code that is in subclasses residing in different packages

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

Guess the out put of below prog


try{
System.exit(-1);
System.out.println("in try");
}
catch(Exception ex){
System.out.println("in Exception block");
}

output : Nothing - as program exits then and there



Java System exit() Method
The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.


System.exit(0) or EXIT_SUCCESS;  ---> indicates Successful termination
System.exit(1) or EXIT_FAILURE;  ---> indicates unsuccessful termination with Exception
System.exit(-1) or EXIT_ERROR;   ---> indicates Unsuccessful termination


Thursday 11 July 2019

Collection Interface - ArrayList : How to make array list thread safe

ArrayList is NOT ThreadSafe

sometimes you need to restrict access one thread at a time by implementing Synchronization.

Collection list3 = Collections.synchronizedList(Arrays.asList(1, 2, 3, 4, 5));
synchronized (list3) {
Iterator j = list3.iterator();
while (j.hasNext())
System.out.println(j.next());
}

Sunday 23 June 2019

Selenium waits - FluentWait, PageLoadTimeOut, ImplicitWait and ExplicitWait,

Fluent Wait: Fluent Wait. The fluent wait is used to tell the web driver to wait for a condition, as well as the frequency with which we want to check the condition before throwing an "ElementNotVisibleException" exception.

Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, TimeUnit.SECONDS)
    .pollingEvery(1, TimeUnit.SECONDS)
    .ignoring(NoSuchElementException.class);

WebElement content = fluentWait.until(new Function<WebDriver, WebElement>() {
   public WebElement apply(WebDriver driver) {
    return driver.findElement(By.xpath("//h4[text()='Hello World!']"));
   }
});

pageLoadTimeout: if any page is taking more than x amount of time, then we can stop executing that script by seetting up pageLoadTimeout
Throws -  TimeoutException.

driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MILLISECONDS);

Implicit Wait: If we setup implicit wait, wait for x amount of time for elements avaialbility
Throws : NoSuchElementException

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

Explicit Wait: This wait is applicable for specific element based on condition provided
WebDriverWait explicitWait = new WebDriverWait(driver, 10);
explicitWait.until(ExpectedConditions.visibilityOf(content));

Thursday 6 June 2019

Friday 24 May 2019

stop loading images for Functionality testing. - For quick test execution

For Automation scrips to run faster, we can completely avoid loading images on to browser - which internally saves lot of time for execution.

Do you wanted to check how? 

here you go.




For Chrome Browser:

Step 1:
Map<String,Object> images = new HashMap<String,Object>();
images.put("images",2);

Step 2:
Map<String,Object> prefs = new HashMap<String,Object>();
prefs.put("profile.default_content_settings_values",images);

Step 3:
ChromeOptions options = new ChromeOptions()
options.setExperimentalOption("prefs",prefs);

Step 4:
WebDriver driver = new ChromeDriver(options);


For FireFox Browser:

Step 1:
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("permissions.default.image",2);

Step 2:
FirefoxOptions options = new FirefoxOptions();
options.setProfile(profile);
options.setCapability(FirefoxDriver.PROFILE,profile);

Step 3:
WebDriver driver = new FirefoxDriver(options);

Thursday 9 May 2019

Interview | @CacheLookup - in Page Object Model | Page Factory


@CacheLookup, as the name suggests helps us control when to cache a WebElement and when not to.

This annotation when applied over a WebElement instructs Selenium to keep a cache of the WebElement instead of searching for the WebElement every time from the WebPage. This helps us save a lot of time.

Syntax:
 @FindBy(how = How.NAME, using = "firstname")
 @CacheLookup
 public WebElement firsNameCached;

Tuesday 7 May 2019

Interview | RestAssured | Gpath | Groovy GPath in REST Assured,

Easy way to query Json Response object using - inbuilt feature of Rest Assured - Gpath

API :http://www.test.com/teams/88
Resp:
{
  "id": 88,
  "name": "Selenium"
}


@Test
public void gpath_extractSingleValue_findSingleTeamName() {
Response response = RestAssured.get("teams/88");
    String teamName = response.path("name");
    System.out.println(teamName);
}

A quick note on the .path() method. How did REST Assured know to use JSONPath, instead of XMLPath? We didn’t specify it! That’s some of the magic of GPath in REST Assured


@Test
public void gpath_extractSingleValue_findSingleTeamName_responseAsString() {
    String responseAsString = get("teams/88").asString();
    String teamName = JsonPath.from(responseAsString).get("name");
    System.out.println(teamName);
}

@Test
public void gpath_extractSingleValue_findSingleTeamName_getEverythingInOneGo() {
    String teamName = get("teams/88").path("name");
    System.out.println(teamName);
}

Other Samples:
Fist Child - response.path("teams.name[0]");
Last Child - response.path("teams.name[-1]");
All Childs -  ArrayList<String> allTeamNames = response.path("teams.name");
All Parents Data - ArrayList<Map<String,?>> allTeamData = response.path("teams");
Query - object.teams.find { it.name == 'Leicester City FC' }

RestAssuredAssertion :

@Test
public void gpath_extractSingleValue_findSingleTeamName_useAssertion() {
    given().
    when().
            get("teams/66").
    then().
            assertThat().
            body("name", equalTo("Manchester United FC"));
}

Interview | How can you solve StaleElementReferenceException

How can you solve StaleElementReferenceException

Answer : ExpectedConditions.refreshed

Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is thrown.


public WebElement waitForElementToBeRefreshedAndClickable(WebDriver driver, By by) {
    return new WebDriverWait(driver, 30)
            .until(ExpectedConditions.refreshed(
                    ExpectedConditions.elementToBeClickable(by)));
}

So basically, this is a method that waits until a DOM manipulation is finished on an object.

When the DOM has manipulated, and say after clicking a button, adds a class to that element. If you try to perform an action on said element, it will throw StaleElementReferenceException since now the  WebElement returned now does not represent the updated element.

You'll use refreshed when you expect DOM manipulation to occur, and you want to wait until it's done being manipulated in the DOM.

Interview | Can we have multiple finally blocks

Answer is NO.



try (1)
catch (0 or more)
finally (0 or 1)


- try block must be followed by either catch or finally block.
- When an exception occurs, that exception occurred is handled by catch block associated with it.
- Java catch block is used to handle the Exception. ...
- This ensures that the finally block is executed even if an unexpected exception occurs.