Tuesday, August 30, 2011

Testing authenticated handlers in Tornado

Tornado is an excellent little async HTTP framework and I have been using it in many projects I've been part of. Documentation is a bit lacking but access to sources makes all the difference.

But say you are implementing handlers that require authentication. You are versed in TDD and you want your handlers tested as well. Here's a little trick that I use to "mock" the authenticated user.

When writing tests, I use excellent pymox library and the following example uses that, but you can use any mocking library you prefer.

Here is the Handler which we want to test:
# encoding: utf-8
__author__ = 'alex'
import tornado.web

class Protected(tornado.web.RequestHandler):
    def get_current_user(self):
        # get an user from somewhere
 return self.retrieve_user_from_db()

    @tornado.web.authenticated
    def get(self):
        self.render("protected-page.html")
We want to test the get() method, but since it's decorated with authenticated decorator, testing the method will result in response code 403. To overcome that (and make our test green!), we'll mock get_current_user() in our Test - it's that easy:
# encoding: utf-8
__author__ = 'alex'
import os, os.path, sys
import tornado.web
import tornado.testing
import mox

import project.handlers

class TestAuthenticatedHandlers(tornado.testing.AsyncHTTPTestCase):
    def get_app(self):
        app = tornado.web.Application([(r'/protected', project.handlers.Protected)])
        self.mox.StubOutWithMock(tornado.web.RequestHandler, 'get_current_user', use_mock_anything=True)
        tornado.web.RequestHandler.get_current_user().AndReturn("authenticated_user")
        return app

    def setUp(self):
        self.mox = mox.Mox()
        super(TestAuthenticatedHandlers, self).setUp()

    def tearDown(self):
        self.mox.UnsetStubs()
        self.mox.ResetAll()

    def test_new_admin(self):
        self.mox.ReplayAll()
        resp = self.fetch('/protected')
        self.assertEqual(resp.code, 200)
 self.mox.VerifyAll()
