| | 8 | import md5, mimetypes |
|---|
| | 9 | |
|---|
| | 10 | |
|---|
| | 11 | def encode_multipart_formdata(files): |
|---|
| | 12 | """Return (content_type, body) ready for httplib.HTTP instance. |
|---|
| | 13 | |
|---|
| | 14 | files: a sequence of (name, filename, value) tuples for multipart uploads. |
|---|
| | 15 | """ |
|---|
| | 16 | BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' |
|---|
| | 17 | L = [] |
|---|
| | 18 | for key, filename, value in files: |
|---|
| | 19 | L.append('--' + BOUNDARY) |
|---|
| | 20 | L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % |
|---|
| | 21 | (key, filename)) |
|---|
| | 22 | ct = mimetypes.guess_type(filename)[0] or 'application/octet-stream' |
|---|
| | 23 | L.append('Content-Type: %s' % ct) |
|---|
| | 24 | L.append('') |
|---|
| | 25 | L.append(value) |
|---|
| | 26 | L.append('--' + BOUNDARY + '--') |
|---|
| | 27 | L.append('') |
|---|
| | 28 | body = '\r\n'.join(L) |
|---|
| | 29 | content_type = 'multipart/form-data; boundary=%s' % BOUNDARY |
|---|
| | 30 | return content_type, body |
|---|
| | 61 | |
|---|
| | 62 | def test_post_multipart(self): |
|---|
| | 63 | # generate file contents for a large post |
|---|
| | 64 | contents = "abcdefghijklmnopqrstuvwxyz" * 1000000 |
|---|
| | 65 | post_md5 = md5.md5(contents).hexdigest() |
|---|
| | 66 | |
|---|
| | 67 | # encode as multipart form data |
|---|
| | 68 | files=[('file', 'file.txt', contents)] |
|---|
| | 69 | content_type, body = encode_multipart_formdata(files) |
|---|
| | 70 | |
|---|
| | 71 | # post file |
|---|
| | 72 | if self.scheme == 'https': |
|---|
| | 73 | c = httplib.HTTPS('127.0.0.1:%s' % self.PORT) |
|---|
| | 74 | else: |
|---|
| | 75 | c = httplib.HTTP('127.0.0.1:%s' % self.PORT) |
|---|
| | 76 | c.putrequest('POST', '/post_multipart') |
|---|
| | 77 | c.putheader('Content-Type', content_type) |
|---|
| | 78 | c.putheader('Content-Length', str(len(body))) |
|---|
| | 79 | c.endheaders() |
|---|
| | 80 | c.send(body) |
|---|
| | 81 | |
|---|
| | 82 | errcode, errmsg, headers = c.getreply() |
|---|
| | 83 | self.assertEqual(errcode, 200) |
|---|
| | 84 | |
|---|
| | 85 | response_body = c.file.read() |
|---|
| | 86 | self.assertEquals(post_md5, response_body) |
|---|