Skip to content

Commit dc36f70

Browse files
committed
Fix handling of unicode strings in the multipart writer.
--HG-- extra : convert_revision : svn%3A7a298fb0-333a-0410-83e7-658617cd9cf3/trunk%40174
1 parent 42826be commit dc36f70

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

couchdb/multipart.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,13 @@ def add(self, mimetype, content, headers=None):
134134
self.fileobj.write(CRLF)
135135
if headers is None:
136136
headers = {}
137+
if isinstance(content, unicode):
138+
ctype, params = parse_header(mimetype)
139+
if 'charset' in params:
140+
content = content.encode(params['charset'])
141+
else:
142+
content = content.encode('utf-8')
143+
mimetype = mimetype + ';charset=utf-8'
137144
headers['Content-Type'] = mimetype
138145
if content:
139146
headers['Content-Length'] = str(len(content))

couchdb/tests/multipart.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
from couchdb import multipart
1414

1515

16-
class ReadMultiPartTestCase(unittest.TestCase):
16+
class ReadMultipartTestCase(unittest.TestCase):
1717

1818
def test_flat(self):
1919
text = '''\
@@ -149,10 +149,36 @@ def test_nested(self):
149149
self.assertEqual(num, 3)
150150

151151

152+
class WriteMultipartTestCase(unittest.TestCase):
153+
154+
def test_unicode_content(self):
155+
buf = StringIO()
156+
envelope = multipart.write_multipart(buf, boundary='==123456789==')
157+
envelope.add('text/plain', u'Iñtërnâtiônàlizætiøn')
158+
envelope.close()
159+
self.assertEqual('''Content-Type: multipart/mixed; boundary="==123456789=="
160+
161+
--==123456789==
162+
Content-Length: 27
163+
Content-MD5: 5eYoIG5zsa5ps3/Gl2Kh4Q==
164+
Content-Type: text/plain;charset=utf-8
165+
166+
Iñtërnâtiônàlizætiøn
167+
--==123456789==--
168+
''', buf.getvalue().replace('\r\n', '\n'))
169+
170+
def test_unicode_content_ascii(self):
171+
buf = StringIO()
172+
envelope = multipart.write_multipart(buf, boundary='==123456789==')
173+
self.assertRaises(UnicodeEncodeError, envelope.add,
174+
'text/plain;charset=ascii', u'Iñtërnâtiônàlizætiøn')
175+
176+
152177
def suite():
153178
suite = unittest.TestSuite()
154179
suite.addTest(doctest.DocTestSuite(multipart))
155-
suite.addTest(unittest.makeSuite(ReadMultiPartTestCase, 'test'))
180+
suite.addTest(unittest.makeSuite(ReadMultipartTestCase, 'test'))
181+
suite.addTest(unittest.makeSuite(WriteMultipartTestCase, 'test'))
156182
return suite
157183

158184

0 commit comments

Comments
 (0)