Wednesday, October 29, 2014

Selenium Webdriver - Find out broken links on a page

Today I will explain how to find out all the broken links present on a webpage using Selenium WebDriver. Providing a ready made method written in Java which will take URL from the user as an argument and give a list of all the broken links present on the webpage as output. Please find the method written below:


    public static void main(String[] args) throws IOException {

                List<String> brokenLinks = new ArrayList<String>();
                brokenLinks = getBrokenLinksOnWebpage("<Webpage URL e.g. https://www.google.com/>");
                System.out.println(brokenLinks);

    }

    // Find out all the broken links
    public static List<String> getBrokenLinksOnWebpage(String pageUrl)
                    throws IOException {

                WebDriver driver = new ChromeDriver();
                driver.get(pageUrl);

                List<WebElement> webElements = driver.findElements(By.tagName("a"));
                List<String> brokenLinks = new ArrayList<String>();

                int isBroken;
                for (int i = 0; i < webElements.size(); i++) {
                    String currentUrl = webElements.get(i).getAttribute("href");
                    isBroken = getHttpResponseCode(currentUrl);
                    if (isBroken != 200) {
                                brokenLinks.add(currentUrl);
                    }

                }

                return brokenLinks;

    }


    // Get HTTP Response code for an URL
    public static int getHttpResponseCode(String URL) throws IOException {

                try {

                    URL url = new URL(URL);
                    HttpURLConnection httpConnection = (HttpURLConnection) url
                                    .openConnection();
                    httpConnection.setRequestMethod("GET");
                    httpConnection.connect();
                    return httpConnection.getResponseCode();

                } catch (Throwable malformedUrlException) {
                    return -1;
                }

    }


Now, we just need to call the getBrokenLinksOnWebpage method and pass in the page URL as the argument. It will return a list of all the urls for the broken links present on the page. We can read the list and do whatever we want to do with this like printing the list/storing the list in a text file.

Hope it helps!

Monday, October 13, 2014

IEDriverServer : Start up messages - Some Pointers

With WebDriver + Internet Explorer, the following start up messages get appeared into Console :

Started InternetExplorerDriver server (32-bit)
2.43.0.0
Listening on port 47206
Oct 13, 2014 3:12:21 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: I/O exception (org.apache.http.NoHttpResponseException) caught when processing request: The target server failed to respond
Oct 13, 2014 3:12:21 PM org.apache.http.impl.client.DefaultRequestDirector tryExecute
INFO: Retrying request

Many of us always feel awkward about this and think to be some potential error with IEDriverServer. Here is some of pointers provided by Jim Evans on why we are wrong : 

Want to block these messages anyway. Here is some code snippet which will do the trick.

Disable log messages

java.util.logging.Logger.getLogger("org.apache.http.impl.client").setLevel(java.util.logging.Level.WARNING);

This is to disable log message from getting displayed on the console. Updated code will look like the following :

// Disable log messages

java.util.logging.Logger.getLogger("org.apache.http.impl.client").setLevel(java.util.logging.Level.WARNING);
System.setProperty("webdriver.ie.driver","D:\\Selenium Info\\IEDriverServer.exe");
DesiredCapabilities dc = DesiredCapabilities.internetExplorer();
dc.setCapability("silent", true);
WebDriver driver = new InternetExplorerDriver(dc);

Note: dc.setCapability("silent", true); only blocks IEDriver starting message.


Hope this helps!

Thursday, September 25, 2014

Character Encoding in Eclipse

The Problem

Sometime we see texts appearing in Multi language in a webpage like in Google homepage (https://www.google.co.in/) i.e. हिन्दी বাংলা తెలుగు मराठी தமிழ் ગુજરાતી ಕನ್ನಡ മലയാളം ਪੰਜਾਬੀ. If we try to print these texts using Selenium WebDriver in Eclipse Console it might give you weird outputs like ???.

Sample Code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

       public static void main(String[] args) {
             
           WebDriver driver = new FirefoxDriver();
           driver.get("https://www.google.co.in");

           List<WebElement> links = driver.findElements(By.xpath("//*[@id='addlang']/a"));

           for(int i=0;i<links.size();i++){
              System.out.println(links.get(i).getText());
           }

       }

}

Output
??????
?????
??????
?????
?????
???????
?????
??????
??????

Why this happens

This happens because of character encoding and output may vary from IDE to IDE based on settings placed for Character Encoding. These regional language characters come under UTF-8 Character Set and if your editor have different settings for Character Encoding other than UTF-8, the above problem will appear.

How can I resolve the problem

In Eclipse, we can resolve the problem by setting Character Encoding in the following way:

File level Settings:
Right click on specific file (e.g. Test.java) -> Properties. Under Text file encoding section -> Select Other radio, Select UTF-8 from combo -> Click OK button.

Project level Settings:

Right click on Project -> Properties and then at the Text file encoding section: Select Other radio, Select UTF-8 from combo -> Lastly click OK button.

Eclipse level Settings:

Window -> Preferences -> General -> Workspace. In Text file encoding section : Select Other radio, Select UTF-8 from combo -> Lastly click OK button.

Now, again re-execute the above code. It should give you all the languages like texts. 


Final Output


हिन्दी

বাংলা
తెలుగు
मराठी
தமிழ்
ગુજરાતી
ಕನ್ನಡ
മലയാളം
ਪੰਜਾਬੀ

Hope this helps!

Thursday, September 18, 2014

Mobile Application Testing - Non Functional Approaches

