Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django testing: mock user login

Tags:

django

testing

I would like to test a Django project:

template news.html:

{% if user.is_authentication %}
  <a href=#>Logout ({{user.username}})</a>
{% else %}
  <a href=#>Login</a>
{% endif %}

How do I create the situation that the user is already logged in (the accounts app, responsible for user login, has not implemented yet) such that the template will display the Logout link?

(a) Functional test:

def test_logged_in_user_can_see_logout_link(self):
    # A logged-in user arrives at the main page
    ## How to mock a logged-in user here? 
    self.browser.get(self.live_server_url)
    self.assertTrue(self.browser.find_element_by_link_text('Logout'))

(b) Unit test:

def test_logged_in_user_can_see_logout_link**(self):
    # How to login the user here?
    request = self.factory.get('/news/')
    response = news(request)
    self.assertContains(response, 'Logout')
like image 327
Randy Tang Avatar asked Apr 11 '26 16:04

Randy Tang


1 Answers

In Django's base user, the property is_authenticated simply returns True in any case. On the AnonymousUser though it returns always False. The login_required decorator also checks for user.is_authenticated, by the way.

(b) Therefore, in the unit test scenario, you can easily pass a mocked object that also returns true for mocked_object.is_authenticated.

def test_logged_in_user_can_see_logout_link(self):

    class MockUser:
        is_authenticated = True

    request = self.factory.get('/news/')
    request.user = MockUser()
    response = news(request)
    self.assertContains(response, 'Logout')

(a) In the functional testing scenario however mocking is not so easy. I don't even think that it's recommended because these tests should actually test if all the parts that have already passed the unit tests work together flawlessly.

In the book "Obey The Testing Goat" by Harry J.W. Percival a session object is created before the first interaction between Selenium browser and site. The browser then uses that session cookie and is authenticated. It's a really nice trick.

like image 124
jnns Avatar answered Apr 13 '26 08:04

jnns