Pages

Tuesday, June 12, 2012

PickerBot- Flipkart Hack Day 2012


"Johnny Sokko And His Flying Robot" Does it ring a bell? It was my favorite program back in school. I am always fascinated by robots , especially the small ones which can be used as utility bots.

 This time at Flipkart Hack Day 2012 we planned to build a bot to serve similar purpose. The idea struck me as I saw an arduino based implementation of bitbeambot http://bitbeam.org/bitbeambot
"Robots that can play angry birds" thats awesome. Our idea was to build a bot that can pick items from one point lets say picking point and deliver to a particular shelf in warehouse.This bot can be used to organise products in warehouses to reduce manual efforts and minimise errors. The elongated plan was to build robotic arms which will pick items,scan and drop it on the Picker Bot.The PickerBot will deliver it to particular location. The PickerBot will be smart to avoid obstacles on the way with the help of sharp IR sensors.PickerBot will be assigned a wireless radios for real time monitoring solutions.Finaly equipped with a barcode reader it will be able to identify the deliverables.In the delivery shelf we will have another robotic arm to pick up the product and arrange it on the shelf. Sounds cool already...

Well I had two alternate plans as well for the bot.

If(success){
 The bot can be used to deliver snacks from the kitchen while I am on a difficult mission on my PS3.
}else {
 The non functional bot will be a toy for my newborn daughter.
}


This was my first hardware hack and I was already nervous about the fate of our robot.We soon realised that the motor drivers were not working as desired means we have to hack their need too.We connected the motors directly to arduino but then realise that the arduino out will not deliver sufficient Volts to power both the motors. Time was running out as it was 24 hrs event and it was already 6pm. We have nimble chance to buy another Motor driver and even if we purchase there is no guarantee that it will work as desired. The confusion was that we probably won't be able to stop the bot without the motor driver. We then connected the arduino to the motors and scripted the Motor controlling functions on arduino.The arduino board was connected directly to   the Motors and was able control the Motors. Victory !!! however small it was, it raised our hopes a little.
   
Few minutes later, we started assembling the parts of the bot. We connected the small motors with wheels and a caster wheel at the front to support and turn the bot left and right.We connected the breadboard, arduino board , connected the batteries and started testing it. The bot moved but was very slow.The second problem with the bot was that one motor moves slower than the other and the bot turns in circles than moving in a straight line.9pm it was , Dinner time.

Post dinner we connected the large DC Motors and large Wheels so that given more power the bot will move faster.To fancy us the bot didn't moved at all.:( The DC Motors were heavy and wheels had better grips in addition to that the carpeted floor were not helping.Our hope sank again.

Post midnight, The rolls arrived.After a short break we planned to add more batteries and the attach the lighter wheels on the front.Once we powered up the bot again the bot started rolling on  the floors. This also subsided the moving in the circle problem.3 am,  we were quite happy by this time so much so that to celebrate our victory we added LEDs to celebrate.

Finally, connected the servo motor and attached the IR sensors and our PickerBot was ready for Demo.


Thursday, May 10, 2012

Http profiler using Selenium to track omniture calls


We often come across issues like missing tracking calls for omniture or beacon tracking. These calls are useful for various reasons like to generate hit map using beacon tracking where it tracks the mouse clicks of users, to track business metrics like page views, number of orders placed online, user engagement with page objects etc.

Traditionally while development we verify the calls using tools like firebug in Firefox or Httpwatch in IE but checking the calls for a end to end flow of order placement or many pages in a automated way could get tricky.

I would like to share how selenium can be used for this purpose. DefaultSelenium has captureNetworkTraffic() method that can be used for this purpose. This method can be used to track omniture , beacon tracking calls for complete page views as well as ajax calls.


Sample code
 
package com.example.common;

import com.thoughtworks.selenium.Wait;
import fitlibrary.SequenceFixture;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.logging.Logger;

public class Omniture extends SequenceFixture {
    public static final String TIMEOUT = "120000";
    Logger logger = Logger.getLogger(Omniture.class.getName());
    static Properties props = new Properties();
 
    String omnitureCall;
 
    // This method validate presence of omniture call in
    // an action like openPage
 
    public boolean validateOmnitureCall(String calls) {
        BufferedReader reader = new BufferedReader(new StringReader(calls));
        String strline;
        try {
            while ((strline = reader.readLine()) != null) {


                if (strline.contains("200 GET http://domain-name.d1.sc.net/b/ss/")) {

                    omnitureCall = strline;
                    return true;
                }
                if (strline.contains("200 GET https://domain-name.d1.sc.net:443/b/ss/")) {

                    omnitureCall = strline;
                    return true;
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("omniture call not found.");
        return false;
    }

// This method validate each omniture params mentioned in
//Omniture.properties file with the actual omniture call for
//the action like openPage

    public boolean validateOmnitureParams(String page, String action) {

        try {
            FileInputStream f = new FileInputStream(config.locators + "/Omniture.properties");
            props.load(f);
            omnitureCall = URLDecoder.decode(omnitureCall);

            String omnitureQueryParamns = omnitureCall.substring(omnitureCall.indexOf("?") + 1);

            StringTokenizer stringTokenizer = new StringTokenizer(omnitureQueryParamns, "&");

            while (stringTokenizer.hasMoreElements()) {
                String param = stringTokenizer.nextToken();
                String paramArray[] = param.split("=");
                String paramName = paramArray[0];
                String paramValue = paramArray[1];

                String value = props.getProperty(page + "." + action + "." + paramName);

                if (!(value == null)){
                    if (!paramValue.contains(value)) {
                        logger.info("page "+page + " action " + action + " paramName " + paramName );
                        logger.info("Omniture param value defined in Omniture.properties for " + paramName + " is  " + value);
                        logger.info("Omniture param value in omniture call for " + paramName + " is " + paramValue);
                        return false;

                    }
                }
            }
            f.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }


// A open page call using selenium to open a webpage
 
     public boolean openPage(String page, String url) throws Exception {
        config.selenium.open(url);
        String calls = config.selenium.captureNetworkTraffic("plain");
        config.selenium.waitForPageToLoad(TIMEOUT);
        setWalletBalance();

        if (!validateOmnitureCall(calls)) {
            return false;
        }
        if (!validateOmnitureParams(page, "openPage")) {
            return false;
        }

        return true;
    }


Sample properties file
       
 Omniture.properties
         
 Homepage.openPage.v1 = Home
 Homepage.openPage.v2 = Home
 Homepage.openPage.v3 = Homepage
 Homepage.openPage.pageName = Homepage

Monday, April 2, 2012

Parallel execution of Fitnesse tests

We often face the problem of selenium tests running so slow.If you are using fitnesse as your testcase manager and testrunner, probably running tests in Suite takes a long time for you.

We faced similar situations as we integrated our testsuite in continuous integration system. Slow running tests ends up slowing down the build and in turn shipping the features to production environment.

The solution we would recommend is to use the trinidad package shipped with version 20100103. More info at the following url

http://www.fitnesse.info/trinidad

We are using the trinidad package testrunner to run our tests in threads in parallel.The fitnesse tests are maintained in a txt file and reading that file as input we create threads to run tests.



Sample code


package travelQa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import fit.Counts;
import fitnesse.trinidad.*;
import java.io.*;

public class InProcessRunner {
public static String testright, testwrong, testexceptions, testname,summary;
public static Counts cs;
public static int right, wrong, exceptions, totalright, totalwrong,
totalexceptions;
public static String str1, strhead , strsummary;
static UUID batchId = UUID.randomUUID();

public static void startProcessing(final List tests)
throws InterruptedException {

Thread t = new Thread() {

@Override
public void run() {
try{
for (String next : tests) {


String dbhost = "jdbc:mysql://localhost/automation?user=root";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(dbhost);

Statement stmt = conn.createStatement();
stmt.executeQuery("select * from environment");

ResultSet rs = stmt.getResultSet();

while(rs.next()){

System.setProperty("browser", rs.getString("browserCode"));



boolean status = new File("C:\\wamp\\www\\output\\"+ batchId +"\\"+ rs.getString("browserName") +"").mkdirs();
System.out.println(status);
TestRunner tdd = new TestRunner(new FitNesseRepository(
"C:\\root\\fitnesse"), new FitTestEngine(),
"C:\\wamp\\www\\output\\"+ batchId+"\\"+rs.getString("browserName")+"");

cs = tdd.runTest(next);
right = cs.right;
wrong = cs.wrong;
exceptions = cs.exceptions;
totalright = right + totalright;
totalwrong = wrong + totalwrong;
totalexceptions = exceptions + totalexceptions;


testname = tests.toString();
testname = testname.replace("[", "");
testname = testname.replace("]", "");
summary = cs.toString();


java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);

String sql = "insert into report(testName,passed,failed,exception,createdTime,batchId,browser) values ('"+ testname +"','"+ right +"','"+ wrong +"','"+ exceptions +"','"+ currentTime + "','"+ batchId +"','"+ rs.getString("browserName") +"')";
System.out.println(sql);
PreparedStatement ps = conn.prepareStatement(sql);
System.out.println(sql);

ps.execute(sql);
ps.close ();


System.out.println(" Test Passed " + totalright);
System.out.println(" Test Failed : " + totalwrong);
System.out.println(" Test Exceptions : " + totalexceptions);
}

}

}catch(Exception e){
e.printStackTrace();
}
}

};
t.start();

}


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

File file = new File("C:\\root\\fitnesse\\TestList.txt");


try {
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String csvline = null;

int c = 0;
List testList = new ArrayList();

while ((csvline = bufRdr.readLine()) != null) {
if (c == 1) {
startProcessing(testList);
testList = new ArrayList();
c = 0;
}
testList.add(csvline);
c++;
}
startProcessing(testList);

} catch (Exception e) {
e.printStackTrace();
}
}


}