Test a view with a JSONfield: 415 Unsupported Media Type #7863
Answered
by
Sispheor
Sispheor
asked this question in
Question & Answer
-
Hi, I'm trying to unit test the update of an object that contains a JSONField Model class Instance(models.Model):
name = models.CharField(max_length=100)
spec = models.JSONField(default=dict) Serializer class InstanceSerializer(serializers.ModelSerializer):
class Meta:
model = Instance
fields = '__all__' View class InstanceDetails(generics.RetrieveUpdateAPIView):
permission_classes = [IsAdminUser]
queryset = Instance.objects.all()
serializer_class = InstanceSerializer Test class TestInstanceUpdate(BaseTestRequest):
def setUp(self):
super(TestInstanceUpdate, self).setUp()
self.url = reverse('api_admin_instance_details', args=[self.test_instance.id])
json_spec = {
"key1": "value1",
"key2": "value2"
}
self.update_data = {
"name": "new_name",
"spec": json.dumps(json_spec)
}
def test_update_instance(self):
response = self.client.put(self.url, data=self.update_data, format='json')
print(response)
self.assertEqual(response.status_code, status.HTTP_200_OK) I get status code 415 Unsupported Media Type. I would like to be able to send json like other flags of my request and not as a binary. Many thanks for your help. |
Beta Was this translation helpful? Give feedback.
Answered by
Sispheor
Mar 22, 2021
Replies: 1 comment
-
Well... without the dumps it actually works as expected class TestInstanceUpdate(BaseTestRequest):
def setUp(self):
super(TestInstanceUpdate, self).setUp()
self.url = reverse('api_admin_instance_details', args=[self.test_instance.id])
self.update_data = {
"name": "new_name",
"spec": {
"key1": "value1",
"key2": "value2"
}
}
def test_update_instance(self):
response = self.client.put(self.url, data=self.update_data, content_type="application/json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.test_instance.refresh_from_db()
expected = {
"key1": "value1",
"key2": "value2"
}
self.assertDictEqual(self.test_instance.spec, expected)
self.assertEqual(self.test_instance.name, "new_name") |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Sispheor
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well... without the dumps it actually works as expected