瀏覽代碼

Fixed #34445 -- Fixed string-casting of non-string lazy objects.

This removes __text_cast() as it's the same as __cast().
_delegate_bytes and __delegate_text are mutually exclusive so the
`if self._delegate_bytes` branch in __cast() is unreachable.

Co-Authored-By: David Sanders <shang.xiao.sanders@gmail.com>
Ran Benita 5 年之前
父節點
當前提交
066aabcb77
共有 2 個文件被更改,包括 6 次插入8 次删除
  1. 2 8
      django/utils/functional.py
  2. 4 0
      tests/utils_tests/test_functional.py

+ 2 - 8
django/utils/functional.py

@@ -125,9 +125,8 @@ def lazy(func, *resultclasses):
                 raise ValueError(
                     "Cannot call lazy() with both bytes and text return types."
                 )
-            if cls._delegate_text:
-                cls.__str__ = cls.__text_cast
-            elif cls._delegate_bytes:
+
+            if cls._delegate_bytes:
                 cls.__bytes__ = cls.__bytes_cast
 
         @classmethod
@@ -141,17 +140,12 @@ def lazy(func, *resultclasses):
 
             return __wrapper__
 
-        def __text_cast(self):
-            return func(*self.__args, **self.__kw)
-
         def __bytes_cast(self):
             return bytes(func(*self.__args, **self.__kw))
 
         def __cast(self):
             if self._delegate_bytes:
                 return self.__bytes_cast()
-            elif self._delegate_text:
-                return self.__text_cast()
             else:
                 return func(*self.__args, **self.__kw)
 

+ 4 - 0
tests/utils_tests/test_functional.py

@@ -233,6 +233,10 @@ class FunctionalTests(SimpleTestCase):
         with self.assertRaisesMessage(ValueError, msg):
             lazy_obj()
 
+    def test_lazy_str_cast_mixed_result_types(self):
+        lazy_value = lazy(lambda: [1], str, list)()
+        self.assertEqual(str(lazy_value), "[1]")
+
     def test_classproperty_getter(self):
         class Foo:
             foo_attr = 123