Showing posts with label futures. Show all posts
Showing posts with label futures. Show all posts

Tuesday, November 25, 2014

Better Polymer.dart Tests with Futures


I lamented Polymer.dart's JavaScript-y callback nature yesterday. But I didn't do much about it. Ultimately I cannot do much until the library matures into more of a Dart library. The Patterns in Polymer book needs to track the library, not my weakly held, strong opinions (and I do admit that it makes sense to track the JavaScript Polymer for now).

That said, I do think it worth exploring Dart futures as a means for cleaning up my tests.

Last night's test looks like:
    group('syncing <input> values', (){
      var input;

      setUp((){
        input = _container.append(createElement('<input>'));
        syncInputFromAttr(input, _el, 'state');
        _el.model.firstHalfToppings.add('pepperoni');
      });

      test('updates the input', (){
        _el.async(expectAsync((_){
          expect(
            input.value,
            startsWith('First Half: [pepperoni]')
          );
        }));
      });
    });
For a small test, that is not too horrible. Problems would arise as the complexity of the Polymer element grows.

The main problem with the above test is in the actual test:
      test('updates the input', (){
        _el.async(expectAsync((_){
          expect(
            input.value,
            startsWith('First Half: [pepperoni]')
          );
        }));
      });
The expectAsync() call in there is a nod to the asynchronous nature of Polymer and my attempt to account for it in my test. I need to wait for Polymer to invoke the supplied callback, which is what wrapping the callback in expectAsync() does. But it obscures the purpose of the test.

The async nature of this particular test is not integral to the functionality. It is merely a necessary evil to ensure that the Polymer element has been updated. Instead, I would much prefer to write:
      test('updates the input', (){
        expect(
          input.value,
          startsWith('First Half: [pepperoni]')
        );
      });
The intent of that test is much clearer.

To make that work, I need a setup that blocks. I had forgotten that vanilla unittest in Dart supports this if the setUp() block returns a Future:
      setUp((){
        input = _container.append(createElement('<input>'));
        syncInputFromAttr(input, _el, 'state');
        _el.model.firstHalfToppings.add('pepperoni');

       var completer = new Completer();
       _el.async(completer.complete);
       return completer.future;
      });
I am none too fond of the completer dance that is necessary. My preference would be to use something along the lines of Ruby's tap(), which in Dart would look something like this:
        return new MyCompleter()
          ..tap((completer){ _el.async(completer.complete); })
          .future;
Alas, Dart does not support tap() or an equivalent. Alas too that Completer is abstract, making it impossible to extend to add this functionality.

When I use the Page Objects testing pattern with my Polymer elements, I typically define a flush() method on the page object. The page object flush() can do the completer dance, making the code pretty nice.

The closest that I can get without page objects is a _flush() test helper:
Future<T> _flush(el) {
  var completer = new Completer();
  el.async(completer.complete);
  return completer.future;
}
This leaves my setup as:
      setUp((){
        input = _container.append(createElement('<input>'));
        syncInputFromAttr(input, _el, 'state');
        _el.model.firstHalfToppings.add('pepperoni');

        return _flush(_el);
      });
That is nice, but ugh, how I hate indirection in tests.

Update: This is one Future method in Polymer: onMutation(). And it works, but there is something of an impedance mismatch as it requires a node argument. I can make the tests pass if I supply the Polymer element's shadow root as the argument:
      setUp((){
        input = _container.append(createElement('<input>'));
        syncInputFromAttr(input, _el, 'state');
        _el.model.firstHalfToppings.add('pepperoni');

        return _el.onMutation(_el.shadowRoot);
      });
While that works, it adds undesirable complexity. Reading that in 6 months I would wonder why I was passing the shadowRoot property—was that a requirement of my test? Of my code? Or was it (as is the case here) just something that made the test work, but has no particular value.

I think I will stick with some variation of the completer dance for now. But it sure would be nice if the Polymer.dart folks would add a proper Future version of async.


Day #5

Monday, January 14, 2013

Testing Futures in Dart

‹prev | My Chain | next›

