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
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?
source share