Example #1
0
 def test_18_api_tags(self):
     """ Adds a tag to a file and then deletes it"""
     self.client.login(username=self.username, password=self.password)
     for filename in [self.documents_pdf[0], self.documents_jpg[0]]:
         # Remove tag
         url = reverse('api_file', kwargs={'code': filename})
         data = {'filename': filename, 'remove_tag_string': self.test_tag}
         content = encode_multipart('BoUnDaRyStRiNg', data)
         response = self.client.put(
             url,
             content,
             content_type='multipart/form-data; boundary=BoUnDaRyStRiNg')
         self.assertEqual(response.status_code, 200)
         # Check that we don't have tag
         url = reverse('api_file_info', kwargs={'code': filename})
         response = self.client.get(url)
         self.assertNotContains(response, self.test_tag, status_code=200)
         # Set tags
         url = reverse('api_file', kwargs={'code': filename})
         data = {'filename': filename, 'tag_string': self.test_tag}
         content = encode_multipart('BoUnDaRyStRiNg', data)
         response = self.client.put(
             url,
             content,
             content_type='multipart/form-data; boundary=BoUnDaRyStRiNg')
         self.assertEqual(response.status_code, 200)
         # Check that we have tag
         url = reverse('api_file_info', kwargs={'code': filename})
         response = self.client.get(url)
         self.assertContains(response, self.test_tag, status_code=200)
         # Get all tags for rule, check our tag
         url = reverse('api_tags',
                       kwargs={'id_rule': self.adlibre_invoices_rule_id})
         response = self.client.get(url)
         self.assertContains(response, self.test_tag, status_code=200)
Example #2
0
 def test_18_api_tags(self):
     """ Adds a tag to a file and then deletes it"""
     self.client.login(username=self.username, password=self.password)
     for filename in [self.documents_pdf[0], self.documents_jpg[0]]:
         # Remove tag
         url = reverse('api_file', kwargs={'code': filename})
         data = {'filename': filename, 'remove_tag_string': self.test_tag}
         content = encode_multipart('BoUnDaRyStRiNg', data)
         response = self.client.put(url, content, content_type='multipart/form-data; boundary=BoUnDaRyStRiNg')
         self.assertEqual(response.status_code, 200)
         # Check that we don't have tag
         url = reverse('api_file_info', kwargs={'code': filename})
         response = self.client.get(url)
         self.assertNotContains(response, self.test_tag, status_code=200)
         # Set tags
         url = reverse('api_file', kwargs={'code': filename})
         data = {'filename': filename, 'tag_string': self.test_tag}
         content = encode_multipart('BoUnDaRyStRiNg', data)
         response = self.client.put(url, content, content_type='multipart/form-data; boundary=BoUnDaRyStRiNg')
         self.assertEqual(response.status_code, 200)
         # Check that we have tag
         url = reverse('api_file_info', kwargs={'code': filename})
         response = self.client.get(url)
         self.assertContains(response, self.test_tag, status_code=200)
         # Get all tags for rule, check our tag
         url = reverse('api_tags', kwargs={'id_rule': self.adlibre_invoices_rule_id})
         response = self.client.get(url)
         self.assertContains(response, self.test_tag, status_code=200)
Example #3
0
    def testUploadTsData(self):
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/1/",
            encode_multipart(BOUNDARY,
                             {'timeseries_records': '2012-11-06 18:17,20,\n'}),
            content_type=MULTIPART_CONTENT)
        t = Timeseries(1)
        t.read_from_db(connection)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, '1')
        self.assertEqual(len(t), 1)
        self.assertEqual(t.items(0)[0], datetime(2012, 11, 06, 18, 17, 0))
        self.assertEqual(t.items(0)[1], 20)
        self.client.logout()

        # Append two more records
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/1/",
            encode_multipart(
                BOUNDARY, {
                    'timeseries_records':
                    '2012-11-06 18:18,21,\n2012-11-07 18:18,23,\n'
                }),
            content_type=MULTIPART_CONTENT)
        t = Timeseries(1)
        t.read_from_db(connection)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, '2')
        self.assertEqual(len(t), 3)
        self.assertEqual(t.items(0)[0], datetime(2012, 11, 06, 18, 17, 0))
        self.assertEqual(t.items(0)[1], 20)
        self.assertEqual(t.items(1)[0], datetime(2012, 11, 06, 18, 18, 0))
        self.assertEqual(t.items(1)[1], 21)
        self.assertEqual(t.items(2)[0], datetime(2012, 11, 07, 18, 18, 0))
        self.assertEqual(t.items(2)[1], 23)
        self.client.logout()

        # Try to append an earlier record; should fail
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/1/",
            encode_multipart(BOUNDARY,
                             {'timeseries_records': '2012-11-05 18:18,21,\n'}),
            content_type=MULTIPART_CONTENT)
        self.client.logout()
        t = Timeseries(1)
        t.read_from_db(connection)
        self.assertEqual(response.status_code, 409)
        self.assertEqual(len(t), 3)
        self.client.logout()
Example #4
0
    def testUploadTsData(self):
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/1/",
            encode_multipart(BOUNDARY,
                             {'timeseries_records': '2012-11-06 18:17,20,\n'}),
            content_type=MULTIPART_CONTENT)
        t = Timeseries(1)
        t.read_from_db(connection)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, '1')
        self.assertEqual(len(t), 1)
        self.assertEqual(t.items(0)[0], datetime(2012, 11, 06, 18, 17, 0))
        self.assertEqual(t.items(0)[1], 20)
        self.client.logout()

        # Append two more records
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/1/",
            encode_multipart(BOUNDARY,
                             {'timeseries_records':
                              '2012-11-06 18:18,21,\n2012-11-07 18:18,23,\n'}),
            content_type=MULTIPART_CONTENT)
        t = Timeseries(1)
        t.read_from_db(connection)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, '2')
        self.assertEqual(len(t), 3)
        self.assertEqual(t.items(0)[0], datetime(2012, 11, 06, 18, 17, 0))
        self.assertEqual(t.items(0)[1], 20)
        self.assertEqual(t.items(1)[0], datetime(2012, 11, 06, 18, 18, 0))
        self.assertEqual(t.items(1)[1], 21)
        self.assertEqual(t.items(2)[0], datetime(2012, 11, 07, 18, 18, 0))
        self.assertEqual(t.items(2)[1], 23)
        self.client.logout()

        # Try to append an earlier record; should fail
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/1/",
            encode_multipart(BOUNDARY,
                             {'timeseries_records': '2012-11-05 18:18,21,\n'}),
            content_type=MULTIPART_CONTENT)
        self.client.logout()
        t = Timeseries(1)
        t.read_from_db(connection)
        self.assertEqual(response.status_code, 409)
        self.assertEqual(len(t), 3)
        self.client.logout()
