Reputation: 684
I am writing django unittests for an application which is having modules with HTTP get,put and post methods. I have been referencing rest_framework's APITestCase method for writing unittest for POST method.
Here is my code for POST method unittest:
def test_postByTestCase(self):
url = reverse('lib:ingredient-detail',args=('123',))
data = {'name':'test_data','status':'draft','config':'null'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
By running this test case I am getting this output:
$ python manage.py test lib.IngredientTestCase.test_postByTestCase
FDestroying test database for alias 'default'...
======================================================================
Traceback (most recent call last): File "C:\Apache2\htdocs\iLab\api\lib\tests.py", line 42, in test_postByTestCase self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 401 != 201
Ran 1 test in 5.937s
FAILED (failures=1)
I have tried passing HTTP_AUTHORIZATION token value, but it is not helping.
Upvotes: 3
Views: 5115
Reputation: 1221
A 401
error means that your request is unauthorized. Does the application that you're trying to test require a login? If this is the case, you'll need to set up an authenticated user in your test before trying the POST
request.
# my_api_test.py
def setUp:
# Set up user
self.user = User(email="[email protected]") # NB: You could also use a factory for this
password = 'some_password'
self.user.set_password(password)
self.user.save()
# Authenticate client with user
self.client = Client()
self.client.login(email=self.user.email, password=password)
def test_postByTestCase(self):
url = reverse('lib:ingredient-detail',args=('123',))
data = {'name':'test_data','status':'draft','config':'null'}
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Once you've logged in a user to your client, then you should be able to call your API correctly and see a 201
response.
Upvotes: 2