Showing posts with label karma. Show all posts
Showing posts with label karma. Show all posts

Sunday, December 28, 2014

A Solution for Karma Testing Polymer on IE (10 & 11)


I coded in WordPad yesterday. 15 years of successfully repressing that sensation and now I fear I may never recover.

Still, I successfully got Karma & Jasmine to test Polymer code with Internet Explorer yesterday. So it was worth it. Kinda.

Regardless, I am happy to have gotten testing of Polymer on IE working, but I still have a few outstanding questions that I'd like answered before moving on to less traumatizing subjects. My IE Polymer tests work with karma-ie-launcher and IE10. I would like to be able to run karma-webdriver-launcher and use it on both IE10 and IE11.

Switching to karam-webdriver-launcher would mean no more WordPad coding (since the code resides on the host machine, not the guest VM), so I will start there. I already have Karma configuration in place that should work:
module.exports = function(config) {
  config.set({
    // ...
    // Use IP so Windows guest VM can connect to host Karma server
    hostname: '192.168.1.129',
    customLaunchers: {
      'IE10': {
        base: 'WebDriver',
        config: {
          hostname: 'localhost',
          port: 4410
        },
        browserName: 'internet explorer',
        name: 'Karma'
      }
    },
    browsers: ['IE10']
  });
};
I was able to use this to connect to webdriver on Windows the other day, I just could not get the tests to pass. Without changing the tests, I still get very unhelpful failures:
$ karma start --single-run 
INFO [karma]: Karma v0.12.28 server started at http://192.168.1.129:9876/
INFO [launcher]: Starting browser internet explorer via Remote WebDriver
INFO [IE 10.0.0 (Windows 8)]: Connected on socket WUsG_gAEAHJFhm1lLF0G with id 61543069
IE 10.0.0 (Windows 8) ERROR
  Object doesn't support property or method 'indexOf'
  at /home/chris/repos/polymer-book/play/plain_forms/js/node_modules/karma-jasmine/lib/jasmine.js:1759
IE 10.0.0 (Windows 8): Executed 1 of 3 ERROR (0.645 secs / 0.547 secs)
This indexOf failure seems to come from calling a “contains” matcher in my tests on undefined values. As I found yesterday, that is more of a symptom of larger Karma issues than individual test failures.

So I try yesterday's wait-a-browser-event-loop / set-timeout-zero solution in my tests:
  describe('properties', function(){
    it('updates value when internal state changes', function(done) {
      el.model.firstHalfToppings.push('pepperoni');
      el.async(function(){
        setTimeout(function(){
          expect(el.value).toContain('pepperoni');
          done();
        }, 0);
      });
    });
  });
The el here is my <x-pizza> pizza building Polymer element. The asyc() method from Polymer accepts a callback that will be invoked after Polymer has updated the UI and all bound variables. That works on its own in Chrome and Firefox, but, as I found yesterday, Polymer's IE implementation seems to have a bug that requires an additional browser event loop before everything is ready.

And, with that set-timeout-zero, I have my IE WebDriver tests passing:
$ karma start --single-run 
INFO [karma]: Karma v0.12.28 server started at http://192.168.1.129:9876/
INFO [launcher]: Starting browser internet explorer via Remote WebDriver
INFO [IE 10.0.0 (Windows 8)]: Connected on socket oggMD2c6Q8c4-xq-Lk_- with id 68843724
IE 10.0.0 (Windows 8): Executed 3 of 3 SUCCESS (0.54 secs / 0.543 secs)
So what about IE11? Things were even worse in that VM because I have yet to get the console in the Web Developer Tools to start successfully, making troubleshooting next to impossible. Perhaps the set-timeout-zero fix works there as well?

In the Windows VM, I fire up a good old command prompt (I can't believe that it hasn't changed in 10+ years). In there, I start WebDriver via the webdriver node.js package:
C:\Users\IEUser>webdriver-manager start --seleniumPort 4411
I run the IE10 WebDriver on port 4410 and the IE11 WebDriver on 4411. So I update my karma.conf.js accordingly:
module.exports = function(config) {
  config.set({
    // ...
    // Use IP so Windows guest VM can connect to host Karma server
    hostname: '192.168.1.129',

    customLaunchers: {
      'IE10': { /* ... */ },
      'IE11': {
        base: 'WebDriver',
        config: {
          hostname: 'localhost',
          port: 4411
        },
        browserName: 'internet explorer',
        name: 'Karma'
      }
    },

    browsers: ['IE11']
  });
};
Unfortunately, when I try to run the same Karma tests against IE11, I find:
$ karma start --single-run 
INFO [karma]: Karma v0.12.28 server started at http://192.168.1.129:9876/
INFO [launcher]: Starting browser Internet Explorer 11 via Remote WebDriver
INFO [IE 11.0.0 (Windows 7)]: Connected on socket xu5uT_EaFT6kfCVrTOpE with id 86153250
IE 11.0.0 (Windows 7) <x-pizza> properties updates value when internal state changes FAILED
        TypeError: Unable to get property 'firstHalfToppings' of undefined or null reference
           at Anonymous function (/home/chris/repos/polymer-book/play/plain_forms/js/test/XPizzaSpec.js:29:7)
IE 11.0.0 (Windows 7) <x-pizza> syncing <input> values updates the input FAILED
...
IE 11.0.0 (Windows 7): Executed 3 of 3 (2 FAILED) (0.4 secs / 0.396 secs)
INFO [WebDriver]: Killed Karma test.
For whatever reason, it seems that my Polymer element is taking more than the usual single event loop to register in IE11. A single event loop is all that is required in Chrome, Firefox, and IE10. But IE11 requires an additional 10 milliseconds before it is ready:
describe('<x-pizza>', function(){
  var el, container;

  beforeEach(function(done){
    container = document.createElement("div");
    container.innerHTML = '<x-pizza></x-pizza>';
    document.body.appendChild(container);
    el = document.querySelector('x-pizza');

    setTimeout(done, 10); // Delay for elements to register in Polymer
  });

  describe('properties', function(){
    it('updates value when internal state changes', function(done) {
      // Same async + set-timeout-zero test here...
    });
  });
});
With that, I have my tests passing on IE11:
$ karma start --single-run 
INFO [karma]: Karma v0.12.28 server started at http://192.168.1.129:9876/
INFO [launcher]: Starting browser Internet Explorer 11 via Remote WebDriver
INFO [IE 11.0.0 (Windows 7)]: Connected on socket sQqPBHAEvsL1ujLtULSD with id 7115351
IE 11.0.0 (Windows 7): Executed 3 of 3 SUCCESS (0.634 secs / 0.566 secs)
And this seems to work reliably. I run through 10 single-run rounds of tests and all pass each time. If I drop down to 2 milliseconds, then tests start failing on occasion. If I really, really needed IE testing, I might bump these timeout delays for 50 or 100 milliseconds. For now, I'm just happy with a reliable local solution.

So it is ugly. It is rife with callbacks, set-timeout-zeros and other more arbitrary set-timeouts. But I have a working solution for testing Polymer on Internet Explorer. And I didn't even need to fire up WordPad.


Day #38

Saturday, December 27, 2014

Finally, Testing Polymer in Internet Explorer


I am not fond of Internet Explorer. The reasons are myriad, but not terribly helpful. Despite my dislike, I must admit that it tends to fail in ways that make sense. More often than not, when troubleshooting an “IE bug” I find myself wondering how code works in other browsers. Maybe that will wind up being the case with my Polymer testing woes.

I am running tests for my <x-pizza> Polymer element with Karma. The tests are written with the Jasmine testing library and look like:
describe('<x-pizza>', function(){
  var el, container;
  beforeEach(function(done){
    // Create <x-pizza> el and other setup...
  });
  // ...
  describe('properties', function(){
    it('updates value when internal state changes', function(done) {
      el.model.firstHalfToppings.push('pepperoni');
      el.async(function(){
        expect(el.value).toContain('pepperoni');
        done();
      });
    });
  });
});
The error for the past two nights (with karma-webdriver-launcher and karma-ie-launcher) occurs when I try to access the firstHalfToppings property of model. In the test, it is undefined:
C:\Users\IEUser\plain_old_forms>node node_modules\karma\bin\karma start --single-run --browsers IE
INFO [karma]: Karma v0.12.28 server started at http://localhost:9876/
INFO [launcher]: Starting browser IE
INFO [IE 11.0.0 (Windows 7)]: Connected on socket qNf8JVIEqjDNilL7AQFH with id 9528228
IE 11.0.0 (Windows 7) <x-pizza> properties updates value when internal state changes FAILED
        TypeError: Unable to get property 'firstHalfToppings' of undefined or null reference
           at Anonymous function (C:/Users/IEUser/plain_old_forms/test/XPizzaSpec.js:29:7)