Example #5
0
    def testUploadTsData(self):
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/{}/".format(self.timeseries1.id),
            encode_multipart(BOUNDARY,
                             {'timeseries_records': '2012-11-06 18:17,20,\n'}),
            content_type=MULTIPART_CONTENT)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, '1')
        t = models.Timeseries.objects.get(pk=self.timeseries1.id
                                          ).get_all_data()
        self.assertEqual(len(t), 1)
        self.assertEqual(t.items(0)[0], datetime(2012, 11, 06, 18, 17, 0))
        self.assertEqual(t.items(0)[1], 20)
        self.client.logout()

        # Append two more records
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/{}/".format(self.timeseries1.id),
            encode_multipart(BOUNDARY,
                             {'timeseries_records':
                              '2012-11-06 18:18,21,\n2012-11-07 18:18,23,\n'}),
            content_type=MULTIPART_CONTENT)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.content, '2')
        t = models.Timeseries.objects.get(pk=self.timeseries1.id
                                          ).get_all_data()
        self.assertEqual(len(t), 3)
        self.assertEqual(t.items(0)[0], datetime(2012, 11, 06, 18, 17, 0))
        self.assertEqual(t.items(0)[1], 20)
        self.assertEqual(t.items(1)[0], datetime(2012, 11, 06, 18, 18, 0))
        self.assertEqual(t.items(1)[1], 21)
        self.assertEqual(t.items(2)[0], datetime(2012, 11, 07, 18, 18, 0))
        self.assertEqual(t.items(2)[1], 23)
        self.client.logout()

        # Try to append an earlier record; should fail
        self.assert_(self.client.login(username='******', password='******'))
        response = self.client.put(
            "/api/tsdata/{}/".format(self.timeseries1.id),
            encode_multipart(BOUNDARY,
                             {'timeseries_records': '2012-11-05 18:18,21,\n'}),
            content_type=MULTIPART_CONTENT)
        self.client.logout()
        self.assertEqual(response.status_code, 400)
        t = models.Timeseries.objects.get(pk=self.timeseries1.id
                                          ).get_all_data()
        self.assertEqual(len(t), 3)
        self.client.logout()
Example #6
0
def create_form_content(data):
    boundary_string = 'BoUnDaRyStRiNg'

    content = encode_multipart(boundary_string, data)
    content_type = 'multipart/form-data; boundary=' + boundary_string

    return content, content_type
Example #7
0
    def maybe_encode_multipart(
        self,
        path,
        data=b"",
        content_type=None,
        secure=False,
        query=None,
        **extra
    ):

        if isinstance(data, bytes):
            if content_type is None:
                content_type = "application/octet-stream"
        elif content_type is None:
            content_type = client.MULTIPART_CONTENT
            data = client.encode_multipart(client.BOUNDARY, data)
        else:
            raise TypeError(
                "Cannot combine data (%r) with content-type (%r)."
                % (data, content_type)
            )

        if query is not None:
            query = urlencode(query, doseq=True)
            path = path + ("&" if "?" in path else "?") + query

        return func(self, path, data, content_type, secure, **extra)