I stubbed out the get_current_code() method on the RequestHandler, but if you have implemented a BaseHandler and extend your handlers from that, you should mock its method (it's closer to your code).

I mock objects extensively in my tests - it is a great practise and helps you focus better on the actual code you're testing. Hopefully this little trick will help you as well.

Friday, October 8, 2010

Pink Mayor


Pink Jon Gnarr, originally uploaded by a13xnet.

I guess you can call it luck. I was passing the Mayor's office in Reykjavík today with my camera in hand, when the Mayor of Reykjavík, popular comedian Jon Gnarr appeared. As he moved quickly towards the awaiting car, I grabbed my camera and took couple of photos.

Since it's Breast Cancer Awareness Day, or Pink Friday (as it is known here), it's only appropriate that he's is dressed in pink, as well.

Wednesday, September 8, 2010

Showing your work


Many dots, originally uploaded by a13xnet.

Learning curve of every aspiring photographer has to, at some point, reach a part where the photographs are shown to (very) critical eyes of others. Beginner photographers mostly dread to the thought of being criticized while still learning the trade. That's happening not just with photography or art, but with every skill that involves producing something.

I went through the same dreadful process while learning icelandic language; fear of speaking, fear of saying something wrong and weer into the uknown parts of the grammar. Let me tell you, it's not pretty. Contrary to my belief, doing exactly what I feared of doing helped me improve, both my skill and my knowledge; I spoke icelandic even if it was terrible and completely gramatically wrong and it payed off.

I am sure that there are many talented photographers and artists out there that still keep their work to themselves and that is a shame. No matter how good or bad you are, you will never know that for sure unless someone else sees your work. It is simply not possible to improve if you don't know for sure what to improve and where.

Today I joined a huge community of photographers and artists on flickr.com - it is time for me to show my work. I wish to improve my skill, wish to learn new techniques and fine-tune ones I already am familiar with. Being in contact with others that share the same passion as me is incredibly valuable and I don't want to miss on that.

So, expect to see more of my work over there and I hope I'll get comments and guidelines where to improve.

Tuesday, August 17, 2010

Point of View matters

Photography is a big interest of mine and I have been enjoying taking photos for quite some time. As an aspiring hobbyist photographer, I always try to find ways to improve my skill and better define my photography style. I try not to worry too much about the equipment, but rather how to use it; although, I must admit I have just recently succumbed to the equipment bug and replaced my Olympus E-510 with a Nikon D90. So far, I'm quite happy with that decision. But I digress.

I went out in the garden with my son to play the other day, and took my camera with me, just in case. It was a sunny morning with not a cloud in the sky. As I was coming out I noticed a little patch in the grass. The sun was shining on it and it produced vibrant greens as the light went through the plant's leaves. It felt like a nice photo opportunity. I could have just taken the photo at that moment from my standing point of view (and I actually did, to help me illustrate the point of this post), but that particular point of view did not offer anything of value as a photograph.

Normal POV
With that in mind, I started thinking about what can be done so the photograph tells the story better. I wanted to focus the viewer on the semi-transparency of the leaves and the beautiful greens so a change of background was definitely required. I decided to simply change the point of view and bring the camera to the same level as the leaves. The result is the image below.
Leveled POV
This photograph is much different and it reveals well what I tried to accomplish. While it's not a winner, it's way better than the photo above. These photos are not processed in any way and this one could use a better crop and a bit of dodging.

Every photographer will tell you that it's not just the subject that matters in a photo; the subject can tell all sorts of different stories depending on the point of view. When taking photos, try to explore the subjects as much as you can - sometimes you can yield many excellent photos from a single subject. Not only it's a great learning expirience, it's also a good exercise, especially if you're shooting with a prime (single focal length) lens.

Go out, take some photos and share your expirience.

Tuesday, March 2, 2010

Simple URL shortener in less than 30 lines of python code

I needed an URL shortener for a project that I'm working on that keeps URLs in their short form for a limited time. No need to go into the details about the project as this URL shortener is a helper hack so we don't need to do last-minute rewrite of the app itself.

As an exercise, I decided to write a fully functional RESTful (*buzz*, *buzz*) app with a persistent store for the URLs. I chose Beaker cache for the storage and bobo as the boilerplate base for the app. Thanks to those two components, the actual script is less than 30 lines of python code.

To save the URL and get it's short ID, you POST the URL to the app. The script is caching the URL for an hour, but it's using persistent storage in case the app crashes (it restores the cache contents). I used my short_id() method I wrote about a while ago to generate the ID for the stored URL. If you supply the ID to the app it will redirect you to the stored URL.

You can check the app the git repo here. Feel free to comment and feel free to use it, of course!

To run the script, use: bobo -f shorty.py (bobo is the command to run an embedded bobo web server).
To save an URL, simply POST to it:
$ curl -d "url=http://www.a13x.info/" http://localhost:8080/
(you'll get something like "ax7dc" returned)
To fetch the URL do: http://localhost:8080/ax7dc. The app will redirect you to the saved URL or throw a 404 if it expired (or it didn't exist).

Simple!

Tuesday, January 12, 2010

Install CouchDB with Homebrew with existing Erlang

If you're using excellent Homebrew to install fantastic unix CLI utilities on your OS X, then you might find this handy. I wanted to install CouchDB using Homebrew, but I quickly realized it depends on Erlang being built with Homebrew as well.. As I have built my own Erlang (and don't need another one) for my machine, I decided to look into the formula for CouchDB to see if I can tweak it to use Erlang that's already on my machine.

It turned out that the fix is very easy to apply. Only thing you need to do is to open the couchdb.rb file (in /usr/local/Library/Formula) and do the following:
  • remove the depends_on 'erlang' line

  • edit the call to the configure script so the line --with-erlang points to your erlang installation (mine is in /usr/local/lib/erlang).

Here's the patch:

10d9
< depends_on 'erlang'
16c15
< "--with-erlang=#{HOMEBREW_PREFIX}/lib/erlang/usr/include"
---
> "--with-erlang=/usr/local/lib/erlang/usr/include/"


Now do brew install couchdb and make something wonderful. Don't forget to let me know about it!

Friday, December 11, 2009

Release early, release often!

Remember that mantra, known in the Open Source world? Well, it's a core part of Agile Methodologies for software development, for precisely the same reason: getting the feel on how your project/product/app is behaving in the real environment and getting feedback from your customer. Feedback is especially important, as the requirements for the project might change (and they usually do!) - you need to be aware of that!

But requirements are not the only ones that change; so does the environment in which your product is supposed to be running and used. While you might have total control over the development and test environments, you usually don't have little or no control over the live (production) environment. That environment is handled by some dedicated person or people.

Keep in mind that those people have their own schedule (backlog if you wish) by which they operate the environment under their control. Systems are upgraded or reinstalled, new versions of services get installed and so forth. Usually, you, the developer, are the last one to find out about that. You find out about those changes when your app is being deployed and (oddly!) doesn't work.

We all tried to talk to those people, hoping they will keep us in sync with the changes they make, but frankly (and I'm talking from personal expirience) that rarely goes as well as you think it would. So, make sure your product owners understand this as well, and push for releases as often as possible. That way, not only you'll be getting (great!) feedback from your owners, but will be able to keep tabs on your environment as well.

This post reflects thoughts, problems (and frustration) over the last week, while trying to get our (quite complex) project into production. While we were really trying to be agile and follow all (or most) of the principles during development, we still managed to fail to deliver our project often to the production environment.

What product owners sometimes fail to understand is that you must follow all of the principles, and follow them well. The developers often fail to help them understand. We must all learn from that, I say.

Wednesday, November 25, 2009

Andri Luka 2 years old && Erlang/OTP R13B03 released

This day is very special and remarkable - our son, Andri Luka was born on this day 2 years ago! Happy 2nd Birthday, dear son!

Also, on the other side, Erlang/OTP R13B03 is released. With this release comes the GIT (mirror) repository of Erlang/OTP source code (available here) to enable people to send in contributions. That is awesome! The release also marks the introduction of NIFs (Native Implemented Functions), but that's still in experimental stage.

Saturday, November 7, 2009

Icelandic Gaming Industry

Just came back from the first IGI workshop, first workshop for the IGIA10, the Icelandic Gaming Industry Awards competition.. It was an excellent starting point for icelandic indie game developers to meet and network. I came a bit late so I missed few talks, but the rest was really good. The talks were held by representatives from companies that are already established game developers (ie. CCP, Gogogic, Dexoris, etc). It was nice of them to share their expirience in their road to success.

I asked couple of questions, mainly focusing on getting more information on how to get connected to artists and/or designers that want to bring their talent into the gaming industry. Lots of indie developers (such as yours truly) have zero-to-none artistic (design) skills. In my opinion, IGI initiative should also focus on that talent, as well as developers.

As we all know, eye-candy and content is a huge help to make it in this business. I am close to a point where I would definitely need an artist to join me, otherwise it might be very difficult to get players to play the game. Not to mention possible funding :)

Next to come, a bit of introduction to the game itself.

p.s. I encourage you, dear reader, to check the Icelandic Gaming Industry website and join me and others in very interesting endeavour of bringing more games in the future..

Saturday, July 11, 2009

Check if an application is running

I'm working on a utility application for Mac OS X, which will display the currently played song in iTunes on the OS X status bar. While working on it, I've made a small utility method to check if a program (identified by BundleID) is running or not.

Here it is:

-(BOOL)isRunning:(NSString *)programBundleId {
return [[[NSWorkspace sharedWorkspace]
valueForKeyPath:@"launchedApplications.NSApplicationBundleIdentifier"]
containsObject:programBundleId] ? YES : NO;
}


The method returns YES if an application is running - in my case, it was useful to check if iTunes is running or not.

Monday, June 29, 2009

TinyURLs reloaded, now with Python3

Few days ago, very smart and great people behind Python project released stable version of Python 3.1; that brings bunch of improvements (including performance ones) and new features. You can check what's new in this release right here, if you wish.

I was quite impressed by the speed improvements over the 3.0.1 version of Python. It's quite fast and comparable to Python 2.6 version (which is pretty damn fast). Running few of my sources with the new version (to test speed and comformance) I noticed that my TinyURL example doesn't work anymore.

The string.letters is gone, and print is (as mentioned before) no longer a statement; it's a function. The updated function now looks like this:

import random
import string

def short_id(num): return "".join(random.sample(string.digits + string.ascii_letters, num))

print(short_id(6))


The only noticable change in the function itself is use of string.ascii_letters. There you have it - now Py3 compliant! :)

Friday, January 30, 2009

Tiny URLs

Want tinyurl.com-style links in your application? Need to generate a random sequence of alphanumerics? Here's a quick function in Python:

import random
import string

def short_id(num): return "".join(random.sample(string.digits + string.letters, num))

print short_id(6)

It will return something like AnLrJl or 9mLXut, or even bK5D4O. Simple and powerful.

Wednesday, January 7, 2009

Христос се роди! Срећан Божић!

To all the people that celebrate Christmas today, we wish you a Merry Christmas and that you and your family are healthy, happy and wealthy!