def test_encode_multipart_data(self): # The encode_multipart_data() function should take a list of # parameters and files and encode them into a MIME # multipart/form-data suitable for posting to the MAAS server. params = {"op": "add", "filename": "foo"} fileObj = BytesIO(b"random data") files = {"file": fileObj} body, headers = encode_multipart_data(params, files) expected_body_regex = b"""\ --(?P<boundary>.+) Content-Disposition: form-data; name="filename" foo --(?P=boundary) Content-Disposition: form-data; name="op" add --(?P=boundary) Content-Disposition: form-data; name="file"; filename="file" Content-Type: application/octet-stream random data --(?P=boundary)-- """ expected_body_regex = dedent(expected_body_regex) expected_body_regex = "\r\n".join(expected_body_regex.splitlines()) expected_body = re.compile(expected_body_regex, re.MULTILINE) self.assertRegexpMatches(body, expected_body) boundary = expected_body.match(body).group("boundary") expected_headers = { "content-length": "365", "content-type": "multipart/form-data; boundary=%s" % boundary} self.assertEqual(expected_headers, headers)
def post(self, path, params): """Dispatch a C{POST} call to a MAAS server. :param uri: The MAAS path for the endpoint to call. :param params: A C{dict} of parameters to encode into the request. :return: A Deferred which fires with the result of the call. """ url = urljoin(self.url, path) body, headers = encode_multipart_data(params, {}) d = self.dispatch_query(url, "POST", headers=headers, data=body) d.addCallback(json.loads) d.addErrback(convert_unknown_error) return d