Example #8
0
    def Test_post_dream(self):
        client = self.get_client()

        data = {
            'id': 1,
            'name': 'Interstellar',
            'description': 'A sci-fi tale',
            'introduction': 'A sci-fi tale',
            'is_available': True,
            'price': 2.0,
            'alarm_sound': 1,
            'alarm_time': 90,
            'alarm_duration': 120,
            'alarm_repetition': 4,
            'dream_sound': 1,
            'group': 1
        }

        content = encode_multipart('BoUnDaRyStRiNg', data)

        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'

        req = client.post(URL + '/dreams/', content, content_type=content_type)

        self.assertEqual(req.status_code, 201)
    def put(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
        "Construct a PUT request."

        if content_type is MULTIPART_CONTENT:
            post_data = encode_multipart(BOUNDARY, data)
        else:
            post_data = data

        # Make `data` into a querystring only if it's not already a string. If
        # it is a string, we'll assume that the caller has already encoded it.
        query_string = None
        if not isinstance(data, basestring):
            query_string = urlencode(data, doseq=True)

        parsed = urlparse(path)
        r = {
            "CONTENT_LENGTH": len(post_data),
            "CONTENT_TYPE": content_type,
            "PATH_INFO": self._get_path(parsed),
            "QUERY_STRING": query_string or parsed[4],
            "REQUEST_METHOD": "PUT",
            "wsgi.input": FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)
Example #10
0
    def test_edit(self):
        created_id = self.dataset.id

        new_data = {
            'name': 'new_name',
            'identifier': 'new_identifier',
            'project': self.project.id
        }
        content = encode_multipart('BoUnDaRyStRiNg', new_data)
        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
        response2 = self.client.put('/api/datasets/' + str(created_id) + '/',
                                    content,
                                    content_type=content_type)

        self.assertEqual(response2.status_code, 200)

        response3 = self.client.get('/api/datasets/' + str(created_id) + '/')

        self.assertEqual(response3.status_code, 200)
        self.assertEqual(response3.data['name'], new_data['name'])
        self.assertEqual(response3.data['identifier'], new_data['identifier'])

        # new folder is created, so no init
        tasks = Task.objects.all()
        self.assertEqual(len(tasks), 0)
Example #11
0
    def test_patch_to_change_the_photo(self):
        # Given
        org, user = self.create_org_user(self.username, self.password)
        project = ProjectFixtureBuilder()\
            .with_partner(org)\
            .build()\
            .object

        update = ProjectUpdate.objects.create(project=project, user=user, title='Test')
        photo = ProjectUpdatePhoto.objects.create(
            update=update,
            photo=SimpleUploadedFile('test_image.jpg', get_mock_image())
        )

        # When
        self.c.login(username=self.username, password=self.password)
        url = '/rest/v1/project_update/{}/photos/{}/?format=json'.format(update.id, photo.id)
        data = encode_multipart(BOUNDARY, {
            'photo': SimpleUploadedFile('changed_image.jpg', get_mock_image()),
        })
        response = self.c.patch(url, data, content_type=MULTIPART_CONTENT)

        # Then
        self.assertEqual(200, response.status_code)
        actual = ProjectUpdatePhoto.objects.get(id=photo.id)
        self.assertTrue('changed_image' in actual.photo.name)
Example #12
0
    def test_edit(self):
        response1 = self.client.post(
            '/api/images/', {
                'name': 'old_name',
                'url': 'http://test.com/image.jpg',
                'dataset': self.dataset.id
            })
        created_id = response1.data['id']
        self.assertEqual(response1.status_code, 201)

        new_data = {
            'name': 'new_name',
            'url': 'http://test.com/new_image.jpg',
            'dataset': self.dataset.id
        }
        content = encode_multipart('BoUnDaRyStRiNg', new_data)
        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
        response2 = self.client.put('/api/images/' + str(created_id) + '/',
                                    content,
                                    content_type=content_type)

        self.assertEqual(response2.status_code, 200)

        response3 = self.client.get('/api/images/' + str(created_id) + '/')

        self.assertEqual(response3.status_code, 200)
        self.assertEqual(response3.data['name'], new_data['name'])
        self.assertEqual(response3.data['url'], new_data['url'])
Example #13
0
    def put(self, url, consumer=None, token=None, callback=False,
            verifier=None, data={}, content_type=MULTIPART_CONTENT, **kwargs):
        """
        Send a resource to the server using PUT.
        """
        # If data has come from JSON remove unicode keys.
        data = dict([(str(k), v) for k, v in data.items()])
        url = get_absolute_url(url)
        params = _get_args(consumer, callback=callback, verifier=verifier)
        params.update(data_keys(data))

        req = oauth.Request(method='PUT', url=url, parameters=params)
        req.sign_request(self.signature_method, consumer, token)
        post_data = encode_multipart(BOUNDARY, data)

        parsed = urlparse.urlparse(url)
        query_string = urllib.urlencode(req, doseq=True)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE': content_type,
            'PATH_INFO': urllib.unquote(parsed[2]),
            'QUERY_STRING': query_string,
            'REQUEST_METHOD': 'PUT',
            'wsgi.input': FakePayload(post_data),
            'HTTP_HOST':  'api',
            'HTTP_AUTHORIZATION': 'OAuth realm=""',
        }
        r.update(req)

        response = self.request(**r)
        return response
Example #14
0
    def test__mapping__partial_update__with_files(self):
        mapping_id = uuid.uuid4()
        self.helper_create_mapping(mapping_id=mapping_id)
        with open(self.samples['xform']['file-xls'], 'rb') as data:
            content_0 = SimpleUploadedFile(
                'xform.xlsx', data.read(), content_type='application/octet-stream')
        with open(self.samples['xform']['file-xml'], 'rb') as data:
            content_1 = SimpleUploadedFile('xform.xml', data.read())
        data = {
            'files': 2,
            # new
            'id_0': 0,
            'file_0': content_0,
            # updating
            'id_1': self.helper_create_xform(mapping_id=mapping_id).pk,
            'file_1': content_1,
        }

        response = self.client.patch(
            '/mappings/{}.json'.format(mapping_id),
            data=encode_multipart(BOUNDARY, data),
            content_type=MULTIPART_CONTENT,
            **self.headers_user,
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
        content = response.json()
        self.assertEqual(len(content['xforms']), 2)
Example #15
0
 def test_upload_not_null_at_path(self):
     with temp_imagefile(500, 500, 'jpeg') as uploaded_file:
         boundary = 'my-boundary'
         content_type = 'multipart/form-data; boundary=' + boundary
         data = encode_multipart(
             boundary, {
                 'data':
                 json.dumps({
                     'data': [{
                         'id': -1,
                         'name': 'Wildlands Adventure Zoo Emmen',
                         'floor_plan': 'foo',
                     }],
                 }),
                 'file:data.0.floor_plan':
                 uploaded_file,
             })
         response = self.client.put('/zoo/',
                                    content_type=content_type,
                                    data=data)
     self.assertEqual(response.status_code, 418)
     data = jsonloads(response.content)
     self.assertEqual(data['code'], 'RequestError')
     self.assertEqual(data['message'],
                      'expected null at path: data.0.floor_plan')
Example #16
0
    def test_upload_file_in_multiput(self):
        with temp_imagefile(500, 500, 'jpeg') as uploaded_file:
            boundary = 'my-boundary'
            content_type = 'multipart/form-data; boundary=' + boundary
            data = encode_multipart(
                boundary, {
                    'data':
                    json.dumps({
                        'data': [{
                            'id': -1,
                            'name': 'Wildlands Adventure Zoo Emmen',
                            'floor_plan': None,
                        }],
                    }),
                    'file:data.0.floor_plan':
                    uploaded_file,
                })
            response = self.client.put('/zoo/',
                                       content_type=content_type,
                                       data=data)
        self.assertEqual(response.status_code, 200)
        data = jsonloads(response.content)

        emmen = Zoo.objects.get(pk=dict(data['idmap']['zoo'])[-1])
        content_type = mimetypes.guess_type(emmen.floor_plan.path)[0]
        self.assertEqual(content_type, 'image/jpeg')
        self.assertEqual(emmen.floor_plan.width, 500)
        self.assertEqual(emmen.floor_plan.height, 500)
Example #17
0
def _calculate_signature(authn_name, method, url, body, username):
    """Do the signed request calculation.
    """
    # We need all arguments and all locals
    # pylint: disable=R0913
    # pylint: disable=R0914
    to_sign = {}
    if username:
        to_sign["X-FOST-User"] = username.encode("utf-7")
    if not isinstance(body, basestring):
        if method in ["POST", "PUT"]:
            logging.info("Encoding POST/PUT data %s", body or {})
            data = encode_multipart(BOUNDARY, body or {})
        else:
            logging.info("Encoding query string %s", body or {})
            data = urlencode(body or {}, doseq=True)
    else:
        data = body or ""
    now = datetime.utcnow().isoformat() + "Z"
    _, signature = fost_hmac_request_signature(settings.SECRET_KEY, method, url, now, to_sign, data)
    headers = {}
    headers["Authorization"] = "FOST %s:%s" % (authn_name.encode("utf-7"), signature)
    headers["X-FOST-Timestamp"] = now
    headers["X-FOST-Headers"] = " ".join(["X-FOST-Headers"] + to_sign.keys())
    for key, value in to_sign.items():
        headers[key] = value
    logging.debug("_calculate_signature %s adding headers: %s", method, headers)
    return headers
Example #18
0
    def put(self, url, consumer=None, token=None, callback=False,
            verifier=None, data={}, content_type=MULTIPART_CONTENT, **kwargs):
        """
        Send a resource to the server using PUT.
        """
        url = get_absolute_url(url)
        params = _get_args(consumer, callback=callback, verifier=verifier)
        req = oauth.Request(method='PUT', url=url, parameters=params)

        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, consumer, token)

        post_data = encode_multipart(BOUNDARY, data)

        parsed = urlparse.urlparse(url)
        query_string = urllib.urlencode(req, doseq=True)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      urllib.unquote(parsed[2]),
            'QUERY_STRING':   query_string,
            'REQUEST_METHOD': 'PUT',
            'wsgi.input':     FakePayload(post_data),
            'HTTP_HOST':      'api',
        }
        r.update(req)

        response = self.request(**r)
        return response
 def test_update_label_wrong_params(self):
     label_data = {
         'label_meta': self.label_meta,
         'shape': self.shape,
         'class_id': 'eye',
         'surface': 'BOL'
     }
     sample_serializer = SampleSerializer(data={
         'label': label_data,
         'image_name': self.image_name
     })
     sample_serializer.is_valid()
     sample = sample_serializer.save()
     label_data.update({'class_id': None, 'surface': False})
     resp = self.client.put(
         f'/api/label/{sample.label.id}/',
         data=encode_multipart('BoUnDaRyStRiNg',
                               {'label': json.dumps(label_data)}),
         content_type='multipart/form-data; boundary=BoUnDaRyStRiNg')
     label_data.pop('label_meta')
     label_data.pop('shape')
     label_data.update({'id': DummyValue()})
     self.assertEqual(resp.status_code, 400)
     expected_data = {
         'class_id': ['This field may not be null.'],
         'surface': ['Not a valid string.']
     }
     self.assertEqual(expected_data, json.loads(resp.content))
