Общо показвания

февруари 13, 2012

Tests running in both browser and nodejs

Following my post about developing on cloud9 and running your tests in both node.js and browser, this post will show how I had to make some sacrifices to allow proper tests constructions and support for assert testing that works on both node and browser.

First - the screenshots!

Tests run in browsers


Same tests run in node

The 'test runner' (debug name designated to 'AllTest' in the screenshot) is exactly the same file (see the post mention in the beginning of this one), the only difference is the run script: we need to use run-in-node.js and run-in-browser.js respectively, which is pretty easy to maintain.

I spend a good part of the Sunday trying to figure out a way to use a test framework that works exactly the same in both the browser and node.js and on top of that can work just fine with requirejs (which I use on the server and on the browser with amdefine and rjs on the server). I have tried several but I either couldn't make it work with requireJS or run the same tests in both environments. The closest thing to what I imagined a test suite would be was Vows. Unfortunately it runs only in node and the code depends on process, file and other objects not found in the list of host objects in the browser.

Never the less, the way one structure the tests in Vows was what I was looking for. The only thing I could do in this case was 'take it and make one for yourself'. Finding assert library that works in both node and browser was easy. Next I created a simplified version of Vows. It is _NOT_ API compatible and it lacks large portion of the features offered in Vows (If you are developing for node.js I suggest using Vows - really!), like nested topics for example.

However for my needs I was satisfied: it supported sync and async topics (thanks Vows for the idea), the topic can be a function or any object, the tests should return its result as boolean.

A simple asynchronous test looks like this:

    vow.addTests({
        topic: function() {
          var callback = this.callback;
            next(function () {
                callback(null);
            });
        },
        'test async assert': function( shoudBeNull ) {
            return assert.isNull( shoudBeNull );
        },
        'test async assert failing': function( willBeNull ) {
            return assert.isTrue( willBeNull );
        }
    });


All topics that are functions are run and the tests are invoked asynchronously. I have also implemented this same thing in a sync manner and it was much slower, so maybe the people that dislike the 'callback spaghetti node code' are not right after all?

Example for sync test ( i.e. tests invoked directly with the topic result ):
vow.addTests({
    topic: (function() {return null;})(),
    'sync test': function(shouldBeNull) {
        return assert.isNull( shouldBeNull );
    }
)};
If you are looking for simple test running suite that works in both browser and nodejs, take a look at it. I am sure there are many improvements to be desired, but I really needed it for my use case mostly and it covers it.

The code is part of the tablet branch of the 'Tornado UI' project and can be found on GitHub.

Happy hacking.

февруари 09, 2012

ACTA и българите

В България всичко е наопъки. Накъдето и да погледнеш, никога нищо не си е на мястото и никога нищо не е наред. В американските филми се питат "всичко наред ли е", в нашите условия се питаме "има ли нещо, което е наред".

Та така и с протестите срещу ACTA. Някакви хора разпространяват от трибуната на що годе популярния си блог (а вероятно и още много, просто спрях да чета БГ блогове, защото ми писна да чета глупост след глупост, този го оставих, защото се списва от чужбина) идеята да се противопоставим на АКТА чрез постване на снимка в фейсбука си.

Сега, аз вярно че фейсбук нямам, като бях малък нямах измислен приятел, сега не са ми нужни 700 такива. Но не това е важното. Важното е, че все още не става ясно как твоя снимка в твоя профил как даряваш кръв фактически (за разлика от имагинерно) влияе на ратифицирането (или не) на АКТА. Мисля, че е ясно, че управниците ни не четат ТВОЯ фейсбук.

Един от "интелигентните" коментари е( перефразирам ): "Какво не е ясно - показваш, че да споделяш не е лошо."

Така е. Сигурно въпросният господин споделя и жена си с нуждаещите се. Вероятно е така, щом толкова е 'за' споделянето. Но дори и той лично да споделя половинката си с който там има нужда или пък чувства близък и достоен за споделяне, не става ясно как това влияе на властите ни, които в крайна сметка взимат решенията вместо нас. 'Щото прочем и да споделя жена си, в законовата нормативна база това си е прелюбодеяние. Нищо, че за него лично е хубаво нещо споделянето. Но да оставим този екземплят.

Насочваме се към "организираните" протести.

Предвид климатичните условия в нашата бедна република (дневна темепратура -10 и надолу), по мои груби убеждения на уречените места ще се явят има няма 10% от заявилите желанието си. Останалите ще протестират от комфорта на отопления си дом или офис с очи широко вперени в монитора, белким се почувстват на мястото на събитието зачитайки някой и друг "туит". Останалите ще се почувстваме на мястото на събитието само ако някоя национална телевизия няма коя бедстваща община да ни покаже та заеме преден пост сред протестиращите/премръзващите.

В крайна сметка и протестите не виждам какво могат да направят специфично в нашата държава. Даже това, което се чудя на нашата държава е как има толкова много 'задник'. Как е възможно някой да се е надупил на толкова много страни едновременно. На мутрите, на Русия, на САЩ, на ЕС, на не знам си кой още.

