[django | email] Build a Backend REST API - 9

Hyeseong·2021년 2월 26일
0

Normalize email addresses

이게 뭘까유?

쉽게 말하면 이메일의 도메인 부분을 소문자로 통일시키기 위한 거에요.

참고 : https://stackoverflow.com/questions/27936705/what-does-it-mean-to-normalize-an-email-address

For email addresses, foo@bar.com and foo@BAR.com are equivalent; the domain part is case-insensitive according to the RFC specs. Normalizing means providing a canonical representation, so that any two equivalent email strings normalize to the same thing.

The comments on the Django method explain:

Normalize the email address by lowercasing the domain part of it.

Share
Improve this answer
Follow

test 코드 작성

test_models.py

from django.test import TestCase
from django.contrib.auth import get_user_model


class ModelTests(TestCase):
    def test_create_user_with_email_successful(self):
        '''Test creating a new user with an email is successful'''
        email = 'test@example.com'
        password = 'testpassword123'
        user = get_user_model().objects.create_user(
            email=email,
            password=password,
        )

        self.assertEqual(user.email, email)
        self.assertTrue(user.check_password(password))

    def test_new_user_email_normalized(self):
        """Test the email for a new user is normalized"""
        email = 'test@EXAMPLE.COM'
        user = get_user_model().objects.create_user(email, 'test123')
        self.assertEqual(user.email, email.lower())

def test_new_user_email_normalized(self): 메서드를 작성할건데요.
email 변수에는 임의의 문자열로된 이메일을 넣고요.
user = get_user_model().objects.create_user(email, password='test123')
커스터마이징한 Manager 클래스의 메서드인 create_user()메서드를 사용해서 간편하게 user 객체를 만들게요. 참고로 password=\'test123\' 적어도 되고 'test123'이렇게 짧게 적어도 기능적 작동은 동일하쥬?!

그럼 테스트~!

manage.py test

fail나조?

user = get_user_model().objects.create_user(email, password='test123') # 이 소스코드 한줄에서 모델에서 만들어진 객체의 이메일이 uppercase로 작성된걸 감지했기 때문이조.

self.normalize_email()🎃

이메일을 표준에 맞게 노멀라이징하게 만들어줘요.

기존

user = self.model(email=email, **extra_fields)

변경후

user = self.model(email=self.normalize_email(email), **extra_fields)

참고 : https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#django.contrib.auth.models.BaseUserManager.normalize_email

다시 테스트를 돌려보면 성공하게 됩니다~

profile
어제보다 오늘 그리고 오늘 보다 내일...

0개의 댓글