在单元测试中创建后,是否可以更新User对象的属性?

时间:2013-08-12 17:44:08

标签: python django unit-testing

在我的观点中,我有以下代码:

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

使用print语句进行调试。当我按如下方式运行单元测试时:

#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

我视图中的print语句会返回您期望的内容:

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-person可以帮助我。

编辑:

这是我创建用户的方式:

#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)

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

1 个答案:

答案 0 :(得分: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
相关问题