Skip to content

Commit e627321

Browse files
committed
PYTHON-1966 Fix unicode(PyMongoError) on Python 2
1 parent 6c4e1c9 commit e627321

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

pymongo/errors.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,16 @@ def _remove_error_label(self, label):
4646
"""Remove the given label from this error."""
4747
self._error_labels.remove(label)
4848

49-
def __str__(self):
50-
if sys.version_info[0] == 2 and isinstance(self._message, unicode):
51-
return self._message.encode('utf-8', errors='replace')
52-
return str(self._message)
49+
if sys.version_info[0] == 2:
50+
def __str__(self):
51+
if isinstance(self._message, unicode):
52+
return self._message.encode('utf-8', errors='replace')
53+
return str(self._message)
54+
55+
def __unicode__(self):
56+
if isinstance(self._message, unicode):
57+
return self._message
58+
return unicode(self._message, 'utf-8', errors='replace')
5359

5460

5561
class ProtocolError(PyMongoError):

test/test_collection.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,6 +1335,12 @@ def test_write_error_unicode(self):
13351335
self.assertIn('E11000 duplicate key error',
13361336
str(ctx.exception))
13371337

1338+
if sys.version_info[0] == 2:
1339+
# Test unicode(error) conversion.
1340+
self.assertIn('E11000 duplicate key error',
1341+
unicode(ctx.exception))
1342+
1343+
13381344
def test_wtimeout(self):
13391345
# Ensure setting wtimeout doesn't disable write concern altogether.
13401346
# See SERVER-12596.

0 commit comments

Comments
 (0)