Our New Year Gift for Our-Self in 2015

We want to say goodbye to this fantastic year,with the idea that, what can be our best gift to no-one but to our self.In this festivity times,most of us spend our time to think of gifts for other people but What about gifting ourselves.It is bit off the way topic on this forum, but we thought of ending this year’s learning on a distinct track,so that we are lot more refined next year. We still remember our snoozy post of 2014, hope to see Your love for uftHelp continues in 2015 and we are connected as a family through Facebook, Google+,LinkedIn and Twitter.

New Year at uftHelp
Warm Welcome to 2015

Lets start with a list of free special gifts that we can give ourselves in 2015 :-

1. Exercise:– Even 15 minutes a day- We will be more healthier,live longer and learn more and share more

2.Yoga:-It boost our energy level and make us shed laziness.

3. Learning:- Learn something new each day, and share it with the world.It cannot be only be limited to selenium,UFT,Angular or HandsOn but even to the minute thing that we did today.

4.Reading:- Read more.

5.Personal hygiene:- It can be brushing of our teeth before sleep or sleeping on time and many more.

6.Smile:- A smile can heal thousand wounds , spread smile and peace everywhere.

7.Tolerance:-We have our prejudices against all kinds of people and things,try dropping that barrier of others and ours and this world be amazing place to live and grow.

8.Environment:-Finally, as we always motivate the whole world through our green and blue post themes, i.e. how about gifting  something to our enviornment. It is not limited to making our house clean but it can be our neighborhood, by planting more trees,promoting and practicing water conservation and greenery.

Hope to share more learning in the coming years and You all would be there to motivate and appreciate our efforts.

Cheers uftHelp lovers and Warm WELCOME TO 2015!!!!

Log4j Configuration file

After executing our basic test case using logger in log4j, we would modify it, to include Appender” and “layout objects by implementing “Configuration file” in our code.


What is Configuration file?
Configuration files are used to configure settings of log4j file. This can bewritten in XML or in Java properties (key=value) format.

Example:-
Using Basic configuration file in the code, which is used to create simple log4j setup.
Syntax
BasicConfigurator.configure();

If we run the same code that we used on our first test case and add BasicConfigurator it would look like this:-

package Log4j_Learning;
import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

public class Log4j_FirstTestCase {
//Creating the logger object
static Logger log = Logger.getLogger(Log4j_FirstTestCase.class);
public static void main(String[] args) {
//log.setAdditivity(false);
BasicConfigurator.configure();
//Setting the log level
log.setLevel(Level.WARN);
//Creating the layout object
Layout sLayout = new SimpleLayout();
//Creating the Appender object
Appender app = new ConsoleAppender(sLayout);
//Adding appender to logger
log.addAppender(app);
log.debug("First debug Message");
log.info("First info Message");
log.warn("First Warning Message");
log.error("First Error Message");
log.fatal("First Fatal Message");
}
}



Output which varies with log.setadditivity(false) is applied:-

setadditivity to avoid repetitive logs in log4j
log4j, logs with/without setAdditivity


Note:-We are having double results in the console,it’s because appenders are not singletons, they are additive.Meaning, A category inherits all the appenders from its ancestors (by default). If we add an appender to a category and it writes to the same underlying stream (console, same file etc.) as some other appender, the same log message will appear twice (or more) in the log. In addition, if two categories in a hierarchy are configured to use the same appender name, Log4j will write twice to that appender.

To avoid such situation we need to Use log.setAdditivity(false) on a category to disable inheriting of appenders. Then, log messages will only be sent to the appenders specifically configured for that category.

Files Required:-

log4j_Selenium.Java [Test Case with logs]
log4j.xml [xml Configuration file, we can use properties file also]
log4j_logfile.txt[File for writing logs]

log4j example file structure
Project Structure for log4j test case.


Java Code:-

package Log4j_Learning; 
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class log4j_Selenium {
//Creating the logger object
static Logger log = Logger.getLogger(log4j_Selenium.class);
public static void main(String[] args)
{
DOMConfigurator.configure("log4j.xml");
log.info("**************Begining of Logs******************");
//Creating WebDriver Object
log.info("Launching the Browser");
WebDriver driver = new FirefoxDriver();
//Opens the given URL
driver.get("http://www.uftHelp.com");
log.info("Fetching the Title");
//Returns the Title of Current Page
String sTitle = driver.getTitle();
log.info("My First Selenium Program using Log4j");
log.info("Title is = '"+sTitle+"'" );
//Closing the Browser
driver.close();
log.info("Browser closed");
System.out.println("Logs Created Successfully");
log.info("**************Ending of Logs*********************");
}

}