I keep thinking that I am almost done with my latest Dart research chain. And this time, I think that I am, but before I move back to finishing off Gaming JavaScript, I need to figure out how to test futures and isolates in Dart. I have already explored asynchronous testing in Dart quite a bit, but I need to make sure that I have futures working properly.

In Dart for Hipsters, I introduce completers and futures with a simple code example:
main() {
  var completer = new Completer();

  var future = completer.future;
  future.then((message) {
    print("Future completed with message: $message");
  });
  completer.complete("foo");
}
Since I immediately complete the completer, the end result of running this code is to simply print out:
Future completed with message: foo
The question is how do I test this. The print() method complicates things, but I use my usual trick of overriding print() for my testing purposes. In this case, I forward the message onto a supplied callback:
main() {
  // ...
}

var cb;
print(msg) => cb(msg);
To enable this to be testable in a separate file, I add a library declaration at the top of the file:
library simple_completer;

main() {
  // ...
}

var cb;
print(msg) => cb(msg);
Now, in the test file, I import the unittest library and my simple_completer.dart library so that I can run my tests:
library completer_test;

import 'package:unittest/unittest.dart';

import '../simple_completer.dart' as Simple;

run() {
  group("[simple completers]", (){
    test('can complete in the future', (){
      // TESTS GO HERE
    });
  });
}
But how to test? The Dart matcher libary includes a completer() matcher that I would love to use in order to match my expectation. Unfortunately, the completer is self-contained within the library's main() method. I could manually create a new matcher and complete in the print() statement, but this seems like cheating. Instead, I fallback to a simple async test:
    test('can complete in the future', (){
      Simple.cb = expectAsync1((msg){
        expect(msg, equals("Future completed with message: foo"));
      });
      Simple.main();
    });