But if I fire this element up in a web page, that property is very definitely defined:



After much futzing, I eventually trace this not to my code, but to Polymer's async() method, which comes on the line after the failure message. Things got so wonky that failures in previous tests would break other tests in non-helpful ways. Only after running single tests — with Karma/Jasmine's ddescribe() / iit() — was I able to identify the culprit as async(), which my test uses:
    it('updates value when internal state changes', function(done) {
      el.model.firstHalfToppings.push('pepperoni');
      el.async(function(){
        expect(el.value).toContain('pepperoni');
        done();
      });
    });
Polymer elements expose this method as a callback mechanism. The supplied callback (my test's assertion in this case), is only invoked once Polymer has updated the UI and all bound variables. This is ideal for testing because the test can be assured that all of the Polymer element's properties and visualizations have been updated—at least in Chrome and Firefox.

In Internet Explorer, it seems that nothing is updated until one more browser event loop. In other words, I have to wait for a setTimeout-0 in addition to the async() callback:
it('updates value when internal state changes', function(done) {
      el.model.firstHalfToppings.push('pepperoni');
      el.async(function(){
        setTimeout(function(){
          expect(el.value).toContain('pepperoni');
          done();
        }, 0);
      });
    });
This quite definitely fixes the test. I have other tests that magically pass with the addition of a setTimeout-0, but reliably fail without.

And once again, after some investigation of an “IE Bug,” I am left with a code error that is not IE's fault. This is almost certainly a Polymer bug. The entire point of async() is that the element is updated when the supplied callback is invoked. That I have to wait for another event loop on top of this seems quite wrong.


Day #37

Friday, December 26, 2014

Polymer and Karma-Ie-Launcher


Testing in Internet Explorer is a low priority for me. It always seems to be more effort than it is worth, given its dwindling market share. Still, I recognize that there is value and that some folks need it. So, even if I will not run automated tests for the code in Patterns in Polymer, I would like to be able to tell people that it does work.

Except that I was unable to get karma-webdriver-launcher to launch IE tests against Polymer last night. I suspect that the problems lie with WebDriver, so tonight, I try karma-ie-launcher instead.

First, I copy the code and tests onto my Windows VM. In there I add karma-ie-launcher to the list of NPM package.json dependencies:
{
  "name": "plain_old_forms",
  "devDependencies": {
    "grunt": "~0.4.0",
    "grunt-contrib-watch": "~0.5.0",
    "karma-jasmine": "~0.2.0",
    "karma-ie-launcher": ">0.0"
  }
}
After an npm install, I try to start Karma:
C:\Users\IEUser\plain_old_forms>karma start --single-run --browsers IE
'karma' is not recognized as an internal or external command,
operable program or batch file.
OK, so I install it globally:
C:\Users\IEUser\plain_old_forms>npm install -g karma
npm WARN optional dep failed, continuing fsevents@0.3.1

> ws@0.4.32 install C:\Users\IEUser\AppData\Roaming\npm\node_modules\karma\node_modules\socket.io\node_modules\socket.io-client\node_modules\ws
> (node-gyp rebuild 2> builderror.log) || (exit 0)

C:\Users\IEUser\AppData\Roaming\npm\node_modules\karma\node_modules\socket.io\node_modules\socket.io-client\node_modules\ws>node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild
karma@0.12.28 C:\Users\IEUser\AppData\Roaming\npm\node_modules\karma
├── ...
With that, when I try Karma now, I get:
C:\Users\IEUser\plain_old_forms>karma start --single-run --browsers IE
'karma' is not recognized as an internal or external command,
operable program or batch file.
Sigh. It looks like I need the full path instead:
C:\Users\IEUser\plain_old_forms>node node_modules\karma\bin\karma start --single-run --browsers IE
INFO [karma]: Karma v0.12.28 server started at http://localhost:9876/
INFO [launcher]: Starting browser IE
WARN [watcher]: Pattern "C:/Users/IEUser/plain_old_forms/bower_components/webcomponentsjs/webcomponents.js" does not match any file.
WARN [watcher]: Pattern "C:/Users/IEUser/plain_old_forms/bower_components/**" does not match any file.
INFO [IE 11.0.0 (Windows 7)]: Connected on socket _0g9fTtXw2PJOCjb5b2y with id 98303942
IE 11.0.0 (Windows 7) <x-pizza> element content has a shadow DOM FAILED
        ReferenceError: 'Polymer' is undefined
           at waitForPolymer (C:/Users/IEUser/plain_old_forms/test/PolymerSetup.js:19:5)
           at Anonymous function (C:/Users/IEUser/plain_old_forms/test/PolymerSetup.js:29:3)
...
IE 11.0.0 (Windows 7): Executed 3 of 3 (3 FAILED) ERROR (0.047 secs / 0.038 secs)
Oops! I neglected to bower install my client-side dependencies (this time I globally install from the start):
C:\Users\IEUser\plain_old_forms>npm install -g bower
C:\Users\IEUser\AppData\Roaming\npm\bower -> C:\Users\IEUser\AppData\Roaming\npm\node_modules\bower\bin\bower
bower@1.3.12 C:\Users\IEUser\AppData\Roaming\npm\node_modules\bower
└── ...
That does get installed in a useful location and it works… to a point:
C:\Users\IEUser\plain_old_forms>bower install
bower polymer#*                 ENOGIT git is not installed or not in the PATH
So it seems that I need Git installed to work with Polymer on Windows. This is already more trouble than it is worth to me, but I must see it through. I install Git the usual way and accept all of the default options but one:



This will allow bower to access Git when running from the command prompt:
C:\Users\IEUser\plain_old_forms>bower install
...
a-form-input#0.0.1 bower_components\a-form-input
└── polymer#0.5.2
polymer#0.5.2 bower_components\polymer
├── core-component-page#0.5.2
└── webcomponentsjs#0.5.2
core-component-page#0.5.2 bower_components\core-component-page
├── polymer#0.5.2
└── webcomponentsjs#0.5.2
webcomponentsjs#0.5.2 bower_components\webcomponentsjs
Yay!

Now, when I karma, I find:
C:\Users\IEUser\plain_old_forms>node node_modules\karma\bin\karma start --single-run --browsers IE
INFO [karma]: Karma v0.12.28 server started at http://localhost:9876/
INFO [launcher]: Starting browser IE
INFO [IE 11.0.0 (Windows 7)]: Connected on socket qNf8JVIEqjDNilL7AQFH with id 9528228
IE 11.0.0 (Windows 7) <x-pizza> properties updates value when internal state changes FAILED
        TypeError: Unable to get property 'firstHalfToppings' of undefined or null reference
           at Anonymous function (C:/Users/IEUser/plain_old_forms/test/XPizzaSpec.js:29:7)
IE 11.0.0 (Windows 7) <x-pizza> syncing <input> values updates the input FAILED
        TypeError: Unable to get property 'firstHalfToppings' of undefined or null reference
           at Anonymous function (C:/Users/IEUser/plain_old_forms/test/XPizzaSpec.js:42:7)
        TypeError: Unable to get property 'value' of undefined or null reference
           at Anonymous function (C:/Users/IEUser/plain_old_forms/test/XPizzaSpec.js:47:7)
IE 11.0.0 (Windows 7): Executed 3 of 3 (2 FAILED) (0.453 secs / 0.444 secs)
Dang it! Those are the same errors that I saw yesterday with WebDriver. So it seems that this is a problem with IE and Polymer rather than WebDriver. The failure is occurring when the test adds a topping to the first half of the pizza being built by the <x-pizza> Polymer element:
  describe('properties', function(){
    it('updates value when internal state changes', function(done) {
      el.model.firstHalfToppings.push('pepperoni');
      el.async(function(){
        expect(el.value).toContain('pepperoni');
        done();
      });
    });
  });
This works in Chrome and Firefox, but it seems that I need a different approach in Internet Explorer. Unfortunately, the web developer tools are still broken in my install so this is going to be tricky to troubleshoot.



Day #36

Thursday, December 25, 2014

Karma IE Testing of Polymer Elements with WebDriver


I think I am resigned to Karma as the best solution for Polymer—especially for the testing chapters in Patterns in Polymer. My experience with WebDriver, and Protractor in particular, made this a tougher decision than I expected. In the end, the combination of WebDriver's lack of shadow DOM support (kinda important with Polymer) and conceptual overload lead me to set Protractor aside. For now.

There are two things that I will miss from Protactor: wait-for-element baked in to element finders and easy Internet Explorer testing. There is not much to be done with async testing in Karma—that is more or less up to the testing library, most of which rely on done() callbacks. Those work, but are not as nice as Protractor's promise-based finders. I can live without them—especially in the book. But crazy as it might seem, I would like to be able to test on Internet Explorer.

In Protractor, I could establish a WebDriver instance in a Windows VM that my Protractor tests could drive from my Linux box. In Karma, I think I am stuck with karma-ie-launcher. There is not a ton of documentation on that project, but I assume that I would have to install Node.js, Karma, and my code on the Windows VM in order to make that work. I much prefer the code residing entirely on my machine with only a WebDriver instance running on the Windows VM.

Enter karma-webdriver-launcher. I add it to the list of NPM package dependencies:
{
  "name": "plain_old_forms",
  "devDependencies": {
    // ....
    "karma-webdriver-launcher": "~ 1.0.1"
  }
}
And then install:
$ npm install

karma-webdriver-launcher@1.0.1 node_modules/karma-webdriver-launcher
└── wd@0.2.8 (vargs@0.1.0, async@0.2.10, q@0.9.7, underscore.string@2.3.3, archiver@0.4.10, lodash@1.3.1, request@2.21.0)
To use in my Karma configuration, I add a custom launcher for IE11:
module.exports = function(config) {
  var webdriverConfig = {
    hostname: 'localhost',
    port: 4411
  };

  config.set({
    // ...
    customLaunchers: {
      'IE11': {
        base: 'WebDriver',
        config: webdriverConfig,
        browserName: 'internet explorer',
        name: 'Karma'
      }
    },

    browsers: ['IE11']
  });
};
I already have WebDriver installed on my Windows VM via the webdriver Node.js package. I start it with:
C:\Users\IEUser>webdriver-manager start --seleniumPort=4411
(I also have port forwarding to 4411 in place)

Then I run the tests from my Linux box, or I try. Instead of successful or failing tests, I see an error:
$ karma start --single-run
INFO [karma]: Karma v0.12.28 server started at http://localhost:9876/
...
INFO [launcher]: Trying to start internet explorer via Remote WebDriver again (2/2).
WARN [launcher]: internet explorer via Remote WebDriver have not captured in 60000 ms, killing.
INFO [WebDriver]: Killed Karma test.
ERROR [launcher]: internet explorer via Remote WebDriver failed 2 times (timeout). Giving up.
On the Windows side, I see that I am unable to connect to the Karma server on port 9876:



I was unaware of this, but it is possible to set the hostname for the Karma web server in the configuration file. So I add the IP address of my Linux box:
  config.set({
    // ...
    hostname: '192.168.1.129',

    customLaunchers: {
      'IE11': {
        base: 'WebDriver',
        config: webdriverConfig,
        browserName: 'internet explorer',
        name: 'Karma'
      }
    },
    browsers: ['IE11']
  });
And that actually works:
$ karma start --single-run
INFO [karma]: Karma v0.12.28 server started at http://192.168.1.129:9876/
INFO [launcher]: Starting browser internet explorer via Remote WebDriver
INFO [IE 11.0.0 (Windows 7)]: Connected on socket JiWBPa2Dzoq-fiGXsSvi with id 96899745
IE 11.0.0 (Windows 7) <x-pizza> properties updates value when internal state changes FAILED
        TypeError: Unable to get property 'firstHalfToppings' of undefined or null reference
           at Anonymous function (/home/chris/repos/polymer-book/play/plain_forms/js/test/XPizzaSpec.js:29:7)
IE 11.0.0 (Windows 7) <x-pizza> syncing <input> values updates the input FAILED
        TypeError: Unable to get property 'firstHalfToppings' of undefined or null reference
           at Anonymous function (/home/chris/repos/polymer-book/play/plain_forms/js/test/XPizzaSpec.js:42:7)
        TypeError: Unable to get property 'value' of undefined or null reference
           at Anonymous function (/home/chris/repos/polymer-book/play/plain_forms/js/test/XPizzaSpec.js:47:7)
IE 11.0.0 (Windows 7): Executed 3 of 3 (2 FAILED) (0.415 secs / 0.409 secs)
INFO [WebDriver]: Killed Karma test.
Well, it kind of works.

The connection is made and one of the test even passes. The two failing tests seem an awful lot like WebDriver and Polymer issues that I have seen over the past two weeks. Satisfied that I can connect, I will call it a night here. I may investigate the failures tomorrow.


Day #35

Saturday, November 29, 2014

Hacking Native Form Inputs with Polymer


Enough fun, let's code JavaScript.

I kid, I kid. I love JavaScript and JavaScript has been very good to me. I might prefer Dart, but I'll always have a special place in my heart for JavaScript. Today, I get to experience some of that specialness by adapting a Polymer.dart approach into the JavaScript flavor of Polymer.

I am rethinking the approach that I suggested in Patterns in Polymer for Polymer elements that behave like normal HTML <form> input elements. The new approach is very much a hack—it injects hidden <input> elements into the containing document, breaking Polymer element encapsulation. But, since Polymer does not (yet) support directly extending native form elements, I am warming to this hack as the best approach to take.

So tonight, I give it a try in JavaScript. I had originally hoped to get this running under test, but a quick review of the documentation for extending custom elements in Polymer scared me off this idea. Mostly, I worry that inheritance in JavaScript Polymer is not as elegant as the Dart counterpart. Working in the "superclass" shadow DOM seems particularly worrisome since the point of this element will be to create hidden <input> elements in the containing document's light DOM.

Still, I can place myself well for testing. So I start by creating a completely new repository for <a-form-input>. In that repository, I make a test directory that will hold a test element / fixture for my tests. I define test/x-double.html as:
<link rel="import" href="../a-form-input.html">
<polymer-element name="x-double" extends="a-form-input" attributes="in">
  <template></template>
  <script>
    Polymer("x-double", {
      attached: function(){
        this.super();
        this.inChanged();
      },
      inChanged: function(){
        this.value = parseInt(this.in) * 2;
      }
    });
  </script>
</polymer-element>
I have previously used this fixture in other Polymer tests, so the bulk of this is copied and pasted. What is new is the extends attribute, indicating that <x-double> will extend the soon-to-be-created <a-form-input>—in other words, <x-double> is a form input element. The attributes listed are also slightly different. In previous fixtures, I have needed an out attribute to reflect the doubling of the input value, but in this case, I will publish on the value attribute, which will come from <a-form-input>. The last difference is the need to call the attached() method in <a-form-input> from <x-double> via this.super()—it is not real inheritance, but it should work.

Next, I create the element that I want define in a-form-input.html:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="a-form-input" attributes="name value">
  <template></template>
  <script src="a_form_input.js"></script>
</polymer-element>
It is a personal preference to keep my JavaScript separate from my HTML. I may wind up combining this when I publish the package. I am unsure of the need to include the <template> tag. For now I do include it, but experimentation will be required.

I define the actual backing class for <a-form-input> in a_form_input.js:
Polymer('a-form-input', {
  publish: {
    name: {value: 0, reflect: true},
    value: {value: 0, reflect: true},

    attached: function(){
      this.lightInput = document.createElement('input');
      this.lightInput.type = 'hidden';
      this.lightInput.name = this.getAttribute('name');

      this.parentElement.appendChild(this.lightInput);
    },

    valueChanged: function(){
      this.lightInput.value = this.value;
    }
  }
});
This is adapted from last night's Dart approach. The name and value attributes need to be published and reflected (i.e. they reflect internal changes in the attributes) so that they behave like normal form input elements. When a-form-input is attached to the DOM, it injects a hidden input into the parent element. It names the hidden input with with the same value as the element itself. Lastly, I establish an attribute watcher on value so that the hidden input in the parent element will always synchronize to the value of the current element.

I can then smoke test this in a page served over a Python simple HTTP server:
<!doctype html>
<html>
  <head>
    <title>Smoke Test</title>

    <!-- 1. Load Polymer before any code that touches the DOM. -->
    <script src="bower_components/webcomponentsjs/webcomponents.js"></script>
    <!-- 2. Load component(s) -->
    <link rel="import" href="test/x-double.html">
  </head>
  <body>
    <div class="container">
      <h1>Smoke Test: a-form-input</h1>

      <form>
        <x-double name="doubled" in=5></x-double>
      </form>
    </div>
  </body>
</html>
Which does the trick:



So it seems that I need not have worried about the shadow DOM. At least in this case. I can use my is-a-form-input <x-double> element as a form input. If I give it a typical input name attribute of something like "doubled", then a corresponding hidden input is added to the containing <form> with the same name attribute. In other words, when I submit this form, it will contain a doubled form value.

There is still some experimentation warranted with all of this, but the overall approach still seems promising. Up tomorrow: tests.



Day #9

Friday, October 3, 2014

Testing CSS Colors in Polymer


I have 5 whole tests covering the functionality of the Bootstrap styled Polymer element. And it is occurs to me that not a single one of those tests has anything to do with the intention of this chapter in Patterns in Polymer, which is styling Polymer elements.

The Polymer element in this case is a simple pricing plans element:



So it seems to me that I ought to be able to test that one of the individual pricing plans in the test is blue.

I have to fiddle with the setup, but I eventually get the following Jasmine test to work:
  describe('defaults', function(){
    var el;
    beforeEach(function(done){
      el = document.querySelector('pricing-plans');
      setTimeout(done, 10);
    });

    it('gets styles from external sources', function(){
      var primary_el = el.querySelectorAll('pricing-plan')[2],
          heading_el = primary_el.shadowRoot.querySelector('.panel-heading'),
          style = window.getComputedStyle(heading_el);

      expect(style.backgroundColor).toEqual('rgb(66, 139, 202)');
    });
  });
This finds the last <pricing-plan> element in my fixture file:
<pricing-plans>
<pricing-plan name="pricing plan 01">desc 01</pricing-plan>
<pricing-plan name="pricing plan 02">desc 02</pricing-plan>
<pricing-plan type="primary" name="pricing plan 03">desc 03</pricing-plan>
</pricing-plans>
The last element has the primary type set which Bootstrap will color blue by default. I had originally tried to grab the <pricing-plan> element directly to test, but found that I had to dive into that shadow DOM to grab the panel header to find the element that actually is blue.

The test then uses the getComputedStyle() method on window to find the background color of this element, which should be the specified shade of blue.

Among the tricks that I need to get this working is the setTimeout() dance in this test's setup—this gives the page time to load Bootstrap CSS and apply it (I am running this with Karma, so loading from a server does work). If I opt to use the apply-author-styles Polymer tag, I will also have to apply Bootstrap CSS to the main testing page. But, since this is just the @import solution for external CSS inside a Polymer element, this is all I need for tonight.

The end result is that the test passes:
...
SUCCESS  gets styles from external sources
Skipped 0 tests
And, more importantly, the test fails if I change the fixture from a panel-primary to a panel-success:
FAILED  gets styles from external sources
Expected 'rgb(223, 240, 216)' to equal 'rgb(66, 139, 202)'.
I was unsure how easy it would be to accomplish this, but testing computed CSS in Polymer elements turns out to be fairly clean and easy.


Day #202

Friday, September 19, 2014

Testing Core-Ajax Polymer Elements with Karma


One of the benefits of a test runner like Karma is that it, y'know, runs tests. More accurately, it runs tests on a test web server, which is a detail that I would like to explore testing the internationalization solution in Patterns in Polymer.

As best I can tell, there is not a single solution for i18n with Polymer. Way back when, I played with using the i18next JavaScript package in Polymer and liked it quite a bit. I just do not know if I like it as the solution. Especially since the book is simultaneously written in JavaScript and Dart, I settled on a strategy that allowed swapping implementations.

Tonight, I hope to test the default JavaScript strategy from the book, which is a simple, hand-rolled solution that loads localization files via <core-ajax> tags. Normally if I am testing Ajax in JavaScript, I would want to pull in the Sinon.js testing library to stub out HTTP requests like those that load the l10n files. But, since Karma is running its own web server for testing, I ought to be able to add the l10n files to the list of files being served and actually load the l10n files in my tests.

In fact, when I run the solitary test that currently tests my i18n chapter, I already see 404s when my Polymer element attempts to load the l10n files:
$  karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket DjAiWyWkVjQjEfu7_8nN with id 73763037
Chrome 37.0.2062 (Linux): Executed 1 of 1 SUCCESS (0 secs / 0.078 secs)
WARN [web-server]: 404: /locales/en/translation.json
WARN [web-server]: 404: /locales/fr/translation.json
Chrome 37.0.2062 (Linux): Executed 1 of 1 SUCCESS (0.096 secs / 0.078 secs)
First, I need to include the l10n files in the list of files that Karma serves:
    files: [
      'bower_components/platform/platform.js',
      'test/PolymerSetup.js',
      {pattern: 'elements/**', included: false, served: true},
      {pattern: 'locales/**', included: false, served: true},
      {pattern: 'bower_components/**', included: false, served: true},
      'test/**/*Spec.js'
    ],
These are not code files—just JSON—so I do not want them automatically included and evaluated on the test page. I just want them served on demand. Hence included: false (the contents are not added directly to the test page) and served: true (the web server will serve them when requested).

That is just part of the puzzle. When I fire up the tests, I still get 404s for the l10n files:
WARN [web-server]: 404: /locales/en/translation.json
WARN [web-server]: 404: /locales/fr/translation.json
This is due to Karma serving everything from the /base URL path. If index.html is at the top-level of my project, then I would need to access it as /base/index.html.

Thankfully, Karma has a somewhat obscure proxies setting which allows resources to be reverse proxied:
proxies:  {
      '/locales/': '/base/locales/'
    }
With that, and a log-level of debug, I see that I have my l10n files being served and proxied:
...
DEBUG [proxy]: proxying request - /locales/en/translation.json to localhost:9876
DEBUG [proxy]: proxying request - /locales/fr/translation.json to localhost:9876
With that, I can write my tests that expect different localizatons:
    it('defaults to English', function(){
      expect(el.shadowRoot.textContent).toContain('Hello');
    });
Updating the locale is slightly tricky, but only because I have to wait for Polymer to update the element display. It only takes a single event loop, but the only way to accomplish this in Jasmine is with a setTimeout call to the asynchronous done():
    describe('it can localize to French', function(){
      beforeEach(function(done) {
        el.locale = 'fr';
        setTimeout(done, 0); // One event loop for element to update
      });

      it('(fr)', function(){
        expect(el.shadowRoot.textContent).toContain('Bonjour');
      });
    });
But, with that, and a similar test for Spanish:
    describe('it can localize to Spanish', function(){
      beforeEach(function(done) {
        el.locale = 'es';
        setTimeout(done, 0); // One event loop for element to update
      });

      it('(es)', function(){
        expect(el.shadowRoot.textContent).toContain('Hola');
      });
    });
Now I have much more meaningful tests for the book's i18n solution. This will be especially useful as Polymer evolves. Should my approach suddenly not localize with a new version of the Polymer library, I will know immediately.

I am marginally dissatisfied with the overhead of beforeEach() just to setTimeout() / done(). I do not normally care too much about the readability of tests, but this seems to unnecessarily obscure the intent of the test. I have larger concerns (like producing screencasts for the Extras readers), so I may just live with this. Still, it bothers me so I may have a look at this in the upcoming days.


Day #188

Thursday, September 18, 2014

Upgrading Old Polymer Elements to Core Elements


I made it through every single chapter in Patterns in Polymer last night. Except one.

I finally have a super test build for the book project. Since Patterns in Polymer is written simultaneously in JavaScript and Dart, my super test build needs to run tests for each chapter in both Dart and JavaScript. After last night, the super test build runs JavaScripts tests for every chapter save for the internationalization chapter.

There are three reasons that I could not get the i18n chapter tested last night. First, I had written no tests when I originally wrote the chapter (bad developer). The eee-polymer-tests generator / dependency manager is capable of generating a simple test, but... The second reason that I could not get the chapter under test is that I am relying on <core-ajax> elements to load JSON localization files. Last, but not least, I am actually relying on <polymer-ajax> elements (the predecessor to <core-ajax>) to load the 110n files.

In other words, I have my work cut out for me to get this tested.

The approach I take is to get the Polymer library updated while still using the old <polymer-ajax>, then try eee-polymer-tests' default test, then upgrade to the new <core-ajax>. Finally, if all goes well, I will try to add some legitimate tests.

My bower.json does not restrict Polymer versions (to enable easy updates to the latest Polymer for testing):
{
  "name": "i18n",
  // ...
  "dependencies": {
    "polymer": "Polymer/polymer",
    "bootstrap": "~3.1.0",
    "i18next": "~1.7.2",
    "polymer-elements": "~0.2.0"
  }
}
Running bower update does not go smoothly, mainly because polymer-elements is so darn old. But, whenever I run across an incompatibility, I opt for the newer instance:
Unable to find a suitable version for platform, please choose one:
    1) platform#0.2.4 which resolved to 0.2.4 and is required by core-component-page#0.2.4, polymer#0.2.4
    2) platform#^0.4.0 which resolved to 0.4.1 and is required by core-component-page#0.4.1, polymer#0.4.1
