gpt4 book ai didi

python - 在单元测试中创建后可以更新用户对象的属性吗?

转载 作者:行者123 更新时间:2023-11-28 18:47:11 25 4
gpt4 key购买 nike

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

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'

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

所以要么我真的很累并且错过了一些明显的东西,要么 View 不可能在单元测试期间更改 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)

此测试函数中没有其他用户

最佳答案

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

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

不过,您可以重新获取它,它的更改应该反射(reflect)您对它所做的更改:

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

关于python - 在单元测试中创建后可以更新用户对象的属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18193314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com