With the tremendous growth of Mobile applications over the past decade or so, testing for both functional and non-functional attributes becoming very critical to get the application a better shape, win the race with other competitors and getting more business done. Here are some of the types of non-functional attributes that we can look into while testing –

GUI & Usability

  • Verify Interface: UI controls in the application like Pop-ups, text boxes, buttons etc. Also layouts and alignments of the interface.
  • Check for Interaction: Behavior of the application with user interactions like Multi touch, Voice Recognition, Tilt behavior etc.
  • Portrait & Landscape: Check behavior of the application in Landscape / Portrait mode.
  • Navigation between screens, text should be visible in supported languages and verification how application behaves when device is online/offline.


Localization
  • Localization testing: Verify application functionality in local languages (Hindi, Bengali, German etc).
  • Interrupt testing: Check how application behaves when Calls, SMS , Low/Critical Battery, Alarms etc are received.
  • Service Provider testing: Check how application behaves with respect to different carriers.


Compatibility
  • With Mobile Browsers (default browser, externally installed browsers).
  • With different mobile device configurations.
  • With Phone Device features (Flip, Camera, Slider etc.).


Mobile Application Performance
Mobile application performance based on different hardware/software configurations.

Tools for Performance testing of Mobile applications:


Referrence : http://www.methodsandtools.com/archive/mobileloadtesting.php

Monday, September 15, 2014

Java - Look for Files under given directory

Using Java utilities we can look for specific files matching specified pattern. Below is a sample:


Path rootDirectory = Paths.get(System.getProperty("user.dir")
+ "\\src\\test\\java");

String fileNamePattern = "*.{txt, doc}";

FileSystem fs = FileSystems.getDefault();
final PathMatcher pathMatcher = fs.getPathMatcher("glob:"fileNamePattern);

FileVisitor<Path> pathMatcherVisitor = new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file,
    BasicFileAttributes attribs) {
        Path name = file.getFileName();
        if (pathMatcher.matches(name)) {
            System.out.println(String.format("Matched file found: '%s'.", file));
        }
        return FileVisitResult.CONTINUE;
    }
};

Files.walkFileTree(rootDirectory, pathMatcherVisitor);


Hope this helps!

Wednesday, May 23, 2012

Run Selenium Tests on Cloud


Selenium IDE is an Integrated Development Environment for record, playback and debug selenium test scripts. As Selenium IDE is implemented as a Firefox add-on, it only works with Firefox. To run selenium IDE test scripts across multiple environments, we have to go through many configurations which needs many headaches.

To remove all these limitations and headaches, Sauce Labs has introduced Sauce Builder. Here are some important features about Sauce Builder :-

  1. Provides features like record, playback and debugging of selenium tests.
  2. Selenium 1 and 2 compatible.
  3. Run selenium tests in local browser and Sauce onDemand.
  4. Video and screen shots of every selenium tests.

Sauce Builder installation guide :-

Sauce Builder comes as a Firefox extension. Here are some to install it into your system :-

  1. Launch Firefox and navigate to the  Sauce Builder download page .
  2. Download Sauce Builder from this page and install.
  3. Restart Firefox.
  4. Open Sauce Builder by choosing Launch Sauce Builder item from the Tools menu of Firefox or press Ctrl+Alt+B from the keyboard.


For more information on Sauce Builder visit : http://saucelabs.com/docs/builder.

Monday, April 30, 2012

Selenium Overview

What is Selenium ?

Selenium is a software testing framework used for testing web applications.

  • It provides support to write test scripts in many popular programming languages, including C#, Perl, Python, Ruby, Java etc.
  • It also provides a great support in running the test scripts across multiple platforms, including Windows, Linux and Macintosh.

Mainly for these two reasons, Selenium is so popular in automation world.

Looking Inside Selenium

Selenium has many components that coalesce well to cook a wonderful automation testing system. Following are the components of Selenium :-
  • Selenium IDE
  • Selenium Remote Control
  • Selenium WebDriver
  • Selenium Grid

Selenium IDE :-
Selenium IDE was originally created by Shinya Kasatani in 2006 and implemented as a Firefox add-on which helps to record, playback and debug selenium tests. It records tests in its special test scripting language called as Selenese. Following are the features supported by Selenium IDE :-
  1. Record of tests and play them back.
  2. Debug test cases by setting break-points.
  3. Convert test cases to JUnit, Python, Ruby, C# or other formats.
  4. Support for adding user extensions.
  5. Locate web elements using IDs, XPaths etc.


Fig : Selenium IDE


Selenium IDE only works with Firefox. To run Selenium IDE tests across multiple browsers we need one server which will help IDE in doing that. Fortunately, we have one : Selenium Remote Control.


Selenium Remote Control :-
Selenium RC is a server which acts as a proxy between Application Under Test (AUT) and the test scripts.
It interacts with different browsers through the selenium core which is bundled with Selenium RC. It removes the need of installing selenium core on the web servers.



Fig : Selenium RC



Selenium Web Driver :-
Selenium web driver is the successor of the Selenium RC. Selenium Web Driver works in the same way users interacts with the web pages. In contrast to Selenium RC, it doesn't need a server to run. It directly starts a browser instance and controls it.


Selenium Grid :-
Selenium Grid is a server used to distribute tests on multiple machine so as to run tests in parallel. It cuts down the time required for running in-browser test suites.



Fig : Selenium Grid



Download Selenium from :- http://seleniumhq.org/download/


For study materials on Selenium :- 
  1. http://seleniumhq.org/docs/
  2. http://qtpselenium.com/selenium-tutorial/