Instantly share code, notes, and snippets.

Embed
What would you like to do?
class FooSerializer(rest_serializers.ModelSerializer):
class Meta:
model = MultipleChoiceQuestion
fields = ('id', 'model_name', 'title', 'student_answer_url', 'block_state', 'ready_preview', )
def validate(self, data):
'''Mostly this just shovels data from the request into validated_data. '''
errors = {}
print('in validate initial data is: ', type(self.initial_data))
pprint(self.initial_data)
# print(self.initial_data['answers[]'])
# print(len(self.initial_data['answers[]']))
# print(self.initial_data.getlist('answers[]'))
for answer in self.initial_data.getlist('answers[]'):
print(json.loads(answer))
if errors:
raise ValidationError(errors)
return data
def update(self, instance, validated_data):
print('validated data')
pprint(validated_data)
return instance
import json
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from django.core.urlresolvers import reverse
from accounts.tests.factories import UserWithCourseRoleFactory
from course_materials.tests.factories import CourseFactory, MultipleChoiceQuestionFactory, MultipleChoiceAnswerFactory
from pprint import pprint
class FooTests(APITestCase):
'''
This class tests permissions for the API endpoints for course_builder/multiple_choice_question.
It also serves as the tests for the most general happy path through our API.
'''
@classmethod
def setUpClass(cls):
super(FooTests, cls).setUpClass()
cls.course = CourseFactory.create()
cls.question = MultipleChoiceQuestionFactory.create(course=cls.course)
cls.answers = []
for i in range(4):
cls.answers.append(MultipleChoiceAnswerFactory.create(question=cls.question, answer_text=i))
cls.question.correct_answer = cls.answers[1]
cls.question.save()
cls.lead = UserWithCourseRoleFactory.create(username='leader', is_superuser=False, role='course_lead', course=cls.course) # noqa
cls.myClient = APIClient()
@classmethod
def tearDownClass(cls):
cls.course.delete()
cls.lead.delete()
super(FooTests, cls).tearDownClass()
def tearDown(self):
self.myClient.logout()
def _update(self):
answer_data = []
for a in self.answers:
data = {'url': a.get_absolute_url(), 'id': a.id,
'answer_text': a.answer_text, 'question': a.question.get_absolute_url()}
answer_data.append(json.dumps(data))
# answer_data.append(data)
req_data = {'title': 'Easy Addition',
'question_text': 'What is 2 + 2?',
'answers': (1,3,4,5),
'correct_answer_id': self.answers[2].id,
'tolerance': '0',
'answer_explanation': '',
}
print('request data will be:', type(req_data))
pprint(req_data)
return self.myClient.post(reverse('course_builder:multiple_choice_question:update_foo',
kwargs={'course_key': self.course.course_key,
'pk': self.question.id}),
data=req_data)
def test_lead_can_access_update(self):
self.myClient.login(username=self.lead.username, password='password')
response = self._update()
# print('the response is: ')
# print(response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
@api_view(['POST', 'PUT'])
@permission_classes((IsAuthenticated, IsOnTeamForCourse))
def update_foo(request, course_key, pk):
question = get_object_or_404(MultipleChoiceQuestion, pk=pk)
serializer = FooSerializer(question, data=request.data, context={'request': request})
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.data)
@cnk

This comment has been minimized.

Show comment
Hide comment
@cnk

cnk Aug 31, 2016

request data will be: <class 'dict'>
{'answer_explanation': '',
'answers': (1, 3, 4, 5),
'correct_answer_id': 1211,
'question_text': 'What is 2 + 2?',
'title': 'Easy Addition',
'tolerance': '0'}
in validate initial data is: <class 'dict'>
{'answer_explanation': '',
'answers': [1, 3, 4, 5],
'correct_answer_id': 1211,
'question_text': 'What is 2 + 2?',
'title': 'Easy Addition',
'tolerance': '0'}

E

