Monday, October 7, 2013

Staircase to Dependency Hell


One of the many reasons that I love Dart is the testing. The built-in unittest is pretty darn amazing. And people are already building things like scheduled_test on top of it. I still haven't figured out when to use unittest and when to use scheduled test, but after last night, I may have found at least one rule of thumb.

While testing the Polymer.dart version of ICE Code Editor, I wound up creating a unittest test like:
      group("after JS has loaded and been evaluated", (){
        setUp(()=> Editor.jsReady);

        test("can still embed code", (){
          var later = createElement('ice-code-editor')
            ..xtag.src = 'embed_baz.html';

          document.body.append(later);

          Timer.run(
            expectAsync0((){
              expect(
                queryAll('ice-code-editor').last.shadowRoot.query('h1').text,
                contains('embed_baz.html')
              );
            })
          );
        });
      });
What bothers me about this is the crazy staircase of curly braces at the end. Admittedly, this is partly due to my stubbornness in insisting on one-concept-per-line-of-code. Still, staircases only appear in code when nested dependencies are present and this is no exception.

So let's see if scheduled_test can help. The scheduled_test add-on to unittest breaks asynchronous tasks into “schedules.” Hopefully that will be of particular use with the Timer.run(). I start by replacing unittest in the dev_dependencies section of my package's pubspec.yaml file:
name: ice_code_editor
version: 0.0.11
description: Code Editor + Preview
# ...
dev_dependencies:
  scheduled_test: any
Then pub install to grab the new package:
➜  ice-code-editor git:(polymer) ✗ pub install
Resolving dependencies.............................
Downloading http 0.7.5 from hosted...
Downloading scheduled_test 0.7.5 from hosted...
Dependencies installed!
The next step is to replace the unittest import with a scheduled_test import in my test file:
library ice_polymer_test;

import 'package:scheduled_test/scheduled_test.dart';
// Other imports here...

main() {
  // Tests here...
}
And, since scheduled_test is a drop-in replacement for unittest, all of my tests continue to pass:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
PASS: [polymer] creates a shadow preview 
PASS: [polymer] creates an editor 
PASS: [polymer] multiple elements can embed code 
PASS: [polymer] multiple elements after JS has loaded and been evaluated can still embed code 
 
All 6 tests passed. 
Although the Timer.run() section of my test is bothering more than other parts of the test, I will start at the the top. The “after JS has loaded and been evaluated” group was written only to get the setUp() to block until the returned Editor.jsReady future completed. With scheduled_test, I no longer need that setUp() allowing me to move the Future into a schedule of the actual test:
      test("can still embed code", (){
        schedule(()=> Editor.jsReady);

        var later = createElement('ice-code-editor')
          ..xtag.src = 'embed_baz.html';

        document.body.append(later);

        Timer.run(
          expectAsync0((){
            expect(
              queryAll('ice-code-editor').last.shadowRoot.query('h1').text,
              contains('embed_baz.html')
            );
          })
        );
      });
Nice, I have already removed one step in my dependency staircase.

The next schedule in my test is adding my custom Polymer element to the DOM and then waiting one event loop for the ice-code-editor element to update the DOM. In the unittest version, the Timer.run() served the purpose of waiting one event loop. In the scheduled_test version, I can put that wait back where it belongs—with the code that adds the element to the DOM.

I cannot use a Timer.run() this time. Instead, I need to return a Future that will wait one event loop before completing. The easiest way that I know to do that is with the named Future.delayed constructor. A delay of zero should wait one event loop:
      test("can still embed code after JS is loaded and evaluated", (){
        schedule(()=> Editor.jsReady);

        schedule((){
          var later = createElement('ice-code-editor')
            ..xtag.src = 'embed_baz.html';

          document.body.append(later);

          return new Future.delayed(Duration.ZERO);
        });

        schedule((){
          expect(
            queryAll('ice-code-editor').last.shadowRoot.query('h1').text,
            contains('embed_baz.html')
          );
        });
      });
With that, I am back to a fully passing test suite:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
PASS: [polymer] creates a shadow preview 
PASS: [polymer] creates an editor 
PASS: [polymer] multiple elements can embed code 
PASS: [polymer] multiple elements can still embed code after JS is loaded and evaluated 
 
