Caffeine-Powered Life

Angular Part 5: Testing

Today is Halloween in the United States. As such, I think we should talk about something scary.

No, not lions and tigers and bears. Something that drives fear into the hearts of developers: unit testing.

Seriously, this is not that difficult. Part of learning any new programming language or framework includes learning how to test that language or framework. This is 2014. If automated unit and integration testing isn’t a first-level design concern by now, you are doing it wrong. (I’m looking at you Microsoft WebAPI.)

Angular makes writing unit tests incredibly easy. JavaScript is fragile enough as-is, so let’s always test all of our *.js files.

Here’s our folder layout. Anything we author will be under either the app or spec folders.

The tools

This is the list of tools we will be using for this project.

The application (app.js)

The application is very easy to define and test.

First we declare it.

app/app.js
1
angular.module("myApp", []);

Then we make sure we can get it.

spec/appSpec.js
1
2
3
4
5
6
7
describe("module: myApp", function () {

  it("is defined", function () {
    expect(angular.module("myApp")).toBeDefined();
  });

});

The point service (point.js)

The point service is taken from our previous post. It looked like this.

app/services/point.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
app.factory("point", [
  function () {
    return function (options) {

      options = options || {};

      var self = {
        x: options.x || 0,
        y: options.y || 0
      };

      self.distanceTo = function (other) {
        var absXSq = sqError(self.x, other.x);
        var absYSq = sqError(self.y, other.y);
        return Math.sqrt(absXSq + absYSq);
      };

      self.toString = function () {
        return "Point: { " + self.x + ", " + self.y + " }";
      };

      function sqError(a, b) {
        return Math.pow(a - b, 2);
      }

      return self;
    };
  }
]);

The unit test below defines what our point service should be able to do.

spec/services/pointSpec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
describe("service: point", function () {

  var point;

  beforeEach(module("myApp"));

  beforeEach(inject(function (_point_) {
    point = _point_;
  }));

  it("can create a new point object representing the origin", function () {
    var pt = point()
    expect(pt.x).toEqual(0);
    expect(pt.y).toEqual(0);
  });

  it("can calculate the distance between two points", function () {
    var origin = point();
    var pt = point({ x: 3, y: 4 });
    expect(pt.distanceTo(origin)).toEqual(5);
  });

  it("returns the expected value for toString()", function () {
    expect(point({ x: 1, y: 2 }).toString()).toEqual("Point: { 1, 2 }");
  });

});

The parts to notice are the two beforeEach() functions. The first one loads the module. The second one sets up the service to be tested. The _point_ is used by the injector to create the point instance.

Yes, it’s a bit magical how the injector works. Basically, any inject() argument that starts with $ is an Angular built-in, and any argument that looks like _something_ is something you’ve written. Beyond the injection magic, the tests are rather straightforward. We can create a new point, calculate the distance between two points, and test its string representation.

The controller (PointCtrl.js)

Our PointCtrl is quite small, especially since most of the work is being handled by the point service. That was why we wrote the service in the first place.

app/controllers/PointCtrl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
app.controller("PointCtrl", [
  "$scope",
  "point",
  function ($scope, point) {

    $scope.point1 = point();
    $scope.point2 = point();

    $scope.getDistance = function() {
      return $scope.point1.distanceTo($scope.point2);
    };

    return $scope;
  }
]);

The test for the controller is similarly simple, once you figure out the test setup steps.

spec/controllers/PointCtrlSpec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
describe("controller: PointCtrl", function () {

  var ctrl, distance, point, scope;

  beforeEach(module("myApp"));

  beforeEach(inject(function ($controller) {
    createMockPoint();
    createController($controller);
  }));

  it("assigns point1 and point2", function () {
    expect(scope.point1).toBeDefined();
    expect(scope.point2).toBeDefined();
  });

  it("returns the expected value for getDistance()", function () {
    expect(scope.getDistance()).toEqual(distance);
  });

  function createController($controller) {
    scope = {};
    ctrl = $controller("PointCtrl", {
      "$scope": scope,
      "point": point
    });
  }

  function createMockPoint() {
    distance = Math.random() * 100;
    point = function () {
      return {
        distanceTo: function () {
          return distance;
        }
      };
    };
  }

});

Again, the trick to these tests is understanding the beforeEach() functions. The first one loads the module. The second loads the $controller factory.

You will notice that we create a mock point object and a mock $scope object. How much of a mock do you need? You need as much of the object surface area as the controller has access. For $scope, an object literal will do, and there is no reason for anything more complicated than this.

The point object is a little more complicated. First, it needs to be a function, so we can call point(). Second, the controller needs access to the distanceTo() function. We will create a stub for this function and return a random value between 0 and 100.

The final result

Running all of tests in the browser, we should see the following.

Angular Part 4: Creating a Service

Our last project covered dependency injection in an Angular application. Now, let’s show how a service works.

An Angular service is a way to encapsulate business logic so that it can be consumed by controllers and other services. Like any well-written program, functionality that goes together should be put together in small, reusable, testable components. Speaking of testing, that’s going to be the next post, so stay tuned.

Demonstration of application

The application should work similar to the following example.

Our new service

We will encapsulate the point object into an Angular service. This service will be called “point”, and it will have no dependencies. You will notice that this block of code looks almost identical to the point() function from our previous post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
angular.module("myApp").factory("point", [
  function () {
    return function (options) {
      var self = {
        x: options.x,
        y: options.y
      };
      self.distanceTo = function (other) {
        var absXSq = sqError(self.x, other.x);
        var absYSq = sqError(self.y, other.y);
        return Math.sqrt(absXSq + absYSq);
      };
      self.toString = function () {
        return "{ " + self.x + ", " + self.y + " }";
      };
      function sqError(a, b) {
        return Math.pow(a - b, 2);
      }
      return self;
    };
  }
]);

By giving our service a unique name, we can now inject it into our controllers as needed.

1
2
3
4
5
6
7
8
9
10
11
12
angular.module("myApp").controller("PointCtrl", [
  "$scope",
  "point",
  function ($scope, point) {
    $scope.point1 = point({ x: 0, y: 0 });
    $scope.point2 = point({ x: 0, y: 0 });
    $scope.getDistance = function () {
      return $scope.point1.distanceTo($scope.point2);
    };
    return $scope;
  }
]);

Adding a service makes our controller much simpler than the previous post. Additionally, our point is now a focused, reusable block of code that can be used anywhere within our application.

It is important to note that all Angular services are lazy singletons. Specifically, they are only created when asked for, and only one instance of the function will ever be created. This is great for your application’s memory profile.

Angular Part 3: Dependency Injection

In my previous post, I showed how a controller is built in Angular. The basic syntax for creating a controller looks like the following.

1
2
3
4
5
6
module.controller("MyCtrl", [
  "$scope",
  function ($scope) {
    return $scope;
  }
]);

This syntax for creating a JavaScript module is incredibly powerful. By letting Angular handle all of the dependencies, and by treating the scope as yet another object to be injected, the developer needn’t ever worry about three of the most difficult concepts in JavaScript: specifically, closures, new, and this.

The Traditional JavaScript Object

For a refresher, here’s the traditional way to create an object in JavaScript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var Point = (function () {

  function Point(options) {
    this.x = options.x;
    this.y = options.y;
  }

  Point.prototype.distanceTo = function (otherPoint) {
    var absXSq = Math.pow(this.x - otherPoint.x, 2);
    var absYSq = Math.pow(this.y - otherPoint.y, 2);
    return Math.sqrt(absXSq + absYSq);
  };

  return Point;

})();

We create a new point in the following manner.

1
var origin = new Point({ x: 0, y: 0 });

In the above class, this is always the functional enclosure that defines the class. This means that this acts the same as we would expect it in C# or Java. However, it wouldn’t take much, just a simple callback, to change the result. Imagine a more complex function that needs to be non-blocking.

1
2
3
4
5
6
7
Point.prototype.distanceTo = function (otherPoint) {
  return setTimeout(function () {
    // Here, any reference to this.x or this.y will cause your
    // program to fail. Inside the setTimeout callback, this
    // refers to the global scope.
  }, 0);
};

Yes, there are ways to get around the above, specifically by learning how bind(this) works, but, in my experience, this is a place where many developers tend to not know what they are doing. Unfortunately, too many JavaScript “developers” are frequently C# or Java developers who have been asked to add functionality to a web site. They then write mediocre, fragile JavaScript.

An Alternate JavaScript Object

Instead, let’s examine an alternate way to writing our Point class. In this example, we are creating an object literal and attaching functions to this new object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function point(options) {

  self = {
    x: options.x,
    y: options.y
  };

  self.distanceTo = function (otherPoint) {
    var absXSq = Math.pow(self.x - otherPoint.x, 2);
    var absYSq = Math.pow(self.y - otherPoint.y, 2);
    return Math.sqrt(absXSq + absYSq);
  };

  return self;
}

No longer do we have to worry about immediate functions, the (function () {})() syntax, this, or even creating a new object. To create a new point in this manner, we simply do the following.

1
var origin = point({ x: 0, y: 0 });

Angular Objects

Angular gets around of all of this (Ha! Ha! Puns!) by injecting the scope object. Anything you wish to expose gets attached to the scope object. Also, the developer never needs to create new objects. The Angular framework does all of that work for you.

Let’s create a simple form for displaying the distance between two points.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<body ng-app="myApp">

  <div ng-controller="PointCtrl">
    <p>
      <label>x1</label>
      <input type="number" ng-model="x1"/>
      <label>y1</label>
      <input type="number" ng-model="y1"/>
    </p>
    <p>
      <label>x2</label>
      <input type="number" ng-model="x2"/>
      <label>y2</label>
      <input type="number" ng-model="y2"/>
    </p>
    <p>
      <label>Distance</label>
      <span ng-bind="getDistance()"></span>
    </p>
  </div>

</body>

Our controller will look something like the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
angular.module("myApp").controller("PointCtrl", [
  "$scope",
  function ($scope) {

    $scope.x1 = 0;
    $scope.x2 = 0;
    $scope.y1 = 0;
    $scope.y2 = 0;

    function squareError(a, b) {
      return Math.pow(a - b, 2);
    }

    $scope.getDistance = function () {
      var absXSq = squareError($scope.x1, $scope.x2);
      var absYSq = squareError($scope.y1, $scope.y2);
      return Math.sqrt(absXSq + absYSq);
    };

    return $scope;
  }
]);

Together, the above HTML and JavaScript should give us something like this.

As mentioned previously, anything that gets attached to $scope is publicly accessible. The squareError() function is not available publicly. There is no binding trick that the developer can use to attach the function to any Angular directive.

Finally, let’s look at the format of the controller definition.

1
module.controller(String, Array);

The String is the name of the controller. The Array is the names of the dependencies with the last element of the array being the definition of the controller. Dependencies that start with a $ are built-ins for Angular — there are several.

Conclusion

I recently watched Douglas Crockford talk about writing JavaScript without using new or this. At first I was quite taken aback. How the hell am I supposed to write JS without objects? As you can see, we can still create plenty of objects, those objects have attributes, attach functions to those objects, and even have private function encapsulation without ever using new or this.

Angular Part 2: Moving to a Controller

In Part 1, we showed how easy it is to add functionality to a website with AngularJS, and compared that to how much work would be necessary to do the same thing using jQuery alone.

We did have a little bit of logic in our views, though, and that’s not ideal. That logic was testing for specific values for our form fields.

1
2
3
4
5
// Showing the form field
ng-show="favoriteColor === 'Other'"

// Requiring the form field
ng-require="favoriteColor === 'Other'"

In my opinion, even something as simple as a test for equality is view logic, and we should do what we can to move that out of the view. Ideally, we want something that looks more like this.

1
2
3
4
5
// Showing the form field
ng-show="showOtherField()"

// Requiring the form field
ng-require="requireOtherField()"

Moving that logic is not difficult. In Angular, this kind of thing is handled by the controller.

Before we can write a controller, we first need a module. Defining a module takes the signature angular.module(String, Array). The string is the name of the module, and the array is the list of dependencies required by the module. Below, we define a module named myApp, followed by an array of dependencies. In this case, we do not have any dependencies, so we just have an empty array.

