Suppling test data to django-cities

Posted on Thu 29 August 2013 in Tech

Django-Cities, is an awesome project that supplies easy to import worldwide location data and a set of very neat location models that you should really be using for any django project needing location information. I've been using it lately but ran into problems when I tried to run unit tests that made use of the django-cities app.

As django-cities populates a load of data via it's import command it can take a long time(over an hour) before a test database with all the data could be created. So I needed a stop-gap solution to quickly get a workable dataset up and running for a few small unit tests.

I find fixtures problematic, data may change over time and maintaining a bunch of JSON files to represent a few simple locations can be a pain. So here's a very quick example of how I use the ORM to populate a single location hierarchy for your tests.py.

def setUp(self):

  self.country = Country(name="United Kingdom", code='UK', tld='co.uk', population = 62740000)
 self.country.save()

  self.region = Region(name = "London", name_std="London", code="LDN", country=self.country)
 self.region.save()

  self.city = City(name='Camden', name_std='Camden', region=self.region, country=self.country, population = 8174000, location='POINT (3400000 6700010)')
   self.city.save()

The city POINT location is totally random, I'll start populating real location values when I need distance based tests.