All 6 tests passed.
More importantly, I have my staircase down to three steps. Given that the concepts in those steps are: test expectation, schedule, and test, I think I can live with that. Maintainability in tests is not quite as important as it is in actual code, but little wins like this can go a long way.


Day #897

Sunday, October 6, 2013

Dart's Timer is the Devil (in tests)


I have grown to think of Dart's Timer as a personal failure. The kind of failure that results in bad things happening to cute, innocent animals. Oh, there are some legitimate uses of Timer to be sure, but I seem to use it as crutch whenever I cannot understand some asynchronous behavior or other.

My Timer abuse is at its worst in tests. Consider last night's test in which I had to use not one but two instances of Timer:
      test("can embed code much later", (){
        new Timer(
          new Duration(milliseconds: 1000),
          expectAsync0((){
            var later = createElement('ice-code-editor');
            var iceElement = later.xtag;
            iceElement.src = 'embed_baz.html';

            document.body.append(later);

            new Timer(
              new Duration(milliseconds: 1000),
              expectAsync0((){
                expect(
                  queryAll('ice-code-editor').last.shadowRoot.query('h1').text,
                  contains('embed_baz.html')
                );
              })
            );
          })
        );
      });
That's just silly. Shame on me.

The first Timer is an attempt to simulate the “later” mentioned in the test description. I am trying to verify that the Polymer.dart custom element works—js-interop and all—after all JavaScript has loaded. I found that the second Timer was necessary as I was exploring adding dynamic attributes to my Polymer.dart custom element for the ICE Code Editor. Hopefully I can find better alternatives to both tonight.

The first is meant to ensure that the JavaScript has fully loaded and been evaluated. As part of last night's work, I now have an Editor.jsReady Future that will complete when the JavaScript is fully loaded. I can use that as part of my test's setUp():
      group("after JS has loaded and been evaluated", (){
        setUp(()=> Editor.jsReady);

        test("can still embed code", (){
          // Same test, but with one Timer now...
        });
      });
Returning a Future, like Editor.jsReady, from a Dart unittest setUp() will block the test until the Future has completed. So I have removed one Timer and gotten a more accurate, deterministic test as a result.