XML file:-

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<!-- Creating the File Appender -->
<appender name="fileAppender" class="org.apache.log4j.FileAppender">

<!-- File to write logs -->
<param name="File" value="log4j_logfile.log"/>
<!-- Layout = "PatternLyaout" -->
<layout class="org.apache.log4j.PatternLayout">
<!-- Printing message with date , time & class name -->
<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n" />
</layout>

</appender>

<root>

<level value="INFO"/>
<appender-ref ref="fileAppender"/>

</root>

</log4j:configuration>


Output:-
Open the log4j_logfile,which will be created in the project folder.

Output of log4j in text file


Explanation:-
We used the root logger to create a “Info” level message and used the “File Appender” to paste the results into the external text file(log4j_logfile).Furthermore we have used layout as “Pattern Layout” to create a pattern of message in the form of “%d{dd MMM yyyy HH:mm:ss} %5p %c{1} – %m%n“, which means date time + log level + message.

log4j structure
Configuration file structure


Note:- Incase we want results to be shown in the “Console” of the IDE(Eclipse), we can use “Console Appender” in our Configuration file(log4j.xml).
Just change the configuration file for the above java code and check the output in the console and same external file.

Configuration file with Console+file Appenders:-

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<!-- Creating the Console Appender -->
<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<!-- Printing message with date , time & class name -->
<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/>
</layout>
</appender>

<!-- Creating the File Appender -->
<appender name="fileAppender" class="org.apache.log4j.FileAppender">
<!-- File to write logs -->
<param name="File" value="log4j_logfile.log"/>
<!-- Layout = "PatternLyaout" -->
<layout class="org.apache.log4j.PatternLayout">
<!-- Printing message with date , time & class name -->
<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n" />
</layout>

</appender>

<root>

<level value="INFO"/>
<appender-ref ref="fileAppender"/>
<appender-ref ref="consoleAppender"/>

</root>

</log4j:configuration>

First Test Case using log4j

After installation and basic overview of log4j, we are implementing log4j in our first test case.Here we would be configuring log4j pro-grammatically but recommended approach is to use it manually by using configuration file.

Also we would be utilizing the main components of log4j i.e. Logger,Appender and Layout.Lets go step by step.

Main components of log4j
Log4j components

Implementation:-
Step1:-Creating a new logger:
Logger logger = Logger.getLogger(“MyLogger”);
MyLogger:-logger name

Log4j logger object
getlogger method

More usually, one instantiates a static logger globally, based on the name of the class:-
static Logger logger = Logger.getLogger(test.class);
Example:-

 /* Getting class name to be printed on */
static Logger log = Logger.getLogger(Log4j_FirstTestCase.class);


Step2:-
Creating the layout object:-
Layout sLayout = new SimpleLayout();
Step3:-
a.Creating the Appender object:-
Appender app = new ConsoleAppender(sLayout);

b.Adding Appender to Logger object
 log.addAppender(app);
Step4:-
Calling the available logger levels:-

Priority level = debug < info < warn < error < fatal

Logger levels in log4j
Logger levels
error level in log4j
Adding level to Logger object

Note:- This priority level is important, as one’s it is applied, only the Log level of that logger and higher than this will be logged. We can set log level of a logger using the Logger.setLevel method.
Example:- If we set the, log.setLevel(Level.WARN), then even if we have code like :- log.Debug(“Debug message”) in our flow, it would not be shown in the output, because as per the priority Debug < Warn.

Code:

package Log4j_Learning;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

public class Log4j_FirstTestCase {
//Creating the logger object
static Logger log = Logger.getLogger(Log4j_FirstTestCase.class);
public static void main(String[] args) {
//Setting the log level
log.setLevel(Level.WARN);
//Creating the layout object
Layout sLayout = new SimpleLayout();
//Creating the Appender object
Appender app = new ConsoleAppender(sLayout);
//Adding appender to logger
log.addAppender(app);
log.debug("First debug Message");
log.info("First info Message");
log.warn("First Warning Message");
log.error("First Error Message");
log.fatal("First Fatal Message");
}
}



Output:-
Note:- In our case as we used log level =WARN ,thus debug and info message won’t be shown in the output.Also the below output is just for illustration, if You run the above code we will have warn,error and fatal messages.

