Distributed Coding Prefunc: Ubuntu Erlang Dev & EUnit

Erlang LogoAfter installing Erlang on OS-X and then getting QuickCheck installing via Erlang, I wanted to expand the OS options I’m using to Ubuntu (i.e. Linux). So in this entry I’m going to cover the Erlang install, a quick eunit bit, and then a QuickCheck install and sample. The first step in geting Erlang installed is deciding how you want to install it. So far, it isn’t like Rails where it is pretty important which method you pick to how well it will work for you on Ubuntu. For Erlang all methods get you started with a good version that is working. The method I used was simply to install with apt-get.

sudo apt-get install erlang erlang-doc

After installing, always a good idea to run things and make sure they’re all content and happy with your machine. Startup the erlang shell.

erl

Then run some of the commands. Some I’ve found that will present you with useful and interesting information ist he erlang:system_info function with appropriate parameter passed. The otp_release parameter will get the version of erlang, the cpu_topology shows you the processor outlay for you machine (or in this case my virtual machine, with a single processor core allocated to it), and allocated_areas shows a bit about system memory allocations.

Eshell V5.9.1  (abort with ^G)
1> erlang:system_info(otp_release).
"R15B01"
2> erlang:system_info(cpu_topology).
[{processor,{logical,0}}]
3> erlang:system_info(allocated_areas).
[{sys_misc,80748},
 {static,1007616},
 {atom_space,98328,73387},
 {atom_table,95961},
 {module_table,9084},
 {export_table,50316},
 {export_list,240960},
 {register_table,180},
 {fun_table,3266},
 {module_refs,2048},
 {loaded_code,3437028},
 {dist_table,403},
 {node_table,227},
 {bits_bufs_size,0},
 {bif_timer,80200},
 {link_lh,0},
 {process_table,262144},
 {ets_misc,52504}]
[{processor,{logical,0}}]

Now that erlang is effectively installed we can write a little sample code. To do this I created a directory called “TestingErlang” and in it placed an Erlang code file called “eunit_tests.erl”. Note: I’m using Sublime 2 on Ubuntu, so exchange that for whatever text editor you’re using for your Erlang coding.

adron@ubuntu:~/Codez$ mkdir TestingErlang
adron@ubuntu:~/Codez$ cd TestingErlang
adron@ubuntu:~/Codez/TestingErlang$ sublime eunit_tests.erl

Add the header file include.

-define(NOTEST, true).
-include_lib("eunit/include/eunit.hrl").

Adding the header file include will cause all the function with _test() or _test_() to automatically be exported. An exported function of test() is created that can be used for running all of the unit tests. This also will include the preprocessor macros of EUnit for writing tests. So now throw a super simple test into the file.

You may want to, amid the automatic export of the methods ending in _test() or _test_() not name them this, and you’ll then need to add a line at the top of your code file like this.

-export([reverse_test/0]).

After this, add the function test as shown below.

reverse_test() -> lists:reverse([1,2,3]).

The complete code file should look like this.

-module(eunit_test).
-define(NOTEST, true).
-include_lib("eunit/include/eunit.hrl").
-export([reverse_test/0]).

reverse_test() -> lists:reverse([1,2,3]).

Build it and call the function.

Eshell V5.9.1  (abort with ^G)
1> c(eunit_test).
{ok,eunit_test}
2> eunit_test:reverse_test().
[3,2,1]
3> 

BOOM! Passing. So now we know we have a good Erlang install and eunit is setup and usable. In the following blog entries I have in the works, we’ll dive deeper into what and how Erlang works from an extremely basic level all the way to diving into some of the more complex features.

Distributed Coding Prefunc: Installing QuickCheck for Great Testing

Erlang LogoA few weeks ago I kicked off this series of “Distributed Coding Prefunc: Up and Running with Erlang” and had wanted to keep up the momentum, but as life goes I had to tackle a few other things first. But now, it’s time to get back on track with some distributed computing. I intend to write tests with my samples, as I often do, I decided to take a stab at .

Before going forward, note that there is QuickCheck for Haskell and there is a QuickCheck for Erlang. Since the point of this “Distributed Coding Prefunc” is to get started coding with Erlang from zero, I’ll be talking about the Erlang version here. This version is created by John Hughes and Koen Claessen, starting the Quviq Company in 2006.

To download QuickCheck choose the version you intend to use, I’ve chosen the commercial license version from the download page.

At the command prompt, install QuickCheck by running Erlang and then run the install with these commands.

Launch Erlang:

