Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Merge branch 't20812'

  • Loading branch information...
commit 85359ec9a4514087e2cc666b77eb635aacba5073 2 parents cc957cb + 2326ded
Florian Apolloner authored September 06, 2013
17  django/utils/encoding.py
@@ -67,16 +67,15 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
67 67
         return s
68 68
     try:
69 69
         if not isinstance(s, six.string_types):
70  
-            if hasattr(s, '__unicode__'):
71  
-                s = s.__unicode__()
72  
-            else:
73  
-                if six.PY3:
74  
-                    if isinstance(s, bytes):
75  
-                        s = six.text_type(s, encoding, errors)
76  
-                    else:
77  
-                        s = six.text_type(s)
  70
+            if six.PY3:
  71
+                if isinstance(s, bytes):
  72
+                    s = six.text_type(s, encoding, errors)
78 73
                 else:
79  
-                    s = six.text_type(bytes(s), encoding, errors)
  74
+                    s = six.text_type(s)
  75
+            elif hasattr(s, '__unicode__'):
  76
+                s = six.text_type(s)
  77
+            else:
  78
+                s = six.text_type(bytes(s), encoding, errors)
80 79
         else:
81 80
             # Note: We use .decode() here, instead of six.text_type(s, encoding,
82 81
             # errors), so that if s is a SafeBytes, it ends up being a
17  tests/utils_tests/test_encoding.py
@@ -4,10 +4,25 @@
4 4
 import unittest
5 5
 import datetime
6 6
 
7  
-from django.utils.encoding import force_bytes, filepath_to_uri
  7
+from django.utils import six
  8
+from django.utils.encoding import force_bytes, force_text, filepath_to_uri
8 9
 
9 10
 
10 11
 class TestEncodingUtils(unittest.TestCase):
  12
+    def test_force_text_exception(self):
  13
+        """
  14
+        Check that broken __unicode__/__str__ actually raises an error.
  15
+        """
  16
+        class MyString(object):
  17
+            def __str__(self):
  18
+                return b'\xc3\xb6\xc3\xa4\xc3\xbc'
  19
+
  20
+            __unicode__ = __str__
  21
+
  22
+        # str(s) raises a TypeError on python 3 if the result is not a text type.
  23
+        # python 2 fails when it tries converting from str to unicode (via ASCII).
  24
+        exception = TypeError if six.PY3 else UnicodeError
  25
+        self.assertRaises(exception, force_text, MyString())
11 26
 
12 27
     def test_force_bytes_exception(self):
13 28
         """

0 notes on commit 85359ec

Please sign in to comment.
Something went wrong with that request. Please try again.