Eventually, I get everything installed and up to date. Amazingly, when I fire the internationalized <hello-you> element up in the browser, it still works perfectly:



OK, so step #1 is done. Next, I try eee-polymer-tests' simple test. I add eee-polymer-tests to the NPM package.json dependencies:
{
  "name": "i18n",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "eee-polymer-tests": "eee-c/eee-polymer-tests"
  }
}
Then I run npm install and instruct the generator to create a test for <hello-you>. That too works:
karma start                                                       
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket ebljUvRurILtOe32-8Gq with id 2242723
Chrome 37.0.2062 (Linux): Executed 1 of 1 SUCCESS (0.093 secs / 0.085 secs)
WARN [web-server]: 404: /locales/en/translation.json
WARN [web-server]: 404: /locales/fr/translation.json
WARN [web-server]: 404: /locales/es/translation.json
The test simply checks that a shadow DOM is present if the <hello-you> element is inserted. It is not much of a test, but it does tell me that Polymer is loading properly for this element, which is especially good to know since the element was written so long ago.

Before writing a real test, this is a good time to upgrade from <polymer-ajax> to <core-ajax>. After removing polymer-ajax from the dependencies in bower.json, I tell bower to replace it with core-ajax:
$ bower install Polymer/core-ajax -S
bower core-ajax#*               cached git://github.com/Polymer/core-ajax.git#0.4.1
bower core-ajax#*             validate 0.4.1 against git://github.com/Polymer/core-ajax.git#*
The -S option saves the dependency in bower.json:
{
  "name": "i18n",
  // ...
  "dependencies": {
    "polymer": "Polymer/polymer",
    "bootstrap": "~3.1.0",
    "i18next": "~1.7.2",
    "core-ajax": "Polymer/core-ajax#~0.4.1"
  }
}
I delete bower_component and re-install to ensure that I am rid of any leftover cruft from the previously very old dependency. But after doing so, the element still works:



