Reputation: 395
I am trying to write tests for an API. I'm having trouble with a couple of User model methods. The methods all work in development and production environments, but the test does not.
Here is the test:
def test_delete_user(self):
USER_DELETED = 1
self.u = self.setup()
result = User.delete_user(self.u, self.u.pk)
# response
self.assertEqual(result, USER_DELETED)
# functionality
self.assertIsNone(self.u)
print(self.u)
When I run this test, the return value USER_DELETED
is correct, but the user object is not actually deleted.
self.setup()
returns a single created user. I can post this if it is needed, but the setup and teardown both work with various other tests in the UserTest class.
Here is the model method being tested:
@staticmethod
def delete_user(requesting_user, user_id):
# static variables
USER_DELETED = 1
NOT_AUTHORIZED = 0
NO_USER = -1
user_to_be_deleted = User.get_user_from_user_id(user_id)
if user_to_be_deleted == NO_USER:
return NO_USER
# check for authorization to delete
if requesting_user != user_to_be_deleted:
return NOT_AUTHORIZED
user_to_be_deleted.delete()
return USER_DELETED
I also tried creating the user with the setup and then calling self.u.delete()
instead of the custom method I have. This gives the same result: AssertionError: <User: test_user> is not None
Can someone explain what I am doing wrong here?
Thanks.
Upvotes: 0
Views: 382
Reputation: 1623
I think you can use asserRaises to test the delete functionality. as Thomas mentioned you should self.u.refresh_from_db
, but that will raise DoesNotExists
since the object is deleted, so the proper way to test as follow.
def test_delete_user(self):
USER_DELETED = 1
self.u = self.setup()
result = User.delete_user(self.u, self.u.pk)
# response
self.assertEqual(result, USER_DELETED)
# functionality
with self.assertRaises(User.DoesNotExist):
self.u.refresh_from_db()
Upvotes: 1