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.

[sourcecode language=”bash”]
sudo apt-get install erlang erlang-doc
[/sourcecode]

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.

[sourcecode language=”bash”]
erl
[/sourcecode]

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.

[sourcecode language=”erlang”]
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}}]
[/sourcecode]

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.

[sourcecode language=”bash”]
adron@ubuntu:~/Codez$ mkdir TestingErlang
adron@ubuntu:~/Codez$ cd TestingErlang
adron@ubuntu:~/Codez/TestingErlang$ sublime eunit_tests.erl
[/sourcecode]

Add the header file include.

[sourcecode language=”erlang”]
-define(NOTEST, true).
-include_lib("eunit/include/eunit.hrl").
[/sourcecode]

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.

[sourcecode language=”erlang”]
-export([reverse_test/0]).
[/sourcecode]

After this, add the function test as shown below.

[sourcecode language=”erlang”]
reverse_test() -> lists:reverse([1,2,3]).
[/sourcecode]

The complete code file should look like this.

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

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

Build it and call the function.

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

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.

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.

[sourcecode language=”javascript”]
(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();
})();
[/sourcecode]

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.

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

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.

[sourcecode language=”html”]
<!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>
[/sourcecode]

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.

[sourcecode language=”javascript”]
(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();
})();
[/sourcecode]

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.

OS-X Cocoa Quickie #1 => Make Sure to Have Unit Tests

When starting an Xcode Cocoa Project you should have a testing project that you include. It’s a simple check box on the project creation dialogs.

Keep This Checked! Write Tests!
Keep This Checked! Write Tests!

If for some reason you inherit a project that doesn’t have unit tests, tests, or anything of the sort and need to add a testing project follow these steps. With the project open add a new target as shown below.

Add a New Target to the Project
Add a New Target to the Project

Add a Cocoa Unit Testing Bundle.

Cocoa Touch Unit Testing Bundle
Cocoa Touch Unit Testing Bundle (Click for full window and full size image)

Set the appropriate parameters for your project. Be sure to select the project from the drop down.

Set the product name and be sure to select the correct Project from the drop down. (Click for full window and full size image)
Set the product name and be sure to select the correct Project from the drop down. (Click for full window and full size image)

Once finished adding the testing target, edit the schema. The project will have an additional schema. I personally like to keep them rolled together, so delete the “*Tests” schema and just make sure that the Tests section has the right target listed.

Schema Settings
Schema Settings

If it isn’t listed, as shown in the above dialog, click the + to add the tests project. Select it in the target dialog as shown below.

Adding the test target for the schema
Adding the test target for the schema

Once all that is done then the tests can be executed from the Product -> Test menu option or the shortcut key combo of ⌘U. With the default code that is added to the target project, you’ll end up with one failing test.

Test FAIL!
Test FAIL!

Now write tests!

A TimePiece of C# and JavaScript

I put together a little project on Github, partially because I’ve been making headway learning the intricacies of JavaScript, and partly because I wanted something that would parse a string that represents a time value. So here’s the TDD I went through. In the process I pulled in QUnit and used that as my testing framework for the JavaScript example. I’d love input on either of these, so feel free to gimme some heat, tell me what I’ve done wrong, and especially how I ought to be doing this.  🙂

The first thing I did was put together the C# Library. I started two projects, one for the tests and one for the actual library.  In the tests project I added a class file and removed the default using statements and replaced them with the following by way of Nuget:

[sourcecode language=”csharp”]
using NUnit.Framework;
using Shouldly;
[/sourcecode]

After adding these references I jumped right into setting up the test fixture. Since I know I want to have something to parse the hour for military time also I’ve setup two test variables.

