It’s been a busy several weeks for me, mostly in my work-related universe. I haven’t been completely disregarding the public sphere, though, and managed to get a CBR / CBZ utility script working, to wit cbfix. Currently it only does one thing, but having the scaffolding around to open up CBR / CBZ files, mess with them, and replace them presents a lot of possibilities. In the meantime I still have a bunch of CoffeeScript and Scala stuff simmering on the back burner.
Well, that took a while
It’s been a minute since my last update, during which time I’ve learnt a great deal about node.js as well as the whole AMD / CommonJS mess mentioned in my last post. Without drowning in detail, here are a few things I’ve been thinking about.
I’ve made the switch to CoffeeScript for a good deal of my Javascript code, mostly because I was worried about wearing out the keys on my keyboard which comprise the phrase function(){}. I rather enjoy CoffeeScript’s cleaned-up syntax, at least for now, and I like how it hews to Javascript’s essential character while smoothing out its rougher bits. I’ve still got plenty of reservations about it, and it sometimes errs a bit too far on the loosey-goosey side of the syntax fence for my taste, but anything that will save me from the ongoing insults to programming-language aesthetics coming out of the Javascript world has my sincere gratitude. (The latest of these I’ve had to endure is the comma-first style, which is just one of the awful emergent results from the most-used data transport format of our day, the JSON spec, needing to fit into three quarters of a page of EBNF for some reason. Why complicate it with an optional comma at the end, or optional quotes around key values? But that’s a rant for another day.)
Meanwhile I also went down a fairly long rabbit hole in learning about electronics – this started with getting a Raspberry Pi and then got a little more low-level with some Ardiuno stuff, and by now I’ve got a bunch of nascent electronics projects in the offing, mostly concerning various robots. The Pi in particular has a robust Python infrastructure, and I have a pretty good imaging-related project in mind, but in the course of writing the software for it I decided that this would be a good opportunity to experiment with node.js development, and so I’ve since ported the stuff I’d written from Python to CoffeeScript and node.js.
More is surely to come about all that, and as usual I ought to have some code available on github before too long. In the course of all this I’ve also learned a great deal more about the server-side javascript ecosystem, and I think I should actually be ready to get the weighted-probability list library into much better shape.
Posted by timgilbert on March 6, 2013
http://timgilbert.wordpress.com/2013/03/06/well-that-took-a-while/
Initial Jasmine impressions
Ok, I must confess that midway into my half-baked project of comparing Javascript testing frameworks, I’m getting a little bored with the entire project. Largely this is due to the fact that of the three major BDD-oriented frameworks I’ve seen so far, the syntax and semantics are roughly the same. Really the only major difference I’ve seen so far is that Mocha warns me about global namespace pollution, and the other frameworks do not.
As a point of reference, I was able to take the nascent set of tests I’d come up with for BusterJS and port them over virtually unchanged to Jasmine, with a few simple syntax changes relating to the setup / teardown methods. I’ll probably finish out the tests in one framework or the other and then move on to more interesting things, like figuring out the whole module mess that seems to be the current state of the art.
Posted by timgilbert on December 6, 2012
http://timgilbert.wordpress.com/2012/12/06/initial-jasmine-impressions/
Forging on with javascript testing frameworks
I’ve got what I consider to be a decent set of unit tests in Chai, though I’m certainly a good deal away from a complete set. (As an aside, the inherently non-deterministic nature of js-weighted-list presents something of a testing challenge in itself, totally apart from the particular framework in use; I’ll have more to say about this in future.) My impressions of it aren’t radically different from how I felt about it last time – I’m still not crazy about the syntax, but it has offered me one or two pleasant surprises when it found scope bugs I had missed.
There’s another aspect of the framework I’ve enjoyed as well. As some background, I’m mostly investigating BDD frameworks, but I have to confess that I don’t really see how BDD is all that different from unit-test based testing, apart from the terminology in use; frankly the difference between a test suite and a spec doesn’t seem all that large to me, and I’m dubious about the vague claims of readability to non-programmers that seem to haunt the rhetoric of some BDD sites I’ve seen. But anyways, according to the classic BDD (or TDD) approach, I’m going about things backwards: I’m writing a suite of tests to cover code which already exists instead of starting with the tests and then writing code to satisfy them.
Certainly I’m not the first programmer in the history of the world to approach testing this way, but I did enjoy adding in some undefined specifications for a few missing features for the library and seeing them show up as elements in the list:
it('should increase the length of the list');
it('should validate its weights');
Seeing the tasks come up with little blue dots in the test-runner output, and then change to red and then green as I implemented first the test code and then the implementing code in the library was a pretty satisfying process, and I can definitely see its appeal. This is a whole aspect of BDD I’ll probably miss out on in this comparison, since I’m not planning on reimplementing the library itself over and over again. In recognition of this, though, I’m hoping to think up some features and hold them in abeyance so I can try more specification-first type development.
At this point I have a decent feel for Chai, and I will move on to the next framework; I’m thinking I’ll try out BusterJS, since from a cursory examination of Jasmine it looks to be very similar to Chai. Another thing which is bubbling up towards the top of my priority list is trying out the coveraje library, which measures test coverage for javascript unit tests. However, as a node.js only project, this will require me to figure out how to get the same test suite and module system running on the command-line and the browser, and I’d just as soon keep my focus on the browser for the moment.
Posted by timgilbert on November 16, 2012
http://timgilbert.wordpress.com/2012/11/16/forging-on-with-javascript-testing-frameworks/
First few stabs at Chai
Continuing on my investigation of what’s what in the state of Javascript testing frameworks, I downloaded Chai and ported several of my existing Qunit tests over to it. Chai is more or less a plugin for Mocha, which is a test harness framework that allows you to organize your tests, while leaving the meaty assertion bits of testing to outside libraries. The decoupling of these two aspects of a testing framework seems like a pretty neat approach, and I may investigate some of the other assertion plugins available for Mocha besides Chai in the future, assuming I’m not completely burnt out on testing frameworks by then. Meanwhile, Chai itself has a plugin infrastructure, with hooks available that expand its vocabulary or integrate it with other libraries such as jQuery and Backbone.
I haven’t got too far yet, but I think I can safely say that I’m not in love with the syntax. Chai exposes two main verbs, which do about the same thing. expect(foo).to.be(5); is the more obvious syntax; optionally Chai can instead attach the function should() to the global Object prototype, which allows assertions like this: foo.should.be(5);. Overall combined with Mocha’s BDD test style, you wind up with code like this:
describe('WeightedList', function() {
describe('Constructor', function() {
it('should succeed with no arguments', function() {
expect(new WeightedList()).to.be.ok;
});
});
describe('Empty List', function() {
var wl = new WeightedList();
it('should have length zero', function() {
wl.should.have.length(0);
});
it('should give an empty list on shuffle', function() {
wl.shuffle().should.deep.equal([]);
});
});
});
I suppose it’s readable enough, maybe I just still haven’t gotten over Javascript’s relentless use of function(){} blocks. I will say that seeing some similar tests (but for Jasmine, a competing framework) written in CoffeeScript is certainly easier on the eyes.
In any event, despite my trepidation at the syntax, Chai has already helped me in one way I hadn’t expected: it found a bug in my code. Running the test that calls shuffle on an empty list, the test runner produced the error “Error: global leaks detected: heap, result.” Sure enough, looking at my code, I’d left off the var declarations from two variables in one of the inner methods there. Adding in the var statements caused the test to pass again. Thanks Chai! As I experiment with other frameworks I might try taking the declarations out again to see whether anyone else will catch the same thing.
Posted by timgilbert on November 13, 2012
http://timgilbert.wordpress.com/2012/11/13/first-few-stabs-at-chai/
Javascript unit testing
(I’m still here. During my time away from the blog I got a job. Hopefully things are about to be calmer and I’ll be updating more frequently.)
I spent a while burnishing up the weighted-list javascript library I wrote last spring, in the process catching up with the latest goings-on in Javascript. I have a real love-hate relationship with Javascript the language and its software ecosystem, but that’s probably a topic for another day; for now I guess I’ll just snarkily mention hasOwnProperty() and leave it at that. In any event, the ascendency of Node.js seems to have sparked a mini-renaissance in software packages written in javascript. Things are moving pretty rapidly and there aren’t necessarily clear favorites in a lot of areas, so you wind up with a great variety of alternatives for various types of useful libraries.
The resulting competition is probably good for the overall quality of javascript open-source software, but it can be a little difficult to determine which packages are good to use right now. All of which is a lead-up to say that I’ve been spending some time looking into Javascript unit-testing frameworks.
js-weighted-list currently has a light suite of unit tests written in Qunit. Qunit seems like an adequate framework overall, and being able to run my tests in a browser is pretty convenient, but it has a few aspects I’m not crazy about: the documentation is a little thin on the ground and I’m not crazy about the actual syntax of the tests, especially for tests where I’m expecting the code under test to throw an exception. I’m also not sure that Qunit is the new hotness any longer, which is of course of paramount importance in Javascript these days.
With that in mind, I’m going to try, as an experiment, to reproduce the minimal suite of unit tests I’ve got in a few other frameworks and see which ones I prefer. The candidates I’ve got in mind so far are Mocha, Chai, BusterJS, Jasmine, and Pavlov. I’m not completely sure I’ll have the attention-span necessary to do a full-on shootout between them, but hopefully I can at least try a few out and see. The weighted-list library is currently small enough that it’s pretty easy and fast to test, and as a bonus, I will hopefully shake some bugs out of it along the way.
While I’m on the subject, another idea I’ve got is to fix up a page that will run selections thousands of times and graph the results, so that I can have some idea as the whether the library works correctly or not. But that’s another topic for a different day.
Posted by timgilbert on November 11, 2012
http://timgilbert.wordpress.com/2012/11/11/javascript-unit-testing/
Mysterious 404 responses with foursquare OAuth2 + google-app-engine
I’ve done a lot of work on my aforementioned foursquare / last.fm mashup project, which I’m still not exactly ready to start crowing about, but whose source is, as ever, available.
I’m currently hitting a bunch of problems in getting my Python code to work while it’s deployed out to Google’s appspot.com production environments. I’ve been able to authenticate successfully against foursquare from my local environment, following their straightforward instructions, but every time I try to run the same code out in Google’s cloud, once I hit the point where I retrieve an access code from foursquare and make a request for a legit session token, this is what I wind up with:
HTTP blarg, feh
Traceback (most recent call last):
File "/base/python27_runtime/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/base/data/home/apps/s~how-you-been/0-2-4.357616581640073459/whence.py", line 97, in get
accessCode = self.getFoursquareAccessToken(code)
File "/base/data/home/apps/s~how-you-been/0-2-4.357616581640073459/howyoubeen/Foursquare.py", line 49, in getFoursquareAccessToken
httpResponse = urllib2.urlopen(url)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 438, in error
return self._call_chain(*args)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
Dang it! My initial instinct is that I’m hitting a timeout in Google’s cloud environment, but are they honestly passing a 404 back to my stack at that point? (I suspect, as an alternate explanation, something about my error-handling handlers are deficient.)
While looking into this I’ve stumbled upon a few Python OAuth2 libraries, about which OAuth2 isn’t exactly rocket science, but if the libraries have a decent interface and can overcome this issue, maybe I’ll give them a shake. (On the js side of the world I’ve been having a few similar issues, where I’d like to move to an open-source library but the ones I’ve seen make odd assumptions about the execution environment.)
Another possibility I’ve considered is that there’s some sort of SSL wildcard issue at play, as suggested by this stack overflow answer which foursquare has bravely elected as their replacement for tech support. But for now,
.
Posted by timgilbert on March 20, 2012
http://timgilbert.wordpress.com/2012/03/20/mysterious-404-responses-with-foursquare-oauth2-google-app-engine/
Generating weighted-probability lists in Javascript
I’ve made a good deal of progress on my Google App Engine application, about which more later. During the course of it, I started to keenly feel the need for a weighted random list. That is, I have a list and want to select a random sample from it, but it has an unequal (weighted) probability distribution; I want some of the items to be selected more frequently than others. I also need to modify the weights depending on what else is going on in the program (eg, in response to user input or web service results. Also, this is all happening on the front-end, so it needs to work in javascript.
Poking around for a while I couldn’t find anything obviously relevant to this, but I did find a pretty good breakdown of the problem and the algorithm to follow in this Stack Overflow answer. This implementation makes use of a heap in order to enable a binary search on the probability space. While digging through to understand it, I wound up reimplementing the thing in Javascript, and then made a bunch of improvements to the API for it. It’s pretty basic and doesn’t have any particular dependencies, so I’m releasing it as its own library, js-weighted-list.
It is available on github under the MIT license. There are still several things I need to improve with it, in particular it’s severely under-tested, but it’s decently documented and immediately usable for what I need it to do.
Posted by timgilbert on March 14, 2012
http://timgilbert.wordpress.com/2012/03/14/generating-weighted-probability-lists-in-javascript/
Using pyjade with webapp2 on Google App Engine
And now for something completely different. I got a little distracted again by an idea for a simple social networking mashup I’ve had and decided that the best place to deploy it would probably on Google App Engine. App Engine supports Scala and I’ve seen one or two positive reports about using Scalatra on it, so I thought it wouldn’t be too hard to spin something up quickly using my existing code.
It turned out not to be as easy as that, unfortunately; I may try to elaborate on the reasons in a later post, but it seems to come down to Scalate always checking the filesystem for its template routines. In any event, I found that I was spending a lot of time trying to glue weird bits of infrastructure to one another rather than working on my idea.
With that in mind, I decided to start over in Python, and of course as my first task I spent a long time glueing random bits of infrastructure together. In this case I’ve been successful, though, so here’s a brief writeup on getting Jade templates to work with Google App Engine and Google’s webapp2 in python.
1. Add dependencies to include webapp2′s jinja2 module in your project.
This is as simple as adding this bit of code to app.yaml:
libraries: - name: jinja2 version: latest
2. Install pyjade in your environment.
I’ve been using a layout similar to the one mentioned in this Stack Overflow answer. It’s puzzling that Google doesn’t really mention anything about a standard way to get libraries and stuff from the wider Python ecosystem installed in a development environment, but essentially I set up a virtualenv, ran pip install pyjade, and then symlinked the pyjade directory from the virtualenv lib directory into the project’s src directory.
3. Add a custom Jinja2 factory.
This is where the magic happens. We write a factory function, jinja2_factory, whose purpose is to add pyjade’s included Jinja2 extension into the Jinja2 instance’s Environment.
def jade_factory(app):
j = jinja2.Jinja2(app)
j.environment.add_extension('pyjade.ext.jinja.PyJadeExtension')
return j
Then, in our handler’s jinja2 method, we pass along the factory method to it:
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app, factory=jade_factory)
(This is based on moraes’s Stack Overflow answer here.)
4. Use the factory and get a template.
Here’s the full source code for a simple “hello world” app. I’m following the examples on Google’s jinja2 page and creating a JadeHandler subclass of RequestHandler.
import os
import webapp2
from webapp2_extras import jinja2
class JadeHandler(webapp2.RequestHandler):
# Per http://stackoverflow.com/a/7081653/87990
@staticmethod
def jade_factory(app):
j = jinja2.Jinja2(app)
j.environment.add_extension('pyjade.ext.jinja.PyJadeExtension')
return j
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app, factory=JadeHandler.jade_factory)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
class MainPage(JadeHandler):
def get(self):
context = {'message': 'Hello, world!'}
self.render_response('index.jade', **context)
app = webapp2.WSGIApplication([('/', MainPage)], debug=True)
Caveat
I’m by no means an expert in Google App Engine, and I’m a little worried that there’s something badly inefficient or similarly wrong about this approach. In particular, I’m hoping the returned templates are cached, but I’m not certain, and I’ve seen reports that Jinja2 Environment creation is an expensive operation on GAE. More to the point, pyjade seems to work as a preprocessor for Jinja2, so it would obviously be better not to need to run it for every request. In any event, this does at least find jade templates and render them properly as HTML.
Edit: as usual, the current code is available on GitHub.
Posted by timgilbert on March 10, 2012
http://timgilbert.wordpress.com/2012/03/10/using-pyjade-with-webapp2-on-google-app-engine/

