I am writing tests for my simple Django web application, checking if user can login and logout correctly. Views:user_login
and user_logout
def user_login(request):
if request.method == 'POST':
email = request.POST.get('email address')
password = request.POST.get('password')
user = authenticate(username=email, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('main_page:index'))
else:
print("\nWARNING: invalid login detected\n\nemail: {}\npassword: {}\n".format(email, password))
messages.error(request, 'Ivalid email or password. Try again.')
return HttpResponseRedirect(reverse('users:login'))
else:
return render(request, 'users/login.html', {})
@login_required
def user_logout(request):
messages.add_message(request, messages.INFO, 'See you Space Cowboy!')
logout(request)
return HttpResponseRedirect(reverse('main_page:index'))
And the tests themself:
class LoginLogoutTests(TestCase):
def setUp(self):
User = get_user_model()
self.user = User.objects.create_user(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF')
print("\nsetup")
def tearDown(self):
self.user
print("teardown\n")
def test_login(self):
# test if email is equal
self.assertEqual(self.user.email, 'test_user@email.com')
# test authentication
self.assertTrue(self.user.is_authenticated)
self.assertFalse(self.user.is_anonymous)
# test if login request index.html
self.assertTrue(self.client.get('main_page.index.html'))
# test login with valid credentials
self.assertTrue(self.client.login(email='test_user@email.com', password='S6y4Mb9Aqfu79YcF'))
# test login with invalid credentials
self.assertFalse(self.client.login(email='test_user@email.com', password='password'))
print("test login")
def test_logout(self):
self.client.logout()
self.assertTrue(self.user.is_authenticated)
self.assertFalse(self.user.is_anonymous)
print("test logout\n")
Tests return this output:
(venv) [user@manjaro django-project]$ ./manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
setup
test login
teardown
setup
test logout
teardown
..
----------------------------------------------------------------------
Ran 4 tests in 0.515s
OK
Destroying test database for alias 'default'...
Last test shouldn't be passed, but paradoxically it is. What goes here wrong?
EDIT: I rebuilt user model that it uses email as login. I used this tutorial: https://testdriven.io/blog/django-custom-user-model/
Aucun commentaire:
Enregistrer un commentaire