Sunday, January 29, 2017

DOM Vs View Source – Some definitions

View Source just shows  the HTML that makes up that page. It is the exact HTML that you wrote.
But the HTML you write is parsed by the browser and turned into the DOM.

When you're looking at the panel in whatever DevTools you are using that shows you stuff that looks like HTML, that is a visual representation of the DOM

The source is the raw HTML that is unadulterated by any client-side scripts. It is the direct response of the HTTP request to the server. The DOM, on the other hand, is the same HTML structure that has been modified by JavaScript.
Source Code reads the page’s HTML as if you opened it in a text editor. The source code reflects your HTML structure before any JavaScript is loaded.

The page source is the result of the GET request by the browser sans headers. If you want to view the updated content after scripts and so forth, you'll have to use a tool like Firebug or the Web Development toolbar.

How a webpage gets displayed?


A request is made when a link is clicked. --Request
1.       The page and its resources (files) are downloaded. -- Response
2.       The web browser uses the page resources to build the page.-- Build
3.       The page then is rendered (displayed) to the user.-- Render

Requests:
Requests are made when
·       A link is clicked
·       A page is refreshed
·       When a URL is typed into a browser
When a linked is clicked a request is made for a document which is a text file ( example .html) located on a web server. The file is requested using the HTTP protocol.

Response:
The response is simply the browser receiving the file  it had requested from the web . Apart from the html the web browser needs to get resources like images, css and javascript for it to display the webpage.The web browser looks at the entire HTML document and looks for any css, javascript and images that are referenced by the page.If resources are found in the HTML the web browser then requests each of those resource files from the webserver.
The images, css, and javascript that the HTML file references will be downloaded by the browser.

Build:
 Once the web browser has the required resources it starts building the web page in below 3 steps:
  • Build the DOM- DOM stands for "Document Object Map". It is  a map of where things are displayed on a page according to the HTML.
  • Build the CSSOM- It is a map of what styles should be applied to different parts of the page according to the CSS.
  • Build the Render Tree- The render tree takes the DOM and the CSSOM and combines them to create a full map of how the page will actually be laid out and painted.
Render
At the end of it browser puts things on to the screen by deciding the Layout and then the browser will convert each node in the render tree to actual pixels on the screen.


Troubleshooting and Debugging WebDriver Tests


Below steps would help in troubleshooting , identifying and finding the root cause of test failure.

1.       Using screenshots:

Adding code to testcase  to take screenshots before and after an action/statement. The screenshots taken can be used to analyse the state of the page before and after the action that requires troubleshooting.
2.       Running the test case in debug mode
·       The test needs to be run by using breakpoints at the line which throws the exception.
·       When the code stops executing at the breakpoint. Check that the application is in the correct state i.e. all elements are ready, you can see the element you want to work with etc.
·       Then step over the line that throws the execption.
·       If it passes then chances are you need some synchronisation code immediately prior to your statement to wait for the element to be ready. Because that is what you did when you debugged: you waited, then you executed the code. You want to add the wait into your code.

3.       Using Conditional breakpoint

Conditional breakpoints can be set by using the breakpoints view in Eclipse.  Select breakpoint properties by right-clicking on the break point. Check the conditional checkbox and write an expression that evaluates to true and the program  should get suspended during Debugging.

4.       Changing Variable values in Debug perspective

The values of variables in the tests can be changed on the fly using the Debug perspective. The top right corner of Eclipse should have the variables view from which you can select a variable name and change its value.

5.       Display View

 The Display View displays the result of evaluating an expression in the context of the current stack frame. You can evaluate and display a selection either from the editor or directly from the Display View.
You can view the Display view as a place where you can inspect all sorts of variables and boolean expressions during runtime. While your debugger is frozen on a breakpoint start typing the name of an object variable for instance and you'll get autocomplete functionality as you start calling methods or fields to reach deeper class datastructures. Then when you select/mark the portion you need to inspect or everything, the buttons on the Display view will be clickable. You can always perform the Ctrl+Shift+I shortcut on the selection to view what's the current runtime state of your selection i.e. variable, object, boolean expression etc.
Taken from: http://stackoverflow.com/questions/4499944/how-to-use-eclipses-display-view-for-debug

6.       Capturing HTML DOM Content

A technique is to capture the HTML DOM contents when a test fails. Capture the contents of the DOM and write them out to a file.
      
If you want to get page source you can get by using the following java code:

String pageSource = driver.getPageSource();
If you want to verify a particular text is present or not on the page, do as below:

boolean b = driver.getPageSource().contains("your text");

Sunday, January 22, 2017

WebDriver: Keeping implicit and explicit waits separate using reusable methods



SeleniumHQ documentation says:

"WARNING: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example setting an implicit wait of 10s and an explicit wait of 15 seconds, could cause a timeout to occur after 20 seconds."
In order to not mix the implicit and explicit waits, an approach can be taken to implement the reusable methods in such a way that when an explicit wait is required, the implicit timeout can be set to 0 and just before coming out of the reusable method setting the implicit wait back to the default value.

Below is the wrapper class implementing the reusable method : findElement(SearchContext, by, long)
public  class WebDriverWrapper {
       
    //Setting a default value of the wait timeout.
    public static final long IMPLICITLY_WAIT_TIMEOUT = 3000;
    private WebDriver driver;

    public WebDriverWrapper(WebDriver driver) {
        this.driver = driver;
    }
   
