Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {model}.objects. 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 {model}.objects 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

like image 836
Tom Avatar asked Feb 19 '26 16:02

Tom


1 Answers

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
like image 114
Rahul Gupta Avatar answered Feb 22 '26 06:02

Rahul Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!