And my simple test still passes.

That will suffice as a stopping point for tonight. Some of the book text will need to be updated after these changes, so will get to that now. More importantly, I can add the last chapter to my super build—even if it is only covered by a very simple test. Up tomorrow, I will do something about that very simple test—I think that I can write some useful tests for this chapter.


Day #187


Wednesday, September 17, 2014

Auto-Choosing Xvfb Display Ports


My current plan is to work through every chapter in Patterns in Polymer, getting the code and tests up to date with the latest Polymer and Karma + Jasmine. Once I have a regular build in place, I will revisit each chapter's content to ensure that it too is up-to-snuff, then perhaps add a chapter or two.

As an aside, I have encountered my share of annoyances with minor Polymer breakages but I can accept those—this is, after all an alpha release of the library. More frustrating is the syntax in Jasmine changing with every patch release (e.g. andReturn() becomes and.returnValue() is my latest favorite). Between this and major syntax changes in other testing libraries for no apparent reason, it almost enough to put me off testing.

Despite the various annoyances, things are moving steadily. I have an outside chance of getting all of the JavaScript code and tests fixed tonight. Except the Dart build randomly breaks for no apparent reason.

The book is written in both Dart and JavaScript so I need to run tests for both sample codebases. Unlike JavaScript testing libraries and JavaScript expectation libraries and JavaScript test runners, Dart's testing has been quite stable. So what gives?