1
2
3
4
if (window.app) {
  throw Error("window.app is already defined.");
}
window.app = angular.module("myApp", []);

Now that we’ve defined our module, let’s define our controller. We get our module from the Angular registry and add a controller to it. Defining a controller takes the signature module.controller(String, Array).

The array is the list of dependencies followed by the definition of the controller. Our controller does have a $scope dependencies. $scope is Angular’s way of not having to deal with JavaScript’s this object. Anything that we want to expose, we add to the $scope object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
angular.module("myApp")
.controller("ColorFormCtrl", [
  "$scope",
  function ($scope) {

    /**
     * Return true if the submit button should be disabled.
     */
    $scope.disableSubmit = function () {
      return $scope.form.$pristine || $scope.form.$invalid;
    };

    /**
     * Return true if the "Other" field is required.
     */
    $scope.requireOtherField = function () {
      return $scope.favoriteColor === "Other";
    };

    /**
     * Return true if the "Other" field should be displayed.
     */
    $scope.showOtherField = function () {
      return $scope.favoriteColor === "Other";
    };

    return $scope;
  }
]);

Let’s take look at updated HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <title>Angular Demo</title>
</head>
<body ng-controller="ColorFormCtrl">
<form method="post" action="#" name="form">
  <div>
    <label>What is your favorite color?</label>
    <select name="favoriteColor" ng-model="favoriteColor" required="required">
      <option></option>
      <option>Red</option>
      <option>Blue</option>
      <option>Other</option>
    </select>
  </div>
  <div ng-show="showOtherField()">
    <label>Favorite color (other)</label>
    <input type="text" name="favoriteColorOther" ng-model="favoriteColorOther" ng-required="requireOtherField()"/>
  </div>
  <div>
    <button type="submit" ng-disabled="disableSubmit()">
      Submit
    </button>
  </div>
</form>
</body>
</html>

We added our module’s name to the ng-app="myApp" directive. We added our controller as part of the ng-controller="ColorFormCtrl" directive. We then moved all of our page logic to a controller.

Angular Part 1: Show and Hide

This week, I have been diving headfirst into AngularJS. I am amazed at how much one can accomplish with very little code. In this example, I want to show and hide various parts of a form based on what selections the user makes elsewhere. That’s a pretty simple thing to do with jQuery. It’s even easier with AngularJS.

First, let’s show our base markup. This is the bare minimum to get our page to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<head>
  <title>Angular Demo</title>
</head>
<body>
  <form method="post" action="#">
    <div>
      <label>What is your favorite color?</label>
      <select name="favoriteColor">
        <option></option>
        <option>Red</option>
        <option>Blue</option>
        <option>Other</option>
      </select>
    </div>
    <div>
      <label>Favorite color (other)</label>
      <input type="text" name="favoriteColorOther"/>
    </div>
    <div>
      <button type="submit">
        Submit
      </button>
    </div>
  </form>
</body>
</html>

The above HTML will render as follows.

"Angular 1-1"

If we already know jQuery, we know that we need to add a little more to our markup to make it play nice with jQuery.

  1. Add an ID to our select box.
  2. Add an ID to our wrapper div tag for our “Other” input.
  3. Hide the “Other” form field by default.
  4. Write a little bit of jQuery.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- Update select -->
<select name="favoriteColor" id="favoriteColor">

<!-- Update div, add inline style -->
<div id="form-field-favoriteColorOther" style="display: none;">

<!-- Write a little script -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
  $("#favoriteColor").on("change", function () {
    if ($("#favoriteColor").val() === "Other") {
      $("#form-field-favoriteColorOther").show();
    } else {
      $("#form-field-favoriteColorOther").hide();
    }
  });
</script>

That’s really not too bad. Let’s however, add a few more requirements.

  1. The Favorite Color option needs to be required.
  2. The Other field needs to be required if Other is selected.
  3. Don’t let the user submit an invalid form.

HTML 5 gives us some of this, but we still run into walls. We’re going to have to add a disabled attribute to the button. We’re going to have to validate our form with another library (or roll our own). We need to add required to the select box. We need to add required to our text box, but only if “Other” is selected.

The program flow should look like this.

This is the default state of the form.

"Angular 1-2a"