Example #20
0
    def put(self, url, consumer=None, token=None, callback=False,
            verifier=None, data={}, content_type=MULTIPART_CONTENT, **kwargs):
        """
        Send a resource to the server using PUT.
        """
        # If data has come from JSON remove unicode keys.
        data = dict([(str(k), v) for k, v in data.items()])
        url = get_absolute_url(url)
        params = _get_args(consumer, callback=callback, verifier=verifier)
        params.update(data_keys(data))

        req = oauth.Request(method='PUT', url=url, parameters=params)
        req.sign_request(self.signature_method, consumer, token)
        post_data = encode_multipart(BOUNDARY, data)

        parsed = urlparse.urlparse(url)
        query_string = urllib.urlencode(req, doseq=True)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE': content_type,
            'PATH_INFO': urllib.unquote(parsed[2]),
            'QUERY_STRING': query_string,
            'REQUEST_METHOD': 'PUT',
            'wsgi.input': FakePayload(post_data),
            'HTTP_HOST': 'api',
            'HTTP_AUTHORIZATION': 'OAuth realm=""',
        }
        r.update(req)

        response = self.request(**r)
        return response
Example #21
0
    def test_edit(self):
        self.create_multi()

        response1 = self.client.post(
            '/api/annotation-segmentations/', {
                'image': self.image.id,
                'category': self.category.id,
                'segmentation': [[10, 10, 20, 10, 20, 20, 10, 20]]
            })
        created_id = response1.data['id']
        self.assertEqual(response1.status_code, 201)

        new_data = {
            'image': self.image.id,
            'category': self.category.id,
            'width': 1000,
            'height': 2000,
            'segmentation': [[10, 10, 20, 10, 20, 20, 10, 20]]
        }
        content = encode_multipart('BoUnDaRyStRiNg', new_data)
        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
        response2 = self.client.put('/api/annotation-segmentations/' +
                                    str(created_id) + '/',
                                    content,
                                    content_type=content_type)

        self.assertEqual(response2.status_code, 200)

        response3 = self.client.get('/api/annotation-segmentations/' +
                                    str(created_id) + '/')

        self.assertEqual(response3.status_code, 200)
        self.assertEqual(response3.data['width'], 10)
        self.assertEqual(response3.data['height'], 10)
Example #22
0
    def test_footprint_viewset(self):
        csrf_client = Client(enforce_csrf_checks=True)

        grp = GroupFactory(permissions=ADD_CHANGE_PERMISSIONS)
        contributor = UserFactory(group=grp)

        csrf_client.login(username=contributor.username, password="******")

        # get a csrf token
        url = reverse('create-footprint-view')
        response = csrf_client.get(url)

        footprint = FootprintFactory()
        data = {'pk': footprint.id, 'title': 'abcdefg'}
        content = encode_multipart('BoUnDaRyStRiNg', data)
        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'

        url = '/api/footprint/%s/' % footprint.id

        csrf_header = response.cookies['csrftoken'].value
        response = csrf_client.patch(url, content,
                                     content_type=content_type,
                                     HTTP_X_CSRFTOKEN=csrf_header)
        self.assertEquals(response.status_code, 200)

        footprint.refresh_from_db()
        self.assertEquals(footprint.title, 'abcdefg')
