def test_candidate_deserializer(self): create_uploaded_file(self.user) candidate_json = b'{"id": 2, "name": "giuseppe", "email": "*****@*****.**", "surname": "pes", "cv" : 2}' stream = BytesIO(candidate_json) data = JSONParser().parse(stream) serializer = CandidateSerializer(data=data) self.assertTrue(serializer.is_valid())
def test_create_dataviz_with_serializer(self): json_data = {'selected_external_ds': [{'id': str(self.di.id), 'description': u'testing testing', 'name': u'unit test data import'}], 'selected_internal_ds': [{'id': str(self.di.id), 'description': u'testing testing', 'name': u'unit test data import'}], 'widgets': [{'viz_datasets': [{'id': str(self.di.id), 'description': u'testing testing', 'name': u'unit test data import'}], 'chart_options': {'chart': {'val2': u'key2', 'val1': u'key1'}}, 'config_fields': {'xAxis': {'id': 1, 'name': u'revenue'}}, 'title': u'some chart', 'viz_type': u'Chart', 'chart_type': None, 'data_fields': []}], 'id': u'54fff3466fe6aa72aa5fe461', 'group_name': u'unit test viz', 'created': datetime(2015, 3, 11, 7, 48, 22, 472729), 'updated': datetime(2015, 3, 11, 7, 48, 22, 472746)} json = JSONRenderer().render(json_data) data = JSONParser().parse(BytesIO(json)) serial = DataVisualizationSerializer(data=data) # make sure we aren't adding data imports init_count = DataImport.objects.count() self.assertTrue(serial.is_valid(), serial.errors) serial.save() # do we have the data imports print(serial.object) self.assertEquals( serial.object.selected_external_ds[0].id, str(self.di.id)) self.assertEquals(init_count, DataImport.objects.count())
def _perform_form_overloading(self): """ If this is a form POST request, then we need to check if the method and content/content_type have been overridden by setting them in hidden form fields or not. """ USE_FORM_OVERLOADING = ( self._METHOD_PARAM or (self._CONTENT_PARAM and self._CONTENTTYPE_PARAM) ) # We only need to use form overloading on form POST requests. if (not USE_FORM_OVERLOADING or self._request.method != 'POST' or not is_form_media_type(self._content_type)): return # At this point we're committed to parsing the request as form data. self._data = self._request.POST self._files = self._request.FILES # Method overloading - change the method and remove the param from the content. if (self._METHOD_PARAM and self._METHOD_PARAM in self._data): self._method = self._data[self._METHOD_PARAM].upper() # Content overloading - modify the content type, and force re-parse. if (self._CONTENT_PARAM and self._CONTENTTYPE_PARAM and self._CONTENT_PARAM in self._data and self._CONTENTTYPE_PARAM in self._data): self._content_type = self._data[self._CONTENTTYPE_PARAM] self._stream = BytesIO(self._data[self._CONTENT_PARAM].encode(self.parser_context['encoding'])) self._data, self._files = (Empty, Empty)
def test_question_deserializer_valid_json(self): question_json = '{"id": 2, "question_text": "text", "question_catalogue": 1}' stream = BytesIO(question_json) data = JSONParser().parse(stream) serializer = QuestionSerializer(data=data) self.assertTrue(serializer.is_valid()) question = serializer.object question.save() # question_from_db = Question.objects.get(pk=2) self.assertEqual(question.question_text, "text") self.assertEqual(question_from_db.question_text, "text") # self.assertTrue(type(question.question_catalogue) is QuestionCatalogue) self.assertEqual(question.question_catalogue.pk, self.question_catalogue.pk) self.assertEqual(question.question_catalogue.catalogue_name, self.question_catalogue.catalogue_name) # self.assertTrue( type(question_from_db.question_catalogue) is QuestionCatalogue) self.assertEqual(question_from_db.question_catalogue.pk, self.question_catalogue.pk) self.assertEqual(question_from_db.question_catalogue.catalogue_name, self.question_catalogue.catalogue_name)
def test_job_position_deserialization(self): create_uploaded_file(self.user) job_spec_json = b'{"id": 2, "position": "text", "job_description": 2}' stream = BytesIO(job_spec_json) data = JSONParser().parse(stream) serializer = JobPositionSerializer(data=data) print(serializer.errors) self.assertTrue(serializer.is_valid())
def test_validation_with_no_data(self): """ Validation should still function when no data dictionary is provided. """ uploaded_file = BytesIO(six.b('stuff')) uploaded_file.name = 'stuff.txt' uploaded_file.size = len(uploaded_file.getvalue()) serializer = UploadedFileSerializer(files={'file': uploaded_file}) self.assertFalse(serializer.is_valid())
def json_to_py(stream_or_string): if isinstance(stream_or_string, basestring): #stream = StringIO(stream_or_string) stream = BytesIO(stream_or_string) else: stream = stream_or_string #return simplejson.load(stream) return JSONParser().parse(stream)
def __call__(self, request, content_object, **kwargs): submit_data = {'authenticated_username': request.user.username} ws_delete_content_uri = settings.ZTREE_WS_BASE_URL + request.tree_context.node.absolute_path + '/delete' resp = dispatch_request_json(ws_delete_content_uri, method='POST', data=submit_data) #resp_py = simplejson.load(StringIO(resp)) resp_py = JSONParser().parse( BytesIO(resp) ) if resp_py.get('status'): return 1 return 0
def test_create(self): now = datetime.datetime.now() file = BytesIO(six.b('stuff')) file.name = 'stuff.txt' file.size = len(file.getvalue()) serializer = UploadedFileSerializer(data={'created': now}, files={'file': file}) uploaded_file = UploadedFile(file=file, created=now) self.assertTrue(serializer.is_valid()) self.assertEquals(serializer.object.created, uploaded_file.created) self.assertEquals(serializer.object.file, uploaded_file.file) self.assertFalse(serializer.object is uploaded_file)
def test_json_to_Status_Report(self): json = JSONRenderer().render(self.expected_dict) stream = BytesIO(json) data = JSONParser().parse(stream) serializer = StatusReportSerializer(data=data) self.assertTrue(serializer.is_valid()) self.assertEqual(self.new_status.status, serializer.object.status) self.assertEqual(self.new_status.when, serializer.object.when) self.assertEqual(self.new_status.user, serializer.object.user) '''self.assertEqual(self.new_status.when.strftime("%Y-%m-%d %H:%M:%S"),
def test_serializer(self): test_stations = util.read_csv(self.test_station_file, 17) a_station = create_station(test_stations[1]) a_station.save() print(a_station.pk) ser = StationSerializer(a_station) content = JSONRenderer().render(ser.data) self.assertIsNotNone(content) stream = BytesIO(content) data = JSONParser().parse(stream) ser = StationSerializer(data=data) self.assertTrue(ser.is_valid())
def deserialize_node(stream_or_string, **serializer_kwargs): if isinstance(stream_or_string, basestring): stream = BytesIO(stream_or_string) else: stream = stream_or_string data = JSONParser().parse(stream) serializer = NodeSerializer(data=data, **serializer_kwargs) if not serializer.is_valid(): raise ValueError('error deserializing node') # return Node object return serializer.object
def test_render_and_parse(self): """ Test rendering and then parsing returns the original object. IE obj -> render -> parse -> obj. """ obj = {'foo': ['bar', 'baz']} renderer = YAMLRenderer() parser = YAMLParser() content = renderer.render(obj, 'application/yaml') data = parser.parse(BytesIO(content)) self.assertEqual(obj, data)
def from_native(self, data): """ Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports). """ f = super(ImageField, self).from_native(data) if f is None: return None from rest_framework.compat import Image assert Image is not None, 'Either Pillow or PIL must be installed for ImageField support.' # We need to get a file object for PIL. We might have a path or we might # have to read the data into memory. if hasattr(data, 'temporary_file_path'): file = data.temporary_file_path() else: if hasattr(data, 'read') and hasattr(data, 'seek'): data.seek(0) file = BytesIO(data.read()) else: file = BytesIO(data['content']) try: # load() could spot a truncated JPEG, but it loads the entire # image in memory, which is a DoS vector. See #3848 and #18520. # verify() must be called immediately after the constructor. Image.open(file).verify() except ImportError: # Under PyPy, it is possible to import PIL. However, the underlying # _imaging C module isn't available, so an ImportError will be # raised. Catch and re-raise. raise except Exception: # Python Imaging Library doesn't recognize it as an image raise ValidationError(self.error_messages['invalid_image']) if hasattr(f, 'seek') and callable(f.seek): f.seek(0) return f
def test_json_to_StatusReport(self): json = JSONRenderer().render(self.expected_dict) stream = BytesIO(json) data = JSONParser().parse(stream) serializer = StatusReportSerializer(data=data) self.assertTrue(serializer.is_valid()) self.assertEqual(self.new_status.status, serializer.object.status) import datetime self.assertAlmostEqual(self.new_status.when, serializer.object.when, delta=datetime.timedelta(seconds=1)) self.assertEqual(self.new_status.user, serializer.object.user)
def test_interview_deserialization(self): create_uploaded_file(self.user) json = b'{"id": 1, ' \ b' "start": "2015-05-04T12:20:34.000343+0000", ' \ b' "end": "2015-05-04T12:21:34.000343+0000", ' \ b' "status": "OPEN", ' \ b' "job_position": 1,' \ b' "candidate": {"id": 1, "name": "giuseppe", "email": "*****@*****.**", "surname": "pes", "cv": 2},' \ b' "overall_score": 0,'\ b' "catalogue": 1}' stream = BytesIO(json) data = JSONParser().parse(stream) serializer = InterviewSerializer(data=data) print(serializer) self.assertTrue(serializer.is_valid())
def _load_stream(self): """ Return the content body of the request, as a stream. """ try: content_length = int(self.META.get('CONTENT_LENGTH', self.META.get('HTTP_CONTENT_LENGTH'))) except (ValueError, TypeError): content_length = 0 if content_length == 0: self._stream = None elif hasattr(self._request, 'read'): self._stream = self._request else: self._stream = BytesIO(self.raw_post_data)
def test_create_point_location_with_serializer(self): json_data = {"name": "test", "points": [1, 2]} json = JSONRenderer().render(json_data) data = JSONParser().parse(BytesIO(json)) serial = LocationSerializer(data=data) self.assertTrue(serial.is_valid(), serial.errors) serial.save() # point saved then returned as GeoJSON self.assertEquals( Location.objects.get(id=serial.object.id).points, { u'type': u'Point', u'coordinates': [1, 2] }) self.assertEqual(serial.object.name, "test")
def testCreateSnippet(self): # 序列化其中一个实例: serializer = SnippetSerializer(self.snippet2) print serializer.data # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language':u'python', 'style': u'friendly'} # 以上代码已将snippet实例转化为Python基本数据类型, 接下来我们完成序列化: content = JSONRenderer().render(serializer.data) print content # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}' # 反序列化也是类似的, 首先将stream转为python基本类型: stream = BytesIO(content) data = JSONParser().parse(stream) # 然后我们将它转化为snippet实例: serializer = SnippetSerializer(data=data) self.assertEqual(serializer.is_valid(), True) # True print serializer.object
def count(parent_path, **kwargs): logger.info("parent_path: %s, kwargs: %s" % (parent_path, kwargs)) if not parent_path or parent_path == '/': ws_url = settings.ZTREE_WS_BASE_URL + '/count' else: ws_url = settings.ZTREE_WS_BASE_URL + parent_path + '/count' resp = dispatch_request_json(ws_url, data=kwargs) if resp: #resp_py = simplejson.load(StringIO(resp)) resp_py = JSONParser().parse(BytesIO(resp)) # did we get a dict back and has it got a 'count' key if type(resp_py) == type({}) and resp_py.has_key('count'): node_count = int(resp_py['count']) logger.debug("got node count: " % node_count) return (node_count, None) logger.error("could NOT get count") return (0, None)
def _get_patient_data_from_alternate_facility(query): r = None obj = None msg = None fac = None c_msg = None conditions = None other_conditions = None patient_id = None key = query.strip()[:3].upper() if urls.has_key(key): raw_url = urls[key] url = raw_url + 'detail/' + query try: r = requests.get(url) print r if not r: msg = "Sorry the patient was not found." except (ConnectionError, HTTPError, Timeout), e: print e, "\n\n" msg = "Sorry there was a problem in the connection. Try Again later..." if r: stream = BytesIO(r.text) try: data = JSONParser().parse(stream) except Exception, e: raise e serializer = PatientSerializer(data=data, partial=True) if serializer.is_valid(): obj = serializer.object fac = data['facility_registered_from'] conditions = data['conditions'] msg = "Patient information was found at %s" % str( fac.capitalize()) patient_id = data['id'] other_conditions_url = raw_url + 'conditions/' + str( patient_id) other_conditions, c_msg = _get_other_conditions( other_conditions_url)
def test_remove_with_empty_string(self): """ Passing empty string as data should cause file to be removed Test for: https://github.com/tomchristie/django-rest-framework/issues/937 """ now = datetime.datetime.now() file = BytesIO(six.b('stuff')) file.name = 'stuff.txt' file.size = len(file.getvalue()) uploaded_file = UploadedFile(file=file, created=now) serializer = UploadedFileSerializer(instance=uploaded_file, data={ 'created': now, 'file': '' }) self.assertTrue(serializer.is_valid()) self.assertEqual(serializer.object.created, uploaded_file.created) self.assertIsNone(serializer.object.file)
def test_interview_deserialization_when_datetime_is_not_iso8610(self): create_uploaded_file(self.user) json = b'{"id": 1, ' \ b' "start": "2014-12-23T11:30", ' \ b' "end": "2014-12-23T12:00", ' \ b' "status": "OPEN", ' \ b' "job_position": 1,' \ b' "candidate": {"id": 1, "name": "giuseppe", "email": "*****@*****.**", "surname": "pes", "cv": 2},' \ b' "catalogue": 1}' stream = BytesIO(json) data = JSONParser().parse(stream) serializer = InterviewSerializer(data=data) self.assertFalse(serializer.is_valid()) self.assertIsNotNone(serializer.errors['start']) self.assertEqual( serializer.errors['start'][0], 'Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ss.uuuuuu[+HHMM|-HHMM]' ) self.assertIsNotNone(serializer.errors['end']) self.assertEqual( serializer.errors['end'][0], 'Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ss.uuuuuu[+HHMM|-HHMM]' )
def test_question_catalogue_invalid_scope(self): catalogue_json = '{"id": 2, "catalogue_scope": "wrong", "catalogue_name": "cat"}' stream = BytesIO(catalogue_json) data = JSONParser().parse(stream) question_catalogue_serializer = QuestionSerializer(data=data) self.assertFalse(question_catalogue_serializer.is_valid())
else: msg = "Sorry the facility with the input search is not available." return (obj, msg, fac, conditions, other_conditions, patient_id) def _get_other_conditions(url): c_msg = None try: r = requests.get(url) if not r: c_msg = "Sorry the patient was not found." except (ConnectionError, HTTPError, Timeout), e: print e, "\n\n" c_msg = "Sorry there was a problem in the connection. Try Again later..." if r: stream = BytesIO(r.text) try: data = JSONParser().parse(stream) except Exception, e: raise e return (data, c_msg) @login_required(login_url='/') def update_patient_data(request, patient_id): patient = get_object_or_404(Patient, pk=patient_id) if request.method == 'POST': update_form = PatientForm(request.POST) if update_form.is_valid(): update_form = PatientForm(request.POST, instance=patient) update_form.save()
def test_question_deserializer_invalid_json(self): question_json = '{"question_catalogue": 1}' stream = BytesIO(question_json) data = JSONParser().parse(stream) serializer = QuestionSerializer(data=data) self.assertFalse(serializer.is_valid())