Reputation: 43
In my views I have the following code:
def edituserview (request):
if request.POST['email']: #yes, I'm using email as username on purpose
print "\nBefore: %s" % (request.user.username)
request.user.username = email
request.user.save()
print "After : %s" % (request.user.username)
messages.add_message(request, messages.SUCCESS, 'Username successfully updated.')
with print statements for debugging purposes. When i run unit tests as follows:
#Try to update user while logged in
response = c.login(username=test_username, password=test_password)
response = c.post('/user/edit/', { 'email': "[email protected]",
'first_name': "",
'last_name': ""
})
#Assert that user gets the correct response
self.assertEqual(response.status_code, 200)
self.assertIn("Username successfully updated.", response.content) # This is the message added above
#Assert that the user object was changed
self.assertEqual(u.username, "[email protected]") ##This test fails
The print statements in my view return what you would expect:
Before: [email protected]
After : [email protected]
But then that last test fails:
FAIL: test_edituser_view (user_management.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/user/user_management/tests.py", line 162, in test_edituser_view
self.assertEqual(u.username, "[email protected]")
AssertionError: u'[email protected]' != '[email protected]'
The change doesn't get saved to the (test) database!
So either I am really tired and have missed something obvious, or it is impossible for the view to change request.user during unittesting, or (hopefully) some smart Django-person somewhere can help me.
EDIT:
This is how i create the user:
#Create a user
test_username = "[email protected]"
test_password = "godsgifttowomen"
u = create_test_user(test_username, test_password)
#Assert that the user object was created with the correct attributes
u = User.objects.get(id=1)
There are no other users in this test-function
Upvotes: 3
Views: 56
Reputation: 55972
Attributes of user can be updated after creation in your test, but they wont update automatically.
For example if you fetch a user in your test method, and then you make a call to your method edituserview
, the user u
will not automatically update
you can refetch it, though, and its changes should reflect the changes you made to it:
def test_method(self):
u = User.objects.get(pk=1)
# make call to edituserview
# right now u still reflects the data it had
# before you modified its record in edituserview
u = User.objects.get(pk=1)
# u should reflect changes
Upvotes: 1