As for that second Timer, I would swear before powerful and mysterious forces that I could only get the test to pass if I made it wait for nearly a full second. This was late last night, so I would not swear before the gods of my chain that the full second was required. My certainly lies somewhere between fear of vague and unknown mystical forces and fear of the very strict chain gods (who are kind and beneficent when you don't mess with them). Anyhow...

Tonight, I find that I can reduce the second Timer all the way to a duration of zero. In other words, I can use plain-old Timer.run():
      group("after JS has loaded and been evaluated", (){
        setUp(()=> Editor.jsReady);

        test("can still embed code", (){
          var later = createElement('ice-code-editor')
            ..xtag.src = 'embed_baz.html';

          document.body.append(later);

          Timer.run(
            expectAsync0((){
              expect(
                queryAll('ice-code-editor').last.shadowRoot.query('h1').text,
                contains('embed_baz.html')
              );
            })
          );
        });
      });
A Timer instance with an arbitrary duration before running code is a lightning rod for my ire. Timer.run(), on the other hand, I can abide. An arbitrary Timer duration says to me that there are mysterious things in my code that I do not understand. Test.run() says that I need to give my code one event loop to render a change. Ultimately, this is what the code is doing—updating the DOM after the described change. So I can live with a test that codifies that.

That said, this might be a good use case for scheduled_test. Perhaps something to explore tomorrow (along with why the preview is no longer being updated). For now, I am satisfied with killing off two Timer instances. I may believe in and fear mysterious gods, but that is no reason to suffer mystery in my tests.


Day #896

Saturday, October 5, 2013

Dynamically Creating Polymer.dart Elements and Attributes


I have multiple <ice-code-editor> working the right way. Last night's fix was not so much a Polymer.dart solution as it was a Dart / js-interop / my-crazy-usage solution. But I do not know if the solution is complete.

I know that, if the first <ice-code-editor> is evaluated before some of the required JavaScript has loaded, then everything will work. The underlying ICE Code Editor code already accounted for this case and it has always worked in the Polymer.dart version. After last night, I also have a second <ice-code-editor> working — even if the JavaScript pulled in by the first element has not finished loading. What I am unsure of is what happens when a third element loads after the JavaScript has been loaded and evaluated.

To figure out if this is working, I am going to dynamically create and add a <ice-code-editor> element to my test page and query that the underlying component is updated correctly:
      test("can embed code much later", (){
        var later = new Element.html(
          '<ice-code-editor src="embed_baz.html" line_number="0"></ice-code-editor>'
        );
        document.body.append(later);
        expect(
          queryAll('ice-code-editor').last.shadowRoot.query('h1').text,
          contains('embed_baz.html')
        );
      });
Adding my custom element like this does not quite work, however. Dart's HTML sanitization strips the tag, causing the test to fail:
Removing disallowed element <ICE-CODE-EDITOR>
ERROR: [polymer] multiple elements can embed code much later
  Test failed: Caught Bad state: No elements
  dart:collection/iterable.dart 266:26 
I try to define the usual NullTreeSanitzer:
class NullTreeSanitizer implements NodeTreeSanitizer {
  void sanitizeTree(node) {}
}
And use that in my test:
      test("can embed code much later", (){
        var later = new Element.html(
          '<ice-code-editor src="embed_baz.html" line_number="0"></ice-code-editor>',
          treeSanitizer: new NullTreeSanitizer()
        );
        document.body.append(later);

        expect(
          queryAll('ice-code-editor').last.shadowRoot.query('h1').text,
          contains('embed_baz.html')
        );
      });
With that, I no longer get the error, but neither is my test passing:
ERROR: [polymer] multiple elements can embed code much later
  Test failed: Caught The null object does not have a method 'query'.
  
  NoSuchMethodError : method not found: 'query'
  Receiver: null
  Arguments: ["h1"]
  dart:core-patch/object_patch.dart 20:25                                                                                                   Object.noSuchMethod
  ../test.dart 70:60               
Even if I wrap that in a Timer delay, I still get the same failure. Eventually, I discover the polymer / custom_element createElement() and createElementFromHtml() methods. These methods ought to serve as a means of creating a custom element that has already been registered. But even these don't work. Well, not without some effort.

I am able to get this working by creating the element with createElement()—without any attributes. I then have to access the web component via the xtag property:
  // This gets: Removing disallowed element  ...
  // var later = createElementFromHtml('<ice-code-editor src="embed_baz.html" line_number="0"></ice-code-editor>');

  // Don't see attributes change ...
  // var later = createElement('ice-code-editor')
  //   ..attributes['src'] = 'embed_baz.html'
  //   ..attributes['line_number'] = '0';

  var later = createElement('ice-code-editor');
  var iceElement = later.xtag;
  iceElement.src = 'embed_baz';

  document.body.append(later);
Though to get the src loaded, I now have to implement the attributeChanged() method in my Polymer class:
class IceCodeEditorElement extends PolymerElement with ObservableMixin {
  @published String src;
  @published int line_number = 0;
  ICE.Editor editor;

  void created() { /* ... */ }

  void attributeChanged(String name, String oldValue) {
    super.attributeChanged(name, oldValue);
    loadContent();
  }

  loadContent() { /* ... */ }
}
With that, I have my test passing:
PASS: [polymer] can embed code
PASS: [polymer] can set line number 
PASS: [polymer] creates a shadow preview 
PASS: [polymer] creates an editor
PASS: [polymer] multiple elements can embed code 
PASS: [polymer] multiple elements can embed code much later 

All 6 tests passed. 
That was a little harder than I expected—at least dynamically updating the attributes on a created element. Which makes me suspect that I am doing something wrong. Ah well, for tonight I will accept the working solution. The right solution is solid grist for tomorrow.


Day #895

Friday, October 4, 2013

Testing Futures in Polymer.dart Elements


Getting multiple instance of my Polymer.dart custom element turned out to be fairly easy. So easy, that it only took a four line hack. Tonight, I remove the hack so that I can do it for real. Even though the hack turned out to be small and self-contained, I originally suspected it to be a more significant problem which led me to explore the fix via a code spike. Now that I understand the problem, I have enough information to fix it the right way: by testing.

The hack had nothing to do with Polymer.dart, but with the manner in which I am loading JavaScript libraries for use via js-interop. To keep my code a black-box I do not load any JavaScript libraries with explicit <script> tags. Rather, I have my library dynamically append the necessary <script> tags to the document. Once the load event for the script fires, an instance of my ICE Code Editor object sees a Future completed so that the remainder of the initialization can occur.

Last night's hack was to wait for a constant amount of time so that multiple instances would delay long enough for the JavaScript to be ready. That is a hack rather than a long-term solution because the delay needs to vary in time depending on latency in the network. Instead of a time-based delay, what I really need is a way to expose the when-javascript-ready Future to all instances of my <ice-code-editor> element.

I suspect that there may be a more general solution that I need to extract for this, but I start with my specific problem by adding a second <ice-code-editor> custom element to my testing context:
<head>
  <link rel="import" href="packages/ice_code_editor/polymer/ice_code_editor.html">
  <script src="packages/polymer/boot.js"></script>
  <script src="packages/unittest/test_controller.js"></script>
  <script type="application/dart" src="test.dart"></script>
</head>
<body>
  <ice-code-editor src="embed_foo.html" line_number="42"></ice-code-editor>
  <ice-code-editor src="embed_bar.html" line_number="0"></ice-code-editor>
  <script src="packages/browser/interop.js"></script>
</body>
My existing tests that still set their expectations on the first element continue to pass:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
PASS: [polymer] creates a shadow preview 
PASS: [polymer] creates an editor

All 4 tests passed. 
The tests pass, but there is a mess of error output:



The errors are coming from no-longer hacked code. Rather than try to address the errors, I start with a test setting an expectation that the last <ice-code-editor> element on my test pages is using the embed_bar.html source (instead of embed_foo.html in the first element):
    group("multiple elements", (){
      var it;
      setUp((){
        it = queryAll('ice-code-editor').last;
      });

      test("can embed code", (){
        expect(
          it.shadowRoot.query('h1').text,
          contains('embed_bar.html')
        );
      });
    });
That fails because there is only one functioning <ice-code-editor> element on the page—the first one with embed_foo.html as the source:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
PASS: [polymer] creates a shadow preview 
PASS: [polymer] creates an editor 
FAIL: [polymer] multiple elements can embed code
  Expected: contains 'embed_bar.html'
    Actual: 'The src is "embed_foo.html" (42)'
To get this passing, I focus on the same area that got hacked up last night—the _startAce() method. This method is responsible for instantiating the JavaScript code that builds the editor part of ICE's editor/preview combo. Instead of adding a delay timer before instantiating the JavaScript objects, I wait for a soon-to-be-created Future, jsReady to complete:
  _startAce() {
    // ...
    jsReady.then((_)=> _startJsAce());
    // ...
  }
Once the JavaScript is ready, then I start the JavaScript Ace objects.

This _startAce() method is an instance method. I might have a hundred instances of the editor—each one of them needs its own Ace instance. But each and every instance of the editor needs to check for the same JavaScript ready. Enter a static getter:
class Editor {
  // ...
  static Future get jsReady { /* ... */ }

  // instance method
  _startAce() {
    jsReady.then((_)=> _startJsAce());
  }
  // ...
}
This is probably one of those cases in which a static method ought to be refactored into a separate singleton class. I'll suffer with the static method for now.

In Dart, if an instance method cannot be found, a class method of the same name will be searched. This is how the call to the static jsReady getter method works from the _startAce() instance method.

For the jsReady function to return a Future, I need a Completer object, which has both a future property and a complete() method which will fire any then() callbacks attached to the Future:
  static Completer _waitForJS;
  static Future get jsReady {
    if (!_isAceJsAttached) {
      _waitForJS = new Completer();
      _attachScripts().
        first.
        onLoad.
        listen((_)=> _waitForJS.complete());
    }

    return _waitForJS.future;
  }
I already have a _isAceJsAttached getter that will return true if a <script> tag exists for the Ace source. If the Ace JavaScript files have not been attached to the document yet, I do so with _attachScripts() and then listen for the load event on the first of those <script> tags. When loaded, I complete my new _waitForJs completer, firing the then() callbacks.

And that does the trick:
unittest-suite-wait-for-done
PASS: [polymer] can embed code
PASS: [polymer] can set line number
PASS: [polymer] creates a shadow preview
PASS: [polymer] creates an editor
PASS: [polymer] multiple elements can embed code

All 5 tests passed.
unittest-suite-success 
So, in the end, a little future-based code goes a long way. Futures can be a little hard to explain (or maybe my brain is just fried), but they make for some easy-to-read, working code.

I think tomorrow that I will pick back up by taking this a step further. I would like to see if I can dynamically create and add my custom element to the document and test that it behaves as desired.


Day #894

Thursday, October 3, 2013

What's Better Than One Polymer Element?


Having gotten the <ice-code-editor> element working in Polymer.dart, I would like to see if it is possible to get two instances of the element on the same page. Something like this would be very useful in a tutorial. The first element could contain an early version of the project, with subsequent elements containing more and more sophistication.

I have some reason to expect this work in the underlying ICE Code Editor. I spent some time getting multiple versions of the editor working to better support testing. Of course none of the tests ever explicitly tried to run two instances at the same time, but what could go wrong?

I kinda feel like spiking this rather than driving a feature via tests. So, in the sample page, I add a second custom element:
<p>
asdf asdf as df sadf as df asdf
</p>

<ice-code-editor src="embed_a.html" line_number="21"></ice-code-editor>

<p>
asdfsadfasd sadf asdf  sdf asdf a sdfsfd
</p>

<ice-code-editor src="embed_b.html" line_number="49"></ice-code-editor>

<p>
asdfsadfasd sadf asdf  sdf asdf a sdfsfd
</p>
Naturally, that does not work. I get a lovely “null object does not have a method” stack trace:



This seems not so much a Polymer issue as it is a js-interop concern. The error is being thrown from the js-interop code that wraps the JavaScript ACE editor:
class Ace extends jsw.TypedProxy {
  static Ace edit(dynamic el) => Ace.cast(js.context['ace'].edit(el));
  // ...
}
Specifically, the js.context['ace'] property is null in the second Polymer instance. My first thought is to despair that the js-interop context created by the first element is not valid in the second instance. But this does not explain how I can create 150 separate instances in my tests. Even though those test instances are never active at the same time, they all reuse the same js.context['ace'] to create the editor part of ICE.

This leads me to suspect a simple timing issue. Specifically, I believe that when the second <ice-code-editor> tag is created, the ACE JavaScript code is not loaded and evaluated. Even though it is not evaluated, ICE can tell that it has been loaded by virtue of checking for a <script> tag with a source of ace.js. Seeing that tag, ICE assumes that ACE is loaded and evaluated. This is a fine assumption in tests, but is not valid in this case.

To try out my theory, I add a simple 100 millisecond delay to ICE when it believes the JavaScript editor to already be loaded:
_startAce() {
    if (_isAceJsAttached) {
      new Timer(
        new Duration(milliseconds: 100),
        _startJsAce
      );
    }
    else {
      // Load ace.js for the first time...
    }
  }
And that seems to do the trick. I now have two different <ice-code-editor> elements running two different Three.js simulations and scrolled to different lines in the code:



Not only does it work, but the two tags seem to be completely separate. Updates to one editor only update the simulation in that instance—the preview in the other editor remains unchanged. This ought to be expected when everything is kept in the shadow DOM in Polymer elements, but I cannot keep the JavaScript code in the shadow DOM. So there was a fear that problems would arise thanks to the shared JavaScript. Happily, this does not seem to be the case.

The timer-based solution is inappropriate for real-world usage. There may be high latency cases in which 100ms is not sufficient. I think that I will back out tonight's changes and TDD the correct behavior—possibly with a static completer—tomorrow. But, for now, this was a successful spike—it seems as though this is gonna work quite nicely.


Day #893

Wednesday, October 2, 2013

TDD the Shadow DOM in Polymer.dart


I am digging messing about with Polymer.dart and Shadow DOM. That's some good clean fun.

Without much difficulty, I have used Polymer to create an <ice-code-editor> tag that embeds nicely into a regular web page:



It seems that it was easy, in part, because I cheated. The actual code editor is not part of the shadow DOM that contains the title of the element:



In some respects, this might qualify as no-harm, no-foul. After all, it works and no harm is being caused by the ICE Code Editor being part of the main DOM tree. On the other hand, encapsulating all of a Polymer element inside the shadow DOM can keep the contents secure. More relevant to this particular case, it will prevent conflicts between elements. ICE has been developed primarily for a one-instance-per-page use case. It might work with multiple instances, but why risk conflicts if I don't have to?

Anyhow, tonight, I am going to attempt to drive the editor into the shadow DOM using tests (that's a pretty cool sentence, eh?). After last night, I already have some tests that are probing the shadow DOM:
    test("can set line number", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('(42)')
      );
    });