User selects an option that is not “Other”. Everything is good. Enable the submit button.

"Angular 1-2b"

User select “Other”. Show a text box and disable the submit button.

"Angular 1-2c"

User enters a value in the text box. Everything is good again. Enable the submit button.

"Angular 1-2d"

Again, none of this is particularly difficult, but you can imagine how all of this blows up when a page gets to be of a certain complexity. Let’s see what AngularJS has to offer.

  1. Add ng-model tags to the form fields that we need to expose to angular. That’s both of them.
  2. Add ng-required to any field that is dynamically required.
  3. Add ng-disabled to any field that is dynamically disabled.
  4. Wire it all together.

Let’s look at our AngularJS markup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>Angular Demo</title>
</head>
<body ng-app="">
  <form method="post" action="#" name="form">
    <div>
      <label>What is your favorite color?</label>
      <select name="favoriteColor" ng-model="favoriteColor" required>
        <option></option>
        <option>Red</option>
        <option>Blue</option>
        <option>Other</option>
      </select>
    </div>
    <div ng-show="favoriteColor === 'Other'">
      <label>Favorite color (other)</label>
      <input type="text" name="favoriteColorOther" ng-model="favoriteColorOther" ng-required="favoriteColor === 'Other'"/>
    </div>
    <div>
      <button type="submit" ng-disabled="form.$invalid">
        Submit
      </button>
    </div>
  </form>
</body>
</html>

Let’s compare our jQuery markup with our AngularJS markup.

  1. The body tag now has an ng-app="" attribute. This is what tells Angular that it should work.
  2. We have added a name="form" attribute to our form. By giving the form a name, it can be accessed by Angular. This access can be seen on the submit button, with the form.$invalid variable.
  3. We have added ng-model="..." to both of our input fields. This exposes the form fields to Angular.
  4. We have added a required HTML5 attribute to our select.
  5. We have added ng-show="favoriteColor === 'Other'" to our div tag that wraps our text box. This means that the field will only be shown if the expression is truthy.
  6. We added an ng-required attribute to our text box. This means the field will be required if the expression is truthy.
  7. Finally, we added an ng-disabled attribute to our button. This means that the button will be disabled if the expression is truthy.

Now, let’s show the JavaScript we need to write to make all this magic happen.

1
// Boo!

Yep. We’re done. Zero lines of JavaScript. Yeah, I could get used to this.

Oops! How to Permanently Delete a File From Git

I accidentally added an uninitialized (appended) SQL Server backup file, a *.bak, to source control and pushed it. Now, no one can fetch a clean copy of the source because of out-of-memory errors. How do I fix this?

1
git filter-branch --tree-filter 'git rm -r -f --ignore-unmatch *.bak' HEAD

This will take a while to run, as it goes through every commit in your project and deletes the file. When you’re done, you’ll need to push the file to your remote.

1
git push origin master --force

You’ll need the --force flag because this is not a fast-forward commit.

Getting Started With MathJax

I’ve spent the past few days getting myself reacquainted with TeX and familiarizing myself with MathJax. As it turns out, it is quite easy to get MathJax working in Octopress.

  1. Open source/_includes/custom/head.html.
  2. Add the a JavaScript source: //cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML.
  3. Start typing your TeX.
  4. In your Gemfile, make sure you are using at least RDiscount version 2.1. gem 'rdiscount', '~> 2.1'
  5. In your _config.yml file, disable automatic superscripts by adding - no_superscript to your RDiscount configuration.

The last two are quite important. Without those two steps, it looks like RDiscount will turn x^2 into x<sup>2</sup>. This will get displayed as x2. That will break the MathJax processor.

Let’s start by demonstrating a simple inline equation, like \( y = mx + c \). This is simple enough by including the inline text: \\( y = mx + c \\).

To enter full equations, like the one below, use the following syntax.

1
2
3
\begin{equation}
x = \dfrac{ -b \pm \sqrt{ b^2 - 4ac } }{ 2a }
\end{equation}

The above code will render as the following equation.

\begin{equation} x = \dfrac{ -b \pm \sqrt{ b^2 - 4ac } }{ 2a } \end{equation}