Well, Dart tests, like JavaScript tests, require a windowing environment in which to execute browser tests. On Linux, this is normally done with Xvfb and on Ubuntu/Debian I have been using the nifty little xvfb-run run script to execute tests:
    # Run the Karma tests
    xvfb-run karma start --single-run --log-level warn
Unfortunately this turns out to be the cause of my Dart failure:
...
xvfb-run: error: Xvfb failed to start
Build step 'Execute shell' marked build as failure
It turns out that the Dart build, which I delay for unrelated reasons, is conflicting with the windowing display port being used by my JavaScript build.

Ugh. I start dreaming up how I might retry the build with a different port or additional delay or maybe even run only one build at a time. Mercifully, before I get around to attempting to implement any of that, I read the xvfb-run man page (to be honest, I was reading it to figure out how to implement some of those crazy ideas). In addition to making it easy to wrap processes inside a windowing environment, the xvfb-run script also has a flag to do just what I need:
-a, --auto-servernum
Try to get a free server number, starting at 99, or the argument to --server-num.

So in the end, all I need to do is add the -a switch to my tests:
    # Run the Karma tests
    xvfb-run -a karma start --single-run --log-level warn
I can even verify this by running my Dart tests several times during the JavaScript build (did I mention that Dart tests tend to be markedly faster than their JavaScript counterparts?). During most builds, there is a note about RANDR missing from the Xvfb windowing environment (which is perfectly OK):
Xlib:  extension "RANDR" missing on display ":99".
During most of the test runs, I see the message on port :99, but on one I see:
Xlib:  extension "RANDR" missing on display ":100".
In other words, the -a flag detected in this case that the JavaScript tests were currently being run on display port :99 and automatically ran on :100 instead. Cool!

With that, I can get back to fixing tests and code without the worry of seemingly random failures.


Day #186

Monday, September 15, 2014

Why Must I Be A Programmer in Love (with Inheritance)?


Why do I hate code inheritance so much? Possibly because no matter how much I pretend to hate it, it still seems to be my first instinct for extending class behavior. Which only makes me hate it more. Or at least pretend to.

Tonight's case in point comes from an unlikely source: the Karma configuration for one of the chapter projects in Patterns in Polymer. I am (slowly) working through each chapter standardizing on the dependencies and generated structure provided by eee-polmer-tests. One of the peer dependencies of eee-polymer-tests is Karma and eee-polymer-tests is kind enough to include a file with common configuration options.

I use those common configuration options in each Polymer project with a karma.conf.js that looks like:
module.exports = function(config) {
  var common = require('./node_modules/eee-polymer-tests/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // Override common settings here...
  }));
};
OK, this is not classical class inheritance. This is typical JavaScript prototypical inheritance. My problem remains the same. I see a problem and I want to solve it by putting junk in the object doing the extending. Worse, once I start down that road, I begin inventing ways to make the inheritance smart.

While converting some old tests over to this new approach, I realized that I was missing two things: the html2js Karma preprocessor and the inclusion of HTML fixtures in the configuration. The fix is simple enough:
module.exports = function(config) {
  var common = require('./node_modules/eee-polymer-tests/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // Override common settings here...
    preprocessors: {
      'test/*.html': 'html2js'
    },

    files: [
      'test/PolymerSetup.js',
      {pattern: 'elements/**', included: false, served: true},
      {pattern: 'bower_components/**', included: false, served: true},
      'test/**/*Spec.js',
      'test/*.html'
    ]

  }));
};
I have added the html2js preprocessor (I am also required to npm install karma-html2js-preprocessor --save-dev). I have copied the list of files from eee-polymer-test's common Karma configuration and added the test/*.html fixtures to the list.

And this is enough to trigger my Pavlovian inheritance response: “I should add preprocessors by default, I should change the mixin_common_opts() so that I can add the one entry to the list rather than copying and pasting, I should support special attribute that are added to existing values instead of overwriting them.”

Maybe this is why inheritance is so insidious. Because each of those things is small enough that they make sense. I would not be violating YAGNI—I would use them immediately. Each would legitimately solve a problem for me. So why not just give in? Why not just implement the configuration like this and be done with it?

There are at least two reasons. The first is a nagging sense that I would be in violation of POLS—that I (or someone else using this code) would find the inheritance confusing or non-obvious. The second reason is that I am jumping to implementation without really considering the problem.

And here's the problem. Here's my dirty little secret. I don't use fixtures in my Polymer testing. In my very first Polymer tests, I used them mostly as I was trying to understand how best to approach testing. The Polymer fixtures worked, but since then I have mostly dynamically created the elements right in my tests. So maybe this is a case of YAGNI after all. But it's not that I don't need the code—this is a situation where I don't need the solution.

As a nod to my struggles, I will likely add the list of files from the common configuration into the generated karma.conf.js as a comment. That way, if I do run into this again, I will have all of the information that I need right in the configuration file.

In the end, I nearly gave into my seemingly natural reflex to add some form of inheritance to everything. Thankfully, I was able to listen to my better nature. Maybe someday that will be my first instinct.


Day #184

Sunday, September 14, 2014

NPM and Polymer Puzzles for Great Coding Fun


I love coding because of the puzzles.

I confess that I am not much of a 1000-piece picture-puzzle person. That just seems like so much tedium. Every piece has one exact place to go. There is only one solution. And you can get to that single solution if you mindlessly try to find pieces that fit together for an hour or two. There is no challenge, just diversion.

Which is why I like coding so much. There is never a single solution. Heck there might not even be a solution. But it sure is fun trying to find these solutions. Maybe that is why I like testing my code so much. As much as I appreciate the assurance and maintainability that testing gives me, it is yet another challenge. It also presents challenges of setting up tests properly, writing tests that actually test something and, of course, getting the actual code to work.

I am working through the project chapters in Patterns in Polymer tonight, hoping to get as much of it covered by tests as possible. This is aided my new eee-polymer-tests test generator / common setup NPM package. Except when it does not work.

I am working on the AngularJS chapter which describes using custom Polymer elements in Angular projects. I have some tests in there, but I have the feeling that they are rather old. So my thinking is to run the test generator on the chapter project and overwrite everything (it is all in Git, so I can always get a test back if it proves useful).

