Exemplo n.º 1
0
 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())
Exemplo n.º 2
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.assertEqual(serializer.object.created, uploaded_file.created)
     self.assertEqual(serializer.object.file, uploaded_file.file)
     self.assertFalse(serializer.object is uploaded_file)
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
 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())
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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")
Exemplo n.º 7
0
    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
        self._full_data = MergeDict(self._data, self._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, self._full_data = (Empty, Empty, Empty)
Exemplo n.º 8
0
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 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
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
 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]'
     )
Exemplo n.º 12
0
 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())
Exemplo n.º 13
0
 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())
Exemplo n.º 14
0
    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()