Happy mathing!

Mocking a JavaScript Constructor

"You're mocking me, aren't you?"

JavaScript, and dynamic languages in general, make it extremely easy to mock out functions. This greatly reduces the need for all the extra programming junk (interfaces, adapters, wrappers, factories, etc.) that gets in the way of us solving our problems. We add tons of extra layers in the name of test isolation and object independence that plainly isn’t necessary in the dynamic languages world.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// lib/Point.js
var Point = (function () {

  function Point(x, y) {
    this.x = x;
    this.y = y;
  }

  Point.prototype.distanceTo = function(point) {
    var dx = this.x - point.x;
    var dy = this.y - point.y;
    return Math.sqrt(dx * dx + dy * dy);
  };

  Point.origin = function () {
    return new Point(0, 0);
  };

  return Point;

}).call(this);

module.exports = Point;

We’ve defined a very simple class, and it has all of the parts that we need to demonstrate how mocking works.

First, let’s define some simple tests. I’m using Jasmine and Node. (See jasmine-node for a command line version of Jasmine.) These tests fully describe the basic functionality of the class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// spec/PointSpec.js
var Point = require("../lib/Point");

describe("Point", function () {

  var point;

  beforeEach(function () {
    point = new Point(3, 4);
  });

  it("can return the distance to the origin", function () {
    var distance = point.distanceTo(Point.origin());
    expect(distance).toEqual(5);
  });

  it("returns the expected value when constructing an origin", function () {
    var origin = Point.origin();
    expect(origin.x).toEqual(0);
    expect(origin.y).toEqual(0);
  });

  it("returns the expected values for x and y", function () {
    expect(point.x).toEqual(3);
    expect(point.y).toEqual(4);
  });

});

Mocking an instance function.

The distanceTo() function exists on the instance of Point. It’s incredibly easy to mock out. Functions are first-class members in JavaScript, so we can simply redefine the function in the unit test. In this example, we simply redefine the function to return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
describe("Point with stubbed distanceTo() function", function () {

  var point;

  beforeEach(function() {
    point = new Point(3, 4);
    point.distanceTo = function (point) {
      return 0;
    };
  });

  it("returns 0 via stub", function () {
    var distance = point.distanceTo(new Point(10, 10));
    expect(distance).toEqual(0);
  });

});

Mocking a class function.

The origin() function is a class function that returns the point {0, 0}. Let’s suppose we need to define a different origin. That’s easy to do!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
describe("Point with stubbed origin() function", function () {

  var point, temp;

  beforeEach(function () {
    temp = Point.origin; // Save the definition for later.
    Point.origin = function () {
      return new Point(1, 1);
    };
    point = Point.origin();
  });

  afterEach(function () {
    Point.origin = temp; // Restore the original definition.
  });

  it("has the expected values for x and y", function () {
    expect(point.x).toEqual(1);
    expect(point.y).toEqual(1);
  });

});

In this case, we need to store the original definition of origin() in the temp variable. In beforeEach(), we will override the origin() function. In afterEach(), we will restore it to its former glory.

Mocking the class constructor.

Of the three, mocking the constructor takes a little more insight, but the activity is functionally the same. We are going to create a new class and copy all of the necessary functionality to the new class. We do this by copying over the prototype of the original point. We also need to explicitly copy over the origin() function, since class functions are not part of the prototype.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
describe("Point with stubbed constructor", function () {

  var MockPoint = (function () {
    function MockPoint(x, y) {
      this.x = 0;
      this.y = 0;
    }
    return MockPoint;
  }).call(this);

  // Apply all functions from Point to MockPoint. Also copy the
  // origin() function to MockPoint.
  MockPoint.prototype = Point.prototype;
  MockPoint.origin = Point.origin;

  var point, temp;

  beforeEach(function () {
    temp = Point; // Save the definition for later.
    Point = MockPoint;
  });

  afterEach(function () {
    Point = temp; // Restore the original definition.
  });

  it("calculates distance correctly", function () {
    var distance = new Point(3, 4).distanceTo(new Point(6, 7));
    expect(distance).toEqual(0);
  });

  it("can stub out the constructor", function () {
    point = new Point(4, 5);
    expect(point.x).toEqual(0);
    expect(point.y).toEqual(0);
  });

  it("leaves the origin() function unchanged", function () {
    point = Point.origin();
    expect(point.x).toEqual(0);
    expect(point.y).toEqual(0);
  });

});