log4j output after run
Console output log4j


Why to avoid above approach:-

Suppose we have used logger in our code, and we wont to change the Appender class or layout design or log level, we need to dig that into the code and have to make the changes.Thus to avoid these code level changes we would recommend going with “configuration file” by which we can control the logger features.In our next tutorial we are implementing the “Configuration file” approach.

Install Log4j in Eclipse

We are done with basic introduction to log4j, now lets make our setup ready to work with log4j in selenium.

Download  Log4j:-
Step1:-
Open the link:-
Note:- we have used the older version of log4j1.2x in our example code, 

New version of  http://logging.apache.org/log4j/2.x/download.html is also available.

Step2:-
Click on the below link 

download apache log4j
log4j zip file link

Step3:-
Click on the Apache Download Mirrors link

log4j downloading link
log4j download link

Step4:-
Save and Extract the file

log4j download from apache
Downloading the log4j jar file
log4j jar file
log4j jar file after extraction


Step5:-
Include the Jar file in project and we are done
How to add Jar to project.

add log4j to eclipse
Adding log4j jar files to Java project

Basic Log4j Example

Log4j introduction in Selenium

What is Log4j?
Log4j is a Java library,which is used in logging.  Log4j came into existence in 1996, as an initiative by SEMPER group to create a tracing API. Log4j is an open source tool and licensed under Apache Software License.

introduction log4j
log4j


At its most basic level, we can imagine this as a replacement for System.out.println(sysout) statement in our code.But it is far more superior than sysout,but how? Let’s elaborate on this.

Why Log4j?
Lets discuss some advantages of log4j:-

  • The output from Log4j can go to the console, to an email server, a database table, a log file, or numerous other destination, unlike sysout which outputs to standard output, which typically is a console window.
  • It allows different levels of logging like TRACE, DEBUG, INFO, WARN, ERROR, and FATAL. Say if we set a  particular log level, messages will get logged for that level and all levels above it, For instance, for log level = Error, we will have log messages that are errors and fatal and if we have log level = Info, we will have log messages that are info, warn, error, and fatal.
  • Log4j provides the feature to define the format of output logs. Furthermore we can configure Log4j via a configuration file, making it easy to control the logging behavior by editing this file, without touching the application binary.


Main components of Log4j:-

  1. Logger 
  2. Appender 
  3. Layout

LOGGER:
Logger is responsible for handling the majority of log operations.This object of logger class is responsible for capturing logging information and Control over which logging statements are enabled or disabled.

APPENDER:
Appender is responsible for controlling the output of log operations.This Appender object is responsible for publishing logging information to various preferred destinations such as a database, file, console, etc.

Some example of appender:-

appender log4j
Appenders in log4j



LAYOUT:
Layout is responsible for formatting the output for Appender.
Layout objects play an important role in publishing logging information in a way that is human-readable and reusable. The most popular layouts are the PatternLayout and HTMLLayout.

Don’t worry will have working codes with more explanation about them.


Follow the below readings to learn more because “the best is yet to come…”:-
Downloading log4j 
First test case using Log4j
Using Configuration file in log4j

JavaScript Questions-(Part-2)

Motivation to learn more and fly free
Prepare well to crack Interview’s



1.What is the functionality of DOM?

2.Tell different ways to refresh the page?
location.reload()
history.go()
window.location.href

3.How to assign value to ViewState?
ViewState.Add(“Name”,”UFT”);
ViewState[“Name”] = “UFT”;

4.What is the output of JS Code?
var title=”User Friendly Techy Help”;
var char = title[13];
alert(char);

5.How to make this string capitalize “UFT”;

6.What will be the output of JS Code?
var str = new String(“User Friendly Techy Help”);
alert(str.charAt(3));

var a=[‘apple’,’orange’,’banana’];
var b=[‘pineapple’, ‘guava’, ‘grapes’];
var c = a.concat(b);
alert(c[2]);

7.How to assign value to a textbox using JS?
document.getElementById(“textName”).value= “UFT”;

8.What is the output of “2” + 3 and “2” – 3 ?

9.Is “JavaScript”  a case-sensitive language?
Yes

10.What does the “noscript” tag do?


JavaScript Questions(Part-1)
More interview Questions

Executing Failed TestCases in Selenium using TestNG

Scenario:-
We want to re-run only the failed testcases in selenium, rather than running the entire suite.

