Skip to content

Commit

Permalink
make "ustr.ustr" Python 3 compatible
Browse files Browse the repository at this point in the history
  • Loading branch information
d-maurer committed Oct 26, 2020
1 parent 8d97fa8 commit 842d384
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ Changelog
4.0 (unreleased)
----------------

- Make ``ustr.ustr`` Python 3 compatible
(`Zope#921 <https://github.com/zopefoundation/Zope/issues/921>`_)

- Restore ``sql_quote`` behavior of always returning native strings
(`#54 <https://github.com/zopefoundation/DocumentTemplate/issues/54>`_)

Expand Down
10 changes: 10 additions & 0 deletions src/DocumentTemplate/tests/testustr.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ class Bar(str):
pass


class RequestLike(object):
def __str__(self): return "RequestLike"

args = () # to confuse `ustr._exception_str`


class UnicodeTests(unittest.TestCase):

def test_bare_string_literall(self):
Expand All @@ -46,6 +52,10 @@ def test_with_force_str(self):
a = ustr(force_str('hello'))
self.assertEqual(a, 'hello')

def test_RequestLike(self):
from DocumentTemplate.ustr import ustr
self.assertEqual(ustr(RequestLike()), "RequestLike")

def test_with_non_ascii_char(self):
from DocumentTemplate.ustr import ustr
a = ustr(chr(200))
Expand Down
4 changes: 2 additions & 2 deletions src/DocumentTemplate/ustr.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
##############################################################################
"""ustr function."""

nasty_exception_str = getattr(Exception.__str__, 'im_func', None)
nasty_exception_str = getattr(Exception.__str__, '__func__', None)


def ustr(v):
Expand All @@ -31,7 +31,7 @@ def ustr(v):
# they all constrain the type which potentially raises an
# exception.
# To avoid exceptions we have to call __str__ direct.
if getattr(fn, 'im_func', None) == nasty_exception_str:
if getattr(fn, '__func__', None) == nasty_exception_str:
# Exception objects have been optimised into C, and their
# __str__ function fails when given a unicode object.
# Unfortunately this scenario is all too common when
Expand Down

0 comments on commit 842d384

Please sign in to comment.