JavaScript Libraries Spilled EVERYWHERE! Series #002

In the last blog entry I wrote up vows.js for testing JavaScript, in this I’ve tried out another testing framework called mocha. This framework is pretty extensive as you can do the things you do with vows.js as well as a lot of other techniques. In addition to mocha I’ve added a few other things to the mix. As well as a few obvious points where I need to RTFM still about how mocha works.

mocha.js

Before falling off into a conversation about reading the manual, I’ll dive into a bit about mocha. Mocha is a project, hosted on github as you might expect, that aims to provide a very feature rich test framework that can run via node or the browser. It also enables asynchronous and synchronous testing with some pretty sweet reporting.

The installation is the standard simplicity of a beautiful and elegant package from npm for node.js.

[sourcecode language=”bash”]
$ npm install -g mocha
[/sourcecode]

Of course, depending on the way you’ve setup your machine, you may need to hit that command with sudo. The sample test on the main documentation & project page is pretty straight forward, I’ve copied it below for easy reference.

[sourcecode language=”bash”]
$ npm install -g mocha
$ mkdir test
$ $EDITOR test/test.js
[/sourcecode]

Note that above, where “$EDITOR” is whatever editor you’re using, such as Sublime 2, Textmate, Webstorm or whatever.

[sourcecode language=”javascript”]
var assert = require("assert")
describe(‘Array’, function(){
describe(‘#indexOf()’, function(){
it(‘should return -1 when the value is not present’, function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
})
[/sourcecode]

Then run the test.

[sourcecode language=”bash”]
$ mocha

.

✔ 1 test complete (1ms)
[/sourcecode]

Overall, pretty sweet and simple. There are ways to setup mocha to do TDD or BDD style also. What I’ve done for my basic name generator I’m building has started of super simple. One of the other additions that I’ve added below is the should.js library. I’ll add more about this library, and the intent behind using it in the next blog article I write up.

My first tests I’ve put together I’ve entered below.

[sourcecode language=”javascript”]
require(‘should’);
var factory = require(‘./../lib/NameFactory’).nameFactory;

describe(‘when working with names using NameFactory’, function(){
var generateThisManyNames = 3;

describe(‘generating names’, function(){
it(‘should return a name between 3 and 20 characters’, function(){
factory.generate_names().length.should.be.approximately(3,20);
});
it(‘should return correct number of names’, function(){
factory.generate_names(generateThisManyNames).length.should.equal(generateThisManyNames);
});
})
});
[/sourcecode]

…and then I’ve implemented the absolute basic to get those tests to pass. You JavaScripters that have been at it for a while can likely detect my massive newbism among this code. I’d love feedback btw. 🙂 So here’s my basic implementation so far.

[sourcecode language=”javascript”]
module.exports.nameFactory = {
generate_names: function (count) {
if (count > 1){
return [”,”,”];
}
else{
return ‘stuff’;
}
}
};
[/sourcecode]

I’m still sketch on best practices around a number of object uses and creation in JavaScript. For instance in my code above, I’m creating a module, and setting up properties with functions, which leads to a number of questions… (maybe it is stack overflow time)

  • Is this an efficient way to create a JavaScript function for returning randomly created names?
  • What would your first tests be when creating a name generator? Any suggestions on some tests to add?
  • This shows some of my intent, such as returning a single result if no count is entered or it is less than 2, any suggestions on doing a kind of overloaded factory pattern method like that?
  • Now that I’ve gotten what I do above, I need some more tests to add to confirm that the returned content isn’t [”,”,”] <- cuz’ obviously that’s useless and not random, just returns the 3 string array that would prospectively have generated (or randomly selected) names. Ideas?
  • Is there another way to create a class or namespace that isn’t “module.export…” like I have above with “module.exports.nameFactory”? I’d love to just have a “NameFactory” or something. Not sure how or what way would be best in JavaScript land to put something like that together.

I’ve already moved past just this, but would love any feedback on the above questions and code snippets. I’ll post my results and the changes and additions from any body that posts feedback and suggestions in a subsequent post.  🙂

Cheers!

Coder’s Vacation : OMG! JavaScript Libraries Spilled EVERYWHERE! Series #001

NOTE: All parts of this series and my other series can be found on my series links page.

I sat down a few days ago on this trip to get a simple project setup, instead something else happened. It is my fault, entirely my fault. I could have stayed focused on a single library but instead I’ve let them explode. They’re everywhere now in my project!  😮  I’ve learned a great deal about breaking and fixing things though when working with testing frameworks and Node.js. All of this being rooted in my exceedingly simple project called NameFactory on Github. Here’s a few of the things I’ve stumbled through over the course of figuring out these testing frameworks.

vows.js (while chillin’ at Phils Coffee)

Phils Coffee, a staunch cup indeed!
Phils Coffee, a staunch cup indeed!

If you aren’t familiar with vows, here’s the brief description. Vows is a node.js testing framework that is built around the notion of BDD, Behavior Driven Development. The other important thing to note, is vows.js was built specifically to test asynchronous code. It can test others, but it is more oriented toward asynchronous code. Vows also runs tests in parallel, which thinking about that it takes the random order execution and ups the game even further by running them this way. It can really tighten up code execution and regression that things will indeed work in many different conditions. Building for web scale on the internet, that’s something we definitely need!  🙂

To install vows, it follows your standard pattern with npm:

[sourcecode language=”bash”]
npm install vows
[/sourcecode]

When I installed it I really bit the bullet and went for a global install.

[sourcecode language=”bash”]
sudo npm install -g vows
[/sourcecode]

From there I spun up a really simple example that is shown on the vows.js site:

[sourcecode language=”javascript”]
var vows = require(‘vows’),
assert = require(‘assert’);

vows.describe(‘Division by Zero’).addBatch({
‘when dividing a number by zero’: {
topic: function () { return 42 / 0 },

‘we get Infinity’: function (topic) {
assert.equal (topic, Infinity);
}
},
‘but when dividing zero by zero’: {
topic: function () { return 0 / 0 },

‘we get a value which’: {
‘is not a number’: function (topic) {
assert.isNaN (topic);
},
‘is not equal to itself’: function (topic) {
assert.notEqual (topic, topic);
}
}
}
}).run();
[/sourcecode]

From this example you run the tests by executing the code with the following command:

[sourcecode language=”bash”]
node division-by-zero-test.js
[/sourcecode]

This is all fine, but I’d rather be using the vows test runnner. To do that you’ll need to, instead of *.run(); call the *.export(); function instead. At this point I started scratching my head a bit and looking for parallels between my understanding of BDD and testing and what vows is doing. So I read further and came up with a few observations.

In vows the convention is to have one test suite per file and have the subject match the name. This makes sense to me, that’s how I’ve generally done similar things with Ruby, C# and the like. You end up with something like this for setting the subject and adding the various test suites:

[sourcecode language=”javascript”]
var suite = vows.describe(‘subject’);

suite.addBatch({/* run 1st */}).addBatch({/* 2nd */}).addBatch({/* 3rd */});

suite.addBatch({
‘A context’: {
topic: function () {/* Do something async */},
‘I am a vow’: function (topic) {
/* Test the result of this topic */
}
},
‘Another context’: {
topic: function () {/* Do something else async */},
‘I am another vow’: function (topic) {
/* Test the result of this topic */
},
‘I am another sub-context vow’: function (topic) {
/* Test the result of the topic */
},
‘And another sub-context’: {
/* Executed when the tests above finish running */
}
}
});
[/sourcecode]

Each of the topics are the thing that is being tested with the secondary element of each test being the test to verify the topic. Each of these things are run asynchronously, in parallel, so be sure to keep that in mind when using this framework. However note, in the sub-context tests above the sub-context happens in order. This can be used in various ways, but be sure to not abuse this execution model to avoid the asynchronous nature of JavaScript, I’ve only been working with vows for a few days and have already seen code snippets on the web that have done exactly that!

So this is the first part in a series where I’ll just cover all sorts of JavaScript libraries. It took a Coder’s Vacation however to get me started on this series, enjoy.

Coder’s Vacation : Getting Some Names…

Actual Live Status of the NameFactory Project

One of the things I’ve started working on is a #PhatData (re: my renamed version of big data) sample. So far what I’ve created is a JavaScript Application that works something like this. (The actual build status is shown to the right here in the “build status” image)

Step #1: Continuous Integration

The first thing I did was setup a solid node.js project that works on Travis CI (Continuous Integration). This is a pretty quick process. First create a directory and add an appropriate .gitignore and README.md file.

[sourcecode language=”bash”]
$ mkdir NameFactory
$ cd NameFactory/
$ git init
Initialized empty Git repository in /Users/adron/coderz/NameFactory/.git/
$ git remote add origin git@github.com:Adron/NameFactory.git
$ mate README.md
$ mate .gitignore
[/sourcecode]

The mate command is merely textmate, use whatever you’d like though to create the files. I also use Sublime 2 and other things, textmate just happens to be the poison I often choose from the command line. The .gitignore has the following to take care of WebStorm and other files that might pop up.

[sourcecode language=”bash”]
*.idea
.idea
idea
.DS_Store
*.DS_Store

lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz

pids
logs
results

node_modules
npm-debug.log
[/sourcecode]

The README.md I just put the following in. You don’t really need this, but I’m showing you what should be put in a minimal project. In addition to being a good practice, we’ll need the README.md file for plugging in Travis CI in a few steps.

[sourcecode language=”bash”]
Name Factory
===
Description: This is JavaScript Node.js Project for generating random names.
[/sourcecode]

Commit those files.

[sourcecode language=”bash”]
$ git add -A
$ git commit -m ‘Adding gitignore and README.md.’
[master (root-commit) 14b1cf8] Adding gitignore and README.md.
2 files changed, 23 insertions(+)
create mode 100644 .gitignore
create mode 100644 README.md
$
[/sourcecode]

Once that is added there are some other files needed for Travis CI that I’ll add before flipping on the actual CI project on the Travis CI Website. First add a .travis.yml file to the project.

[sourcecode language=”ruby”]
language: node_js

# test on two node.js versions: 0.6 and 0.8
node_js:
– 0.6
– 0.8
[/sourcecode]

The packages file should look like this.

[sourcecode language=”javascript”]
{
"author": "Adron Hall <adronhall@gmail.com>",
"name": "NameFactory",
"description": "A library that creates randomly generated names for insert into various databases.",
"version": "0.0.1",
"homepage": "https://github.com/Adron/NameFactory/wiki&quot;,
"main": "./lib/names",
"repository": {
"type": "git",
"url": "git@github.com:Adron/NameFactory.git"
},
"scripts": {
"test": "vows –spec"
},
"engines": {
"node": ">= 0.4"
},
"dependencies": {},
"devDependencies": {
"vows": "0.6.x"
}
}
[/sourcecode]

At this point add a few tests that you know pass. I added the following examples from the vows site (this is the default example on the site).

[sourcecode language=”javascript”]
var vows = require(‘vows’),
assert = require(‘assert’);

// Create a Test Suite
vows.describe(‘Division by Zero’).addBatch({
‘when dividing a number by zero’: {
topic: function () { return 42 / 0 },

‘we get Infinity’: function (topic) {
assert.equal (topic, Infinity);
}
},
‘but when dividing zero by zero’: {
topic: function () { return 0 / 0 },

‘we get a value which’: {
‘is not a number’: function (topic) {
assert.isNaN (topic);
},
‘is not equal to itself’: function (topic) {
assert.notEqual (topic, topic);
}
}
}
}).run();
[/sourcecode]

…now make sure the tests run ok…

[sourcecode language=”bash”]
$ node test/names_object_should_exist.js
··· ✓ OK » 3 honored (0.003s)
$
[/sourcecode]

So that’ll get the continuous integration via Travis-CI for NameFactory up and running, with a Github NameFactory Repository that is ready for the name generation code to be added. For my next blog entry I’ll leap into some generation strategies, dig up some good name lists (if you know of any, leave a comment w/ a link), and work on figuring out the fastest way to generate names.

Once that’s done, it’s time to setup some distributed databases.
Shout it

The #TypeScript Bomb Went off With a BANG Today!

First thing in the morning today the east coast was talking about Mary Jo Foley’s article about the TypeScript release. Later in the day Matt Baxter-Reynolds (@mbrit) released a bit of write up titled “Microsoft TypeScript: Can the father of C# save us from the tyranny of JavaScript?“. My first reactions went something like this:

  1. TypeScript sounds interesting. Anders is on it, so that’s a big plus. It’s a “superset” & “syntactic sugar” which is also interesting.
  2. TypeScript is a lousy name. I wish MS could find people to name things with something entertaining. It just seems disconnected.

After a little bit more review and an explosion on twitter I came to a few other conclusions.

  • The whole large applications notion just doesn’t cut it for me. Writing big applications well is about a good team, not about your language taking up the slack of a bad team.
  • I get that this makes things easier in Visual Studio and other IDEs to do certain “easy button” and F5 type development for coders that use those tools. There’s big plusses and really big negatives to this.
  • If you check out the site http://www.typescriptlang.org/ you’ll see open source with the code available. I’m stoked to see that Microsoft isn’t just playing lip service to this. They’re walking the walk these days, there’s even a pull requests section albeit no requests yet, and it is indeed using Git.  Just (git clone https://git01.codeplex.com/typescript)
  • A huge cool factor too, are the tons of plugins available already.
  • There’s a tutorial, which I plundered through real quick at lunch amid the plethora of pictures I took. Working through this tutorial I found the thing I’m happiest about, more so than the plugins, is that there is indeed an npm package (npm install -g typescript). Remember when installing, you’ll probably need to do a sudo.
  • The TypeScript Playground is a cool feature. Kind of like jsbin, except for toying around with TypeScript. However change the following snippet of code:

[sourcecode language=”javascript”]
class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}

var greeter = new Greeter("world");

var button = document.createElement(‘button’)
button.innerText = "Say Hello"
button.onclick = function() {
alert(greeter.greet())
}

document.body.appendChild(button)
[/sourcecode]

…and change the instantiation of…

[sourcecode language=”javascript”]
var greeter = new Greeter("world", 123);
[/sourcecode]

…or change it to…

[sourcecode language=”javascript”]
var greeter = new Greeter("world", "WTF");
[/sourcecode]

…and then think about it for a second. I thought the point was to do strong typing, but it seems that isn’t strong typing the bits in the parameter list of the object instantiation. Beyond little nuances like that, I’m generally ok with the enhancements they’ve added with TypeScript. Not sure people that know how to write JavaScript really need to have this. It seems there is a strong case that this is created to make it easier for C# (and by proxy Java) coders to grok and write JavaScript code. That’s fine by me too. The sooner people can stop whining about how horrible the language is (which I also will admit I’m totally fine with the language, just learn it, it isn’t hard).

Summary

In the end, I’m fine with TypeScript. I think Anders & team have put this together in a responsible, positive way and inclusive of prospective community feedback and interaction. After so many years of the opposite, I’m still always impressed when things are done in good faith with the community. Do I think they need to work on how they put these efforts together? Yes. Do I think the approach of bombing the community with this new thing with a whole pre-built MS community around it pre-existing? Yes. But I digress, overall all looks good, and nothing truly negative about it (unless one is personally perturbed). So I’d suggest to try it out, it can definitely make things easier in a number of ways. I might even have some examples cropped up over the next few days.

Thor Project Opens Up, Building the Cloud Foundry Ecosystem with the Community

The Iron Foundry Team are big advocates of open source software. We write code across all sorts of languages, just like many of the development shops out there do. Sometimes we’re heavy on the .NET, other times we’re all up in some Java, Ruby on Rails, spooling up a Node.js Application or something else. So keeping with our love of open source and our polyglot nature we’ve created the Thor Project with three distinct apps.

Before jumping into the applications though, a little context for what and where Thor is in the grand scheme of things. We need to roll back to the Cloud Foundry Project to get into that. The Cloud Foundry Project is an open source project built around software for PaaS (Platform as a Service) which can be used to build your own PaaS internally or externally, in a cloud provider or directly on hardware. It’s your choice how, when and where you want to use it. For more context on PaaS check out my previous entry “The Confusions of IaaS, PaaS and SaaS“.

Thor Project

Cocoa for OS-X

Thor Odinson
Thor Odinson, God of Thunder

You know who Thor is right? He’s this mythic Norse God, also known as the God of Thunder. Since we’re all about bringing the hamma we welcomed Thor into our team’s stable of applications. So starting immediately we’ve released Thor into the realms for contributions and fighting the good open source software battle! If you’d like to join the effort, check out the github project and feel free to join us!

Technically, what is the Thor Application? This is a Cocoa Application built for OS-X that is used for managing, deploying and publishing applications to Cloud Foundry enabled and or Iron Foundry extended PaaS Environments.

.NET for Windows 7

The .NET Metro version of the Thor Application is also released via github with a provided installer. We’ve almost taken the same path, except of course for the very different UX and UI queues with Windows 7 and the Metro UX design guidelines.

WinRT for Windows 8

I wasn’t really sure what to call this version. Is it Metro or WinRT or Windows 8 or something else? Anyway, there is a project, it is albeit empty at this point, but it is the project where the Windows 8 version of Thor will go! For now get the Windows 7 version and install it on Windows 8, it won’t have touch interface support and things, but should work just like a regular application on Windows 8.

The Code

To get started with these, generally you’d just clone the repo and do a build, then get started checking out the code. There is one catch, for the OS-X version you’ll want to pull down the sub-modules with the following command.

[sourcecode language=”bash”]
git clone git@github.com:YourForkHere/Thor.git
git submodule update –init –recursive
[/sourcecode]

Once you do that in XCode just make sure to then select the right project as the starting build project.

…then when the application is launched…

Thor Running in OS-X
Thor Running in OS-X

I’ll have more in the coming days and weeks about Thor & Iron Foundry. For now, check out the blog entry on the Iron Foundry Blog and subscribe there for more information.