Approach:-
Every time tests fail in a suite, TestNG creates a file called testng-failed.xml in the output directory. This XML file contains the necessary information to rerun only these methods that failed, utlizing this we can easily rerun the failed tests without having to run the entire test suite.

Note:- For running the test exactly after the failure we need to call the method that failed. We can get that method name from  IRetryAnalyzer interface . If we just want to rerun all the failed test cases together, then we can give the testng-failed.xml as input xml after the first execution.But remember this will result in creation of 2 reports, one of previous run + latest run of the failed test cases, rather than having the consolidated report

Solution:-
Locate the testng-failed.xml file
Project->test-output->testng-failed.xml

rerrun failed tests in selenium
opening testng-failed


Rerun this file to execute only the failed test cases.
(Open file -> CTRL+F11)

testng-failed.xml file
testng-failed.xml file view

How to run parallel Selenium Tests

Skip Selenium TestCase Run using TestNG

Scenario:-We have a test case in the test set, which is not ready for testing and we wont this test case to be disabled while Selenium is executing the complete test suite.

Solution:-
We can disabled the test case in TestNG using enabled property.

Syntax
@Test(enabled=false)
By default it is enabled= true

Code:-

XML file:-

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite">
<test name="uftHelp">
<classes>
<class name="TestNG_Learning.DisableTest"/>
</classes>
</test>
</suite>


Java:-

package TestNG_Learning;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class DisableTest {
private WebDriver driver;

@Test
public void login() {
//Fill the UserName and Password fields
driver.findElement(By.id("userName")).sendKeys("uftHelp");
driver.findElement(By.id("password")).sendKeys("Password");
}
//Test is disabled
@Test(enabled=false)
public void signIn() {
//Click the Sign in Button
driver.findElement(By.id("SignIn")).click();
//Clicking on the alert message
driver.switchTo().alert().accept();
}

@BeforeMethod
public void beforeMethod() {
driver = new FirefoxDriver();
//Adding Implicit wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Maximize browser
driver.manage().window().maximize();
//Open the Login Application
driver.get("http://www.ufthelp.com/p/testpage.html");
}

@AfterMethod
public void afterMethod() {
//Closing the browser
driver.quit();
}

}



Output:-

enabled=false example testng
Output result have missing “signIn” test case 

More practical scenarios

Implement ReportNG in TestNG

What is ReportNG?
ReportNG is a reporter add-on for TestNG that implements the report listener of TestNG. ReportNG reports provides better user interface(look and feel)compared to the original HTML reports. To generate a ReportNG report we have to add the reporting class to the list of listeners of TestNG while executing the tests. 
Lets implement this in our basic example that we have used in our First Test case with TestNG

Step1:-
Download the required JAR files from :- 
ReportNG+Velocity 
Guice-3.0

Download Guice for ReportNG
Downloading Guice-3.0.zip

Step2:-
Unzip the JAR files and add to the project.
How to add JAR files in Eclipse

Guice-3.0 jar files adding in Eclipse
Adding Guice JAR’s 

Step3:-
Add listener to testng.xml file
listener class-name=”org.uncommons.reportng.HTMLReporter”

JavaCode

XML file:-

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Suite" >
<listeners>
<listener class-name="org.uncommons.reportng.HTMLReporter"/>
</listeners>
<test name="My first TestNG run using ReportNG">
<classes>
<class name="srcTest.FirstTest"/>
</classes>
</test>
</suite>


Note:-
Incase you are getting the below error,it can be due to missing JAR files in Guice, try adding them again.

java.lang.NoClassDefFoundError: com/google/inject/Module
Code Error 



Step4:-
Observing the results,
test-ouput ->html->index.html

ReportNG results file in Eclipse
index.html
Fancy test results in TestNG using ReportNG
Test Results in ReportNG

Note:– 
We can absorb Reporter.log messages inside output.html

Reporter.log output in ReportNG
Reporter.log messages in ReportNG

Data Parameterization in Selenium using TestNG

AngularJS $watch() ,$digest() and $apply()

This post is meant for novice AngularJS programmers to enlighten them with basic comprehension of how data-binding works. To deep-dive into data-binding, you need a clear vision of how $watch(), $digest(), $apply() and dirty checking works.Lets go step by step on this topic.

Do folow us on FB page, Twitter or G+ for more updates and learning.

“It is not about doing so much as understanding the process itself”

