Unit Testing

For those new to the concept of Unit Testing, the basic idea is to write a suite of automated tests which run against your code and test the smallest piece of functionality possible which usually means each method. You define a set of expected outputs for a set of inputs and ensure that the code does what you expect it to do.

A well designed unit test suite, once in place, gives various benefits: you can confidently change code safe in the knowledge that it still does what it was doing before; regressions can be seen immediately; new developers can get a sense of what the code is meant to do and how to use the API; you can design your API without having to write the client code – this makes it easier to divide up work and probably most importantly – coding to enable unit tests requires you to write loosely coupled code which is good for maintainability and flexibility. A poorly designed or incomplete test suite on the other hand can have some negative effects.

Javascript Unit Testing

There are a lot of JavaScript unit testing frameworks around now that Test Driven Development has become popular. Jasmine and jsUnit QUnit .Here we go with QUnit, which is developed to test jQuery, is the best fit.

QUnit provides a simple API. I only really used 4 functions:

  • module which provides access to setup and teardown methods.
  • test which defines a test as you might think.
  • ok an assertion.
  • equal also an assertion.

For those unfamiliar with Unit Testing parlance, an assertion is a test for the expected result. Just like in the English language you make an assertion, which could be true or false, in a unit test you do so with code. The functions setup and teardown provide a way to run code before and after each test is executed, enabling the state to be reset.

The ok assertion just takes a single argument which it expects to be a boolean. If it is true: the test passes, if it is false: the test fails.

The test function takes 2 arguments, the first is the name of the test and the second is a function which is the test. It’s imperative to follow a consistent structure with your test names and to be descriptive, remember unit test code is code too. If you don’t, you will be kicking yourself later when trying to debug why “mytest234″ failed with “Object does not support this property or method”.

For example:

test("2 plus 2 should equal 4", function() {
   var expected = 4;
   var result = (2 + 3);
   ok(result == expected,"2 plus 2 was not 4, universe broken. Good luck fixing that.");
});

In the above test you can see that we’re using the test function and the ok function. Let’s get this working.

Source : http://blog.building-blocks.com/technical-tips/javascript-unit-testing-with-qunit-and-sinon-js

Flash Firefox OS 2.1 into your Tablet

Originally posted on OpenMoz:

Excited about flashing 2.1 into your device? Well am too excited!

Flashing can be done via Windows as well as Linux and I will be explaining both the ways:

Point to be remember:

1: You have remote debugging enabled on your device.

2: Screen lock should be off, because when screen is off, device is disconnected.

For Linux user:

Step 1: Navigate to this link.

Step 2: Download all files and extract all files into home directory.

Step 3: Open your terminal and navigate to your home directory by this command.

$ cd

Step 4: Install adb and fastboot package into your system.

$sudo apt-get install android-tools-adb
$sudo apt-get install android-tools-fastboot

Step 5: connect your device through usb and type $adb devices in terminal.

$ adb devices
List of devices attached 
FLATFISH_123456    device

it would show your device name.

if it doesn’t echo anything then try running…

View original 404 more words

Improving JPEG image encoding

Originally posted on Andreas Gal:

Images are a big proportion of the data that browsers load when displaying a website, so better image compression goes a long way towards displaying content faster. Over the last few years there has been debate on whether a new image format is needed over the ubiquitous JPEG to provide better image data compression.

We published a study last year which compares JPEG with a number of more recent image formats, including WebP. Since then, we have expanded and updated that study. We did not find that WebP or any other royalty-free format we tested offers sufficient improvements over JPEG to justify the high maintenance cost of adding a new image format to the Web.

As an alternative we recently started an effort to improve the state of the art of JPEG encoders. Our research team released version 2.0 of this enhanced JPEG encoder, mozjpeg today. mozjpeg reduces the size…

View original 186 more words

Gaia Hacks – Part 2

Some useful commands that i came across  while contributing to OPEN SOURCE  to  Mozilla  (Firefox OS: Gaia hack)

All commands are used on Linux system (Ubuntu 14.04)

Hack – 1.  Flashing your Geeksphone(Keon) with Latest nightly

Get the latest stable and nightly builds as self contained downloads for flashing your phone from here :http://downloads.geeksphone.com/

