gpt4 book ai didi

python - Django 休息框架 : testing update action doesn't return 400 if request data is invalid

转载 作者:行者123 更新时间:2023-11-28 18:30:38 26 4
gpt4 key购买 nike

我正在为特定的 View 集编写单元测试,发现响应不符合预期。 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 都包含原始资源(如此正确,没有应用任何更新)但状态代码为 200 并且没有消息。我已经尝试将 read_only 添加到序列化程序(在几个地方)并编写一个验证方法,该方法在生产中被调用,但似乎在测试中没有做任何事情。我做错了什么?

View .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)

序列化器.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

最佳答案

序列化程序丢弃来自未知或只读字段的数据。因此,这两个测试都将返回 200,并在验证后以“{}”结束。

关于python - Django 休息框架 : testing update action doesn't return 400 if request data is invalid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37802030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com