August 14, 2009

Django Test Trick: Fixture Migration the Easy Way

This is not a way to do real model migration in the database. There are various projects underway for that; we had our own home rolled version, but I'm not in the mood to talk about it now.

However when you're running like mad you do probably keep changing what fields are in your models. This is 100% double plus true if you are running to keep up with a larger team of programmers who need your tool to configure their rapidly evolving applications.

And if you're running properly, you have a bunch of test fixture files which hold useful test data which probably won't even load when you're finished with today's changes.

You can hand-edit the fixtures, or write scripts to edit the fixtures, and I got pretty good at that. But sometimes you're adding new relations which are tricky enough that it the best tool to make a test fixture is the application you're already building. The trick is a simple two-stage process.

  1. When you add your new fields, you want to make them blank=True and null=True.
  2. Zero your database, load your old test fixture, which will load fine because it has no data and you demand none.
  3. Run around your test data doing the setup you need.
  4. Export your test data again.
  5. Go back to your models and remove the blank and null arguments.
  6. Now your models are as you want them, and your test data will load.
Also speaking from experience: do your field changes one or two at a time, and run your unit tests after each one. Nothing is worse than sorting through ten different model field changes causing errors at once.

No comments:

Post a Comment