geeksphone

Download your particular build and extract the archive to your filesystem. The archive contains the images and commands required to flash the phone using Windows, Mac OS, or Linux. Before attempting to flash the phone make sure that you have enabled Remote debugging on the phone. This option can be set by launching the Settings app and navigating to the Device information -> More information -> Developer tab. Also do not attempt to flash the phone if the power level is below 50%.

Enabling remote debugging on the Firefox OS Settings app

For Linux

To flash a Keon from Ubuntu add the following rules to /etc/udev/rules.d/51-android.rules

SUBSYSTEM==”usb”, ATTR{idVendor}==”05c6″, ATTR{idProduct}==”8013″, MODE=”0666″
SUBSYSTEM==”usb”, ATTR{idVendor}==”18d1″, ATTR{idProduct}==”d00d”, MODE=”0666″

Open a Terminal (control-alt-t on Ubuntu) window and cd to the directory containing the extracted files. Run:

./flash.sh

This should flash the new image to the phone. The phone will need to be set up again as all data will be cleared.

Hack – 2.  Flashing Latest Gaia repo to device

This development require installation of adb, the Android Debug Bridge. So first of all install adb .

Newer Linux distributions have adb already in their repositories. For Ubuntu 12.10 and later, run the following command:

sudo apt-get install android-tools-adb

Troubleshooting (If you get any error)

If you’re using a 64-bit install, and you get a “File not found” error when running ‘adb’ even though the file is present, you’ll need to install 32-bit compatibility libraries. To do this with apt:

sudo apt-get install ia32-libs

Restarting the b2g Process (if not running)

b2g is the equivalent of a XULRunner application running on the phone atop an Android-based kernel. Sometimes you may want to restart it; this is a way to reset the application environment without rebooting the entire device. You can do this by entering the following on your terminal while your device is connected to your computer (or while running the debugger):

adb shell killall b2g

Push to device

make install-gaia
make reset-gaia

With ADB (Android Debug Bridge) setup, these make targets will push Gaia to the device. install-gaia will just push updates of Gaia from your working directory to your device. reset-gaia will purge all existing configuration, profiles, web apps and database entries (a new settings database will be initialized) before pushing Gaia.

Now if you want to flash the master branch of your gaia repo

git checkout master
make install-gaia installs everything

if you want to flash some different branch you created, let’s say  branch :-  newbug

git checkout newbug
make install-gaia installs everything

If you want to flash any particular app say SMS instead of complete gaia repo

git checkout master (or newbug whichever you want)
APP=sms make install-gaia

One of my friend ask me how to make my own build app let’s say fitness app as default one (like Sms,Contact,Calendar which cannot be uninstall)

Simple Solution : Copy and paste your  app folder  in :  cd gaia/apps folder

Then push that app or complete repo to your device using above commands.

Hack – 3.   How to resolve ‘whitespace errors’ ? 

Whitespace errors ??   What the HELL is this (this was my reaction when i encountered first time :) )

When you made some changes to your files (say some js file), then sometime it give whitespace errors (Check using jshint tool) when commiting changes which is difficult to find.If you are here, you’ve seen the trailing whitespace errors shown by Git when committing changes.

Following shell scripts will help you…

  1. In a terminal of some sort, go to your working git repository ($GIT_DIR) : (In our case : cd gaia)
    cd $GIT_DIR
  2. Now open a new file for writing:
    cat > .git/hooks/pre-commit
  3. Paste the following code in the terminal:
    #!/bin/sh

    if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
    against=HEAD
    else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
    fi
    # Find files with trailing whitespace
    for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do
    # Fix them!
    sed -i 's/[[:space:]]*$//' "$FILE"
    git add "$FILE"
    done
    exit

  4. Hit “Enter” and then “Control+D” to end editing.
  5. Finally, make the file executable:
    chmod +x .git/hooks/pre-commit

Now every time you commit changes, Git will run the hook and clear trailing whitespace before actually saving the changes.

If you feel any problem then ping on irc channel #gaia or #b2g or join the gaia mailing list. You can ping me too on rishav006@gmail.com .

More blogs are coming on gaia and related hacks

Till then Happy Hacking !  :)

