Thursday, September 17, 2015

Showing jesmin test coverage details on SonarQube


Problem:
In our company we have separate SonarQube server which shows all the aspects of quality profiles in most of the projects. (This is a SonarQube – Jenkins implementation)
And then we newly implement a Karma-Jasmin test server which runs JavaScript based unit test cases.
Output from the Karma-Jasmin server is available on karma server not in the SonarQube server.
So we need to get that Karma-Jasmin server output in to the SonarQube server.then we can get all the quality details of our projects from SonarQube server.

SonarQube server don’t know what is Karma- Jasmine test server, there is no any link between these to,
So how do we do this? :D

Assumption:
Currently you have perfect up and running karma server with Jasmine test framework as on the below images.






Below is sample Karma.config JS file.(there should be a config file in order to run the karma- Jasmine server)
/// <reference path="tests/lib/Jasmine-jquery.js" />
// Karma configuration
// Generated on Fri Oct 31 2014 10:20:13 GMT+1100 (AUS Eastern Daylight Time)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
               
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['Jasmine', 'sinon'],


    // list of files / patterns to load in the browser
    files: [
                './tests/lib/Jasmine-jquery.js',

      { pattern: './tests/data/**/*.json', included: false },
      './tests/specs/**/*.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors : {
        './www/app/**/*.js': 'coverage'
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
  reporters: ['spec', 'html', 'coverage','junit'],


    // web server port
    port: 7777,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],
    //browsers: ['PhantomJS', 'Chrome'],
                //browsers: ['Chrome'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};

Prerequisites :
We are going to install the below plugin and generate an info file which contain all the unit test coverage details regarding the Karma-Jasmin test server.
Then we will pass that info file to our SonarQube server.
So please install below plugin.

npm install karma karma-coverage --save-dev


Let’s get start :
1).Normally when we start the karma server it is referring to the Karma.config JS in the root directory.
In our case we need to add some more configuration details to the same Karma.config JS file.
But I will not going to modify the original Karma.config JS.
So I will create a new karma.conf.ci JS file which refer to the original Karma.config JS file and at the same time I will add my own configurations to the new karma.conf.ci JS  file.

So create a new js file and name it whatever you won’t.(I name it as karma.conf.ci).
Add below lines to the newly created js file and keep it next to the original karma.config file.(at the same directory).

// refer to the original Karma.config JS file in order to get the original instructions and configurations
var baseConfig = require('./karma.conf.jS');
module.exports = function (config) {
    // Load base config
    baseConfig(config);

    // Override base config
    config.set({
        singleRun: true,
        colors:    false,
        autoWatch: false,
                reporters: ['junit', 'coverage', 'progress'],

//Out put file of this command will be an xml file
//My folder name is reports
//It is at the root folder
//This is not really mandetory becouse the xml file which generate from below code will not be use to populate the sonarqube.
        junitReporter: {
                     outputDir: 'reports'
        },
//we use the newly install plugin to generate a test output file.
//generate a coverage report 
//this the place where it contain the info file
.
 coverageReporter: {
            type:   'lcov',
            dir:    'reports',
            subdir: 'coverage'
        }
    });
};

Below is the junit report and coverage report folder.


Now let’s configure the Jenkins,
As I told you our goal is to parse the data on that info file in to sonarqube server.
So I have Jenkins server on my PC and I’m controlling the sonarQube using that Jenkins server.
So let’s go to Jenkins and do some adjustments.

Add below two configurations to your Jenkins project configurations,

//coverage report path
sonar.javascript.lcov.reportPath=./reports/coverage/lcov.info
//junit report path
sonar.surefire.reportsPath=./reports/ (this line is not really mandatory because im not going to use this file to get any data to the SonrQube)

Now build you Jenkins project in order to populate details at the SonarQube server.

Navigate to SonarQube server, And now you should able to see the UNIT TEST COVERAGE section at the sonar quality profile.

So for this unit tests coverage report is FULLY based on the icov.inf file.
(sonar.javascript.lcov.reportPath=./reports/coverage/lcov.info).

And there is nothing populated using the PhantomJS 1.9.8 (Windows 7 0.0.0).xml file.
i will use that file to populate some more details at the sonarqube.


So this is what we are looking for.
This unit test coverage details are getting from the coverage report and junit report.
And that’s it. :D




Wednesday, August 5, 2015

Implementation of Page Object Model in Appium C#

  • Initialize the web driver in a separate class.
  • Make auto implemented IwebDriver type property.
  • We can use this property in all the other places thru out this project by simply calling “InitialiseAppium.driver






  • In another class find the elemenats using below mechanism.

  1. ·Create propertyes for all the elemant (text box, lable,button,dropdownlist) that you need to cominuicate / identify.
  2. ·Add attributes to find the elemant using Id,Name,Xpath or anyother mechanisam in the selenium.
User can maintain multiple class files to locate elements in each and every web page in the project.



  • In the same class write your test steps, including clicks, scrolls, enter text ..etc.










  • Create another class file and write the test code with the relavant test attibutes ([TestFixtureSetUp], [Test]).

For the below exapleim I have use Nunit.



More test attributes in Nunit test: http://www.nunit.org/index.php?p=attributes&r=2.4.8


Monday, June 22, 2015

How to perform wait in selenium

Using the thread,sleep user can pause the currant thread.But handling a simple waiting for a element is a bit advance thing,
Because this need more resources from the computer(mainly ram usage)

1).Thread.Sleep(5000);


Using the webdriverwait:

2).WebDriverWait wait = new WebDriverWait(<webdriver>,<timetowait>);
eg:

   WebDriverWait wait = new WebDriverWait(WebDriverInti.driver, TimeSpan.FromSeconds(5000));

   wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id=\"rdiv\"/h3/a")));



Using webdriverwait: (More advance way)

3).
WebDriverWait wait = new WebDriverWait(WebDriverInti.driver, TimeSpan.FromSeconds(5000));
wait.Until<IWebElement>((d) =>
            {
              IWebElement element = WebDriverInti.driver.FindElement(By.XPath("//*[@id=\"rso\"]/div[2]/li[1]/div/h3/a"));
                if (element.Displayed && element.Enabled)
                {
                    return element;
                }

                return null;

            });


Using webdriverwait: (Friends way)

_driver = new ChromeDriver(@"C:\ChromeDriver", options, TimeSpan.FromSeconds(180));

Wednesday, June 17, 2015

Passing values to a "Authentication Required" alert box on selenium automation

Below is a sample "Authentication Required" alert box which we need to pass values.
In standard selenium automation we cant find the elements on "Authentication Required" alert directly, there for we cant communicate with the alert box and our test case will fail.Because cant move ahead without giving the correct credentials to the  "Authentication Required" alert box.
There are several defendant methods which are widely use in java and .net .Some methods might not successfully work based on the development framework or the selected web driver.

I will be given a easy way to pass values to Authentication alert box in .net development framework.
To do this we need to have a 3rd party library called "AutoItX3.dll".Download the latest EXE from here,().
  1. Install the AutoIt.exe and keep the installed location in your mind in order to get the AutoItX3.dll as a reference to our project in latter part of this article.
  2. In your selenium project create a separate class to do all the steps in order to handle the  "Authentication Required" alert box.
  3. Add the AutoItX3.dll as a reference to the selenium project.(as default this dll file will be available under the (C:\Program Files (x86)\AutoIt3\AutoItX ).
  4. Use the reference by adding the namespace "using AutoItX3Lib" at the top of the class.
  5. Now by using AutoIt.dll we can communicate with the "Authentication Required" alert box using below piece of code.

     var AutoIT = new AutoItX3();
     IWebDriver driver = new FirefoxDriver();
     Thread.Sleep(1000);
     driver.Url ="your desired wep page url/default.aspx";//required web page.
    //Wait for the authentication window to appear, then send username and password
     AutoIT.WinWait("Authentication Required");
     AutoIT.WinActivate("Authentication Required");
     AutoIT.Send("chathura");//username
     AutoIT.Send("{TAB}");//TAB key on the key board
     AutoIT.Send("Welcome@123");//password
     AutoIT.Send("{ENTER}");//enter key on the key board.
  6. Now user will directed to the required web page with the given credentials.

Sunday, June 7, 2015

Test Attributes in Unit Test

This is a sample well coded test class.
This contain the correct flow of using Unit Test Attributes.
  • [AssemblyInitialize()]
  • [ClassInitialize()]
  • [TestInitialize()]
  • [TestCleanup()]
  • [AssemblyCleanup()]
  • [TestMethod()]

using Microsoft.VisualStudio.TestTools.UnitTesting;
using SampleClassLib;
using System;
using System.IO;
using System.Windows.Forms;

namespace TestNamespace
{
   [TestClass()]
   public class DivideClassTest
   {
      [AssemblyInitialize()]
      public static void AssemblyInit(TestContext context)
      {
         MessageBox.Show("Assembly Init");
         }

      [ClassInitialize()]
      public static void ClassInit(TestContext context)
      {
         MessageBox.Show("ClassInit");
      }

      [TestInitialize()]
      public void Initialize()
      {
         MessageBox.Show("TestMethodInit");
      }

      [TestCleanup()]
      public void Cleanup()
      {
         MessageBox.Show("TestMethodCleanup");
      }

      [ClassCleanup()]
      public static void ClassCleanup()
      {
         MessageBox.Show("ClassCleanup");
      }

      [AssemblyCleanup()]
      public static void AssemblyCleanup()
      {
         MessageBox.Show("AssemblyCleanup");
      }

      [TestMethod()]
      [ExpectedException(typeof(System.DivideByZeroException))]
      public void DivideMethodTest()
      {
         DivideClass target = new DivideClass();
         int a = 0; 
         int actual;
         actual = target.DivideMethod(a);
      }
   }
}



ref:https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.testinitializeattribute.aspx

Monday, January 5, 2015

Building a iOS release using terminal commands

xcodebuild -showsdks to get the SDK versions you have.
then navigate to the Xcode project folder 

Build the project
xcodebuild -scheme <Xcode Project File> -sdk <SDK version name> -configuration <release type>

e.g.

xcodebuild -scheme DTZ\ Mobility -sdk iphoneos8.1 -configuration "Release"
Generate the IPA File

/usr/bin/xcrun -sdk iphoneos PackageApplication -v <Xcode project file> -o <Destinstion file psth>

e.g.

/usr/bin/xcrun -sdk iphoneos PackageApplication -v DTZ\ Mobility -o /Users/exilesoft/Documents/Chathurage/testDTZ.ipa

Error i got while building this is because our xcodebuild parameters are wrong.
/Users/exilesoft/Documents/Mobility.client/platforms/ios/DTZ Mobility/Plugins/com.danielcwilson.plugins.googleanalytics/UniversalAnalyticsPlugin.h:5:9: fatal error:       'Cordova/CDV.h' file not found#import <Cordova/CDV.h>        ^1 error generated.** BUILD FAILED **