Writing Functional Tests for the Django RESTful API

I am trying to write some functional tests for the REST API written using the Django REST Framework. This is not very specific to this structure, though, since it is basically general Django stuff.

This is what I want to do.

  • Create a user in the setUp method of the test class
  • Request user token from API using test client

tests.py

 from django.test import LiveServerTestCase from django.contrib.auth.models import User from django.test.client import Client from rest_framework.authtoken.models import Token class TokenAuthentication(LiveServerTestCase): def setUp(self): user = User.objects.create(username='foo', password='password', email=" foo@example.com ") user.save() self.c = Client() def test_get_auth_token(self): user = User.objects.get(username="foo") print user # this outputs foo print Token.objects.get(user_id = user.pk) # this outputs a normal looking token response = self.c.post("/api-token-auth/", {'username': 'foo', 'password': 'password'}) print response.status_code # this outputs 400 self.assertEqual(response.status_code, 200, "User couldn't log in") 

When I run the test, it returns the status of 400, not 200, so the user did not authenticate. If I enter the credentials of a user who is already in the database, it passes. Therefore, I assume that the records created in the test class are available only in its own methods, which is probably due to the fact that it is intended for unit testing. But I use the data from the database to run the test, which will work if the data changes.

How should a functional test be performed, for example, when data must be created before running a test in Django?

+4
source share
1 answer

You are not creating the user correctly. User.objects.create sets the password in plain text, not through a hash mechanism. Instead, you should use User.objects.create_user , which will set the password correctly so that you can authenticate with the username and password.

+9
source

Source: https://habr.com/ru/post/1494710/


All Articles