Using that test as a basis, I can describe my expectations as:
    test("creates an editor and preview", (){
      expect(
        query('ice-code-editor').shadowRoot.query('.ice-code-editor-editor'),
        isNotNull
      );

      expect(
        query('ice-code-editor').shadowRoot.query('.ice-code-editor-preview'),
        isNotNull
      );
    });
And, just like that, I have a failing test:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
FAIL: [polymer] creates an editor and preview
  Expected: not null
    Actual: <null>
A quick look at my Polymer code shows where I need to address the situation:
@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement with ObservableMixin {
  @published String src;
  @published int line_number;

  void created() {
    super.created();

    var container = new DivElement();
    host.append(container);
    var editor = new ICE.Editor(container);
    // Other setup...
  }
}
Instead of adding the container element to the document, I need only add it to the Polymer element's shadow root:
@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement with ObservableMixin {
  @published String src;
  @published int line_number;

  void created() {
    super.created();

    var container = new DivElement();
    shadowRoot.append(container);
    var editor = new ICE.Editor(container);
    // Other setup...
  }
}
Easy peasy. Except, of course, it does not work at all.

It turns out that the JavaScript code editor (ACE code editor) that is being used via js-interop does a lot of mucking with the DOM. The real DOM. The DOM that needs to have access to document and various top-level methods.

