Django REST Framework-在序列化程序测试中设置请求? [英] Django REST Framework - Set request in serializer test?
问题描述
我构建了一个Web应用程序,其中使用Django REST Framework实现了后端。现在,我正在编写单元测试,在测试序列化器方法时遇到了一个问题。这是我正在苦苦挣扎的串行器方法的一个示例:
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()
但是现在当 get_can_edit
执行 self.context.get时,我需要
。我使用 RequestFactory 创建了具有正确信息的虚假请求: self.serializer
具有正确的请求。 (请求)
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
现在我被卡住了,因为我不确定如何添加 request1
到 serializer
,这样 self.context.get('request')
将返回 request1
。
Now I am stuck because I am unsure how to add request1
to serializer
such that self.context.get('request')
will return request1
.
谢谢。
推荐答案
您需要传递上下文
参数,以将 request1
添加到序列化程序的上下文
,同时在测试中实例化序列化程序。
You need to pass context
argument to add request1
to serializer's context
while instantiating the serializer in your test.
来自包括其他上下文:
您可以提供任意加法在实例化序列化程序时,通过传递 context
参数来获得上下文。
You can provide arbitrary additional context by passing a
context
argument when instantiating the serializer.
您需要执行以下操作:
# pass context argument
self.serializer = ConferenceSerializer(context={'request': request1})
这将提供所需的 request1
在其上下文
中指向序列化程序。
This will provide the desired request1
object to your serializer in its context
.
这篇关于Django REST Framework-在序列化程序测试中设置请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!