gpt4 book ai didi

python - Django 模型实例仅在再次调用 objects.get() 后更新(DRF 测试用例)

转载 作者:行者123 更新时间:2023-12-05 05:44:35 25 4
gpt4 key购买 nike

我有一个 APIView (DRF),我在其中将用户 is_active 字段设置为 False 而不是删除他,一切都按预期进行,但是当我尝试进行测试时出现有线行为对于 View 的情况,我尝试在调用 ApiView 后测试字段“is_active”是否为 False,但如果稍微更改代码并在调用后使用相同的用户电子邮件调用 user.objects.get(),它仍然为“True” ApiView,新实例字段is_active为False。

我从来没有遇到过这种行为,有人能解释一下背后的原因吗?谢谢!

这个测试通过了:

def test_delete_account(self):
self.authentication() # create user and log him in
user = User.objects.get(email=self.sample_user['email'])
self.assertEqual(user.is_active, True)
response = self.client.post(reverse('delete-account'))
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
user = User.objects.get(email=self.sample_user['email'])
self.assertEqual(user.is_active,False)

这个测试失败了:

def test_delete_account(self):
self.authentication() # create user and log him in
user = User.objects.get(email=self.sample_user['email'])
self.assertEqual(user.is_active, True)
response = self.client.post(reverse('delete-account'))
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertEqual(user.is_active,False) # FAILS HERE

删除帐户 ApiView:

class DeleteAccountAPIView(GenericAPIView):

permission_classes = (permissions.IsAuthenticated,)

def post(self, request):
user = self.request.user
user.is_active = False
user.save()
return Response(status=status.HTTP_204_NO_CONTENT)

最佳答案

在您的测试中,您正在调用“远程”请求,更改在“远程”中:


client ---- (call via post) --> remote
(the test) (django web app)
| |
---------------------------------
|
database

事情是这样的:

# you get a user from database
user = User.objects.get(email=self.sample_user['email'])

# you make a post to 'remote' server
response = self.client.post(reverse('delete-account'))

# no changes should be in 'client' side
self.assertEqual(user.is_active,True)

# when you refresh data from database
user = User.objects.get(email=self.sample_user['email'])

# you get the current database data that contains changes from remote
self.assertEqual(user.is_active,False)

关于python - Django 模型实例仅在再次调用 objects.get() 后更新(DRF 测试用例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71568649/

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