So I am pretty much out of luck in trying to add the editor to the shadow DOM. At least until the underlying JavaScript code supports the shadow DOM. That said, I am not at a complete dead end. Even though the editor part of ICE cannot be added to the shadow DOM, the preview layer can be:
    test("creates a shadow preview", (){
      expect(
        query('ice-code-editor').shadowRoot.query('.ice-code-editor-preview'),
        isNotNull
      );
    });
I make that test pass by adding a <div> to the shadow DOM and then passing it to the ICE Editor constructor:
@CustomTag('ice-code-editor')
class IceCodeEditorElement extends PolymerElement with ObservableMixin {
  // ...
  void created() {
    super.created();

    var container = new DivElement();
    host.append(container);

    var preview_el = new DivElement();
    shadowRoot.append(preview_el);

    var editor = new ICE.Editor(container, preview_el: preview_el);
    // Other setup...
  }
}
Now that I think about it, it will not hurt to test that the editor is added to the main DOM tree as well:
    test("creates an editor", (){
      expect(
        query('ice-code-editor').query('.ice-code-editor-editor'),
        isNotNull
      );
    });
With that, I have four passing tests:
PASS: [polymer] can embed code 
PASS: [polymer] can set line number 
PASS: [polymer] creates a shadow preview 
PASS: [polymer] creates an editor 
 
All 4 tests passed. 
Best of all, I drove new behavior—element encapsulation—with tests. At some point I will need to verify that multiple instances of <ice-code-editor> on the same page will not cause trouble, but I will leave that for another day. This first pass at TDDing Polymer.dart features seems a fine stopping point for tonight.


Day #892

Tuesday, October 1, 2013

Testing the Shadow DOM


Yet again, the gap between where I expect to find trouble and where I actually find it… amazes. Last night I set out to test a Polymer.dart version of the ICE Code Editor. I cobbled something akin to a test together, but it proved unexpectedly difficult in unexpected ways.

I intentionally kept the implementation and the test heavy—the custom <ice-code-editor> tag has elements of js-interop and HTTP request while the test was of the full-stack variety. I had expected the js-interop or HTTP request bits to cause me problems—and they probably will, if I can get to them. The main problem wound up being the full-stack test.

I suppose that I should have expected this. “Full stack,” as it relates to Polymer, include multiple parts. There is the actual page that uses the custom Polymer element. When testing, this looks something like:
<html>
  <head>
    <link rel="import" href="packages/ice_code_editor/polymer/ice_code_editor.html">
    <!-- Polymer and test setup here --> 
    <script type="application/dart" src="test.dart"></script>
  </head>
  <body>
    <ice-code-editor src="embed.html" line_number="0"></ice-code-editor>
  </body>