ERROR: test_lead_can_access_update (course_builder.multiple_choice_question.test_foo.FooTests)

Traceback (most recent call last):
File "/Users/cnk/Code/mereokratos/mk_web_core/course_builder/multiple_choice_question/test_foo.py", line 72, in test_lead_can_access_update
response = self._update()
File "/Users/cnk/Code/mereokratos/mk_web_core/course_builder/multiple_choice_question/test_foo.py", line 67, in _update
data=req_data)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 170, in post
path, data=data, format=format, content_type=content_type, **extra)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 92, in post
return self.generic('POST', path, data, content_type, **extra)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/test/client.py", line 379, in generic
return self.request(**r)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 159, in request
return super(APIClient, self).request(**kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 111, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/test/client.py", line 466, in request
six.reraise(_exc_info)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise
raise value
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, *_callback_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(_args, *_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, _args, *_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, _args, *_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/decorators.py", line 53, in handler
return func(_args, *_kwargs)
File "/Users/cnk/Code/mereokratos/mk_web_core/course_builder/multiple_choice_question/views.py", line 148, in update_foo
if serializer.is_valid():
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/serializers.py", line 213, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/serializers.py", line 410, in run_validation
value = self.validate(value)
File "/Users/cnk/Code/mereokratos/mk_web_core/course_materials/serializers.py", line 268, in validate
for answer in self.initial_data.getlist('answers[]'):
AttributeError: 'dict' object has no attribute 'getlist'


Ran 1 test in 0.571s

FAILED (errors=1)

Owner

cnk commented Aug 31, 2016

request data will be: <class 'dict'>
{'answer_explanation': '',
'answers': (1, 3, 4, 5),
'correct_answer_id': 1211,
'question_text': 'What is 2 + 2?',
'title': 'Easy Addition',
'tolerance': '0'}
in validate initial data is: <class 'dict'>
{'answer_explanation': '',
'answers': [1, 3, 4, 5],
'correct_answer_id': 1211,
'question_text': 'What is 2 + 2?',
'title': 'Easy Addition',
'tolerance': '0'}

E

ERROR: test_lead_can_access_update (course_builder.multiple_choice_question.test_foo.FooTests)

Traceback (most recent call last):
File "/Users/cnk/Code/mereokratos/mk_web_core/course_builder/multiple_choice_question/test_foo.py", line 72, in test_lead_can_access_update
response = self._update()
File "/Users/cnk/Code/mereokratos/mk_web_core/course_builder/multiple_choice_question/test_foo.py", line 67, in _update
data=req_data)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 170, in post
path, data=data, format=format, content_type=content_type, **extra)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 92, in post
return self.generic('POST', path, data, content_type, **extra)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/test/client.py", line 379, in generic
return self.request(**r)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 159, in request
return super(APIClient, self).request(**kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/test.py", line 111, in request
request = super(APIRequestFactory, self).request(**kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/test/client.py", line 466, in request
six.reraise(_exc_info)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/utils/six.py", line 686, in reraise
raise value
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/core/handlers/base.py", line 132, in get_response
response = wrapped_callback(request, *callback_args, *_callback_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(_args, *_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, _args, *_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, _args, *_kwargs)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/decorators.py", line 53, in handler
return func(_args, *_kwargs)
File "/Users/cnk/Code/mereokratos/mk_web_core/course_builder/multiple_choice_question/views.py", line 148, in update_foo
if serializer.is_valid():
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/serializers.py", line 213, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/Users/cnk/.pyenv/versions/mk-web-core-3.5.1/lib/python3.5/site-packages/rest_framework/serializers.py", line 410, in run_validation
value = self.validate(value)
File "/Users/cnk/Code/mereokratos/mk_web_core/course_materials/serializers.py", line 268, in validate
for answer in self.initial_data.getlist('answers[]'):
AttributeError: 'dict' object has no attribute 'getlist'


Ran 1 test in 0.571s

FAILED (errors=1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment