Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for AnonymousUser in Django Unittesting

Tags:

django

testing

  • I'm testing a form
  • A user may be logged in, or anonymous, when presented with the form
  • If the form succeeds, the user will be logged in
  • If the form fails, the user will remain as they were
  • I'd like to confirm this behaviour by unit testing.

django.test.Client does have a login method for this kind of thing, but given a response object how do I determine who is logged in?

    data = {'email':'[email protected]','password':'abc'}
    c = Client()
    # here was can assume `request.user` is the AnonymousUser
    # or I can use `c.login(..)` to log someone in
    r = c.post('/myform/', data)

Can my unittest determine who the request.user would now be if I were to submit a second request?

like image 809
John Mee Avatar asked Jun 28 '13 05:06

John Mee


People also ask

How do I run a test case in Django?

Open /catalog/tests/test_models.py.TestCase , as shown: from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.

How do I skip a Django test?

Just trick it to always skip with the argument True : @skipIf(True, "I don't want to run this test yet") def test_something(): ... If you are looking to simply not run certain test files, the best way is probably to use fab or other tool and run particular tests.

Does Django use Pytest or Unittest?

Writing testsDjango's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach.

What is RequestFactory in Django?

The request factory class RequestFactory. The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view.


1 Answers

You can do this:

client = Client()
# here was can assume `request.user` is the AnonymousUser
# or I can use `c.login(..)` to log someone in
from django.contrib import auth
user = auth.get_user(client) # it returns User or AnonymousUser

if user.is_anonymous():
   ...

It works because client keeps a user session (client.session).

like image 89
Andrei Kaigorodov Avatar answered Sep 21 '22 21:09

Andrei Kaigorodov