The problem? When I run the generator with the --force flag, it seems to overwrite my existing test files and karma configuration, but... they are not affected:
$ ./node_modules/eee-polymer-tests/generator.js x-pizza --force

Generating test setup for: x-pizza
Force overwrite: karma.conf.js.
Force overwrite: test/PolymerSetup.js.
Force overwrite: test/XPizzaSpec.js.
Force overwrite: bower.json.
Done!

$ git status
On branch master
Changes not staged for commit:
  (use "git add ..." to update what will be committed)
  (use "git checkout -- ..." to discard changes in working directory)

        modified:   bower.json
        modified:   karma.conf.js
        modified:   package.json
So what gives? Also, I know this was working in my other projects. What is it about this project that is preventing the force-overwrite option from behaving as desired?

Since this is working for some of the generators, but not others, it seems likely that there is a difference in implementation between the different generators. That or it's a permissions issue. It's usually a permissions issue. But not this time.

In this case, the problem is my Node.js code—it is too Node.js-y. Sidenote: it is hard adding an “-y” to the end of a proper noun that includes punctuation. The difference between the generators is that some are synchronized file system operations while the problem ones are asynchronous—as is typical in Node.js-land (hrm… that doesn't seem any better). The Nodey (bleh) version looks like:
function generatePolymerSetup() {
  var template = __dirname + '/templates/PolymerSetup.js';
  fs.readFile(template, 'utf8', function (err, data) {
    if (err) {
      console.log(err);
      process.exit(1);
    }

    var content = data.replace(/\{\{element-name\}\}/g, element);
    fs.writeFile(POLYMER_SETUP, content);
  });
}
The lack of the word “sync” in there is the giveaway that this is asynchronous code. Node opens a stream to read then merrily executes whatever other code is ready to be evaluated / run outside of this function. Eventually the filesystem responds with the contents of the file and, if Node is not busily executing code elsewhere, it will invoke the callback function with any file content or error information that it might have. And again, when Node tries to write the content to the POLYMER_SETUP file, it will open a write file descriptor then move on to some other business until the filesystem responds that writing is ready. Unless it never gets the chance.

And herein lies my problem. While Node is waiting on the filesystem, it continues to work through the other generator business with which it is tasked until there is no more work. And unlike a Node.js server, this generator script just stops without giving the filesystem operations a chance to complete.

Once the problem has been identified as too much async, the solution is to use the synchronous versions of file system operations:
function generatePolymerSetup() {
  var template = __dirname + '/templates/PolymerSetup.js';
  var content = fs.
    readFileSync(template, 'utf8').
    replace(/\{\{element-name\}\}/g, element);

  fs.writeFileSync(POLYMER_SETUP, content);
}
Node.js will block (not do anything else) until the readFileSync() operation returns. Similarly, it will not do anything else until the new setup file is written and writeFileSync() returns. And once both are done—and only once both are done—Node.js is free it move onto the next generator. In other words, there is no way to accidentally skip any generated files.

Is this the best solution? For a command-line operation, it probably is. There might a more Node.js solution (that kind of works)—especially if I am more careful about tracking open file descriptors. But this seems a good enough solution.

I am a little unsure why I am seeing this problem now. It may be that the filesystem has more work to do before signaling back to Node that streams are ready. When initially testing, I may have manually deleted some of these files before running the generator.

Solving that little puzzle is a nice win, but I am not rewarded with a passing test. Even the skeleton Jasmine test created by my generator is failing when run with Karma:
$ karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket K5_WrlH4x_H2n31y3Iz6 with id 85813120
Chrome 37.0.2062 (Linux) <x-pizza> element content has a shadow DOM FAILED
        Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Chrome 37.0.2062 (Linux): Executed 1 of 1 (1 FAILED) ERROR (5.072 secs / 5.066 secs)
I would not unhappy if all of this just worked, but the harder it is to solve, the more satisfying the solution.

In this case, my PolymerSetup.js is failing, not the actual test. In the setup, I poll for Polymer to be fully initialized before allowing the tests to run. In Jasmine (2.0+), this is done by calling the done() callback:
// Delay Jasmine specs until Polymer is ready
var POLYMER_READY = false;
beforeEach(function(done) {
  function waitForPolymer() {
    if (Polymer) {
      Polymer.whenReady(done);
      return;
    }
    setTimeout(waitForPolymer, 1000);
  }
  waitForPolymer();

  if (POLYMER_READY) done();
});
The problem turns out to be that whenReady() has been renamed as whenPolymerReady() in the Polymer project. Fun. It takes me a bit to track that one down, including a trip into the Karma debugger and the Chrome debugger:



So, even though Polymer.whenPolymerReady() seems a little redundant, that would seem to be the solution du jour:
// Delay Jasmine specs until Polymer is ready
var POLYMER_READY = false;
beforeEach(function(done) {
  function waitForPolymer() {
    if (Polymer && Polymer.whenReady) {
      Polymer.whenReady(done);
      return;
    }
    if (Polymer && Polymer.whenPolymerReady) {
      Polymer.whenPolymerReady(done);
      return;
    }
    setTimeout(waitForPolymer, 100);
  }
  waitForPolymer();

  if (POLYMER_READY) done();
});
Yeah, I think I'll hedge my bets on that one by including both whenReady() and whenPolymerReady(). Unless the name is changed in another unique way, I should be covered.

And, thankfully, this time I am rewarded. Not only does the generated test pass, but so does the test that used to be in there:
$ karma start
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [watcher]: Changed file "/home/chris/repos/polymer-book/book/code-js/angular/test/XPizzaSpec.js".
Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.063 secs / 0.057 secs)
So I got to solve fun puzzles and have as my reward some code that is more maintainable and future proofed. For a coder like me, that is a good day.


Day #183

Wednesday, September 10, 2014

Clean, Working Jenkins Tests for Polymer Elements


I wound up yesterday thinking that the only way to run Karma tests under Jenkins on my Linode was to upgrade from Debian 6 to Debian 7. So that is what I do.

This is more work than I am inclined to do for a CI server—especially when there are so many good CI services to be purchased. But, then again, it never hurts to keep things up-to-date. The instructions for upgrading Debian 6 to 7 from Linode work quite nicely, thank you very much.

Once I have that installed, making it through the last step of the Jenkins/Karma/Polymer test setup—installing Chrome—is easy enough:
$ sudo dpkg -i ~/Downloads/google-chrome-stable_current_i386.deb
Selecting previously unselected package google-chrome-stable.
(Reading database ... 55887 files and directories currently installed.)
Unpacking google-chrome-stable (from .../google-chrome-stable_current_i386.deb) ...
dpkg: dependency problems prevent configuration of google-chrome-stable:
 google-chrome-stable depends on libappindicator1; however:
  Package libappindicator1 is not installed.
Well, of course I needed one last yak. But, after installing that missing dependency (first correcting the broken Chrome install):
$ sudo apt-get -f install
$ sudo apt-get install libappindicator1
I can now get Chrome installed:
$ sudo dpkg -i ~/Downloads/google-chrome-stable_current_i386.deb
(Reading database ... 57351 files and directories currently installed.)
Preparing to replace google-chrome-stable 37.0.2062.120-1 (using .../google-chrome-stable_current_i386.deb) ...
Unpacking replacement google-chrome-stable ...
Setting up google-chrome-stable (37.0.2062.120-1) ...
Processing triggers for man-db 
Yay!

More importantly, I finally have a passing Jenkins build:



No really, it is passing:



And it is reproduceable as well, which is always a bonus. Actually, that is kind of a must for CI.

I am not quite done, however. My eee-polymer-tests package, which provides reasonable default NPM dependencies for testing Polymer elements (Karma, Jasmine, Bower, etc) also generates skeleton test code. If run with no arguments, as is done with a NPM install from a CI server, eee-polymer-tests code will query the developer for the name of the element being tested. In fact, it is doing so in my Karma run:
> eee-polymer-tests@0.0.1 postinstall /var/lib/jenkins/jobs/Patterns in Polymer/workspace/book/code-js/parent_child/node_modules/eee-polymer-tests
> ./generator.js

What is the name of the Polymer element being tested? 
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests
├── colors@0.6.2
├── minimist@1.1.0
└── bower@1.3.9
The readline module that is doing this seems to know that this is being run in a non-interactive process—it does not wait for an answer nor does it run any of the code that would generate testing code after an answer.

Still, I would like to save it the trouble (and myself some concern). The way to accomplish this seems to be via the tty module in Node. With it, I can interrogate a file descriptor like STDIN to see if it is associated with a terminal:
var fs = require('fs');
var readline = require('readline');
var tty = require('tty');

