diff --git a/InvenTree/InvenTree/test_api.py b/InvenTree/InvenTree/test_api.py new file mode 100644 index 0000000000..4ec173bf7d --- /dev/null +++ b/InvenTree/InvenTree/test_api.py @@ -0,0 +1,45 @@ +""" Low level tests for the InvenTree API """ + +from rest_framework.test import APITestCase +from rest_framework import status + +from django.urls import reverse + +from django.contrib.auth import get_user_model + + +class APITests(APITestCase): + """ Tests for the InvenTree API """ + + username = 'test_user' + password = 'test_pass' + + def setUp(self): + + # Create a user (but do not log in!) + User = get_user_model() + User.objects.create_user(self.username, 'user@email.com', self.password) + + def test_get_token_fail(self): + """ Ensure that an invalid user cannot get a token """ + + token_url = reverse('api-token') + + response = self.client.post(token_url, format='json', data={'username': 'bad', 'password': 'also_bad'}) + + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.assertFalse('token' in response.data) + + def test_get_token_pass(self): + """ Ensure that a valid user can request an API token """ + + token_url = reverse('api-token') + + # POST to retreive a token + response = self.client.post(token_url, format='json', data={'username': self.username, 'password': self.password}) + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertTrue('token' in response.data) + self.assertTrue('pk' in response.data) + self.assertTrue(len(response.data['token']) > 0) + diff --git a/InvenTree/InvenTree/test_views.py b/InvenTree/InvenTree/test_views.py index 150a6a4f30..171dcbb05f 100644 --- a/InvenTree/InvenTree/test_views.py +++ b/InvenTree/InvenTree/test_views.py @@ -10,13 +10,16 @@ import os class ViewTests(TestCase): """ Tests for various top-level views """ + username = 'test_user' + password = 'test_pass' + def setUp(self): # Create a user User = get_user_model() - User.objects.create_user('username', 'user@email.com', 'password') + User.objects.create_user(self.username, 'user@email.com', self.password) - self.client.login(username='username', password='password') + self.client.login(username=self.username, password=self.password) def test_api_doc(self): """ Test that the api-doc view works """ diff --git a/InvenTree/users/urls.py b/InvenTree/users/urls.py index 6082ef14df..312789b55b 100644 --- a/InvenTree/users/urls.py +++ b/InvenTree/users/urls.py @@ -5,7 +5,7 @@ from . import views user_urls = [ url(r'^(?P[0-9]+)/?$', views.UserDetail.as_view(), name='user-detail'), - url(r'token', views.GetAuthToken.as_view()), + url(r'token', views.GetAuthToken.as_view(), name='api-token'), url(r'^$', views.UserList.as_view()), ]