</html>
For the <ice-code-editor> element to work, Polymer has to import the definition in the linked ice_code_editor.html file. Even that is not sufficient as ice_code_editor.html contains a reference to the backing class, which is located in yet another file:
<polymer-element name="ice-code-editor" attributes="src,line_number">
  <template><!-- template work here --></template>
  <script type="application/dart" src="ice_code_editor_element.dart"></script>
</polymer-element>
Last night's problem was in the initial load of the ice_code_editor.html template. When I load the test page in Dartium, I get a lovely CORS violation:
XMLHttpRequest cannot load 
  file:///home/chris/repos/ice-code-editor/test/polymer/packages/ice_code_editor/polymer/ice_code_editor.html. 
Cross origin requests are only supported for HTTP.
I was able to get the test working by loading the test page (and everything else) from a simple web server. Possibly because all of my client-side Dart testing to date has been from file:// URLs, running a web server to support tests—even full stack tests—feels like overkill. Realistically, Polymer testing will likely have to involve at least some full-blown web server work. Tonight, I would like to see if I can skip it by supplying a command line option to Dartium.

The --allow-file-access-from-files option should do the trick, so I close Dartium and restart it with:
$ chrome --allow-file-access-from-files
Currently, my test does not actually set an expectation, so I am only checking that everything compiles. In this case, it does as I see no errors or warnings in the console—only a pleasant, test successful message:



But what about real testing? When I use the <ice-code-editor> element on a real page, it currently places an <h1> above the actual code editor that mirror the attributes used in the tag:



If I set the src and line_number attributes in my test page, then I ought to be able to query that <h1> for those values:
<ice-code-editor src="embed.html" line_number="42"></ice-code-editor>
In test.dart, I try to query for the src value by checking the text contents of the first <h1> on the page:
    test("can embed code", (){
      expect(query('h1').text, 'foo');
    });
But that fails. In fact there is no <h1> on the page—not even in the working sample page. The <h1> is in the shadow DOM of the <ice-code-editor>. That is, I now have a DOM fragment that is completely separate from the main document DOM. This shadow DOM is included when the page is rendered, but it is entirely encapsulated within the <ice-code-editor>'s shadow root.

All of this means that I need to query for the <h1> inside the shadow root of <ice-code-editor>:
test("can embed code", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('embed.html')
      );
    });
And that works!
PASS: [polymer] can embed code
All 1 tests passed. 
Just for the heck of it, I write a separate test to query for the line number. This works without incident. The end result test looks as follows:
library polymer_test;

import 'package:unittest/unittest.dart';
import 'dart:html';
import 'dart:async';

main() {
  setUp((){
    var ready = new Completer();
    new Timer(
      new Duration(milliseconds: 250),
      ready.complete
    );
    return ready.future;
  });

  group("[polymer]", (){
    test("can embed code", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('embed.html')
      );
    });
    test("can set line number", (){
      expect(
        query('ice-code-editor').shadowRoot.query('h1').text,
        contains('(42)')
      );
    });
  });
}
The 250 millisecond delay in the setUp() gives ICE enough time to get up and running. I am unsure why (something to investigate another night) such a high number is needed more when running the test page from content_shell than directly in Dartium. I will find a better way of implementing that delay another day. More pressing is that, when I inspect things in the JavaScript console, I find that that the ICE code editor is outside of the <ice-code-editor> shadow root. It is actually in the main document DOM tree, which violates the spirit of Polymer. And I would still like to get this tested without relying on the --allow-file-access-from-files command line option for Dartium.

Those issues aside, I have two simple tests of my Polymer custom element. Once I figured out that --allow-file-access-from-files trick, it was pretty darn easy to write these tests. And where there are tests… robust, accurate, maintainable code is sure to follow.



Day #891