$ erl
Erlang R15B01 (erts-5.9.1) 1 [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1  (abort with ^G)
1>

Then execute the install:

1> eqc_install:install().

If the execution of the install displays this error, you’ll need to use sudo.

Installing ["pulse-1.27.7","eqc-1.27.7","eqc_mcerlang-1.27.7"].
Failed to copy pulse-1.27.7--copy returned {error,eacces}??
** exception exit: {{error,eacces},"pulse-1.27.7"}
     in function  eqc_install:'-copy_quickcheck/3-lc$^0/1-0-'/3 (../src/eqc_install.erl, line 63)
     in call from eqc_install:install2/4 (../src/eqc_install.erl, line 44)

Kill Erlang with a ctrl+c and restart Erlang with the sudo command.

$ sudo erl

Now when you install you should see the following result or something similar. You’ll be asked to continue, select lowercase ‘y’ to continue. It may be different for some, but when I hit uppercase ‘Y’ (I suppose I got overzealous to install QuickCheck) it finished as if I’d hit no or something else.

1> eqc_install:install().
Installation program for "Quviq QuickCheck" version 1.27.7.
Installing in directory /usr/local/lib/erlang/lib.
This will delete conflicting versions of QuickCheck, namely
    []
Proceed? y
Installing ["pulse-1.27.7","eqc-1.27.7","eqc_mcerlang-1.27.7"].
Quviq QuickCheck is installed successfully.
Looking in "/Users/adronhall"...   .emacs not found
Could not find your .emacs file!
Try install("path-to-emacs-file") or install(new_emacs).
Bookmark the documentation at /usr/local/lib/erlang/lib/eqc-1.27.7/doc/index.html.
ok

You’ll note above, I don’t currently have emacs installed. The reason it looks for emacs is because QuickCheck has templates/ops mode for emacs. So if you use emacs you’re in luck. I on the other hand, don’t, so I’ll just be using this from wherever I’m using it.

In addition to the lack of emacs, another important thing to note from the message is the link to documentation. Once you get this link open it up and check out the docs. They’re broken out into easily readily topic spaces and are a good place to do initial reference checking while you’re writing up your specs.

If you have a license, it is important to note, that if you’ve used sudo with your installation you’ll need to kill your running Erlang session and start it anew without sudo. Otherwise you’ll run into issue down the road trying to use the libs (unless of course you want to go hack on your permissions manually). Once you’re ready to register the software it’s simply one command, where xxxxx is your license key.

eqc:registration("xxxxxxxxxxxx").

Alright, next time we’re on to next steps…

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!  :o  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:

npm install vows

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

sudo npm install -g vows

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

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();

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

node division-by-zero-test.js

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:

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 */
        }
    }
});

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.

HTML, CSS, JavaScript and Metro App Building on Windows 8 Part 2

In the first part of this seriesI kicked everything off by starting a Windows 8 JavaScript Project and added QUnit-Metro via Nuget. Now that we have a small executable application, I’ll get some things added and cover what exactly it is we’re doing in each part. Open the project up that we created in the previous blog entry of the series. Once open find and open the default.html, default.js and default_tests.js files to work with. In the default.js file you’ll find the following code in the default.js.

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
            } else {
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
    };

    app.start();
})();

A Bit of Context – default.js

At the beginning you’ll find that all the code is enclosed in a self-executing anonymous function. This gives us the ability to avoid naming conflicts or accidentally modifying variables in other spaces. Kind of the “namespaces” of C# or other organizational code features from other languages (I said kind of, there are other ways to do this too, this is just one). The other cool thing about this is it keeps identifiers out of the global namespace which also helps performance (it’ll also get you called all sorts of stuff if you create global variables in JavaScript! I’m nice, I won’t do it, but be prepared to be appropriately punished for such dissension as global variable creation! I warned ya.).

This next part (reminds me of why I find JavaScript scary in addition to awesome) has a variable that turns “strict mode” on. What this does, just like those of you may know from the Visual Basic days, is turn on a strict mode of additional error checking for code. It helps prevent you from doing all sorts of dumb things, like trying to assign a value to a read-only variable. For more on “strict mode” check out Microsoft’s Strict Mode Page.

The remaining bits of code in the default.js are the handlers for the application activated and checkpoint events. These events are fairly self explanatory, suffice it to say they happen when the application launches and checkpoint fires when a particular checking event happens against the Process Lifetime Management. The Process Lifetime Management handles all of the application suspend, resume and background events.

TDD & BDD For The Win!

Ok, so this isn’t the best example of either really, but to get started we want to wire up an event to a button. But first we want to test if the event is wired up. How does someone tests if an event is wired up in JavaScript? Like this.

test("Where the text box is populated ", function () {
    var result = document.getElementById("messageOutput").innerText;
    ok(result == "", "should have empty inner text.");
});

Adding a Button & Some Button Functionality

Ok, done with the context. Let’s add a button and make some magic happen. Bring focus to the default.html page and add a button, a text box and the respective components.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Readingz</title>
    <!-- These files are included when the project is generated, I don't really know where they are... -->
    <link href="//Microsoft.WinJS.1.0.RC/css/ui-light.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
    <!-- Turned on the testing. -->
    <script src="/js/qunitmetro.js"></script>
    <script src="/js/default_tests.js"></script>
    <!-- Default Metro files. -->
    <script src="/js/default.js"></script>
    <link href="/css/default.css" rel="stylesheet" />
</head>
<body>
    <p>Click the button to run the tests for the default.html and default.js code.</p>
    <input id="peripheralParameters" type="text" />
    <button id="runTests">Run Tests</button>
    <p id="messageOutput"></p>
</body>
</html>

NOTE: I made more than a few changes from the default.html included in the previous part of this series. One hard to notice change is that I switched the style sheet from the dark Metro theme to the light Metro theme.

With those additions add a function to the default.js file as shown below and then add the event handler.

(function () {
    "use strict";

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    WinJS.strictProcessing();

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {

            } else {

            }
            args.setPromise(WinJS.UI.processAll());

            var runTests = document.getElementById("runTests");
            runTests.addEventListener("click", buttonClickHandler, false);
        }
    };

    app.oncheckpoint = function (args) {};

    function buttonClickHandler () {
        document.getElementById("messageOutput").innerText =
           "Parameters Passed: " +
           document.getElementById("peripheralParameters").value +
           "!";
    }

    app.start();
})();

I now have one button now working, actually doing something, with a unit tests to verify that the button exists and the event is wired up. Some progress is being made!

If I run the application I get passing tests. That’s it for now. In the next entry we’ll dive deeper into testing and into functionality.

Until next time, happy scripting with the JavaScript on Windows 8.

HTML, CSS, JavaScript and Metro App Building on Windows 8 Part 1

I’m a fan of JavaScript and I’m warming to some of the Metro interfaces on Windows 8. I’ve always found the Windows 7 Phone UI, which is the first iteration of the Metro UI, to be a very slick phone interface. So with this blog entry I’m going to lay out setting up a default Windows 8 Metro application using JavaScript as the language of choice.

Prerequisites:

  • Windows 8
  • Visual Studio 2012

Open Visual Studio 2012 and click on file -> new project -> and then find the JavaScript section and pick the blank metro app.

New Windows 8 Metro Project

New Windows 8 Metro Project

Once you have the application created, I’d suggest following good practice and adding QUnit-Metro to your project with Nuget(or get the actual files if you don’t want to use Nuget).

Getting QUnit-Metro via Nuget

Getting QUnit-Metro via Nuget

Once you’ve added the QUnit-Metro interface you’re ready to get started writing tests. But before writing a test take a look at the additional files that the QUnit-Metro Nuget Package adds to the project.

Things Added With QUnit-Metro

Things Added With QUnit-Metro

In the screenshot (click for a full size image), I’ve pointed in a clockwise order:

  • The package is added and listed in the packages file now for Nuget.
  • There are now three CSS files added for QUnit. Two are Metro specific, which gives a more Metro look to the results of the tests.
  • The qunitmetro.js file is the testing framework.

With this collateral added we can setup a test within the default.html page of the project. First add the following code so that your default.html file looks like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Readingz</title>
    <!-- These files are included when the project is generated, I don't really know where they are... -->
    <link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
    <!-- These are the CSS and JavaScript files that I've edited for testing. -->
    <script src="/js/qunitmetro.js"></script>
    <script src="/js/default.js"></script>
    <script src="/js/default_tests.js"></script>
    <link href="/css/default.css" rel="stylesheet" />
    <link href="/css/qunitmetro-light.css" rel="stylesheet" />
</head>
<body>
    <p>Content goes here</p>
    <button>Press This!</button>
    <!-- This is for testing only. It goes away when application is ready to ship. -->
    <div id="qunit"></div>
</body>
</html>

The Microsoft.WinJS.1.0.RC libraries are included by default, which I’m assuming when I get fully upgraded to the released version of Windows 8 and Visual Studio 2012 that this might just read Microsoft.WinJS.1.0. The section of scripts and links below that are the added QUnit-Metro files. I included the qunitmetro-light.css file for metro style test results.

In the body of the page the div with the id of qunit…

<div id="qunit"></div>

is added where the test results will display. That’s how simple it actually is. To add actual tests, I’ve added a default_tests.js file to the js directory. I then added a simple test to the file that I’ve shown below.

test("hello windows world of javascript tests!", function () {
    ok(1 == "1", "Passed!");
});

Run the application and you’ll find the following result displayed in your application.

The Running Application

The Running Application

This is one place where an odd thing seems to be occurring (if you have any idea what the problem is, leave a comment, and I’ll do the same when I get the issues resolved). The test just keeps reporting “Running…” until you click on Readingz, noglobals, or somewhere else on the screen in that area to make an action occur. When I click on Readingz the test runs successfully like it should.

Test Ran

Test Ran

What’s up with that? It’s a pretty odd action.

Another issue that I ran into, which was a user error issue on my behalf, was I swapped around the three script files so the qunit-metro file loaded last. I actually stumbled and posted the issue on Stackoverflow here.

Shout it