Skip to content

Commit

Permalink
Fix the return type of escape to Markup
Browse files Browse the repository at this point in the history
This patch fixes the return type of escape to always be Markup. It
addresses the issue with custom class that implements the __html__
method - see issue #68. A new test case, test_escape_return_type, is
added to test the behavior.
  • Loading branch information
dawranliou committed May 24, 2017
1 parent d2a40c4 commit dc5a6bb
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion markupsafe/_native.py
Expand Up @@ -18,7 +18,7 @@ def escape(s):
such characters in HTML. Marks return value as markup string.
"""
if hasattr(s, '__html__'):
return s.__html__()
return Markup(s.__html__())
return Markup(text_type(s)
.replace('&', '&')
.replace('>', '>')
Expand Down
5 changes: 4 additions & 1 deletion markupsafe/_speedups.c
Expand Up @@ -131,8 +131,11 @@ escape(PyObject *self, PyObject *text)
/* if the object has an __html__ method that performs the escaping */
html = PyObject_GetAttrString(text, "__html__");
if (html) {
rv = PyObject_CallObject(html, NULL);
s = PyObject_CallObject(html, NULL);
Py_DECREF(html);
/* Convert to Markup object */
rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);
Py_DECREF(s);
return rv;
}

Expand Down
7 changes: 7 additions & 0 deletions tests.py
Expand Up @@ -173,6 +173,13 @@ def test_splitting(self):
def test_mul(self):
self.assertEqual(Markup('a') * 3, Markup('aaa'))

def test_escape_return_type(self):
self.assertIsInstance(escape('a'), Markup)
class Foo:
def __html__(self):
return '<strong>Foo</strong>'
self.assertIsInstance(escape(Foo()), Markup)


class MarkupLeakTestCase(unittest.TestCase):

Expand Down

0 comments on commit dc5a6bb

Please sign in to comment.