The browser behavior on events:
Generally, browser waits for user interactions, eg: button click event or change events. If you click on a button or select a checkbox, the event’s callback function will run inside JavaScript where all the DOM manipulations will be completed. Browser will get notification to render appropriate changes in the DOM after the callback is completed.

Angular extends this events-loop into a vital concept known as angular-context. To explain what this context is and how it works we will need to explain more concepts.

$watch
When you create a data-binding in your view, AngularJS internally creates a $watch in the $watch list . It means it will detect the changes in the modal it is watching.
Eg:

$Watch example Angular JS

Here we are having $scope. 
customerName which is bound to the first input and $scope.customerId which is bound to second input. 

Hence, we have created two $watch in the $watch list.

WatchList example Angular JS
         
Guess how many $watch are created here?
2 –Wrong(For customer name and id)
3-Right (2 for customer name,id and 1 for ng-repeat)

So if we have 5 customers in a list, the $watch count will be 1+(2*5) i.e. 11
So all the bindings in UI creates a $watch.

But now the question arises is when $watch created for ng-repeat or other directives are?
When template has loaded, the compiler starts looking for every directive and subsequently creates required $watch.

$digest (Extended event loop)
The $digest loop will get invoked when the browser receives an event which can be managed by angular context. This comprises of two inner loops. One process the $evalAsync queue while the other keeps an eye on $watch list of the current scope and its children checking following process:

Hey $watch, what is your value?
I am “Selenium”.
Is it changed?
No, Boss.
No action will perform on this, it will iterate to the  next.
Buddy, what is your value?
          It is “User Friendly Techy Help”.
Is it changed?
Yes, It was “Unified Functional Testing”.
Great, now we have to update the DOM.

The $digest() keeps calling the all the watchers that were being created and then make changes in the DOM.
This process is called as dirty-checking

Key Points:

  • If any one of them has changed, the loop will run again until all of the $watch, report no changes to ensure that the model is clean.
  • This function will throw ‘Maximum iteration limit exceeded.’ if the number of iterations exceeds 10.
  • Usually, $digest is never called directly, instead we use $apply() which will force a $digest().
  • The significant point is that “All the events” that enters the angular context will fire a $digest loop. Eg:

appcontroller example in TestNG

In this example, we have only two $watch as ng-click doesn’t create any $watch(the function will not change).

Who notifies which event enters the angular context and which one do not?
Answer is: $apply
Whenever an event is fired, it will go through the angular-context and fire $apply(), else it will run outside it. In earlier example: You may have noticed that it works without calling $apply(). The reason behind this is Angular called the $apply method internally.

So, when do you need to call $apply()? 
There are some corner cases where AngularJS does not call the $digest() function for you. You will usually observe that by checking that the data bindings do not update the displayed values.Actually, the events never enter the angular context and the $digest loop is never fired. Be sure you call, $apply() if you need to run a $digest loop to update your DOM.

Key Points:

  • AngularJS calls almost all of your code within an $apply call. So you need not to call it explicitly.
  • Calling $apply() inside $apply() will throw an error.
  • You need to call it only if you code is not written using methods from AngularJS library. Ex: if you are binding a double-click event on an element using jQuery, then you have to wrap your code in $apply().If you write any code that uses Ajax without $http, or listens for events without using Angular’s ng-* listeners, or sets a timeout without $timeout, you should wrap your code in $apply().
  • Some people don’t recommend calling $apply because they think that they are doing something wrong. That is not true. It is just Angular that doesn’t get any notification when a 3rd party library wants to update the bindings.

Sample:
Working Demo

HTML:-

Angular JS binding Textbox


JavaScript :-

Databinding example code
JavaScript Code


 Output:-

Try to execute the code and observe how output varies, it is changing from “Title” ->”UFT”->”User Friendly Techy Help”

Scope’s $apply() method transitions through the following stages:
1.The expression is executed using the $eval() method.
2.Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.
3.The watch listeners are fired immediately after the expression was executed using the $digest() method.

If you want to create your own $watch, checkout this tutorial.

We hope that you understand how data-binding works in Angular. Don’t assume that dirty-checking is slow. It is fast as lightening. It can be laggy, if you have 2k-3k $watch in your template. In ECMAScript 7, we will have Object.observe which will improve the $digest loop.
If you find that we have missed something or there is some improvements or any thing You want to share please feel free to add Your comments or contact us.

Create movable tooltip in AngularJS