Django PUT TestCase fails if client initialised in setUpTestData() but passes if client initialized in setUp()

Multi tool use
Multi tool use


Django PUT TestCase fails if client initialised in setUpTestData() but passes if client initialized in setUp()



I am writing tests where every test case passes except the PUT


from django.test import TestCase
from rest_framework.test import APIClient


class ViewTestCase(TestCase):

@classmethod
def setUpTestData(cls):
cls.client = APIClient()

def setUp(self):
"""setUp() runs before every single test method."""
self.user_data = {'first_name': "John", 'last_name': "Doe", 'email_id': "john@doe.com",
'phone_number': "987654321", 'is_verified': False}
self.response = self.client.post(
reverse('create'),
self.user_data,
format='json')

def test_api_can_update_user(self):
user = User.objects.get()
changes = {'first_name': "Johnny"}
changed_user_data = {**self.user_data, **changes}

response = self.client.put(
reverse('details', kwargs={'email': user.email_id}),
changed_user_data,
format='json')

self.assertEqual(response.status_code, status.HTTP_200_OK)



This test case fails with response.status_code = 415 (unsupported media type)
whereas if I just move the client initialization from setUpTestData() to setUp()
everything passes.


def setUp(self):
self.client = APIClient() # Test case passed now.
...



There are other tests for GET, POST, DELETE all of which pass
irrespective of whether client instance is shared(setUpTestData) or not.



PS: All apis including PUT work from DRF web api view.




1 Answer
1



From my understanding and with your test above client is not an instance attribute of the class instead it is a class attribute so hence the error response. Try changing self.client to cls.client in your setUp method and test_api_can_update_user method.
Also in my experience it is advisable to initialise client before creating the testcases.


client


self.client


cls.client


setUp


test_api_can_update_user


client






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

tKcWzIf6CJ431SEaQp,PX,zeq98pEAOuDEVF8gKUNI82DOaA99eYmN zQn BdTvHeD
LJSDK 4hahIX5f,bIc,Ukay2i5YdYKcF8 KI dCpnz0B3O5iPCOoCn,EoSsxhWM c4Z54slE

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

List of Kim Possible characters