"""logintokens app unittests for forms

"""
import re

from django.test import TestCase, RequestFactory
from django.core import mail
from django.shortcuts import reverse

from logintokens.forms import TokenLoginForm


class LoginFormTest(TestCase):
    """Tests the form which validates the email used for login.

    """
    def setUp(self):
        self.test_email = 'newvisitor@example.com'
        self.request = RequestFactory().get('/')

    def test_valid_email_accepted(self):
        form = TokenLoginForm({'email': self.test_email})
        self.assertTrue(form.is_valid())

    def test_invalid_email_declined(self):
        form = TokenLoginForm({'email': 'invalidemail'})
        self.assertFalse(form.is_valid())

    def test_can_send_email(self):
        form = TokenLoginForm({'email': self.test_email})
        if form.is_valid():
            form.save(self.request)
        self.assertEqual(len(mail.outbox), 1)

    def test_email_contains_link(self):
        form = TokenLoginForm({'email': self.test_email})
        if form.is_valid():
            form.save(self.request)
        email = mail.outbox[0]
        url_search = re.search(r'https?://.+/.+$', email.body)
        self.assertIsNotNone(url_search)
        url = url_search.group(0)
        self.assertIn(reverse('token_login'), url)

@@ -162,16 +162,63 @@
  reverse
+%0Afrom django.contrib.auth import get_user_model
 %0A%0Afrom l
@@ -258,16 +258,42 @@
 nForm%0A%0A%0A
+USER = get_user_model()%0A%0A%0A
 class Lo
@@ -401,32 +401,192 @@
 ef setUp(self):%0A
+        self.existing_user = USER._default_manager.create_user(%0A            'loginformtest-existinguser',%0A            'loginformtest-existinguser@example.com')%0A
         self.tes
@@ -815,151 +815,8 @@
 ))%0A%0A
-    def test_invalid_email_declined(self):%0A        form = TokenLoginForm(%7B'email': 'invalidemail'%7D)%0A        self.assertFalse(form.is_valid())%0A%0A
     
@@ -1346,16 +1346,16 @@
 roup(0)%0A
-
         
@@ -1397,8 +1397,405 @@
 ), url)%0A
+%0A    def test_normal_user(self):%0A        %22%22%22The link is sent to the user's email not to their username.%0A%0A        %22%22%22%0A        form = TokenLoginForm(%7B'email': self.existing_user.get_username()%7D)%0A        if form.is_valid():%0A            form.save(self.request)%0A        email = mail.outbox%5B0%5D%0A        self.assertEqual(%0A            email.to,%0A            %5Bgetattr(self.existing_user, USER.EMAIL_FIELD)%5D)%0A

Add test for users logging in by username