Skip to content
This repository
Browse code

Add "Make Your Tests Deterministic" post

  • Loading branch information...
commit 5f220e7bcd3250ff750e5625a5975d00036a2f11 1 parent 92f026c
Vojta Jina authored August 13, 2012
57  articles/make-your-tests-deterministic.markdown
Source Rendered
... ...
@@ -0,0 +1,57 @@
  1
+Title: Make Your Tests Deterministic
  2
+Author: Vojta Jina
  3
+Date: Tue Aug 13 2012 01:12:01 GMT-0800 (PST)
  4
+Node: v0.8.4
  5
+
  6
+
  7
+Non-deterministic issues like [race conditions] or [thread deadlocks] are very difficult to test, because they are by nature hard to reproduce. Fortunately, in the JavaScript world, we only have a single thread, so we are safe, right? Well, not really because...
  8
+
  9
+**Execution order of callbacks can cause the same race condition issues that plague multi-threaded environments.**
  10
+
  11
+
  12
+## Example
  13
+
  14
+Let's say we need a function that will return an array of timestamps representing the last modification time of a set of files.
  15
+
  16
+<make-your-tests-deterministic/get-last-modified.js>
  17
+
  18
+To unit test this code, we need to mock out `fs` module (using real file system would require setting up some initial state, cleaning up afterwards and would make the test slow). That's pretty easy with [node-mocks] - we can use a fake in-memory file system.
  19
+
  20
+<make-your-tests-deterministic/get-last-modified.spec.js>
  21
+
  22
+This unit test passes, but the production code is broken. Even worse, it sometimes works, sometimes it does not... The problem is that this code relies on the order of `fs.stat` callbacks, which is preserved in the mock version of `fs`, but can't be guaranteed on real fs - it's non-deterministic.
  23
+
  24
+
  25
+## Solution
  26
+
  27
+Our solution needs to simulate the problematic behavior during the test.
  28
+
  29
+We could make the fake `fs` to fire callbacks in a random order, which would be very similar to the real `fs` behavior. However, that would result in a flaky tests that sometimes pass, sometimes not - just like our production code. Yep, we could do "stress" testing - execute the test multiple times, to make the probability of failing bigger, but that's still flaky.
  30
+
  31
+What we really want is our tests to be always deterministic - reliable, not flaky. So we need to simulate this behavior in a predictable - controlled way.
  32
+That's why the `fs` mock uses something called `predictableNextTick`, which behaves similar to [process.nextTick], but fires callbacks in a specific order.
  33
+
  34
+Let's add this line into our unit test:
  35
+
  36
+    mocks.predictableNextTick.pattern = [1, 0];
  37
+
  38
+Suddenly, the test is failing, because now the `fs.stat` callbacks are fired in different order than they were registered. They are fired in order specified by the pattern - second callback first, then first, then fourth, then third, etc...
  39
+
  40
+**The important thing is, they are ALWAYS fired in THIS order. It's predictable, deterministic !**
  41
+
  42
+This was very simple example of an issue, that can easily happen when dealing with asynchronous APIs. The same type of issues can happen in web applications as well, for instance by sending multiple xhr requests.
  43
+**In production, this behavior is out of our control. However, in order to guarantee correct behavior of our code, we need to be sure that it handles correctly all these different situations. The best way to do that is by simulating these situations in a fully controlled - a deterministic way.**
  44
+
  45
+
  46
+
  47
+The full source code of `predictableNextTick` implementation can be found on [github].
  48
+
  49
+The full source code of this example is on [gist].
  50
+
  51
+
  52
+[thread deadlocks]: http://en.wikipedia.org/wiki/Deadlock
  53
+[race conditions]: http://en.wikipedia.org/wiki/Race_condition
  54
+[node-mocks]: https://github.com/vojtajina/node-mocks
  55
+[github]: https://github.com/vojtajina/node-mocks/blob/master/lib/util.js
  56
+[gist]: https://gist.github.com/3283670
  57
+[process.nextTick]: http://nodejs.org/api/process.html#process_process_nexttick_callback
15  articles/make-your-tests-deterministic/get-last-modified.js
... ...
@@ -0,0 +1,15 @@
  1
+var fs = require('fs');
  2
+
  3
+var getLastModified = function(files, done) {
  4
+  var timestamps = [];
  5
+
  6
+  files.forEach(function(file) {
  7
+    fs.stat(file, function(err, stat) {
  8
+      timestamps.push(stat.mtime);
  9
+
  10
+      if (timestamps.length === files.length) {
  11
+        done(null, timestamps);
  12
+      }
  13
+    });
  14
+  });
  15
+};
30  articles/make-your-tests-deterministic/get-last-modified.spec.js
... ...
@@ -0,0 +1,30 @@
  1
+// Jasmine Syntax
  2
+describe('getLastModified', function() {
  3
+
  4
+  var mocks = require('mocks');
  5
+  var mockery = {
  6
+    // reate a fake in-memory FS
  7
+    fs: mocks.fs.create({
  8
+      'one.js': mocks.fs.file('2012-01-01'),
  9
+      'two.js': mocks.fs.file('2012-02-02'),
  10
+      'three.js': mocks.fs.file('2012-02-02')
  11
+    })
  12
+  };
  13
+
  14
+  // load the module (using fake FS)
  15
+  var getLastModified = mocks.loadFile('get-last-modified.js', mockery).getLastModified;
  16
+
  17
+
  18
+  it('should return last modified timestamps for every file', function() {
  19
+    var spy = jasmine.createSpy('done').andCallFake(function(err, timestamps) {
  20
+      expect(timestamps).toEqual([
  21
+        new Date('2012-01-01'), new Date('2012-02-02'), new Date('2012-02-02')
  22
+        ]);
  23
+    });
  24
+
  25
+    getLastModified(['/one.js', '/two.js', '/three.js'], spy);
  26
+
  27
+    // wait for done callback
  28
+    waitsFor(function() {return spy.callCount;});
  29
+  });
  30
+});

0 notes on commit 5f220e7

Please sign in to comment.
Something went wrong with that request. Please try again.