Example #23
0
    def test_post_success(self, mock_sink):
        mock_sink.save.return_value = None

        mock_file = MagicMock()
        mock_file.read.return_value = "this is a mock file"
        mock_file.name = "mock_file.txt"

        data = {
            "lol": mock_file,
            "url": "abc",
            "repo": "test-repo",
            "date": "1234",
            "sha": "zxc321",
        }
        boundary_value = "some_boundary_value"
        content = encode_multipart(boundary_value, data)

        response = self.client.post(
            reverse("uplol"),
            data=content,
            content_type=f"multipart/form-data; " f"boundary={boundary_value}",
        )
        self.assertEqual(response.status_code, 201)

        (repo, date, sha, file_ref), kwargs = mock_sink.save.call_args
        self.assertEqual(repo, "test-repo")
        self.assertEqual(date, "1234")
        self.assertEqual(sha, "zxc321")
        self.assertEqual(file_ref.name, "mock_file.txt")
        self.assertEqual(file_ref.closed, True)
Example #24
0
    def post(self, path, data={}, content_type=MULTIPART_CONTENT,
             **extra):
        "Construct a POST request."

        if content_type is MULTIPART_CONTENT:
            post_data = encode_multipart(BOUNDARY, data)
        else:
            # Encode the content so that the byte representation is correct.
            match = CONTENT_TYPE_RE.match(content_type)
            if match:
                charset = match.group(1)
            else:
                charset = settings.DEFAULT_CHARSET
            post_data = smart_str(data, encoding=charset)

        parsed = urlparse(path)
        r = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   parsed[4],
            'REQUEST_METHOD': 'POST',
            'wsgi.input':     FakePayload(post_data),
        }
        r.update(extra)
        return self.request(**r)
Example #25
0
def _calculate_signature(authn_name, method, url, body,
        username, for_fake_client):
    """Do the signed request calculation.
    """
    # We need all arguments and all locals
    # pylint: disable=R0913
    # pylint: disable=R0914
    to_sign = {}
    if username:
        to_sign['X-FOST-User'] = username
    if not isinstance(body, basestring):
        if method in ['POST', 'PUT']:
            logging.info("Encoding POST/PUT data %s", body or {})
            data = encode_multipart(BOUNDARY, body or {})
        else:
            logging.info("Encoding query string %s", body or {})
            data = urlencode(body or {}, doseq=True)
    else:
        data = body or ''
    now = datetime.utcnow().isoformat() + 'Z'
    _, signature = fost_hmac_request_signature(
        settings.SECRET_KEY, method, url, now, to_sign, data)
    headers = {}
    headers['Authorization'] = 'FOST %s:%s' % (authn_name, signature)
    headers['X-FOST-Timestamp'] = now
    headers['X-FOST-Headers'] = ' '.join(['X-FOST-Headers'] + to_sign.keys())
    for key, value in to_sign.items():
        headers[key] = value
    logging.debug("_calculate_signature %s adding headers: %s", method, headers)
    if for_fake_client:
        return dict([('HTTP_' + k.upper().replace('-', '_'), v)
            for k, v in headers.items()])
    else:
        return headers
Example #26
0
 def test_24_mdt_handler(self):
     """Refs #1435 TEST: MDT handler"""
     mdt_name = 'mdt1.json'
     mdt_id = 'mytesttemplate'
     self.client.login(username=self.username, password=self.password)
     url = reverse('api_mdt')
     response = self.client.get(url)
     self.assertEqual(response.status_code, 200)
     mdt_path = os.path.join(self.test_document_files_dir, '..', 'mdts_json', mdt_name)
     data = {'mdt': str(open(mdt_path, 'r').read())}
     response = self.client.post(url, data)
     if response.status_code == 409:
         raise AssertionError('MDT for tests exists')
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, '"ok"')
     self.assertContains(response, '"mdt_id"')
     self.assertContains(response, mdt_id)
     ok_resp_data = json.loads(response.content)
     if not 'status' in ok_resp_data.iterkeys():
         raise AssertionError('MDT POST wrong parsed result data.')
     # Retrieving MDT that was posted via API
     response = self.client.get(url, {'docrule_id': "100000"})
     self.assertEqual(response.status_code, 200)
     got_mdts = json.loads(response.content)
     if not '1' in got_mdts.iterkeys():
         raise AssertionError('no MDT returned')
     self.assertEqual(mdt_id, got_mdts['1']['mdt_id'])
     # Deleting mdt that exists in the API
     content = encode_multipart('BoUnDaRyStRiNg', {'mdt_id': mdt_id})
     response = self.client.delete(url, content, content_type='multipart/form-data; boundary=BoUnDaRyStRiNg')
     self.assertEqual(response.status_code, 204)
     # Checking now for mdt presence
     response = self.client.get(url, {'docrule_id': "100000"})
     self.assertEqual(response.status_code, 404)
Example #27
0
 def test_29_api_post_document_index_data(self):
     """Put document's couchdb indexes via API call"""
     self.client.login(username=self.username, password=self.password)
     content = encode_multipart('BoUnDaRyStRiNg', {'indexing_data': json.dumps(self.doc1_dict)})
     doc_url = reverse('api_file', kwargs={'code': self.documents_pdf[0], 'suggested_format': 'pdf'})
     response = self.client.put(doc_url, content, content_type='multipart/form-data; boundary=BoUnDaRyStRiNg')
     self.assertEqual(response.status_code, 200)
Example #28
0
 def put(
     self,
     url,
     data=None,
 ):
     content = encode_multipart(BOUNDARY, data or {})
     return self.client.put(url, content, content_type=MULTIPART_CONTENT)
