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

Февруари 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.

Декември 23, 2011

TUI status update

The Tornado UI project is now more or less in stable phase, there are some small issues here and there, but the transport layer is stable and the HTML UI is complete. Also the closure-library link for the transport layer is ready.

As of today the develop branch from the last 2 months is merged in the master, which means that it is useful as it is, no need for special setup. You can just host it anywhere and point your Tornado device to the start URL (edit the M55/M70 settings and set 'Start URL' and 'Use start URL' to true).

The one piece still missing is the picture browser, we are working to resolve the memory restriction making web-kit to crash after a while with large files. Once this is ready you will have a complete interface, fully customizable via CSS only and very easy to extend with JavaScript.

The code is available on GitHub.

The documentation is progressing well, for now it covers only the transport layer and its abstraction layers, but the plan is for it to include the UI elements as well for easier use of the source as SDK for your own AV application or even your games.

The binding for closure library will be released soon, we are still clearing some compiler warnings in strict mode with type checking. Stay tuned. Using the closure compiler brings some new features, like compilation for a particular device, cutting out large portions of the code base and making the application faster. We are also working on some nifty features like app cache and local storage for even faster loading as well as some advanced visualization features, that will run on the newer devices and will bring the cutting edge presentation layer one expects from a modern web application.

Декември 22, 2011

Списание Дъга

Ако сте над 25 годишни и сте от мъжки пол (пък даже и от женски да сте..) сигурно си спомняте списание "Дъга". На мен ми беше любимото. Нещо като социалистическа версия на "комиксите". Интересното при него беше, че освен разказите съдържаше и игри и статии. Също друго, много интересно нещо бе, че различните истории се рисуваха в различен стил, което развива артистичните усещание у младежта. Нещо такова.

Та така де, всички броеве можете да разгледате или свалите от тук: списание Дъга

What is better than Glee?

Short answer: Mary Lou by Eytan Fox. 


Why? Because it treats real life and real problems and not high school imaginary drama with bunch of adults in their mids pretending to be high-school students. Yup. 

And the music is better. I like Svika Pick! And you like it too, if you like Harel Skaat. 

Attention (Anti Semites): the movie is from Israel and is in Hebrew
Attention (Anti Gays): the movie contains some homosexual imagery and transvestite imagery - nothing profane though. 

Декември 16, 2011

Developing JavaScript in Vim

Vim is great for coding, anyone can tell you that. It is customizable and extendable beyond anything I have encountered. However this is not seen as s plus immediately by JavaScript developers.

In this post I will try to summarize my experience with Vim for JavaScript programming and in particular with closure tools and node.

First of course you will need Vim 7.x. You will also need exuberant ctags or gjstags. The former is preferred though (explained later) and a JavaScript hinter/linter (jsl, jshint, jslint or gjslint).

Now for the vim plugins: you will need syntactic, taglist, nerd three and writeJSDOCcommen.

ctags is used to annotate your code and while it does not have the fancy options of Aptana Studio or Eclipse (like annotation for variables in the scope of a method or the properties of an object enumerated in the Object annotation as well as properties on its prototype all arranged in a nice tree view) it has something I often fine more useful - the fact that it is able to append the annotations so when you have opened 10 files and you see only one in your editor you still see all annotations for all open files. This is especially useful when working with code you do not know well (like the vast closure library for example, did I mentioned that I struggled with a tool to help me getting better knowledge of closure).

To use ctags effectively in vim I would suggest taglist. I use the following option setting in my vimrc:

let tlist_javascript_settings = 'javascript;f:functions;c:classes;m:methods;p:properties;v:globals'


This is - I want everything annotated in JavaScript files. I also use this shortcut:

nmap :TlistToggle


In ftplugin/javascript.vim I also have:

nnoremap   :call WriteJSDocComment()

This is not extremely useful, but a time saver. This was for code annotation, not lets begin with code checking.  I used to go with node js and jshint, but the truth is it does not make sense to install node js just to run hinting on it - after all it is marketed as server side JavaScript. Hinting is actually better done with syntactic.

By default it will look for any linter installed, I tried gjslint (the closure instrumentation linter) and jsl. The former tend to be too much closire library centric so probably the later would be better if you are not developing with closure in mind. Also the gjslint executable is much slower on larger files.


The last is NERD_tree which is not JavaScript must have, but it helps a lot see and browse your files as you do in any other IDE.

What I was not able to find is help system that is able to read JSDoc annotation for JavaScript and hint the usage. If anyone knows about such, please let me know.

PS: I often switch OSes, Looks and feels, IDEs and editors, browsers etc. I like diversity. However to this day I have not found the perfect JavaScript editor. Every one out there has a feature that I like but the others lack and each one lacks multiple features I like. Looks like finding the perfect tool is a never ending quest.

Октомври 14, 2011

What Is Wrong About 17259 Lines Of Code, Q&A

Web Reflection: What Is Wrong About 17259 Lines Of Code

I can answer and it is pretty simple and they have answered already by the way, you seem to just failed to read it: They have the resource and the will. Which means they can put 30 or 100 developers into something for months and even years and pay them to do something that might fail epically and still they would not mind! While the smaller companies and single developers cannot invest months into something that might fail or just be useless.

On the 'why' - it is just an experiment. The high expectations are to be the browsers that 'runs it native' and maybe they believe it will give chrome and chromeos some better user acceptance. Or maybe they really believe it is a step forward.

Anyway, just let them be. AFAIK very little number of companies are using the other attempts: GWT, Closure library, Go and so on. If we leave it alone it might become just one more project of them.