The pattern is the same. Create a copy. Redefine the function. (The constructor is just another function, just treated a little differently.) Do your tests. Restore the original definition.

I hope this clears up some of the issues around mocking JavaScript objects. This can be done easily with the language and require no additional 3rd party libraries.

A Pox on Static Languages

It’s no secret that I am tired of .NET, C#, and static language stupidity.

My curent project went in for a code review, and I’m going to share the before snippet. This is a simple part of the project, containing no business logic — it’s just a way to check the status to make sure that the server is up.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Status
{
  public Status()
  {
    ServerTime = Clock.Instance.UtcNow;
    Timestamp = Clock.Instance.UtcNow.ToEpoch();
    Version = GetVersionString();
  }

  public DateTime ServerTime { get; set; }

  public long Timestamp { get; set; }

  public string Version { get; set; }

  private static string GetVersionString()
  {
    var version = Assembly.GetExecutingAssembly().GetName().Version;
    var versionString = string.Format("{0}.{1}", version.Build, version.Revision);
    return versionString;
  }
}

public class StatusController
{
  public Status Get()
  {
    return new Status();
  }
}

That’s all the relevant code in this particular example. Here is the reviewers comment.

Factor all of the work out of the Status class’s constructor. Treat Status as a DTO. Put unit tests around the new factory to ensure it is properly initializing Status.

Damn. The problem with that above review is that (1) it is a lot more code to write for such a simple thing, and (2) I completely agree that’s how it should be done in C# (and probably other static languages, too). From a testing and code design point of view, the above comment represents all of the best practices that good code should follow. It keeps the result object as a plain DTO. It makes sure that the controller is responsible for nothing beyond negotiation. The reviewer’s comment is valid and accepted for work.

If I sound too put off by this, please realize that this is less than 30 minutes of work for me to do. This is much more about my distaste with the current state of static language patterns than my critique of the code reviewer.

So, let’s start by adding a factory, moving the initialization logic to the factory. We are using Ninject, so we’ll also need to be sure to register this with our IoC container.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public interface IStatusFactory
{
  Status Create();
}

public class StatusFactoryImpl : IStatusFactory
{
  public Status Create()
  {
    return new Status
    {
      ServerTime = Clock.Instance.UtcNow,
      Timestamp = Clock.Instance.UtcNow.ToEpoch(),
      Version = GetVersionString()
    }
  }

  private static string GetVersionString()
  {
    var version = Assembly.GetExecutingAssembly().GetName().Version;
    var versionString = string.Format("{0}.{1}", version.Build, version.Revision);
    return versionString;
  }
}

// In our registration...
Kernel.Bind<IStatusFactory>().To<StatusFactoryImpl>().InRequestScope();

We also need to modify our existing StatusController.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class StatusController
{
  private readonly IStatusFactory statusFactory;

  public StatusController(IStatusFactory statusFactory)
  {
    if (statusFactory == null)
      throw new ArgumentNullException("statusFactory");
    this.statusFactory = statusFactory;
  }

  public Status Get()
  {
    var status = statusFactory.Create();
    return status;
  }
}

Finally, let’s modify the Status object, removing the logic from the constructor.

1
2
3
4
5
6
public class Status
{
  public DateTime ServerTime { get; set; }
  public long Timestamp { get; set; }
  public string Version { get; set; }
}

Finally, we need to modify our StatusControllerTests file to get all of our tests to pass. We will introduce a mock object to the controller’s constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class StatusControllerTests
{
  private StatusController controller;
  private Mock<IStatusFactory> mockStatusFactory;

  [SetUp]
  public void Before_each_test()
  {
    mockStatusFactory = new Mock<IStatusFactory>();
    mockStatusFactory.Setup(x => x.Create()).Returns(new Status());
    controller = new StatusController(mockStatusFactory.Object);
  }

  /* snip */
}