Example #29
0
    def patch_request(
            self, path, data=False,
            content_type=MULTIPART_CONTENT, **extra):

        "Construct a PATCH request."

        data = data or {}

        if content_type is MULTIPART_CONTENT:
            post_data = encode_multipart(BOUNDARY, data)
        else:
            post_data = data

        # Make `data` into a querystring only if it's not already a string. If
        # it is a string, we'll assume that the caller has already encoded it.
        query_string = None
        if not isinstance(data, basestring):
            query_string = urlencode(data, doseq=True)

        parsed = urlparse(path)
        request_params = {
            'CONTENT_LENGTH': len(post_data),
            'CONTENT_TYPE':   content_type,
            'PATH_INFO':      self._get_path(parsed),
            'QUERY_STRING':   query_string or parsed[4],
            'REQUEST_METHOD': 'PATCH',
            'wsgi.input':     FakePayload(post_data),
        }
        request_params.update(extra)
        return self.request(**request_params)
def put(self, path, data={}, content_type=MULTIPART_CONTENT,
         follow=False, **extra):
    """
    Requests a response from the server using POST.
    """
    if content_type is MULTIPART_CONTENT:
        post_data = encode_multipart(BOUNDARY, data)
    else:
        # Encode the content so that the byte representation is correct.
        match = CONTENT_TYPE_RE.match(content_type)
        if match:
            charset = match.group(1)
        else:
            charset = settings.DEFAULT_CHARSET
        post_data = smart_str(data, encoding=charset)

    parsed = urlparse(path)
    r = {
        'CONTENT_LENGTH': len(post_data),
        'CONTENT_TYPE':   content_type,
        'PATH_INFO':      urllib.unquote(parsed[2]),
        'QUERY_STRING':   parsed[4],
        'REQUEST_METHOD': 'PUT',
        'wsgi.input':     FakePayload(post_data),
    }
    r.update(extra)

    response = self.request(**r)
    if follow:
        response = self._handle_redirects(response)
    return response
Example #31
0
def _calculate_signature(authn_name, method, url, body, username):
    """Do the signed request calculation.
    """
    # We need all arguments and all locals
    # pylint: disable=R0913
    # pylint: disable=R0914
    to_sign = {}
    if username:
        to_sign['X-FOST-User'] = username.encode('utf-7')
    if not isinstance(body, basestring):
        if method in ['POST', 'PUT']:
            logging.info("Encoding POST/PUT data %s", body or {})
            data = encode_multipart(BOUNDARY, body or {})
        else:
            logging.info("Encoding query string %s", body or {})
            data = urlencode(body or {}, doseq=True)
    else:
        data = body or ''
    now = datetime.utcnow().isoformat() + 'Z'
    _, signature = fost_hmac_request_signature(settings.SECRET_KEY, method,
                                               url, now, to_sign, data)
    headers = {}
    headers['Authorization'] = 'FOST %s:%s' % \
        (authn_name.encode('utf-7'), signature)
    headers['X-FOST-Timestamp'] = now
    headers['X-FOST-Headers'] = ' '.join(['X-FOST-Headers'] + to_sign.keys())
    for key, value in to_sign.items():
        headers[key] = value
    logging.debug("_calculate_signature %s adding headers: %s", method,
                  headers)
    return headers
Example #32
0
def test_post_file_with_custom_uid(storage, api_client):
    fake = faker.Faker('ru_RU')
    url = reverse('file_upload-list')
    file_data = get_random_string().encode()
    attachment = SimpleUploadedFile(fake.file_name(category='image',
                                                   extension='jpeg'),
                                    file_data,
                                    content_type='image/jpeg')
    attachment_uid = uuid.uuid4()
    post_data = {'file': attachment}

    with patch('apiqa_storage.serializers.storage', storage):
        res = api_client.post(url + f'?uid={attachment_uid}',
                              data=encode_multipart(BOUNDARY, post_data),
                              content_type=MULTIPART_CONTENT)

    assert res.status_code == status.HTTP_201_CREATED
    info = file_info(attachment)
    attachment = Attachment.objects.get(uid=res.data['uid'])
    assert attachment.user == api_client.user
    assert res.data == OrderedDict([('uid', str(attachment_uid)),
                                    ('created',
                                     attachment.created.isoformat()),
                                    ('name', info.name), ('size', info.size),
                                    ('content_type', info.content_type),
                                    ('tags', [])])
Example #33
0
def test_post_file_with_tags(storage, api_client):
    fake = faker.Faker('ru_RU')
    url = reverse('file_upload-list')
    file_size = fake.random_int(min=1, max=settings.MAX_FILE_SIZE)
    file_data = get_random_string(file_size).encode()
    attachment = SimpleUploadedFile(fake.file_name(category='image',
                                                   extension='jpeg'),
                                    file_data,
                                    content_type='image/jpeg')
    post_data = {
        'file':
        attachment,
        'tags': [
            fake.pystr(min_chars=1, max_chars=settings.TAGS_CHARACTER_LIMIT)
            for _ in range(fake.random_int(min=1, max=settings.TAGS_COUNT_MAX))
        ]
    }

    with patch('apiqa_storage.serializers.storage', storage):
        res = api_client.post(url,
                              data=encode_multipart(BOUNDARY, post_data),
                              content_type=MULTIPART_CONTENT)
    assert res.status_code == status.HTTP_201_CREATED
    info = file_info(attachment)
    attachment = Attachment.objects.get(uid=res.data['uid'])
    assert attachment.user == api_client.user
    assert res.data == OrderedDict([('uid', str(attachment.uid)),
                                    ('created',
                                     attachment.created.isoformat()),
                                    ('name', info.name), ('size', info.size),
                                    ('content_type', info.content_type),
                                    ('tags', post_data['tags'])])
Example #34
0
 def test_upload_unauthenticated(self):
     url = reverse('user-resource', kwargs={'pk': self.user.pk})
     f = open(str(self.test_file.resolve()), 'w+')
     content = encode_multipart('BoUnDaRyStRiNg',  {'file': f})
     content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
     response = self.client.put(url, data=content, content_type=content_type)
     f.close()
     self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
