Search code examples
djangodjango-testingdjango-tests

Testing customized django user class


My goal: when a user is saved, set the username to the email address

Test class 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)

My solution 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) 

I'm still new to django (and web development) so I'm not sure if there is a better way to do this..? Perhaps by implementing AbstractBaseUser in some way?

My main issue is that the test fails because:

======================================================================
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',)

why/how is user_email being converted to a tuple?


Solution

  • You have a trailing comma after the email in your test. That converts your variable into a tuple.

    Specifically this line:

        user_email = u"testuser@baflist.com",
    

    Remove the trailing comma to fix it like this:

        user_email = u"testuser@baflist.com"