Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I setup a unit test user for django app? The unit test can't login

I've enabled login authentication for my django app. Unit tests for views are not working because they get stuck at the login page. Setting a breakpoint immediately after the view's response is returned and using

print response.content

results in output that contains the phrase 'please login'

How do I setup a user so the testcase can login? I've tried using my username and password, but it doesn't work in the unit test context.

like image 245
dolphus333 Avatar asked Apr 29 '16 14:04

dolphus333


People also ask

How do I login as user in Django?

Django by default will look within a templates folder called registration for auth templates. The login template is called login. html . Create a new directory called templates and within it another directory called registration .

How do I test my Django app?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.

How do you write unit test cases in Django?

To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...


1 Answers

The following code inserted at the beginning of the testcase creates a user, logs them in, and allows the rest of the test to contiue

self.user = User.objects.create_user(username='testuser', password='12345') login = self.client.login(username='testuser', password='12345') 
like image 56
dolphus333 Avatar answered Sep 21 '22 01:09

dolphus333