Tom Tom - 2 months ago 10x
Python Question

Django REST Framework - Fake objects for unit tests

I'm writing unit tests for my Django app. Currently I'm using factory_boy to make fake objects for testing. This works fine for most of my tests, but I'm having the following problem: My factory_boy objects aren't showing up in

. For example, I'm trying to test the following method in my serializer:

def get_can_edit(self, obj):
request = self.context.get('request')
user = request.user
admin = SimpleLazyObject(obj.admin)
user = User.objects.get(username=request.user)
return user == obj.admin

Going through it with a debugger, I've determined that request.user correctly has my fake user, but User.objects does not have my fake user.

I'm wondering if there's a simple alternative to factory_boy that will actually add my fake objects to
or if I'm just using factory_boy incorrectly? Or maybe there's a whole different approach... who knows.

Here's the code:

The serializer

The test


You need to inherit from DjangoModelFactory instead of Factory base class in your UserFactory for objects to be saved onto the database.

From factory_boy docs:

All factories for a Django Model should use the DjangoModelFactory base class.

class UserFactory(factory.DjangoModelFactory): # use DjangoModelFactory base class

    class Meta: 
        model = models.User