Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework - Set request in serializer test?

I built a web app where the back-end is implemented using the Django REST Framework. Now I'm writing unit tests and I have come across a problem in testing my serializer methods. Here is one example of a serializer method I'm struggling with:

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

When trying to call this from the test, first I declare an instance of the serializer:

self.serializer = ConferenceSerializer()

But now I need self.serializer to have the correct request when get_can_edit does self.context.get('request'). I've created a fake request with the correct information using RequestFactory:

self.request1 = RequestFactory().get('./fake_path')
self.request1.user = self.user1

Now I am stuck because I am unsure how to add request1 to serializer such that self.context.get('request') will return request1.

Thanks.

like image 235
Tom Avatar asked Aug 04 '16 15:08

Tom


1 Answers

You need to pass context argument to add request1 to serializer's context while instantiating the serializer in your test.

From DRF docs on including extra context:

You can provide arbitrary additional context by passing a context argument when instantiating the serializer.

You need to do something like:

# pass context argument
self.serializer = ConferenceSerializer(context={'request': request1})

This will provide the desired request1 object to your serializer in its context.

like image 99
Rahul Gupta Avatar answered Sep 22 '22 16:09

Rahul Gupta