Question

I have functionality that I want to test that allows the user to add records on the home page and later view the records in the saved page - which works when running the app.

When running the test below initially the user is logged in but when the browser url is pointed to /saved the user has turned into an AnonymousUser.

Is there a reason for this? Here is my code below.

Test:

def test_viewing_logged_in_users_saved_records(self):

    # A user logs in
    self.client.login(username = 'testuser1', email='testuser1@test.com', password = 'testuser1password')
    self.browser.get(self.live_server_url)

    # set up our POST data - keys and values are strings
    # and post to home URL
    response = self.client.post('/',
                                {'title': TestCase3.title
                                 })

    # The user is redirected to the new unit test display page
    self.assertRedirects(response, 'unittestcase/hLdQg28/')

    # Proceeds to the page where they can see their saved records
    self.browser.get(self.live_server_url + '/saved')

    # The user can view the tests that they have saved
    body = self.browser.find_element_by_tag_name('body')
    self.assertIn(TestCase3.title, body.text)

View:

def home_post(request):
    logging.warning('In home_post') 
    logging.warning(request.user) 
    if request.method == 'POST':
        if request.user.is_authenticated():
    ....

def saved(request):
    logging.warning('In saved')
    logging.warning(request.user)
    if request.user.is_authenticated():
    ....

Logging:

WARNING:root:In home_post
WARNING:root:testuser1

WARNING:root:In saved
WARNING:root:AnonymousUser
Was it helpful?

Solution

Your first post request to the home url uses the dummy client, which you have logged in.

Your request to the /saved url uses self.browser, which is not logged in.

It is not clear why you are using both self.client and self.browser in the same test. If you don't need to use the live server in this test, then I would use self.client throughout. For the example you've shown, you could do:

response = self.client.get('/saved')
self.assertContains(response, TestCase3.title)

If you do need to use the live server, see the live server test case docs for an example of logging in using the selenium client.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top