[sourcecode language=”csharp”]
[TestFixture]
public class with_static_parsing_of_time
{
protected string sampleTimeOne = "10:12am";
protected string sampleTimeTwo = "2:30pm";
[/sourcecode]

The first test I then dived into was to test the hour.

[sourcecode language=”csharp”]
[Test]
public void should_return_a_time_piece_with_correct_hour()
{
var timePiece = TimePiece.Parse(sampleTimeOne);
timePiece.Hour.ShouldBe(10);
}
[/sourcecode]

I then fleshed out the object and implemented enough to get this test to pass.

[sourcecode language=”csharp”]
namespace TimeSlicer
{
public class TimePiece
{
public TimePiece(string time)
{
ParseTime(time);
}

private void ParseTime(string time)
{
SetHour(time);
}

private void SetHour(string time)
{
Hour = Convert.ToInt32(time.Split(Convert.ToChar(":"))[0]);
}

public int Hour { get; set; }
[/sourcecode]

I then continued back and forth writing tests and implemented each. For the complete code check out the Github Repository. This example is really simple. I’d love any thoughts on adding to it or what you might think is a better way to test the object.

For the JavaScript I downloaded QUnit. Again I stepped into the testing, which is a whole different ballgame than in C#.

[sourcecode language=”javascript”]
<link rel="stylesheet" href="qunit/qunit.css" type="text/css" media="screen"/>
<script type="text/javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript" src="qunit/qunit.js"></script>
<script type="text/javascript" src="TimeSlicer/TimePiece.js"></script>
<script type="text/javascript">

var timeValueOne = "1:30am";
var timeValueTwo = "8:15pm";

$(document).ready(function() {

module("Parse hour from value.");

test("Should parse hour from value.", function() {
TimePiece(timeValueOne);
equal(TimePiece.Hour(), 1, "The appropriate hour value is returned for AM meridian value.");
});
[/sourcecode]

For the full test file with other JavaScript libraries and CSS check out the code file on github.

…and directly into implementation. With the caveat that I’m extremely unfamiliar with actual psuedo/pretend/faux object creation in JavaScript. In this realm I’m still reading up on best ways to do this.

[sourcecode language=”javascript”]
TimePiece = function(time) {
TimePiece.Hour = function () {
return time.toString().split(":")[0];
}
return time;
};
[/sourcecode]

I went on from here writing tests and implementing as I did with the C#. The JavaScript was interesting. I’ve also noticed that I get a lot of strings back versus the number values that I’d actually want, thus the addition of the “parseInt” in the final version.

Check out the overall project on Github at: https://github.com/Adron/Time-Slice

Iteration End, Velocity++, Chart Awesomeness, Contribute Back Plz K Thx!

Here’s a few charts and such from the end of an iteration that the team I’m on just wrapped.  I’d love to see any TFS charts of this nature or other solutions in JIRA, TeamCity, or whatever is used.  Anyone else out there want to get a blog post up about it, I’ll add a link at the end of my entry here.

Lots of Tests, Good Continuous Integration Build
Lots of Tests, Good Continuous Integration Build

Gotta have solid test coverage for any reasonable expectation of maintenance.  When I mean tests, I’m talking about properly abstracted, mocked, stubbed, faked, or otherwise built so as they don’t depend on all sorts of nonsensical external dependencies like file systems, database, or other things.

Code Coverage, in general keeps an upward trend!
Code Coverage, in general keeps an upward trend!

100% is a little fanatical, but an upward trend after the beginning of a project and the initial work beginning is one of the best things to see.  Code coverage with tests means you’ll be able to get all sorts of goodies:  maintainable code, non-increasing tech debt, faster refactors, etc.

The Few Fixes Needed, Get Fixed Pretty Quick!
The Few Fixes Needed, Get Fixed Pretty Quick!

Unit test fixes.  Should be quick, should be furiously done, and shouldn’t take more than about an hour on the infrequent times they occur at all.

Unit Test Coverage Up...
Unit Test Coverage Up...
Increasing Count
Increasing Count

…and of course, the burn down.

BURN baby BURN!

Burn Down
Burn Down