Gaia Hacks – Part 1

Following are some useful commands that i came across  while contributing to OPEN SOURCE  to  Mozilla  (Firefox OS)

All commands are used on Linux system (Ubuntu 14.04)

Hack – 1.  How to Run Gaia in your nightly browser

Install nightly browser in your system

  • sudo add-apt-repository ppa:ubuntu-mozilla-daily/ppa
  • sudo apt-get update
  • sudo apt-get install firefox-trunk

Getting the Source code

To get the source code for Gaia, fork us on GitHub and then clone your fork using git.This repo is around 1GB so have patience while clonning the repo.

$ git clone https://github.com/mozilla-b2g/gaia.git

Now go to your gaia directory.

cd gaia

After the above is complete, you are ready to make your local Gaia profile. Inside the gaia directory, which you should be in now, run:

DEBUG=1 make

The process above is going to do a bunch of things and the first time you run it, it is going to take some time so my suggestion is, take a break and make yourself some coffee. Once the above has completed the last line of output should be something like:

Profile Ready: please run [b2g|firefox]
-profile /Users/schalkneethling/mozilla/projects/gaia/profile

Now that we have our profile and nightly browser, let’s join the two. Open up a terminal (command line) and enter the following:This will open nightly browser and gaia running in browser :)

/path/to/nightly-browser -profile /path/to/profile

Something like this:-

rishav@rishav:~$ /usr/bin/firefox-trunk -profile /home/rishav/mozilla/gaia/profile-debug/ -no-remote
Screenshot from 2014-06-01 01:19:30

Hack – 2.  How to Update your forked gaia repo

Now another important thing.There is lots of changes takes place daily in master branch of mozilla-b2g/gaia repo.It’s not necessary for running gaia but it’s good if you update your forked gaia repo daily so that you will get updated with new changes.

git remote add upstream https://github.com/mozilla-b2g/gaia.git

Then run ‘git remote -v‘  you should see four lines, two called ‘origin’ (your fork) and two called ‘upstream’ (the mozilla-b2g original repo).

then, fetch from upstream repo:

git fetch upstream

Wait until gets all the changes, then go into your master branch (if you are not) and update it with the upstream master branch

git checkout master

git merge upstream/master

Once you have done that do ‘git push – -all‘  to push the updates into your fork (origin).

Hack – 3.  How to Run gaia unit-test

First of all what is unit test? :)

As part of the Gaia/B2G source code, we have  various unit tests available to run, for testing different aspects of Gaia and B2G.

Install nodejs and npm in your system.

The first thing you will need to do is open two terminals and go into main gaia directory in both terminals.

Now we need to set an environment variable to point to nightly firefox into both terminals.

We can do this by following command :

export FIREFOX=/path/to/your/nightly/firefox

Basically the FIREFOX environment variable has to point to nightly firefox binary.

Now after done with this, run following command in one of the terminal:

./bin/gaia-test

This will download a bunch of things and open the nightly browser.Now we are ready to run the unit test.

Now go to other terminal and run this command.This will run the unit test for SMS app.

make test-agent-test APP=sms

You can do this with any app whether it is contact, setting, calendar, sms etc….

If you run   ‘make test-agent-test‘    it will run unit test for all the app i.e complete gaia.

Best thing, once you start the unit test for any app (say sms), then if you make any changes in the code related to that app it will run the unit-test automatically and also very quickly :)

If you feel any problem then ping on irc channel #gaia or #b2g or join the gaia mailing list. You can ping me too on rishav006@gmail.com .

More blogs are coming on this till then

Happy Hacking  :)

 

 

 


			

Gsoc_weekly_report_3

Finally official coding period of Gsoc 2014  began from 21st may. First part of my gsoc project is  Bug 829820 - Ability to mark selected SMS threads as read https://bugzilla.mozilla.org/show_bug.cgi?id=829820. After a long discussion ,i think around one month, We arrived at important conclusions. As new features is landing for  SMS app, we planned to redesign new UI-flow  for SMS app.Thanks to Omega who designed the new UI-flow and my mentor Gabriele Svelto  who suggested more  changes and planned how to carried out these changes.

