3

在我看来,我有以下代码:

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

带有用于调试目的的打印语句。当我按如下方式运行单元测试时:

#Try to update user while logged in
response = c.login(username=test_username, password=test_password)
response = c.post('/user/edit/', { 'email': "test@test.com", 
                                   '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, "test@test.com") ##This test fails

在我看来,打印语句会返回您所期望的:

Before: johnnybravo@gphone.com
After : test@test.com

但是最后一次测试失败了:

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, "test@test.com")
AssertionError: u'johnnybravo@gphone.com' != 'test@test.com'

更改不会保存到(测试)数据库中!

所以要么我真的很累,错过了一些明显的东西,要么在单元测试期间视图不可能改变 request.user,或者(希望)某个聪明的 Django 人可以帮助我。

编辑:

这就是我创建用户的方式:

#Create a user
test_username = "johnnybravo@gphone.com"
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)

此测试功能中没有其他用户

4

1 回答 1

1

用户的属性可以在您的测试中创建后更新,但它们不会自动更新。

例如,如果您在测试方法中获取用户,然后调用您的方法edituserview,用户u将不会自动更新

但是,您可以重新获取它,并且它的更改应该反映您对其所做的更改:

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
于 2013-08-12T17:56:47.023 回答