我正在为特定的视图集编写单元测试,并且发现响应并不像预期的那样。 docs表示不正确的数据会导致状态码400,但我得到200 ......
def test_retrieve_resource_patch_authenticated(self):
"""Update field, then try and patch a protected field (username)"""
self._require_login()
# Attempt to patch protected field, and non-existant field
test_response_2 = self.client.patch(self.url_detail, data={'username': 'cantchangethis'}, format='json')
test_response_3 = self.client.patch(self.url_detail, data={'usernamedoesntexist': 'new_username'}, format='json')
test_response_2.data和test_response_3.data都包含原始资源(正确地说,没有应用更新),但是status_code为200且没有消息。我尝试将read_only添加到序列化程序(在几个地方)并编写一个在生产中调用的validate方法,但似乎没有在测试中做任何事情。我做错了什么?
views.py
class UserProfileView(generics.RetrieveUpdateDestroyAPIView):
serializer_class = user.serializer.UserProfileSerializer
permission_classes = [permissions.IsAuthenticated]
lookup_field = 'username'
def get_queryset(self):
user = self.request.user
return User.objects.filter(username=user)
serializer.py
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
username = serializers.CharField(read_only=True)
query = serializers.HyperlinkedRelatedField(many=True, view_name='query-detail', read_only=True)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'query')
extra_kwargs = {
"username": {
"read_only": True,
},
}
def validate(self, data):
if 'username' in data:
raise Conflict('Usernames cannot be changed')
return data
答案 0 :(得分:1)
Serializers会丢弃来自未知或只读字段的数据。 因此,两个测试都将返回200,并在验证后结束为“{}”。