Finally me and my mentor decided to split this bug into smaller one so that it will become easy to track all the changes.

The idea would be to split it in the following bugs:
- Refactor the existing edit mode to use Omega's proposal 
  but w/o additional features (i.e. delete only),this would include 
  the thread edit mode too (UI should be rather compatible).
- Add mark-as-read mode to the thread list edit mode.
  From here i am extending my gsoc project.
- Add undo for both delete and mark-as-read in both modes.

I worked on the first section in this week.I refactor the existing edit mode to use Omega’s Proposal but without additional feature (i.e delete only), this would include the thread edit mode too.Apart from these i added select all and deselect all in one button.When we select all threads then it will show ‘deselect all’  button, other wise it will show ‘select all’  button.All codes are in my github forked repo.Link of the patch for this first section https://github.com/kumarrishav/gaia/compare/sms-interaction

Below are some screen shots of SMS app after landing this patch

.
Screen Shot 2014-05-03 at 04.55.46 Screen Shot 2014-05-03 at 04.55.50 Screen Shot 2014-05-03 at 04.55.56 Screen Shot 2014-05-03 at 04.56.00 Screen Shot 2014-05-03 at 04.56.04 Screen Shot 2014-05-03 at 04.56.07 Screen Shot 2014-05-03 at 04.56.14

 

 

How to build B2G emulator in Linux Environment

Before obtaining the code to build Firefox OS, you need a properly configured build system — this page shows you how. You can currently build on 64-bit Linux distributions .I built the B2G emulator on Ubuntu 14.04 (64-bit).Steps given here are same like in MDN, except few changes.

64 bit requirement installation

With Ubuntu 14.04, multi-arch packages are now the main way to support multiple architectures (e.g. 32-bit on a 64-bit install).  You must tell your Ubuntu system that you want to support 32-bit packages as well:

sudo dpkg --add-architecture i386
sudo apt-get update

Once you’ve completed that, then you can install the necessary packages:

sudo apt-get install --no-install-recommends autoconf2.13 bison bzip2 ccache curl flex gawk gcc g++ g++-multilib gcc-4.6 g++-4.6 g++-4.6-multilib git lib32ncurses5-dev lib32z1-dev zlib1g:amd64 zlib1g-dev:amd64 zlib1g:i386 zlib1g-dev:i386 libgl1-mesa-dev libx11-dev make zip libxml2-utils 

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 1 

sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 2 

sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 1 

sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.8 2 

sudo update-alternatives --set gcc "/usr/bin/gcc-4.6" 

sudo update-alternatives --set g++ "/usr/bin/g++-4.6"

Emulator build issues

If you are making an emulator build, you need to pay attention to these issues:

First, note that you shouldn’t use the x86 emulator — it is hard to install and not well supported.

Next, the build-system for the emulator builds both 32bit and 64bit versions of the emulator. As the emulator depends on OpenGL, this means that you need to have both 32bit and 64bit versions of OpenGL libraries installed on your system. See the discussion in bug 897727.

Way that you can solve this problem:

If your linux distro has multilib packages for OpenGL libraries, you can attempt installing them. You might then have to manually create some symlinks.

For example, here is the situation on Ubuntu 12.04 LTS x86-64. On this distribution, the libgl1-mesa-dev package cannot be installed simultaneously in x86-64 and i386 versions, but you can have the following combination of packages simultaneously installed:

sudo apt-get install libgl1-mesa-dev libglapi-mesa:i386 libgl1-mesa-glx:i386

After having run this command, you will still have to manually create some symlinks for the emulator build to succeed:

sudo ln -s /usr/lib/i386-linux-gnu/libX11.so.6 /usr/lib/i386-linux-gnu/libX11.so
sudo ln -s /usr/lib/i386-linux-gnu/mesa/libGL.so.1 /usr/lib/i386-linux-gnu/libGL.so

Clone B2G repository

The first step, before you can start your first build, is to clone the B2G repository. This will not fetch everything! Instead, it will fetch the B2G build system and setup utilities. Most of the actual B2G code is in the main Mozilla Mercurial repository.

To clone the repository, use git:

git clone git://github.com/mozilla-b2g/B2G.git (or git clone https://github.com/mozilla-b2g/B2G.git)

