Search code examples
djangodjango-testingdjango-testsmodel-mommy

Testing Login with Model Mommy


I having a problem testing my login in my functional test. I am using model mommy to create a a user call Megan with a password, but my test still does not pass since when the information is sent it throws up and error on the html page of "Please enter a correct username and password. Note that both fields may be case-sensitive." So I suspect that the test user is not being created or something like that.

functional_test:

from django.test import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from model_mommy import mommy
from django.contrib.auth.models import User


class NewUserTest(LiveServerTestCase):

    def setUp(self):
        self.user = mommy.make('User', 
        username='Megan',
        password = 'password',
        is_active = True)

        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(15)

    def tearDown(self):
        self.browser.quit()

    def test_user_can_start_a_new_movement(self):
        #some code
        self.browser.get(self.live_server_url)
        self.assertIn('P2', self.browser.title)

        #Megan first logs in 
        login_link = self.browser.find_element_by_link_text('Log In')
        login_link.click()
        #Megan then puts in her user information
        username = self.browser.find_element_by_id('id_username')
        password = self.browser.find_element_by_id('id_password')
        submit = self.browser.find_element_by_id('id_submit')
        username.send_keys('Megan')
        password.send_keys('password')
        submit.click()

login.html

{% extends 'base.html' %}

{% block body_block %}

<form action="/accounts/login/" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" id='id_submit'>

</form>

{% endblock %}

users.urls.py:

from django.conf.urls import url, patterns
from django.contrib.auth.views import login, logout

from movements import views 

urlpatterns = [
    url(r'^login/', login,
 {'template_name': 'login.html'}, name='login'),
]

Solution

  • I believe your code is not working at the moment because mommy.make is not hashing the password. I don't see any advantage of using mommy in this case, so it should be fine to use the regular create_user method instead.

    self.user = User.objects.create_user 
        username='Megan',
        email='[email protected]',
        password = 'password',
    )
    

    This will ensure that the password is hashed properly.

    If you still want to use model mommy so that it creates foreign keys to other models, you can call set_password to correctly hash the password. Thanks mislavcimpersak for suggesting this in their answer.

        self.user = mommy.make('User', 
        username='Megan',
        is_active = True)
        self.user.set_password('password')
        self.save()