I have an APIView (DRF), where I set the user is_active field to False instead of deleting him, everything works as expected, but I have a wired behavior when I try to make a test case for the view, I try to test if the field 'is_active' is False after calling the ApiView but it remains 'True' if change the code a little bit and call user.objects.get() with the same user email after calling the ApiView, the new instance field is_active is False.
I've never encountered this behavior, can someone explain the reason behind it? thanks!
this test passes:
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)
this test fails:
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
delete account 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)
CodePudding user response:
In your test, you are calling a 'remote' request, the changes are in 'remote':
client ---- (call via post) --> remote
(the test) (django web app)
| |
---------------------------------
|
database
This is what it happens:
# 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)