私の見解では、次のコードがあります。
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
私の見解では、印刷ステートメントはあなたが期待するものを返します:
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)
このテスト機能には他のユーザーはいません