I set the callback variable in the Simple libary to a function that accepts a single parameter (that's what the 1 in expectAsync1() indicates). And inside that function, I set the expectation of the print message.

And amazingly, it works:
➜  isolates git:(master) ✗ dart test/test.dart
unittest-suite-wait-for-done
PASS: [simple completers] can complete in the future

All 1 tests passed.
unittest-suite-success
I am so surprised that this works with my first try that I have to intentionally break it to ensure that I really am testing what I think I am testing. So I change the test to expect a "bar" in the printed message instead of a "foo" and find:
➜  isolates git:(master) ✗ dart test/test.dart
unittest-suite-wait-for-done
FAIL: [simple completers] can complete in the future
  Expected: 'Future completed with message: bar'
       but: was 'Future completed with message: foo'.
So it seems that I really do have a test in place. Asynchronous testing in Dart is crazy easy.

Just because I enjoy playing with Dart testing matcher so much, I must see how the completion matcher works. The answer? Pretty much as neatly as do the other testing matchers. I set the expectation on the future as to which message that I expect to receive in the future. Then, when the associated completer finishes at some future point, the test executes:
    test('can complete once', (){
      var completer = new Completer();
      var future = completer.future;

      expect(future, completion("foo"));

      completer.complete("foo");
    });
I am saying that I expect that my future to be a completion with the value "foo", which it is:
➜  isolates git:(master) ✗ dart test/test.dart
unittest-suite-wait-for-done
PASS: [simple completers] can complete in the future
PASS: [simple completers] can complete once

All 2 tests passed.
Very nice. I will pick back up tomorrow with isolates testing, then I really need to get back to Gaming JavaScript.


Day #630

Sunday, March 4, 2012

Complete is not Broken

‹prev | My Chain | next›

I ran into a weird behavior in exceptional Dart Futures yesterday. In the simplest case, the following works:
main() {
  var completer = new Completer();
  var future = completer.future;

  future.handleException((e) {
    print("Handled: $e");
    return true;
  });

  completer.completeException("That ain't gonna work");
}
(try.dartlang.org)

In this case, the completer completes with an exception, not with the normal successful complete(). But, since the future associated with the completer injects a handleException() method, the exception is handled. More specifically since the injected handleException() returns true, the exception is handled.

If I remove the true return, I see both the "Handled" print() statement as well as the exception bubbling all the way up:
Handled: That ain't gonna work
Exception: That ain't gonna work
Stack Trace:  0. Function: 'FutureImpl._complete@924b4b8' url: 'bootstrap_impl' line:3124 col:9
 1. Function: 'FutureImpl._setException@924b4b8' url: 'bootstrap_impl' line:3146 col:14
 2. Function: 'CompleterImpl.completeException' url: 'bootstrap_impl' line:3207 col:30
 3. Function: '::main' url: 'file:///home/cstrom/repos/dart-book/book/includes/no_more_callback_hell/main.dart' line:12 col:30
(try.dartlang does not seem to care about the return value—it always considers handleException() to have handled the exception)

My problem is that, although this behaves as expected in a simple case, it does not seem to work as expected in a more complex case. In my Hipster MVC library, my syncing layer that is responsible for coordinating in-browser data with permanent storage can have different behavior injected. So the HipsterSync.call() class method first needs a conditional to return a Future from the appropriate behavior (_defultSync in this case):
class HipsterSync {
  // ...
  static Future<Dynamic> call(method, model) {
    if (_injected_sync == null) {
      return _defaultSync(method, model);
    }
    else { /* ... */ }
  }
  // ...
}
The default syncing behavior then creates the completer and invokes completeException() when a non-200 response is received from the backend:
class HipsterSync {
  // ...
  static Future<Dynamic> _defaultSync(method, model) {
    var request = new XMLHttpRequest(),
        completer = new Completer();

    request.
      on.
      load.
      add((event) {
        var req = event.target;

        if (req.status > 299) {
          completer.
            completeException("That ain't gonna work: ${req.status}");
        }
        else { /* ... */ }
      });
    // ...

    return completer.future;
  }
}
Finally, the HipsterModel class is invoking HipsterSync.call() and trying to do the right thing with handleException():
class HipsterCollection implements Collection {
  // ...
  create(attrs) {
    Future after_save = _buildModel(attrs).save();

    after_save.
      then((saved_model) {
        this.add(saved_model);
      });

    after_save.
      handleException(bool (e) {
        print("Exception handled: ${e.type}");
        return true;
      });
  }
  // ...
}
When I generate a 409, however, that handleException() does not kick in. Instead, I see the exception bubbling all the way up to the Dart console:
POST http://localhost:3000/comics 409 (Conflict)
Exception: That ain't gonna work: 409
Stack Trace:  0. Function: 'FutureImpl._complete@924b4b8' url: 'bootstrap_impl' line:3124 col:9
 1. Function: 'FutureImpl._setException@924b4b8' url: 'bootstrap_impl' line:3146 col:14
 2. Function: 'CompleterImpl.completeException' url: 'bootstrap_impl' line:3207 col:30
 3. Function: 'HipsterSync.function' url: 'http://localhost:3000/scripts/HipsterSync.dart' line:44 col:30
 4. Function: 'EventListenerListImplementation.function' url: 'dart:htmlimpl' line:23163 col:35
Seemingly, the problem lies somewhere in between the simplest use-case and my complex Hipster MVC. So I start expanding from this simple case to more and more complex cases. After a time, I have worked through no less than six test cases on increasing complexity—all of them working. In my last test case, I have a static method from one class produce a completer exception that another class handles. Both are in separate libraries.

They say you can't prove a negative, but I seem to have just done so.

So I go back to my code and, indeed, the bug was mine. I eventually realize that the Future in HipsterCollection is not coming from HipsterSync as I thought. Rather it comes from HipsterModel:
class HipsterCollection implements Collection {
  // ...
  create(attrs) {
    Future after_save = _buildModel(attrs).save();
    // ...
  }
}
In hindsight this seems perfectly obvious.

When I first refactored into Completers and Futures, I did take into account that HipsterModel required changes as well:
class HipsterModel {
  // ...
  Future<HipsterModel> save() {
    Completer completer = new Completer();

    HipsterSync.
      call('post', this).
      then((attrs) {
        this.attributes = attrs;
        on.load.dispatch(new ModelEvent('save', this));
        completer.complete(this);
      });

    return completer.future;
  }
}
What is missing from that implementation is concern about an exception from HipsterSync.call(). The only thing that I do is wait patiently for a then() that never comes. So, just as I do in the HipsterCollection, I grab the Future returned by HipsterSync.call() and inject then() and handleException() behavior:
class HipsterModel {
  // ...
  Future<HipsterModel> save() {
    Completer completer = new Completer();

    Future after_call = HipsterSync.call('post', this);

    after_call.
      then((attrs) {
        this.attributes = attrs;
        on.load.dispatch(new ModelEvent('save', this));
        completer.complete(this);
      });

    after_call.
      handleException((e) {
        completer.completeException(e);
        return true;
      });

    return completer.future;
  }
}
It feels a bit much having to completeException() / handleException() all the way from HipsterSync, through HipsterModel and on up to HipsterCollection. Then again, the model has need to perform error handling before notifying the collection that something went wrong, so I see no real way around this.

At any rate, the Future exception is now captured in the model, re-raisd to the collection in such a way that the collection can handle it:


It is difficult when working with new languages to judge whether a mistake like this lies with the language (e.g. too much complexity) or myself. In this case, my understanding of the technique was solid, but I muffed the implementation—was that Dart's fault or my own? I think in this case, it was my own. I think the architecture that I have chosen necessitates this type of propagation on occasion and I need to be cognizant of this. Re-examining my ultimate solution, I do not see anywhere that Dart could have eased my burden. Then again, perhaps I simply lack imagination.


Day #315

Saturday, March 3, 2012

Errors from the Future (of Dart)

‹prev | My Chain | next›

Last night I cleaned up a bit of callback hell in my Dart-based Hipster MVC library. Today, I am going to strike out off of the happy path. I had not begun to deal with errors in my callback version of the MVC library. Let's see how easy it is to handle the unexpected with Futures and Completers.

So I modify the express.js backend to always throw an error when POSTing:
app.post('/comics', function(req, res) {
  res.send(409);
}
Then I modify the frontend code to handle errors:
class HipsterSync {
  // ...
  static Future<Dynamic> _defaultSync(method, model) {
    var request = new XMLHttpRequest(),
        completer = new Completer();

    request.
      on.
      error.
      add((event) {
        print("Something bad happened");
      });

    request.
      on.
      load.
      add((event) {
        var req = event.target,
            json = JSON.parse(req.responseText);
        completer.complete(json);
      });

    request.open(method, model.url, true);

    // POST and PUT HTTP request bodies if necessary
    if (method == 'post' || method == 'put') {
      request.setRequestHeader('Content-type', 'application/json');
      request.send(JSON.stringify(model.attributes));
    }
    else {
      request.send();
    }

    return completer.future;
  }
}
I may need to break that up -- possibly extracting the Ajax callbacks into their own methods. For now, I will focus on getting it to work. When I try to POST from my comic book application, however, I get:


So Dart seemingly does not see this as an error. The stacktrace is because my normal "load" listener is handling this case. Bah!

I remove my "error" listener and add the error handling directly in the normal "load" handler:
  static Future<Dynamic> _defaultSync(method, model) {
    // ...
    request.
      on.
      load.
      add((event) {
        var req = event.target;

        if (req.status > 299) _handleError(req, completer);

        var json = JSON.parse(req.responseText);
        completer.complete(json);
      });
    // ...
  }

  static void _handleError(request, completer) {
    completer.completeException(new Exception("That ain't gonna work: ${request.status}"));
  }
That does the trick, as I now see my "That ain't gonna work error" at the top of the stacktrace in the Dart console:


To get rid of this, I ought to be able to define a handleException method on the Future returned from save(). So I change this:
  create(attrs) {
    _buildModel(attrs).
      save().
      then((saved_model) {
        this.add(saved_model);
      });
  }
To This:
  create(attrs) {
    Future after_save = _buildModel(attrs).save();

    after_save.
      then((saved_model) {
        this.add(saved_model);
      });

    after_save.
      handleException((e) {
        print("Exception handled: ${e.type}");
        return true;
      });
  }
The return true statement at the end of my handleException function is supposed to mark this exception as handled. But reality is not matching the spec in this case. Instead, I continue to see the exception bubbling all the way up to the user.


Ugh. Straying from the happy path in Dart is not working well for me tonight. So, in the end, I have to settle for catching the HipsterSync exception directly. That is not a huge loss, but the exception types could become a bit tricky (depending on if the sync is for a collection or a model). And really, that handleException() method should work properly. Well, I'm off to the Dart bug tracking system....

Update: this seems to work in simpler cases. That also works in Dartium. So somewhere between my complex multi-library completer/future and this simple case, things break down. I will keep investigating tomorrow.


Day #314

Friday, March 2, 2012

From the Future: Hipster MVC

‹prev | My Chain | next›

Yesterday, I failed miserably to get Dart to work with IndexedDB in Dartium. It was a pretty disappointing outing all around, but not a complete waste. I eventually came across a nice example of Dart IndexedDB written by Seth Ladd. It only works when compiled into Javascript, so it was not directly useful to me. But it did get me to thinking about my callback ways.

Coming from a very functional Javascript / node.js background, I am perfectly comfortable slinging callbacks about. In my Hipster MVC library, for example, I supply a callback when I save individual models:
  create(attrs) {
    var new_model = modelMaker(attrs);
    new_model.collection = this;
    new_model.save(callback:(event) {
      this.add(new_model);
    });
  }
When I read through Seth's IndexedDB code, it struck me how much he relies on Futures. This, naturally enough, made me feel all inadequate in my Dart coding. Well today, I shall be inadequate no more! Well... at least in this area.

Looking into HipsterModel, I see that my save is awash in callback... stuff:
class HipsterModel {
  // ...
  save([callback]) {
    HipsterSync.call('post', this, options: {
      'onLoad': (attrs) {
        attributes = attrs;

        var event = new ModelEvent('save', this);
        on.load.dispatch(event);
        if (callback != null) callback(event);
      }
    });
  }
  // ...
}
Instead of this approach, I declare that save() returns a Future. In the method body, I need a Completer, whose future I can return:

  Future<HipsterModel> save() {
    Completer completer = new Completer();

    HipsterSync.call('post', this, options: {
      'onLoad': (attrs) {
        attributes = attrs;

        var event = new ModelEvent('save', this);
        on.load.dispatch(event);

        completer.complete(this);
      }
    });

    return completer.future;
  }
The future is not invoked until the Completer completes, which happens inside the onLoad callback (say, I can probably get rid of that too). Back in the Collection class, I now need a then() method for the returned Future:
class HipsterModel {
  // ...
  create(attrs) {
    var new_model = modelMaker(attrs);
    new_model.collection = this;
    new_model.
      save().
      then((saved_model) {
        this.add(new_model);
      });
  }
  // ...
}
Ooh! I like that. It reads a heck of a lot better than my callback parameter. Here, I can read that I save my new model, then add it to the current collection.

A quick sanity check verifies everything still works:


Back in HipsterModel#save, I am still invoking HipsterSync.call() with a callback:
class HipsterModel {
  // ...
  Future<HipsterModel> save() {
    Completer completer = new Completer();

    HipsterSync.call('post', this, options: {
      'onLoad': (attrs) {
        attributes = attrs;

        var event = new ModelEvent('save', this);
        on.load.dispatch(event);

        completer.complete(this);
      }
    });

    return completer.future;
  }
  // ...
}
If I replace the callback in HipsterSync with a Future, the callback becomes:
class HipsterModel {
  // ...
  Future<HipsterModel> save() {
    Completer completer = new Completer();

    HipsterSync.
      call('post', this).
      then((attrs) {
        this.attributes = attrs;
        on.load.dispatch(new ModelEvent('save', this));
        completer.complete(this);
      });

    return completer.future;
  }
  // ...
}
That is so much nicer to read. I am calling HipsterSync, telling it to POST the model. Then, I take the attributes returned from the sync and assign them to the model's attributes, dispatch any events, and, finally, complete the save() completer from earlier.

That is much cleaner than the callback approach. I may have to start using custom-built Futures in Javascript. One thing missing from this is exceptions—I have a lot of happy path going on. Fortunately, there are exception facilities built into Futures. I will take a look at those tomorrow.


Day #313