   //Method to let implicit wait to be set on the basis of the passed parameter      //value   
    public void setTimeout(long seconds) {
        driver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
    }

   
    //Set implicitly wait timeout to the default value
        public void setTimeout() {
        driver.manage().timeouts().implicitlyWait(IMPLICITLY_WAIT_TIMEOUT, TimeUnit.SECONDS);
    }

    //Implementing reusable method FindElement  
        public WebElement findElement(SearchContext context, By by, long timeoutSeconds) {
        setTimeout(0); //Implicit timeout has been set to 0
        FluentWait<SearchContext> wait = new FluentWait<SearchContext>                   (context).withTimeout(timeoutSeconds,                TimeUnit.SECONDS).ignoring(NotFoundException.class);
        WebElement element;
        try {
            element = wait.until(elementLocated(by));
        } catch (Exception e) {
            element = null;
        } finally {
            setTimeout();//implicit timeout has been set to default value.
        }
        return element;
    }


//explicitFind() Method implemented in MyHomepage class
// to demonstrate usage of findElement method implemented in WebDriverWrapper //class to avoid mixing implicit and explicit wait.
public boolean explicitFind() {
     
      if((findElement(getDriver(), By.id("Submit"), 5000))!=null){
            return true;
      } else
            return false;
}



 //This test uses findElement method implemented in WebDriverWrapper
    class which helps in keeping implicit and explicit wait separate.
      @Test
      public void testTimeouts() throws InterruptedException {
            Boolean val = MyHomepage.explicitFind();
            Assert.assertTrue(val);
           

      }

Friday, December 30, 2016

Automation Tests - Best Practices

It’s a danger to consider automation just as a routine task to be completed. Automation should be considered as an integral part of delivering a quality end product and the focus should be consistently on designing and developing relevant test suites. Below set of practices would come in handy.

Design Tests Before Automating Them
We need to keep in mind that test design has to be of prime importance. A well designed test is what finds the bug. The tests and scenarios needs to be clearly defined before start of test automation.
Foccus on the big picture
The objective of automation is not passing the test or making it work. The focus should be on producing a quality deliverable and hence the scope of testing should not be compromised for making the automation tests work.

Consistent and stable tests
We should be able to rely on the automation test results as the automation regression suite gives confidence to the team. Unstable tests that produce inconsistent results should not be part of the automation test suite.

Use testing techniques
Using testing techniques - Boundary Value Analysis, Equivalence Partitioning, and State Transition, while designing tests can greatly increase the value of the tests.

Manual testing vs Automation

When transitioning from a manual tester to automation test developer avoid trying to automate every single test scenario. Automation tests should be written based on the business critical scenarios and considering the objectives of test automation.

Review tests

To avoid redundant tests in the test suite it is a good practice to review the tests constantly (maybe in every sprint) so that the relevancy of the test suite can be maintained.

Create tests that take data sets as inputs

Hard coding data into the tests is never a good idea. When tests can accept different data combinations from data sheets , maintaining the tests becomes a much easier job.

Use data sets in tests according to business rules

Rather than using random data, tests should take data based on conditions. For example selection of date, can be tested by grouping input data into holidays, weekdays, weekends.


Wednesday, December 28, 2016

When I started with automation tests I did some research and by asking below questions I was able to set the expectations from automation and gave me some direction on the way forward.

Question 1 : Why to automate ?

The tests should generate value to the project. And the value automated tests can give are:
Quick feedback:
In the times of continuos integration running automated tests can let the developers know if the new changes have not caused any regression defects.
Tests that needs to be repeated in every cycle :
The business critical scenarios, end to end scenarios, the flows that user will follow (for example in an ecommerce site (select product, add to card,checkout, payment) should be automated.
Confidence for the team:
When a new feature is rolled out automation ensures that regression tests pass and gives confidence on the existing functionalities.
Automate monotonous tasks:
Manual testers can be freed from doing monotonous repeated tasks and can focus more on exploratory testing.

Question 2: When to automate ?

Enhancements to existing functionality
When existing functionalities are modified on account of defects or enhancements. In such cases the existing automated tests for the functionalities may just need to modified.
Stable system
Automation works best when the application is comparatively stable and well defined. The data set is known and the outputs are defined.
When at least one round of manual tests have been already run
Automation test results can be considered meaningful if the manual test has been passed before and the results are available for comparison.

Question 3: What to automate ?

Tests that need to be executed repeatedly in each test cycle.
Regression tests are the best candidates. Helps in time saving and QA can do more exploratory testing and be freed from doing boring tasks. Gives confidence that existing functionalities continue to function correctly after the new features are introduced.
The business critical cases and scenarios must be automated.
This can be figured out by using a Risk based approach. A matrix can be created

Challenges during automation test development:

Let us consider some challenges that we may run into while automating tests:
Automating a feature that’s getting developed: The automation test developer may end up spending more time on writing and updating tests as the feature under development keeps changing during the release cycle.
Maintaining and reviewing tests: A set of regression tests , if not maintained properly can have redundant tests which may not add any value in the current scenario.
Long test suites: If the tests suite takes a long time to finish running , it may cause bottleneck while considering continuous integration as the developer may become reluctant to commit frequently.


Considering the Why, When and What and keeping in mind the challenges we encounter we will be able to create automation test suites that will add value to the tests and project delivery as a whole.