Django Permissions In Test Fixtures
August 12, 2011
I wanted to use some Permissions in a Group in my test fixtures. This meant having the following json in the fixture, which referred to the Permission by serial:
{ "pk": 4, "model": "auth.group", "fields": { "name": "View Volume 4", "permissions": [ 25, 26, 27, 28 ] } }
The problem here is that if you add more model objects into your application, then the serials for the Permissions can often change. I couldn't find a way of controlling this, as the permissions are defined on the model and auto generated. They aren't manually defined in the test fixture json.
I solved the problem by using a setUp() function in my test to populate the appropriate data for the test:
def setUp(self): lVolumeFourGroup = Group.objects.filter(name='View Volume 4')[0] lVolumeFourGroup.permissions.add(Permission.objects.filter(name="View Part 25")[0]) lVolumeFourGroup.permissions.add(Permission.objects.filter(name="View Part 26")[0]) lVolumeFourGroup.permissions.add(Permission.objects.filter(name="View Part 27")[0]) lVolumeFourGroup.permissions.add(Permission.objects.filter(name="View Part 28")[0])
Note that the data set up here doesn't have to be saved to the database to be available.
The test now loads the fixture, and then runs this code before running each test in the suite.
UPDATE 16-Oct-2012
The --natural option now sorts this problem out, see https://docs.djangoproject.com/en/1.4/ref/django-admin/#django-admin-option---natural