Example #35
0
 def test_can_update_package(self):
     Package.objects.create(name="ember", url="/foo")
     url = reverse("find", kwargs={'name': 'ember'})
     encoded_data = encode_multipart(BOUNDARY, {'url': '/bar', 'name': 'ember'})
     response = self.client.put(url, encoded_data, content_type=MULTIPART_CONTENT)
     self.assertEqual(200, response.status_code)
     result = json.loads(response.content)
     self.assertEqual(result['url'], '/bar')
     self.assertEqual(result['name'], 'ember')
Example #36
0
 def load_shop_data(self):
     with open(
             os.path.join(settings.MEDIA_ROOT, 'fixtures/shop1.yaml',
                          'rb')) as file:
         response = self.client.post(reverse('backend:partner-update'),
                                     data=encode_multipart(
                                         BOUNDARY, {'file': file}),
                                     content_type=MULTIPART_CONTENT)
     self.assertEqual(response.status_code, status.HTTP_201_CREATED)
Example #37
0
    def _get_post_data(self, post_data={}, content_type='application/json'):
        post_data = super()._get_post_data(post_data)
        if content_type == 'multipart/form-data':
            self.content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
            post_data = encode_multipart('BoUnDaRyStRiNg', post_data)

        else:
            post_data = json.dumps(post_data).encode()
        return post_data
Example #38
0
    def _get_post_data(self, post_data={}, content_type='application/json'):
        post_data = super()._get_post_data(post_data)
        if content_type == 'multipart/form-data':
            self.content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
            post_data = encode_multipart('BoUnDaRyStRiNg', post_data)

        else:
            post_data = json.dumps(post_data).encode()
        return post_data
Example #39
0
 def _update_code(self, doc_name, code=None, suggested_format="pdf", check_response=True):
     """Method to uploade an already existing document into DMS"""
     self.client.login(username=self.username, password=self.password)
     url, data = self._get_tests_file(doc_name, code, suggested_format)
     content = encode_multipart("BoUnDaRyStRiNg", data)
     response = self.client.put(url, content, content_type="multipart/form-data; boundary=BoUnDaRyStRiNg")
     if check_response:
         self.assertEqual(response.status_code, 200)
     return response
Example #40
0
 def render(self, data, accepted_media_type=None, renderer_context=None):
     if hasattr(data, 'items'):
         for key, value in data.items():
             assert not isinstance(value, dict), (
                 "Test data contained a dictionary value for key '%s', "
                 "but multipart uploads do not support nested data. "
                 "You may want to consider using format='json' in this "
                 "test case." % key)
     return encode_multipart(self.BOUNDARY, data)
Example #41
0
 def testUploadTsDataUnauthenticated(self):
     # Attempt to upload some timeseries data, unauthenticated
     response = self.client.put(
         "/api/tsdata/{}/".format(self.timeseries1.id),
         encode_multipart(BOUNDARY,
                          {'timeseries_records': '2012-11-06 18:17,20,\n'}),
         content_type=MULTIPART_CONTENT)
     t = self.timeseries1.get_all_data()
     self.assertEqual(response.status_code, 403)
     self.assertEqual(len(t), 0)
Example #42
0
    def _patch_user_with_context(client, header, context):
        enc_content = encode_multipart('BoUnDaRyStRiNg', context)
        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'

        response = client.patch(resolve_url('users:me-profile'),
                                **header,
                                data=enc_content,
                                content_type=content_type)

        return response
 def render(self, data, accepted_media_type=None, renderer_context=None):
     if hasattr(data, 'items'):
         for key, value in data.items():
             assert not isinstance(value, dict), (
                 "Test data contained a dictionary value for key '%s', "
                 "but multipart uploads do not support nested data. "
                 "You may want to consider using format='json' in this "
                 "test case." % key
             )
     return encode_multipart(self.BOUNDARY, data)
Example #44
0
def encode_data(data) -> Tuple[Dict, str]:
    """
    Encode data for PUT requests.
    :param data: Dict.
    :return: Encoded data and content type with boundary string.
    """
    boundary_string = 'BoUnDaRyStRiNg'
    encoded_data = encode_multipart(boundary_string, data)
    content_type = f'multipart/form-data; boundary={boundary_string}'
    return encoded_data, content_type
Example #45
0
 def test__mapping__partial_update__with_files__length_0(self):
     mapping_id = uuid.uuid4()
     self.helper_create_mapping(mapping_id=mapping_id)
     response = self.client.patch(
         '/mappings/{}.json'.format(mapping_id),
         data=encode_multipart(BOUNDARY, {'files': 0}),
         content_type=MULTIPART_CONTENT,
         **self.headers_user,
     )
     self.assertEqual(response.status_code, status.HTTP_200_OK)
Example #46
0
 def testUploadTsDataUnauthenticated(self):
     # Attempt to upload some timeseries data, unauthenticated
     response = self.client.put(
         "/api/tsdata/1/",
         encode_multipart(BOUNDARY, {"timeseries_records": "2012-11-06 18:17,20,\n"}),
         content_type=MULTIPART_CONTENT,
     )
     t = Timeseries(1)
     t.read_from_db(connection)
     self.assertEqual(response.status_code, 403)
     self.assertEqual(len(t), 0)
Example #47
0
 def testUploadTsDataGarbage(self):
     self.assert_(self.client.login(username='******', password='******'))
     response = self.client.put(
         "/api/tsdata/{}/".format(self.timeseries1.id),
         encode_multipart(BOUNDARY,
                          {'timeseries_records': '2012-aa-06 18:17,20,\n'}),
         content_type=MULTIPART_CONTENT)
     t = self.timeseries1.get_all_data()
     self.assertEqual(response.status_code, 400)
     self.assertEqual(len(t), 0)
     self.client.logout()
    def api_put(self,
                path,
                query={},
                expected_status=200,
                follow_redirects=False,
                expected_redirects=[],
                expected_mimetype=None,
                **extra):
        """Perform and check an HTTP PUT to an API resource.

        This will perform the request to the resource and validate that all
        the results are what the caller expects.

        Args:
            path (unicode):
                The path to the resource to request.

            query (dict):
                The form data to post.

            expected_status (int):
                The expected HTTP status.

            follow_redirects (bool):
                Whether to expect and follow redirects to another URL.

            expected_redirects (list of unicode):
                The list of expected redirects performed by the resource(s),
                in order.

            expected_mimetype (unicode):
                The expected mimetype for the response payload.

        Returns:
            bytes:
            The parsed payload data.
        """
        path = self._normalize_path(path)

        print('PUTing to %s' % path)
        print("Post data: %s" % query)
        data = encode_multipart(BOUNDARY, query)

        response = self._api_func_wrapper(self.client.put,
                                          path,
                                          data,
                                          expected_status,
                                          follow_redirects,
                                          expected_redirects,
                                          expected_mimetype,
                                          content_type=MULTIPART_CONTENT,
                                          extra=extra)

        return self._get_result(response, expected_status)