After cloning (which should only take a minute with a fast connection), cd into the B2G directory:

cd B2G

Till so far it was exactly same as what’s given in MDN.Now here are some changes.May be some of you are behind college firewall, Codeaurora.org and some other repo won’t allow to get the codes (Details are here : https://bugzilla.mozilla.org/show_bug.cgi?id=979986). So my mentor Gabriele Gsvelto came up with a good solution.We did some modifications in Xml files of B2G repo.Only thing you have to do is to use this patch.That’s it.We are done. :)  Really i struggled a lot for this.So, i thought to share with you guys.May it help you in future.Thanks to my mentor who came up with such a great solution.

Once you’ve retrieved the core B2G build system, you need to configure it for the device on which you plan to install it. To get a list of supported devices, you can use the config.sh utility — run the following command from within the B2G directory:

Now run this command :

env BRANCH="bug-979986-https-only" GITREPO="https://github.com/gabrielesvelto/b2g-manifest" ./config.sh emulator

Time for coffee break :) To build Boot to Gecko, simply use the build.sh tool.This will collect all the necessary code for building b2g emulator from various repos.So you don’t need to get those from all repos one by one. Whole procedure gonna take long time.If your internet connection is good, still i may take 3-4 hours.It’s around 12 GB :) Next step is to build the emulator.

To build Boot to Gecko, simply use the build.sh tool

cd B2G
./build.sh

Time for another coffee break, or possibly a nap (especially if this is your first build).

FInally we are done :) cheers  :)

Starting the emulator

To start the B2G emulator, type the following command:

./run-emulator.sh

This will handle all the emulator startup tasks for you. Now wait patiently while the emulator starts up and Boot to Gecko boots up on it. It can take a couple of minutes, so be patient.

Screenshot from 2014-05-19 08:16:56

Now you are thinking what is the use of doing all this, we can do same in simulator or in gaia (running in Nightly browser). Nope, there are some functionality that you cannot simulate on above stuff.So to simulate those functionality like Hardware Events Emulation, Telephony Emulation,SMS Emulation and much more  you need b2g emulator.

Using the Emulator Console


Each running emulator instance provides a console that lets you query and control the emulated device environment. For example, you can use the console to manage port redirection, network characteristics, and telephony events while your application is running on the emulator. To access the console and enter commands, use telnet to connect to the console’s port number.

To connect to the console of any running emulator instance at any time, use this command:

telnet localhost <console-port>

An emulator instance occupies a pair of adjacent ports: a console port and an adb port. The port numbers differ by 1, with the adb port having the higher port number. The console of the first emulator instance running on a given machine uses console port 5554 and adb port 5555. Subsequent instances use port numbers increasing by two — for example, 5556/5557, 5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility.

So open up a new terminal and type this command

telnet localhost 5554

It will show results something like this in your terminal  

rishav@rishav:~$ telnet localhost 5554
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: type 'help' for a list of commands
OK

Bingo you did this! cheers :) Now you can test stuffs by writing commands in same terminal.Some of the examples i have shown below :

SMS Emulation

The  emulator console lets you generate an SMS message and direct it to an emulator instance. Once you connect to an emulator instance, you can generate an emulated incoming SMS using the following command:

sms send <senderPhoneNumber><textmessage>

For ex :  sms send 12345 hello b2g

Screenshot from 2014-05-19 08:27:25

Telephony Emulation

The emulator includes its own GSM emulated modem that lets you simulate telephony functions in the emulator. For example, you can simulate inbound phone calls, establish data connections and terminate them. The system handles simulated calls exactly as it would actual calls. The emulator does not support call audio.

You can use the gsm command to access the emulator’s telephony functions after connecting to the console. The syntax for this command is as follows:

gsm <call|accept|busy|cancel|data|hold|list|voice|status>

For ex : gsm call 12345
Screenshot from 2014-05-19 08:28:05


Stuck somewhere? Got any problem! Feel free to ask either on irc channel (#b2g, #gaia) or in dev-gaia/dev-b2g  mailing list.
You can ping me too (comment here or mail me : rishav006@gmail.com).Happy to help :)
Till then HAPPY HACKING ! :) :)