0

我的目标: 保存用户时,将用户名设置为电子邮件地址

测试类userAccount/tests.py

#----------------------------------------------------------------------#
#   Test that the User is saved correctly 
#----------------------------------------------------------------------#
class UserAccountTests(TestCase):

    # assert that a users email address is saved as the username also
    def test_username_is_email(self):
        from userAccount.models import *
        from django.contrib.auth.hashers import make_password
        user_email = u"testuser@baflist.com",
        test_user = User.objects.create(
                first_name="test", 
                last_name="user",
                email="testuser@baflist.com",
                password=make_password("whatever")
                )

        self.assertEqual(test_user.username, user_email)

我的解决方案userAccount/models.py

from django.contrib.auth.models import User as DjangoUser

class User(DjangoUser):
    def save(self, *args, **kwargs):
        self.username = self.email
        super(User, self).save(*args, **kwargs) 

我对 django(和 Web 开发)还是新手,所以我不确定是否有更好的方法来做到这一点..?也许通过以某种方式实现AbstractBaseUser ?

我的主要问题是测试失败,因为:

======================================================================
FAIL: test_username_is_email (userAccount.tests.UserAccountTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/bdhammel/Documents/web_development/baflist/baflist/userAccount/tests.py", line 55, in test_username_is_email
    self.assertEqual(test_user.username, user_email)
AssertionError: 'testuser@baflist.com' != (u'testuser@baflist.com',)

为什么/如何user_email转换为元组?

4

1 回答 1

3

测试中的电子邮件后面有一个逗号。这会将您的变量转换为元组。

特别是这一行:

    user_email = u"testuser@baflist.com",

删除尾随逗号以修复它,如下所示:

    user_email = u"testuser@baflist.com"
于 2014-06-01T20:31:57.153 回答