На протестиращи ще кажа: вместо да си губите времето да протестирате в БГ, особено пък извън столицата, вземете се вдигнете да идете до някоя европейска държава, в която задника на държавния апарат не е изцяло насочен към бизнес интересите на САЩ, ами поне частично, ей така, с един градус обсег, и към поданиците и. Там протестирайте, белким там не мине ратификацията, а пък те нашите по напъна отзад ще усетят дали трябва или не трябва и какво трябва да направят.

Това е.

февруари 05, 2012

Developing frontend with node js and cloud9

Not so long ago I was describing how disguised I am with the whole nodejs and cloud9 story, how it was working bad, how it does not support 'MY' use case and so on.

Well as with most things I tend to re-evaluate my position from time to time, just to be sure and sometimes to check if things are progressing.

The last few days I was starting an spin-off of my Tornado UI project ( an Open Source interface for Tornado IPTV devices, read more ). The new code is loosely based on the existing one, re-using some of the components, but still is a chance for fresh start and evaluation of new options in code organization and structuring.

Part of the code for the previous project was ported to closure-library to allow it to cleanly compile with closure compiler. I can gladly tell that it was a success, all tests of the converted code passed and it is available online for anyone to use it in a closure based project. It covers completely the communication layer for Tornado, but does not provide any UI. It assumes the closure developer would use closure techniques for the UI as well and I doubt my ability to fully utilize closure paradigm for UI components.

The effort to use closure library was an enlightening in a way, allowing me to free myself from Crockford's mantra for privacy in the code. Meanwhile I have read tons of posts and articles about patterns, speed, reuse as well as package management, what Harmony will bring, what should we do until then and so on and so on, basically re-educating myself on the matter of serious JavaScript.

One big problem for me was the fact that I am not actually using any of the power of the 'abstraction' the libraries provide (i.e. Jquery, MooTools, closure and so on), when developing for a known environment one does not need abstractions and polyfils (well, mostly does not, if you have seen the code for TUI, you'd notice that bind is not part of the Function prototype). It just bloats the code and rarely enforces useful patterns ( unlike closure, mootools and jquery allow you to code in any style possible, even with no style).

Another problem was that I wanted to be able to test the code on a test server or at least in a console with cli, instead of loading it in browser every time. At the time I started the project there was no clean way to run the same code without any change on node and in the browser. Or at least I could not find it.

This week I started the new project, it aims to bring new features to the Tornado line of device, at least two of which will be co-developed with the in-house development team at the company. It will also be able to work on any android device (2.2+). This time I was determined to use some CLI testing for the code to speed up development and bug catching.

I went looking for a suitable tool again. First I was thinking about closure library and found nclosure. Unfortunately it seem to be not updated lately and does not work with node 0.6+. Then I tried JSClass, it require shift in package management, but still is manageable. Unfortunately the dependency tracking and loading is not working as I expected, maybe it is me, that cannot figure it out, (even though I figured out closure and requirejs), but after two attempts I gave it up.

The last was amdefine. It requires node 0.6+ but apart from that works very well and suits me perfectly. Very good explanation on how to use it could be found on their github page, linked above.

Lastly I wanted to try cloud9 again. I downloaded the latest source from github and it work very nicely with node 0.4. Unpleasantly for me it does not work with node 0.6, while amdefine requires it, which makes it impossible to use nodejs as test run and cloud9 locally. The only possibility remained hosted version of cloud9. Recently they announced support for running your code on node 0.4 or node 0.6, configurable from your IDE. Month ago they also featured npm command line interface, so I figured I should try it.

A working setup follows:

On c9.io open your project and add requirejs and amdefine:

npm install requirejs
npm install amdefine

In your project, configure the test runners, one for node and one for browser. Node:

var requirejs = require('requirejs');

requirejs.config({
    baseUrl: __dirname + '/javascript',
    nodeRequire: require
});

//Use eyes-console in node js for prettier output

requirejs(['tests', 'debug/eyes-console'], function(tests, SimpleConsole) {
//    Enable logging in node
    (new SimpleConsole()).enable();
    tests.run();
});

Browser:

require.config({
    baseUrl: "tablet/javascript"
});
require([
    'tests',
    'debug/simple-console'
], function(tests, SimpleConsole) {
    (new SimpleConsole()).enable();
    tests.run();
});

Note: the past are relative and fit my project, those may vary for yours. 

The browser runner requires html file as well, however the node test runner can be run as easily as starting a node process with the file. Remember to set the run process to use node 0.6.

Conclusion: Cloud9 ide is a viable option for developing and testing your code, even if you are developing only a front-end application. However not all approaches for code organization work, currently I have managed to make only AMD with requireJS. I expect the future to bring more variety in the options.

As a side note, Eclipse Orion has much better git UI (as a real UI, not only cli), however it is still in a very early development and on top it does not support running node instance, so you cannot really test your JS code in it.