if (element) {
  generate();
}
else if (tty.isatty(process.stdin)) {
  queryForElementName();
}
else {
  console.log('Nothing to generate.');
}
In this case, if STDIN is not a TTY, then it is not coming from an interactive session and I do nothing. All that needs to happen is to install the normal Karma, Bower, etc. dependencies.

That works just fine:
> eee-polymer-tests@0.0.1 postinstall /var/lib/jenkins/jobs/Patterns in Polymer/workspace/book/code-js/parent_child/node_modules/eee-polymer-tests
> ./generator.js

Nothing to generate.
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests
├── colors@0.6.2
├── minimist@1.1.0
└── bower@1.3.9 
I may still have a problem on my hand. Readers of the book that I am testing here, Patterns in Polymer, might want to run the tests themselves. But if they try to npm install like my test code is doing, they will be prompted for an element because they will be running the command in an interactive shell.

Looks like I am going to need a lockfile mechanism of some sort for this. Tomorrow.

Day #179

Tuesday, September 9, 2014

One Yak Too Many?


Yesterday I was able to get a Jenkins server up and running on a Linode, properly secured, and checking out Dart and JavaScript code for testing. Although the test script ran, I do not yet have a successful test—mostly due to lack of additional dependencies.

I am still building this on a Debian 6 LTS Linode host. I continue working through the error messages as they occur on the server. First up:
scripts/test.sh: line 14: xvfb-run: command not found
That is easy enough:
$ sudo apt-get install xvfb
I was happy to discover xvfb-run the other day as it makes testing life easier. Since I had never used it, I thought it might be an new addition to the xvfb package, but it is even present on this old LTS system.

Next, I install Bower and Karma globally:
$ npm install -g bower karma-cli
I might be able to do away with the global bower install, but really there is no harm in having it globally. It seems like a reasonable system-wide dependency to have available on a test box.

Now if I run the Jenkins build, I get:
...
[TEST] book/code-js/angular (Bower updated).
/home/cstrom/local/node-v0.10.31/lib/node_modules/karma/node_modules/di/lib/injector.js:9
      throw error('No provider for "' + name + '"!');
            ^
Error: No provider for "framework:jasmine"! (Resolving: framework:jasmine)
...
This one is a little tricky. The solution is obvious enough—I need to install the karma-jasmine NPM package. But how should this get installed?

