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.
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
contextargument 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With