All of this is easier how? The answer, obviously, is that this isn’t easier. I’m not even convinced that it is cleaner, even if it is more clearly separating concerns.

Total changes?

  • 6 files modified (Status, StatusController, StatusControllerTests, StatusTests, plus two .csproj files)
  • 3 files added (IStatusFactory, StatusFactoryImpl, StatusFactoryImplTests)

Ugh.

Reconciling with Ruby on Rails

How would I write the exact same thing in Ruby on Rails, and have the exact same level of testability (including mocking), etc.?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Status
  attr_reader :server_time, :timestamp, :version

  def initialize
    @server_time = Time.now
    @timestamp = @server_time.to_i
    @version = Application::VERSION
  end
end

class StatusController < ApplicationController
  def index
    @status = Status.new
    render json: @status, status: :ok
  end
end

Wait. Doesn’t that look like the original code? Yes, it does. Thanks to Ruby’s basic attr_reader, I can quickly create the attributes for a class with very little code. The Ruby version is so much shorter because there is no reason to add extra layers (interfaces, factories) for the sake of object independence and testability in the dynamic objects world. We never require an actual type in dynamic languages, just something that conforms to the contract.

This is just another reason why I love Ruby. I can get more done faster, less typing, more clarity, and the same (or even better testability) than anything C# even comes close to accomplishing.

The Easiest WebAPI Authorization Tutorial Ever

So, it took a lot of scouring of the internets, but I was finally able to piece together the bare minimum necessary to create your own authoritization client in WebAPI.

Step 1: Create a DelegatingHandler

The DelegatingHandler is a class that will be attached to all requests coming into your API. This is going to be the easiest authorization handler ever. Here are the rules.

  1. If there is a token, any token at all, the request is valid.
  2. Otherwise, the request is unauthorized.

Yes, this is simple. In reality, you’d want to check the value of the token against something, at the very least a local database. That is left as an exercise for the reader.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class AuthorizationHeaderHandler : DelegatingHandler
{
  private string authorizationParameter;

  public bool HasAuthorizationParameter
  {
    get { return authorizationParameter != null; }
  }

  protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
  {
    ParseAuthorizationHeader(request);
    if (HasAuthorizationParameter)
    {
      ConfigureClaimsIdentity();
      return base.SendAsync(request, cancellationToken);
    }

    return ConfigureUnauthorizedRequest();
  }

  private void ConfigureClaimsIdentity()
  {
    var claims = new List<Claim>();
    // Ideally, you'd add some claims here.
    var claimsIdentity = new ClaimsIdentity(claims);
    Thread.CurrentPrincipal = new ClaimsPrincipal(claimsIdentity);
  }

  private Task<HttpResponseMessage> ConfigureUnauthorizedRequest()
  {
    var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
    var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
    taskCompletionSource.SetResult(response);
    return taskCompletionSource.Task;
  }

  private void ParseAuthorizationHeader(HttpRequestMessage request)
  {
    if (request.Headers == null || request.Headers.Authorization == null || request.Headers.Authorization.Parameter == null)
      return;

    authorizationParameter = request.Headers.Authorization.Parameter;
  }
}

Step 2: Wire Your Handler to Your Configuration

Somewhere, you probably have a class that sets up your WebAPI configuration. You need to add this line to your configuration.

1
2
3
4
private static void ConfigureMessageHandlers(HttpConfiguration config)
{
  config.MessageHandlers.Add(new AuthorizationHeaderHandler());
}

Step 3: Add an Authorization Header to Your Requests

For this to work, you’ll need to add an authorization header to all of your requests. It needs to be in the following format.

1
Authorization: <scheme> <parameter>

Here’s a sample. (No don’t actually use this token. It’s just the SHA256 hash of Hello, World!.)

1
Authorization: Token DFFD6021BB2BD5B0AF676290809EC3A53191DD81C7F70A4B28688A362182986F

Step 4: Test With and Without an Authorization Header

Fire up Fiddler. Let’s create a request without an authorization header.

The request.

The reponse. We can see the 401 Unauthorized coming back from the server.

Now, let’s look at the same request with an authorization header.

The response. Now with more 200 OK.

We’re successfully grabbing the token from the request. Everything else is left as an exercise for the reader!