I think the answer is that my test script should be responsible for this. The karma-jasmine plugin is technically a dependency of each individual project chapter. The testing script is already working through each project chapter, installing bower components and running Karma:
for X in book/code-js/*
do
    # Change the current working directory to a chapter's code directory:
    cd $X

    # Update bower
    bower update --quiet
    echo "(Bower updated)."

    # Run the Karma tests
    xvfb-run karma start --single-run --log-level warn
    # ...
done
On my dev box, I manually ensure that the NPM dependencies (like karma plugins) are installed with a command line npm install. I need some way to automate this on my test server. Since I am already bower installing, I might as well npm install first.

I think.

I am honestly unsure about that so, for now, I add a sed script before the test runner in Jenkins' Execute Shell entry:
#!/bin/bash -l

export PATH=/home/cstrom/local/node-v0.10.31/bin:$PATH

sed -i 's/bower update --quiet/npm install; bower update --quiet/' scripts/test.sh

scripts/test.sh
The sed script modifies the all-chapters test runner, adding npm intall before the bower install. If this works, I will ruminate on it and possibly edit the test.sh global test runner. Of course, that does not work...

After all that, I finally reach:
ERROR [launcher]:  Cannot start Chrome
 Can not find the binary google-chrome
 Please set env variable CHROME_BIN
This seems easy enough. I grab the latest stable Chrome:
$ wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb
And install it:
sudo dpkg -i google-chrome-stable_current_i386.deb                                                                   ~/Downloads
Selecting previously deselected package google-chrome-stable.
(Reading database ... 40540 files and directories currently installed.)
Unpacking google-chrome-stable (from google-chrome-stable_current_i386.deb) ...
dpkg: dependency problems prevent configuration of google-chrome-stable:
 google-chrome-stable depends on gconf-service; however:
  Package gconf-service is not installed.
 google-chrome-stable depends on libgconf-2-4 (>= 2.31.1); however:
  Package libgconf-2-4 is not installed.
 google-chrome-stable depends on libgdk-pixbuf2.0-0 (>= 2.22.0); however:
  Package libgdk-pixbuf2.0-0 is not installed.
 google-chrome-stable depends on libglib2.0-0 (>= 2.28.0); however:
  Version of libglib2.0-0 on system is 2.24.2-1.
...
And here, I may be stuck.

I do not know if it is going to be possible to install Chrome on Debian 6 because of these errors. I suppose I might try Firefox instead, but that seems more like a nice-to-have whereas Chrome is a requirement to fully test Polymer. It looks like I may need to upgrade to Debian 7. Which may be one yak too many.


Day #178

Saturday, September 6, 2014

Xfvb-run for Profitable JS Testing


Now that I am getting my Patterns in Polymer testing house back in order with eee-polymer-tests, it is time to revisit my whole project testing script.

It already works through each code chapter in the book:
#!/bin/bash

for X in book/code-js/parent*
  # Run all tests for a chapter X here...
do
For each chapter's tests, it already upgrades Bower packages (mostly to get the latest Polymer) and performs a single run of Karma:
    # ...
    # Update bower
    echo -n "Updating bower..."
    bower update --quiet
    echo " done."

    # Run the Karma tests
    karma start --single-run

    # Handle failure
    if [[ $? -ne 0 ]]; then
        echo
        echo "Some tests failed in $X."
        exit 1
    fi
    # ...
That still works, even with my updates to the testing setup, but it pops up a browser window to execute the tests. Instead, I would like to run this all under Xvfb. I don't know if I have a standard way of doing this, but I seem to think that I should start Xvfb with a display port (e.g. :99) then run everything with that same display port:
#!/bin/bash

Xvfb :99 2>&1 >/dev/null &
DISPLAY=:99

for X in book/code-js/parent*
do
  # Run all tests for a chapter X here...
do
That works, but it produces a lot of noise. Even redirecting STDOUT/STDIN to /dev/null like I am doing, I get:
Updating bower...Initializing built-in extension Generic Event Extension
Initializing built-in extension SHAPE
Initializing built-in extension MIT-SHM
Initializing built-in extension XInputExtension
Initializing built-in extension XTEST
Initializing built-in extension BIG-REQUESTS
Initializing built-in extension SYNC
Initializing built-in extension XKEYBOARD
...
Initializing built-in extension XVideo-MotionCompensation
Initializing built-in extension SELinux
Initializing built-in extension GLX
[dix] Could not init font path element /usr/share/fonts/X11/cyrillic, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/100dpi/:unscaled, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/75dpi/:unscaled, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/100dpi, removing from list!
[dix] Could not init font path element /usr/share/fonts/X11/75dpi, removing from list!
Even after individual runs, I get a lot of junk like:
GC: 4 objects of 16 bytes = 64 total bytes 0 private allocs
CURSOR: 1 objects of 8 bytes = 8 total bytes 0 private allocs
TOTAL: 5 objects, 72 bytes, 0 allocs
1 CURSORs still allocated at reset
CURSOR: 1 objects of 8 bytes = 8 total bytes 0 private allocs
TOTAL: 1 objects, 8 bytes, 0 allocs
1 CURSOR_BITSs still allocated at reset
TOTAL: 0 objects, 0 bytes, 0 allocs
It is just noise obscuring the important testing stuff. I do not really understand how redirecting STDOUT/STDIN is failing, but I just want it gone.

Eventually, I find xvfb-run (on my Ubuntu system). I thought this might be a shell interpreter—the kind that goes after the sh-bang at the top of my shell script. But it turns out to be even simpler. I remove the DISPLAY setting as well as the Xvfb call. Instead, this simply wraps the call to Karma (which starts the browser):
    # Run the Karma tests
    xvfb-run karma start --single-run
With that, the output from my whole-book test script is just Karma output:
$ ./scripts/test.sh
START: book/code-js/parent_child
Updating bower... done.
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket Pg5IMgnAOxMo5KIogEba with id 28554454
Chrome 37.0.2062 (Linux): Executed 3 of 3 SUCCESS (3.086 secs / 3.079 secs)
/home/chris/repos/polymer-book

START: book/code-js/parent_events
Updating bower... done.
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket VI7JUF1u0gF4z62ngGTV with id 68348849
Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.078 secs / 0.074 secs)
/home/chris/repos/polymer-book
...
Success!
I can even take this a step further and switch Karma to log warnings only:
    # Run the Karma tests
    xvfb-run karma start --single-run --log-level warn
Which results in test output like:
$ /scripts/test.sh
[TEST] book/code-js/parent_child (Bower updated).
Chrome 37.0.2062 (Linux): Executed 3 of 3 SUCCESS (3.08 secs / 3.075 secs)

[TEST] book/code-js/parent_events (Bower updated).
Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.067 secs / 0.061 secs)

Success!
Success indeed.


Day #175

Friday, September 5, 2014

Standardizing My Polymer Testing Strategy with Generators


Now that I have a nifty Polymer test generator in eee-polymer-tests, it is time to put it to use. The next oldest chapter in Patterns in Polymer is the parent-child chapter which explores communication strategies between parent and child custom elements.

It turns out that I already have tests for this chapter. Furthermore, it turns out that they are complete rubbish. I have tests that are waiting 1500ms:
  it('updates the parent', function() {
    waits(1500);
    runs(function(){
      expect(el.shadowRoot.textContent).toContain('Count: 1');
    });
  });
Hopefully I had a good reason for that, but it is still raises a red flag. You know what else raises a red flag? All tests failing:
karma start --single-run
Chrome 37.0.2062 (Linux) [parent/child] updates the parent FAILED
        TypeError: Cannot read property 'call' of undefined
            at HTMLElement.webkitCreateShadowRoot (/home/chris/repos/polymer-book/book/code-js/parent_child/scripts/polymer.min.js:34:7402)
            at Object.defineProperties.createShadowRoot.value [as createShadowRoot] (/home/chris/repos/polymer-book/book/code-js/parent_child/scripts/polymer.min.js:34:7641)
...
Chrome 37.0.2062 (Linux) [parent/child] updates the child FAILED
        TypeError: Cannot read property 'call' of undefined
            at HTMLElement.webkitCreateShadowRoot (/home/chris/repos/polymer-book/book/code-js/parent_child/scripts/polymer.min.js:34:7402)
            at Object.defineProperties.createShadowRoot.value [as createShadowRoot] (/home/chris/repos/polymer-book/book/code-js/parent_child/scripts/polymer.min.js:34:7641)
...
Chrome 37.0.2062 (Linux): Executed 2 of 2 (2 FAILED) ERROR (3.385 secs / 3.163 secs)
If I had to guess, I would say that the version of Polymer in use here is so old that it no longer works with Chrome. Rather than try to troubleshoot, I start fresh, which is what eee-polymer-tests does nicely. First, I delete everything related to old tests (they're still in git if I need them):
$ rm -rf node_modules karma.conf.js test bower.json bower_components
I add eee-polymer-tests to the list of NPM dependencies for this element's package.json:
{
  "name": "parent-events",
  "description": "Exploring communication between parent and child custom elements",
  "repository": {
    "type": "git",
    "url": "https://github.com/eee-c/patterns-in-polymer"
  },
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-watch": "~0.5.3",
    "eee-polymer-tests": "eee-c/eee-polymer-tests"
  }
}
A quick npm install and I am ready to test... almost:
$ npm install
npm WARN package.json parent-events@ No README data
/
> eee-polymer-tests@0.0.1 postinstall /home/chris/repos/polymer-book/book/code-js/parent_child/node_modules/eee-polymer-tests
> ./generator.js

What is the name of the Polymer element being tested? x-parent

Generating test setup for: x-parent
[WARN] There is no elements subdirectory for Polymer elements. Tests will fail!
Done!

The Polymer test generator can be re-run with: ./node_modules/eee-polymer-tests/generator.js <x-element-name>
It turns out the code in this chapter is so old that, not only was the previous installed Polymer too old to work, I had not even adopted my convention of placing custom element code in the elements directory. Crazy!

Thanks to Bower's API, installing a fresh eee-polymer-tests will take care of installing the latest Polymer. I have to manually move the custom element definitions into the proper location. Once that is done, I still fail:
$ karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket 6n0eubWSCoKotAYxEOhX with id 21476441
WARN [web-server]: 404: /base/elements/x-parent.html
Chrome 37.0.2062 (Linux) <x-parent> element content has a shadow DOM FAILED
        TypeError: undefined is not a function
            at waitForPolymer (/home/chris/repos/polymer-book/book/code-js/parent_child/test/PolymerSetup.js:20:15)
            at Object.<anonymous> (/home/chris/repos/polymer-book/book/code-js/parent_child/test/PolymerSetup.js:25:3)
        Expected null not to be null.
        Error: Expected null not to be null.
            at Object.<anonymous> (/home/chris/repos/polymer-book/book/code-js/parent_child/test/XParentSpec.js:23:33)
Chrome 37.0.2062 (Linux): Executed 1 of 1 (1 FAILED) ERROR (0.035 secs / 0.029 secs)
At first, I focus on the stacktrace. But eventually, I notice the warning message from the test server that there is no x-parent.html Polymer definition file. In fact, I had named it parent.html instead of x-parent.html. I do not know why I would have done this—the actual element name is <x-parent>.

Looks like I need to add another check to eee-polymer-tests' generator script. Once I resolve this by renaming the element, the dummy test passes. And, indeed the other tests (which did need the timeout after all), also pass when I add them back in:
karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket bPbsoJmY6CEp5lr1HACY with id 22145708
Chrome 37.0.2062 (Linux): Executed 3 of 3 SUCCESS (3.08 secs / 3.074 secs)
Aside from some non-standard code locations, it seems that the overall approach in this chapter still works (phew!). Interestingly, I now have another chapter standardized on the same code structure, testing configuration, naming conventions, and the latest version of Polymer—all thanks to eee-polymer-tests and its generator. I have some updates to the chapter in order, but only filenames.


Day #174

Thursday, September 4, 2014

Generating Code from NPM that Installs Bower(!)


I have my eee-polymer-tests testing package for custom Polymer elements in pretty good shape. It will install and configure the necessary Karma configuration and skeleton tests to run a single, generated test on a Polymer element (which passes!). But...

My approach assumes two things: that the element definition is located in the elements subdirectory of the current package and that Bower is being used to install Polymer and its dependencies. Neither is a particularly poor assumption. The elements subdirectory is my personal preference, but I like it because it keeps my custom elements separate from any apparatus used to maintain the code. The Polymer project itself uses Bower for its elements, so I am OK sticking with it.

But, unlike all of the other checks that I have in eee-polymer-tests:
What is the name of the Polymer element being tested? click-sink

Generating test setup for: click-sink
[WARN] File exists: karma.conf.js. (use --force to overwrite)
[WARN] File exists: test/PolymerSetup.js. (use --force to overwrite)
[WARN] File exists: test/ClickSinkSpec.js. (use --force to overwrite)
I am not checking for the proper elements subdirectory, nor the Polymer + Bower configuration.

Testing for the existence of the elements directory is pretty straight-forward after my previous efforts:
function okElements() {
  if (!fs.existsSync('elements')) {
    var message = '[WARN] There is no elements subdirectory for Polymer elements. Tests will fail!';
    console.log(message.red);
    return false;
  }
  return true;
}
Checking for the existence of the bower.json is pretty much the same, except for the filename. I can even read the NPM module's package.json, which is what is running the generator in eee-polymer-tests, and write a corresponding bower.json if it does not already exist:
  var npmJson = JSOaN.parse(fs.readFileSync('package.json'));
  var bowerJson = {
    "name": npmJson.name,
    "version": "0.0.0",
    "description": npmJson.description,
    "ignore": [
      "**/.*",
      "node_modules",
      "bower_components",
      "test",
      "tests"
    ],
    "dependencies": {
      "polymer": "Polymer/polymer"
    }
  };
This gives me the brilliant idea to install Bower as part of eee-polymer-tests and ensure that Polymer is installed. Installing Bower is easy enough with NPM—it is, after all, the JavaScript package manager that is installed with the NPM JavaScript package manager. I add it to the list of eee-polymer-tests' dependencies:
{
  "name": "eee-polymer-tests",
  // ...
  "dependencies": {
    "colors": ">0.0",
    "minimist": ">0.0",
    "bower": ">0.0"
  },
  "peerDependencies": {
    "karma-jasmine": "~0.2.0",
    "karma-chrome-launcher": ">0.0"
  }
}
To actually install, it turns out that Bower has an API:
var bower = require('bower');
function generateBower() {
  // ...
  bower.commands
    .install(['Polymer/polymer'], { save: true }, { /* custom config */ })
    .on('end', function (installed) {
        console.log(installed);
     });
}
Which works quite as expected. Well, the installed object that is logged is just an empty object literal, but it does save changes to the bower.json file that is currently installed.

As cool as that is, I lean toward not using it. I have no idea if any besides myself will have use for eee-polymer-tests. Generating a simple test structure with it is one thing (and will be quite helpful), but I already install bower out of habit. I will likely file this under “good to know,” but focus elsewhere. Like actually writing some new tests tomorrow.

Update: Ah, the heck with it. I added bower generation after all: bfe13c3.

Day #173