Test your django-piston API (with auth)

I have to build the API for one of my web service. It’s Django and django-piston powered application and it works well. Okay. I chose the TDD technique. So my problem was: how do I test the API parts which need authentication (basic HTTP, not OAuth for now)? The built-in test client of Django doesn’t seem to have such a feature.

So, here is my small workaround: you have to generate the HTTP_AUTHORIZATION field of your HTTP request. I wrote a small base test class for tests which need authentication:

import base64
import unittest
from django.test.client import Client

class BaseAuthenticatedClient(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        auth = '%s:%s' % ('username', 'password')
        auth = 'Basic %s' % base64.encodestring(auth)
        auth = auth.strip()
        self.extra = {
            'HTTP_AUTHORIZATION': auth,
        }

You just have to replace username and password, and write your own test suite:

class TestAPIAuth(BaseAuthenticatedClient):

    def testrootauth(self):
        response = self.client.get('/api/aresource/id', {}, **self.extra)
        self.assertEqual(response.status_code, 200)

It should be OK. Have fun!

Posted in None at December 17th, 2009. Comments.

Sync Google Contacts and AddressBook.app

You may be aware of some limitations you may encounter to sync your Google Contacts with your built-in Mac OS X address book, especially if you don’t have an iPhone/iPod Touch. Here is the most suitable solution I found to get round of this annoying problem.

  1. First of all, you must let your system think you have an iPod. Just open the file ~/Library/Prefereces/com.apple.iPod.pllist, and change de FamilyID to 1001, then save it. Property List Editor

  2. Open your AdressBook.app, go to Preferences, then click Account button, pick the “Sync with Google” checkbox and click the “Configure” button on the right of the latest. AdressBook preferences You will be prompted for you Google credentials.

  3. One last thing. Your contacts are not sync automatically when you edit some of them or when you quit AdressBook.app. You have to set up a small script which will be executed hourly (Note: this part uses the notion of cron). Create the file ~/Library/crontab, and write the following line inside:

    @hourly /System/Library/PrivateFrameworks/GoogleContactSync.framework/Versions/A/Resources/gconsync —sync com.google.ContactSync

Then open your Terminal.app and invoke: crontab ~/Library/crontab.

You should be ok, and your contacts will sync every hour. Have fun.

Posted in None at December 7th, 2009. Comments.