Skip to content

Instantly share code, notes, and snippets.

@AmirTugi
Created December 4, 2015 20:44
Show Gist options
  • Select an option

  • Save AmirTugi/3b09822f95988594f2c2 to your computer and use it in GitHub Desktop.

Select an option

Save AmirTugi/3b09822f95988594f2c2 to your computer and use it in GitHub Desktop.
Cannot authenticate with APIClient
class AuthenticationTest(TestCase):
def setUp(self):
self.client = APIClient(enforce_csrf_checks=True)
self.user_password = 'a12345678'
self.user_username = 'admin'
self.data = {
'username': self.user_username,
'password': self.user_password
}
def test_authenticating_jwt(self):
"""
Given a username to authenticate,
When user authenticates
Then the DRF should return a JWT
"""
# Not working
response = self.client.post('/api-token-auth/', self.data, format='json')
print response # Status 400 -- 'Unable to authenticate with provided credentials'
# Works
# response = requests.post('http://localhost:8080/api-token-auth/', self.data)
# print response.content --> {'token': ...}
@blaklites
Copy link
Copy Markdown

"Tests that require a database (namely, model tests) will not use your “real” (production) database. Separate, blank databases are created for the tests"

Refer to: https://docs.djangoproject.com/en/1.9/topics/testing/overview/#the-test-database

So when you are running the test for the user with username ''admin' and password 'a12345678', the user is not yet in your test database and thus you are unable to authenticate this user. So you should add the following in your setUp method

self.user = User.objects.create_user(self.user_username, self.user_password)
self.data = {
'username': self.username,
'password': self.password
}

It should work after this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment