How do I write a test for a custom update that uses getlist?

396 views
Skip to first unread message

Cynthia Kiser

unread,
Mar 25, 2016, 1:23:51 AM3/25/16
to Django REST framework
I have a nested serializer for which I am writing a custom update method. It works fine in the browser, but I am having trouble constructing a test for it. I am getting "AttributeError: 'dict' object has no attribute 'getlist'". The crux of the problem seems to be that in a real request, the data comes in as QueryDict, while in my test, I have a regular python dict. I didn't see any obvious example tests when searching the repo on github. How can I set up my tests so I can verify the correct behavior of my update method?

```
class CBNumericQuestionSerializer(serializers.HyperlinkedModelSerializer):
...
def validate(self, data):
...
if 'new_hints' in self.initial_data:
for hint in self.initial_data.getlist('new_hints'):
hints.append(json.loads(hint))
...

___________
from rest_framework.test import APITestCase, APIClient

class CBNumericQuestionAPIFunctionalTests(APITestCase):

def test_update_can_add_hints(self):
client = APIClient(enforce_csrf_checks=True)
before_count = len(self.question.hints)
# required field + new hint
data = {'question_text': 'A hard question.',
'new_hints': [{'hint_text': 'completely new', 'position': 2}],
}
response = client.post(reverse('course_builder:numeric_question:update',
kwargs={'course_key': self.course.course_key,
'pk': self.question.id}),
data=data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data['block']['hints']), before_count + 1)
hint_content = [hint['hint_text'] for hint in response.data['block']['hints']]
self.assertIn('completely new', hint_content)

______________
File "...serializers.py", line 390, in validate
for hint in self.initial_data.getlist('new_hints'):
AttributeError: 'dict' object has no attribute 'getlist'
```

My tests are defaulting to JSON per the docs:

REST_FRAMEWORK = {
# Have our API tests default to speaking JSON
# http://www.django-rest-framework.org/api-guide/testing/
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}

Reply all
Reply to author
Forward
0 new messages