Creating a Go Module & Writing Tests in Less Than 3 Minutes

In this short (less than 4 minutes) video I put together a Go module library, then setup some first initial tests calling against functions in the module.

 

00:12 – Writing unit tests.

00:24 – Create the first go file.

00:40 – Creating the Go go.mod file. When creating the go.mode file, note the command is go mod init [repopath] where repopath is the actual URI to the repo. The go.mod file that is generated would look like this.

module github.com/adron/awesomeLib

go 1.13

00:56 Enabling Go mod integration for Goland IDE. This dialog has an option to turn off the proxy or go direct to repo bypassing the proxy. For more details on the Go proxy, check out goproxy.io and the Go docs for more details.

01:09Instead of TDD, first I cover a simple function implementation. Note the casing is very important in setting up a test in Go. The test function needs to be public, thus capitalized, and the function needs accessible, thus also capitalized. The function in the awesomeLib.go file, just to have a function that would return some value, looks like this.

package awesomeLib

func GetKnownResult() string {
    return "known"
}

01:30Creating the test file, awesomeLib_test.go, then creating the test. In this I also show some of the features of the Goland IDE that extracts and offers the function names of a module prefaced with Test and other naming that provides they perform a test, performance, or related testing functionality.

package awesomeLib

import "testing"

func TestGetKnownResult(t *testing.T) {
    got := GetKnownResult()
    if got != "known" {
        t.Error("Known result not received, test failed.")
    }
}

02:26Running the standard go test to execute the test. To run tests for all files within this module, such as if we’ve added multiple directories and other files, would be go test ./....

02:36Using Goland to run the tests with singular or multiple tests being executed. With Goland there are other capabilities to show test coverage, what percentage of functionality is covered by tests, and other various code metrics around testing, performance, and other telemetry.

That’s it, now the project is ready for elaboration and is setup for a TDD, BDD, or implement and test style approach to development.

For JavaScript, Go, Python, Terraform, and more infrastructure, web dev, and coding in general I stream regularly on Twitch at https://twitch.tv/adronhall, post the VOD’s to YouTube along with entirely new tech and metal content at https://youtube.com/c/ThrashingCode.

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.

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:

[sourcecode language=”bash”]
$ erl
Erlang R15B01 (erts-5.9.1) [source] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.1 (abort with ^G)
1>
[/sourcecode]

Then execute the install:

[sourcecode language=”Erlang”]
1> eqc_install:install().
[/sourcecode]

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

[sourcecode language=”bash”]
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)
[/sourcecode]

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

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

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.

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

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.

[sourcecode language=”bash”]
eqc:registration("xxxxxxxxxxxx").
[/sourcecode]

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!  😮  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.

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.