Example #49
0
 def _encode_data(self, data, content_type, ):
     if content_type is MULTIPART_CONTENT:
         return encode_multipart(BOUNDARY, data)
     else:
         # Encode the content so that the byte representation is correct.
         match = CONTENT_TYPE_RE.match(content_type)
         if match:
             charset = match.group(1)
         else:
             charset = settings.DEFAULT_CHARSET
         return smart_str(data, encoding=charset)
Example #50
0
 def testUploadTsDataUnauthenticated(self):
     # Attempt to upload some timeseries data, unauthenticated
     response = self.client.put(
         "/api/tsdata/1/",
         encode_multipart(BOUNDARY,
                          {'timeseries_records': '2012-11-06 18:17,20,\n'}),
         content_type=MULTIPART_CONTENT)
     t = Timeseries(1)
     t.read_from_db(connection)
     self.assertEqual(response.status_code, 403)
     self.assertEqual(len(t), 0)
Example #51
0
 def testUploadTsDataGarbage(self):
     self.assert_(self.client.login(username="******", password="******"))
     response = self.client.put(
         "/api/tsdata/1/",
         encode_multipart(BOUNDARY, {"timeseries_records": "2012-aa-06 18:17,20,\n"}),
         content_type=MULTIPART_CONTENT,
     )
     t = Timeseries(1)
     t.read_from_db(connection)
     self.assertEqual(response.status_code, 400)
     self.assertEqual(len(t), 0)
     self.client.logout()
Example #52
0
 def testUploadTsDataAsWrongUser(self):
     # Attempt to upload some timeseries data as user 2; should deny
     self.assert_(self.client.login(username='******', password='******'))
     response = self.client.put(
         "/api/tsdata/{}/".format(self.timeseries1.id),
         encode_multipart(BOUNDARY,
                          {'timeseries_records': '2012-11-06 18:17,20,\n'}),
         content_type=MULTIPART_CONTENT)
     t = self.timeseries1.get_all_data()
     self.assertEqual(response.status_code, 403)
     self.assertEqual(len(t), 0)
     self.client.logout()
Example #53
0
    def test_existing_upload_fail(self):
        # put testfile1 filename
        self.client.force_authenticate(self.user)
        url = reverse('user-resource', kwargs={'pk': self.user.pk})

        f = open(str(self.test_file.resolve()), 'w+')
        content = encode_multipart('BoUnDaRyStRiNg',  {'file': f})
        content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg'
        response = self.client.put(url, data=content, content_type=content_type)
        f.close()

        self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
Example #54
0
 def client_put_multipart(self, url, info={}, **kwargs):
     # type: (Text, Dict[str, Any], **Any) -> HttpResponse
     """
     Use this for put requests that have file uploads or
     that need some sort of multi-part content.  In the future
     Django's test client may become a bit more flexible,
     so we can hopefully eliminate this.  (When you post
     with the Django test client, it deals with MULTIPART_CONTENT
     automatically, but not put.)
     """
     encoded = encode_multipart(BOUNDARY, info)
     django_client = self.client  # see WRAPPER_COMMENT
     return django_client.put(url, encoded, content_type=MULTIPART_CONTENT, **kwargs)
Example #55
0
 def testUploadTsDataAsWrongUser(self):
     # Attempt to upload some timeseries data as user 2; should deny
     self.assert_(self.client.login(username="******", password="******"))
     response = self.client.put(
         "/api/tsdata/1/",
         encode_multipart(BOUNDARY, {"timeseries_records": "2012-11-06 18:17,20,\n"}),
         content_type=MULTIPART_CONTENT,
     )
     t = Timeseries(1)
     t.read_from_db(connection)
     self.assertEqual(response.status_code, 403)
     self.assertEqual(len(t), 0)
     self.client.logout()
Example #56
0
    def api_put(
        self, path, query={}, expected_status=200, follow_redirects=False, expected_redirects=[], expected_mimetype=None
    ):
        """Perform and check an HTTP PUT to an API resource.

        This will perform the request to the resource and validate that all
        the results are what the caller expects.

        Args:
            path (unicode):
                The path to the resource to request.

            query (dict):
                The form data to post.

            expected_status (int):
                The expected HTTP status.

            follow_redirects (bool):
                Whether to expect and follow redirects to another URL.

            expected_redirects (list of unicode):
                The list of expected redirects performed by the resource(s),
                in order.

            expected_mimetype (unicode):
                The expected mimetype for the response payload.

        Returns:
            The parsed payload data.
        """
        path = self._normalize_path(path)

        print("PUTing to %s" % path)
        print("Post data: %s" % query)
        data = encode_multipart(BOUNDARY, query)

        response = self._api_func_wrapper(
            self.client.put,
            path,
            data,
            expected_status,
            follow_redirects,
            expected_redirects,
            expected_mimetype,
            content_type=MULTIPART_CONTENT,
        )

        return self._get_result(response, expected_status)
Example #57
0
    def apiPut(self, path, query={}, expected_status=200,
               follow_redirects=False, expected_redirects=[],
               expected_mimetype=None):
        path = self._normalize_path(path)

        print('PUTing to %s' % path)
        print("Post data: %s" % query)
        data = encode_multipart(BOUNDARY, query)

        response = self.api_func_wrapper(self.client.put, path, data,
                                         expected_status, follow_redirects,
                                         expected_redirects, expected_mimetype,
                                         content_type=MULTIPART_CONTENT)

        return self._get_result(response, expected_status)