summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
authorFederico Caselli <cfederico87@gmail.com>2021-09-13 23:09:06 +0200
committerFederico Caselli <cfederico87@gmail.com>2021-10-23 11:11:48 +0200
commita1d70afb5974125a1a65f590418c7c371bbdb3e6 (patch)
tree0f4d4ef4170e963aa6784a222e192d16ba753e21 /test
parent09cf4f68a7f7f63c2f249d61d7cc6600afe12c1a (diff)
downloadmako-workflow_test_initial_1_2.tar.gz
- remove python 2 support - add github workflows - remove disable unicode - cleanup compat file - modernize setup - use pep517 Change-Id: Ic38dbf478046cec5d0815b468f0c235b4ea5e20c
Diffstat (limited to 'test')
-rw-r--r--test/__init__.py33
-rw-r--r--test/ext/test_babelplugin.py17
-rw-r--r--test/ext/test_linguaplugin.py1
-rw-r--r--test/templates/chs_unicode.html11
-rw-r--r--test/templates/read_unicode.html10
-rw-r--r--test/templates/runtimeerr.html4
-rw-r--r--test/templates/unicode_arguments.html9
-rw-r--r--test/templates/unicode_code.html7
-rw-r--r--test/templates/unicode_expr.html2
-rw-r--r--test/test_ast.py35
-rw-r--r--test/test_cache.py7
-rw-r--r--test/test_cmd.py2
-rw-r--r--test/test_def.py11
-rw-r--r--test/test_exceptions.py178
-rw-r--r--test/test_filters.py55
-rw-r--r--test/test_inheritance.py24
-rw-r--r--test/test_lexer.py197
-rw-r--r--test/test_pygen.py2
-rw-r--r--test/test_template.py462
-rw-r--r--test/test_tgplugin.py3
-rw-r--r--test/test_util.py5
21 files changed, 287 insertions, 788 deletions
diff --git a/test/__init__.py b/test/__init__.py
index 1770962..6c5047a 100644
--- a/test/__init__.py
+++ b/test/__init__.py
@@ -2,11 +2,10 @@ import contextlib
import os
import re
import unittest
+from unittest import mock # noqa
-from mako import compat
from mako.cache import CacheImpl
from mako.cache import register_plugin
-from mako.compat import py3k
from mako.template import Template
from mako.util import update_wrapper
@@ -23,11 +22,9 @@ class TemplateTest(unittest.TestCase):
def _file_path(self, filename):
name, ext = os.path.splitext(filename)
-
- if py3k:
- py3k_path = os.path.join(template_base, name + "_py3k" + ext)
- if os.path.exists(py3k_path):
- return py3k_path
+ py3k_path = os.path.join(template_base, name + "_py3k" + ext)
+ if os.path.exists(py3k_path):
+ return py3k_path
return os.path.join(template_base, filename)
@@ -38,7 +35,7 @@ class TemplateTest(unittest.TestCase):
filters=None,
unicode_=True,
template_args=None,
- **kw
+ **kw,
):
t1 = self._file_template(filename, **kw)
self._do_test(
@@ -56,7 +53,7 @@ class TemplateTest(unittest.TestCase):
filters=None,
unicode_=True,
template_args=None,
- **kw
+ **kw,
):
t1 = Template(text=source, **kw)
self._do_test(
@@ -98,12 +95,6 @@ def teardown():
shutil.rmtree(module_base, True)
-if py3k:
- from unittest import mock # noqa
-else:
- import mock # noqa
-
-
@contextlib.contextmanager
def raises(except_cls, message=None):
try:
@@ -112,9 +103,9 @@ def raises(except_cls, message=None):
except except_cls as e:
if message:
assert re.search(
- message, compat.text_type(e), re.UNICODE
+ message, str(e), re.UNICODE
), "%r !~ %s" % (message, e)
- print(compat.text_type(e).encode("utf-8"))
+ print(str(e).encode("utf-8"))
success = True
# assert outside the block so it works for AssertionError too !
@@ -150,14 +141,6 @@ def skip_if(predicate, reason=None):
return decorate
-def requires_python_3(fn):
- return skip_if(lambda: not py3k, "Requires Python 3.xx")(fn)
-
-
-def requires_python_2(fn):
- return skip_if(lambda: py3k, "Requires Python 2.xx")(fn)
-
-
def requires_pygments_14(fn):
try:
import pygments
diff --git a/test/ext/test_babelplugin.py b/test/ext/test_babelplugin.py
index ca12444..bf21aa2 100644
--- a/test/ext/test_babelplugin.py
+++ b/test/ext/test_babelplugin.py
@@ -2,7 +2,6 @@ import io
import os
import unittest
-from mako import compat
from .. import skip_if
from .. import template_base
from .. import TemplateTest
@@ -24,26 +23,24 @@ def skip():
class Test_extract(unittest.TestCase):
@skip()
def test_parse_python_expression(self):
- input_ = io.BytesIO(compat.b('<p>${_("Message")}</p>'))
+ input_ = io.BytesIO(b'<p>${_("Message")}</p>')
messages = list(extract(input_, ["_"], [], {}))
- self.assertEqual(messages, [(1, "_", compat.u("Message"), [])])
+ self.assertEqual(messages, [(1, "_", ("Message"), [])])
@skip()
def test_python_gettext_call(self):
- input_ = io.BytesIO(compat.b('<p>${_("Message")}</p>'))
+ input_ = io.BytesIO(b'<p>${_("Message")}</p>')
messages = list(extract(input_, ["_"], [], {}))
- self.assertEqual(messages, [(1, "_", compat.u("Message"), [])])
+ self.assertEqual(messages, [(1, "_", ("Message"), [])])
@skip()
def test_translator_comment(self):
input_ = io.BytesIO(
- compat.b(
- """
+ b"""
<p>
## TRANSLATORS: This is a comment.
${_("Message")}
</p>"""
- )
)
messages = list(extract(input_, ["_"], ["TRANSLATORS:"], {}))
self.assertEqual(
@@ -52,8 +49,8 @@ class Test_extract(unittest.TestCase):
(
4,
"_",
- compat.u("Message"),
- [compat.u("TRANSLATORS: This is a comment.")],
+ ("Message"),
+ [("TRANSLATORS: This is a comment.")],
)
],
)
diff --git a/test/ext/test_linguaplugin.py b/test/ext/test_linguaplugin.py
index a563969..f505759 100644
--- a/test/ext/test_linguaplugin.py
+++ b/test/ext/test_linguaplugin.py
@@ -17,6 +17,7 @@ if lingua is not None:
class MockOptions:
keywords = []
domain = None
+ comment_tag = True
def skip():
diff --git a/test/templates/chs_unicode.html b/test/templates/chs_unicode.html
deleted file mode 100644
index 7b897e9..0000000
--- a/test/templates/chs_unicode.html
+++ /dev/null
@@ -1,11 +0,0 @@
-## -*- coding:utf-8 -*-
-<%
- msg = u'新中国的主席'
-%>
-
-<%def name="welcome(who, place=u'北京')">
-Welcome ${who} to ${place}.
-</%def>
-
-${name} 是 ${msg}<br/>
-${welcome(u'你')}
diff --git a/test/templates/read_unicode.html b/test/templates/read_unicode.html
deleted file mode 100644
index 50f00c3..0000000
--- a/test/templates/read_unicode.html
+++ /dev/null
@@ -1,10 +0,0 @@
-<%
-try:
- file_content = open(path)
-except:
- raise "Should never execute here"
-doc_content = ''.join(file_content.readlines())
-file_content.close()
-%>
-
-${unicode(doc_content, encoding='utf-8')}
diff --git a/test/templates/runtimeerr.html b/test/templates/runtimeerr.html
deleted file mode 100644
index 6b36b95..0000000
--- a/test/templates/runtimeerr.html
+++ /dev/null
@@ -1,4 +0,0 @@
-<%
- print y
- y = 10
-%> \ No newline at end of file
diff --git a/test/templates/unicode_arguments.html b/test/templates/unicode_arguments.html
deleted file mode 100644
index e6d7c2c..0000000
--- a/test/templates/unicode_arguments.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-<%def name="my_def(x)">
- x is: ${x}
-</%def>
-
-${my_def(u'drôle de petite voix m’a réveillé')}
-<%self:my_def x='drôle de petite voix m’a réveillé'/>
-<%self:my_def x="${u'drôle de petite voix m’a réveillé'}"/>
-<%call expr="my_def(u'drôle de petite voix m’a réveillé')"/>
diff --git a/test/templates/unicode_code.html b/test/templates/unicode_code.html
deleted file mode 100644
index 700c043..0000000
--- a/test/templates/unicode_code.html
+++ /dev/null
@@ -1,7 +0,0 @@
-## -*- coding: utf-8 -*-
-<%
- x = u"drôle de petite voix m’a réveillé."
-%>
-% if x==u"drôle de petite voix m’a réveillé.":
- hi, ${x}
-% endif
diff --git a/test/templates/unicode_expr.html b/test/templates/unicode_expr.html
deleted file mode 100644
index cad7522..0000000
--- a/test/templates/unicode_expr.html
+++ /dev/null
@@ -1,2 +0,0 @@
-## -*- coding: utf-8 -*-
-${u"Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »"}
diff --git a/test/test_ast.py b/test/test_ast.py
index ce6c082..daa7c6e 100644
--- a/test/test_ast.py
+++ b/test/test_ast.py
@@ -1,12 +1,9 @@
import unittest
from mako import ast
-from mako import compat
from mako import exceptions
from mako import pyparser
from test import eq_
-from test import requires_python_2
-from test import requires_python_3
exception_kwargs = {"source": "", "lineno": 0, "pos": 0, "filename": ""}
@@ -132,7 +129,7 @@ import foo.bar
def test_locate_identifiers_8(self):
code = """
-class Hi(object):
+class Hi:
foo = 7
def hoho(self):
x = 5
@@ -187,7 +184,7 @@ def foo():
def test_locate_identifiers_13(self):
code = """
def foo():
- class Bat(object):
+ class Bat:
pass
Bat
"""
@@ -198,7 +195,7 @@ def foo():
def test_locate_identifiers_14(self):
code = """
def foo():
- class Bat(object):
+ class Bat:
pass
Bat
@@ -208,18 +205,6 @@ print(Bat)
eq_(parsed.declared_identifiers, set(["foo"]))
eq_(parsed.undeclared_identifiers, set(["Bat"]))
- @requires_python_2
- def test_locate_identifiers_15(self):
- code = """
-def t1((x,y)):
- return x+5, y+4
-
-t2 = lambda (x,y):(x+5, y+4)
-"""
- parsed = ast.PythonCode(code, **exception_kwargs)
- eq_(parsed.declared_identifiers, set(["t1", "t2"]))
- eq_(parsed.undeclared_identifiers, set())
-
def test_locate_identifiers_16(self):
code = """
try:
@@ -259,14 +244,9 @@ import x as bar
parsed = ast.PythonFragment("try:", **exception_kwargs)
- if compat.py3k:
- parsed = ast.PythonFragment(
- "except MyException as e:", **exception_kwargs
- )
- else:
- parsed = ast.PythonFragment(
- "except MyException, e:", **exception_kwargs
- )
+ parsed = ast.PythonFragment(
+ "except MyException as e:", **exception_kwargs
+ )
eq_(parsed.declared_identifiers, set(["e"]))
eq_(parsed.undeclared_identifiers, set(["MyException"]))
@@ -299,7 +279,6 @@ import x as bar
eq_(parsed.argnames, ["a", "b", "c", "args"])
eq_(parsed.kwargnames, ["kwargs"])
- @requires_python_3
def test_function_decl_3(self):
"""test getting the arguments from a fancy py3k function"""
code = "def foo(a, b, *c, d, e, **f):pass"
@@ -313,7 +292,7 @@ import x as bar
x = 1
y = 2
- class F(object):
+ class F:
def bar(self, a, b):
return a + b
diff --git a/test/test_cache.py b/test/test_cache.py
index d662872..7c6e3a5 100644
--- a/test/test_cache.py
+++ b/test/test_cache.py
@@ -4,7 +4,6 @@ import unittest
from mako import lookup
from mako.cache import CacheImpl
from mako.cache import register_plugin
-from mako.compat import py27
from mako.ext import beaker_cache
from mako.lookup import TemplateLookup
from mako.template import Template
@@ -17,7 +16,7 @@ if beaker_cache.has_beaker:
import beaker
-class SimpleBackend(object):
+class SimpleBackend:
def __init__(self):
self.cache = {}
@@ -601,7 +600,7 @@ class CacheTest(TemplateTest):
assert m.kwargs["context"].get("x") == "bar"
-class RealBackendTest(object):
+class RealBackendTest:
def test_cache_uses_current_context(self):
t = Template(
"""
@@ -650,8 +649,6 @@ class BeakerCacheTest(RealBackendTest, CacheTest):
def setUp(self):
if not beaker_cache.has_beaker:
raise unittest.SkipTest("Beaker is required for these tests.")
- if not py27:
- raise unittest.SkipTest("newer beakers not working w/ py26")
def _install_mock_cache(self, template, implname=None):
template.cache_args["manager"] = self._regions()
diff --git a/test/test_cmd.py b/test/test_cmd.py
index ac0db25..0dfa378 100644
--- a/test/test_cmd.py
+++ b/test/test_cmd.py
@@ -1,5 +1,3 @@
-from __future__ import with_statement
-
from contextlib import contextmanager
import os
diff --git a/test/test_def.py b/test/test_def.py
index 99b929d..6505c1f 100644
--- a/test/test_def.py
+++ b/test/test_def.py
@@ -1,9 +1,7 @@
-from mako import compat
from mako import lookup
from mako.template import Template
from test import assert_raises
from test import eq_
-from test import requires_python_3
from test import TemplateTest
from test.util import flatten_result
from test.util import result_lines
@@ -49,7 +47,6 @@ class DefTest(TemplateTest):
"""hello mycomp hi, 5, 6""",
)
- @requires_python_3
def test_def_py3k_args(self):
template = Template(
"""
@@ -86,12 +83,8 @@ class DefTest(TemplateTest):
"""
)
# check that "a" is declared in "b", but not in "c"
- if compat.py3k:
- assert "a" not in template.module.render_c.__code__.co_varnames
- assert "a" in template.module.render_b.__code__.co_varnames
- else:
- assert "a" not in template.module.render_c.func_code.co_varnames
- assert "a" in template.module.render_b.func_code.co_varnames
+ assert "a" not in template.module.render_c.__code__.co_varnames
+ assert "a" in template.module.render_b.__code__.co_varnames
# then test output
eq_(flatten_result(template.render()), "im b and heres a: im a")
diff --git a/test/test_exceptions.py b/test/test_exceptions.py
index 2ec46cf..b0e2bb1 100644
--- a/test/test_exceptions.py
+++ b/test/test_exceptions.py
@@ -1,9 +1,7 @@
# -*- coding: utf-8 -*-
import sys
-from mako import compat
from mako import exceptions
-from mako.compat import u
from mako.lookup import TemplateLookup
from mako.template import Template
from test import requires_no_pygments_exceptions
@@ -68,53 +66,29 @@ class ExceptionsTest(TemplateTest):
"""test the html_error_template with a Template containing UTF-8
chars"""
- if compat.py3k:
- code = """# -*- coding: utf-8 -*-
+ code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${'привет'}
% endif
"""
- else:
- code = """# -*- coding: utf-8 -*-
-% if 2 == 2: /an error
-${u'привет'}
-% endif
-"""
try:
template = Template(code)
template.render_unicode()
except exceptions.CompileException:
html_error = exceptions.html_error_template().render()
- if compat.py3k:
- assert (
- (
- "CompileException: Fragment &#39;if 2 == 2: /an "
- "error&#39; is not a partial control statement "
- "at line: 2 char: 1"
- ).encode(sys.getdefaultencoding(), "htmlentityreplace")
- in html_error
- )
- else:
- assert (
+ assert (
+ (
"CompileException: Fragment &#39;if 2 == 2: /an "
"error&#39; is not a partial control statement "
"at line: 2 char: 1"
- ) in html_error
+ ).encode(sys.getdefaultencoding(), "htmlentityreplace")
+ in html_error
+ )
- if compat.py3k:
- assert (
- "".encode(sys.getdefaultencoding(), "htmlentityreplace")
- in html_error
- )
- else:
- assert (
- "&#39;"
- "&#x43F;&#x440;&#x438;&#x432;&#x435;&#x442;"
- '&#39;</span><span class="cp">}</span>'.encode(
- sys.getdefaultencoding(), "htmlentityreplace"
- )
- in html_error
- )
+ assert (
+ "".encode(sys.getdefaultencoding(), "htmlentityreplace")
+ in html_error
+ )
else:
assert False, (
"This function should trigger a CompileException, "
@@ -126,53 +100,30 @@ ${u'привет'}
"""test the html_error_template with a Template containing UTF-8
chars"""
- if compat.py3k:
- code = """# -*- coding: utf-8 -*-
+ code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${'привет'}
% endif
"""
- else:
- code = """# -*- coding: utf-8 -*-
-% if 2 == 2: /an error
-${u'привет'}
-% endif
-"""
try:
template = Template(code)
template.render_unicode()
except exceptions.CompileException:
html_error = exceptions.html_error_template().render()
- if compat.py3k:
- assert (
- (
- "CompileException: Fragment &#39;if 2 == 2: /an "
- "error&#39; is not a partial control statement "
- "at line: 2 char: 1"
- ).encode(sys.getdefaultencoding(), "htmlentityreplace")
- in html_error
- )
- else:
- assert (
+ assert (
+ (
"CompileException: Fragment &#39;if 2 == 2: /an "
"error&#39; is not a partial control statement "
"at line: 2 char: 1"
- ) in html_error
-
- if compat.py3k:
- assert (
- "${&#39;привет&#39;}".encode(
- sys.getdefaultencoding(), "htmlentityreplace"
- )
- in html_error
- )
- else:
- assert (
- u("${u&#39;привет&#39;}").encode(
- sys.getdefaultencoding(), "htmlentityreplace"
- )
- in html_error
+ ).encode(sys.getdefaultencoding(), "htmlentityreplace")
+ in html_error
+ )
+ assert (
+ "${&#39;привет&#39;}".encode(
+ sys.getdefaultencoding(), "htmlentityreplace"
)
+ in html_error
+ )
else:
assert False, (
"This function should trigger a CompileException, "
@@ -189,29 +140,22 @@ ${u'привет'}
def test_py_utf8_html_error_template(self):
try:
- foo = u("日本") # noqa
+ foo = "日本" # noqa
raise RuntimeError("test")
except:
html_error = exceptions.html_error_template().render()
- if compat.py3k:
- assert "RuntimeError: test" in html_error.decode("utf-8")
- assert "foo = u(&quot;日本&quot;)" in html_error.decode(
- "utf-8"
- ) or "foo = u(&#34;日本&#34;)" in html_error.decode("utf-8")
- else:
- assert "RuntimeError: test" in html_error
- assert (
- "foo = u(&quot;&#x65E5;&#x672C;&quot;)" in html_error
- or "foo = u(&#34;&#x65E5;&#x672C;&#34;)" in html_error
- )
+ assert "RuntimeError: test" in html_error.decode("utf-8")
+ assert "foo = &quot;日本&quot;" in html_error.decode(
+ "utf-8"
+ ) or "foo = &#34;日本&#34;" in html_error.decode("utf-8")
def test_py_unicode_error_html_error_template(self):
try:
- raise RuntimeError(u("日本"))
+ raise RuntimeError("日本")
except:
html_error = exceptions.html_error_template().render()
assert (
- u("RuntimeError: 日本").encode("ascii", "ignore") in html_error
+ "RuntimeError: 日本".encode("ascii", "ignore") in html_error
)
@requires_pygments_14
@@ -267,25 +211,13 @@ ${foobar}
exceptions reported with format_exceptions=True"""
l = TemplateLookup(format_exceptions=True)
- if compat.py3k:
- l.put_string(
- "foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}"""
- )
- else:
- l.put_string(
- "foo.html",
- """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""",
- )
+ l.put_string(
+ "foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}"""
+ )
- if compat.py3k:
- assert "&#39;привет&#39;</span>" in l.get_template(
- "foo.html"
- ).render().decode("utf-8")
- else:
- assert (
- "&#39;&#x43F;&#x440;&#x438;&#x432;"
- "&#x435;&#x442;&#39;</span>"
- ) in l.get_template("foo.html").render().decode("utf-8")
+ assert "&#39;привет&#39;</span>" in l.get_template(
+ "foo.html"
+ ).render().decode("utf-8")
@requires_no_pygments_exceptions
def test_utf8_format_exceptions_no_pygments(self):
@@ -293,31 +225,16 @@ ${foobar}
exceptions reported with format_exceptions=True"""
l = TemplateLookup(format_exceptions=True)
- if compat.py3k:
- l.put_string(
- "foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}"""
- )
- else:
- l.put_string(
- "foo.html",
- """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""",
- )
+ l.put_string(
+ "foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}"""
+ )
- if compat.py3k:
- assert (
- '<div class="sourceline">${&#39;привет&#39; + foobar}</div>'
- in result_lines(
- l.get_template("foo.html").render().decode("utf-8")
- )
- )
- else:
- assert (
- "${u&#39;&#x43F;&#x440;&#x438;&#x432;&#x435;"
- "&#x442;&#39; + foobar}"
- in result_lines(
- l.get_template("foo.html").render().decode("utf-8")
- )
+ assert (
+ '<div class="sourceline">${&#39;привет&#39; + foobar}</div>'
+ in result_lines(
+ l.get_template("foo.html").render().decode("utf-8")
)
+ )
def test_mod_no_encoding(self):
@@ -358,10 +275,6 @@ ${foobar}
except:
t, v, tback = sys.exc_info()
- if not compat.py3k:
- # blow away tracebaack info
- sys.exc_clear()
-
# and don't even send what we have.
html_error = exceptions.html_error_template().render_unicode(
error=v, traceback=None
@@ -457,7 +370,8 @@ def broken():
t.render()
except:
text_error = exceptions.text_error_template().render_unicode()
- assert """
+ assert (
+ """
File "base.html", line 5, in render_body
%> body starts here
File "foo.html", line 4, in render_foo
@@ -466,6 +380,8 @@ def broken():
${broken()}
File "base.html", line 4, in broken
raise RuntimeError("Something went wrong.")
-""" in text_error
+"""
+ in text_error
+ )
else:
assert False
diff --git a/test/test_filters.py b/test/test_filters.py
index a58a01f..4def5f8 100644
--- a/test/test_filters.py
+++ b/test/test_filters.py
@@ -2,11 +2,8 @@
import unittest
-from mako import compat
-from mako.compat import u
from mako.template import Template
from test import eq_
-from test import requires_python_2
from test import TemplateTest
from test.util import flatten_result
from test.util import result_lines
@@ -88,36 +85,6 @@ class FilterTest(TemplateTest):
"foo &lt;'some bar'&gt;",
)
- @requires_python_2
- def test_quoting_non_unicode(self):
- t = Template(
- """
- foo ${bar | h}
- """,
- disable_unicode=True,
- output_encoding=None,
- )
-
- eq_(
- flatten_result(t.render(bar="<'привет'>")),
- "foo &lt;&#39;привет&#39;&gt;",
- )
-
- @requires_python_2
- def test_url_escaping_non_unicode(self):
- t = Template(
- """
- http://example.com/?bar=${bar | u}&v=1
- """,
- disable_unicode=True,
- output_encoding=None,
- )
-
- eq_(
- flatten_result(t.render(bar="酒吧bar")),
- "http://example.com/?bar=%E9%85%92%E5%90%A7bar&v=1",
- )
-
def test_def(self):
t = Template(
"""
@@ -176,8 +143,8 @@ class FilterTest(TemplateTest):
default_filters=["decode.utf8"],
)
eq_(
- t.render_unicode(x=u("voix m’a réveillé")).strip(),
- u("some stuff.... voix m’a réveillé"),
+ t.render_unicode(x="voix m’a réveillé").strip(),
+ "some stuff.... voix m’a réveillé",
)
def test_encode_filter_non_str(self):
@@ -187,21 +154,7 @@ class FilterTest(TemplateTest):
""",
default_filters=["decode.utf8"],
)
- eq_(t.render_unicode(x=3).strip(), u("some stuff.... 3"))
-
- @requires_python_2
- def test_encode_filter_non_str_we_return_bytes(self):
- class Foo(object):
- def __str__(self):
- return compat.b("å")
-
- t = Template(
- """# coding: utf-8
- some stuff.... ${x}
- """,
- default_filters=["decode.utf8"],
- )
- eq_(t.render_unicode(x=Foo()).strip(), u("some stuff.... å"))
+ eq_(t.render_unicode(x=3).strip(), "some stuff.... 3")
def test_custom_default(self):
t = Template(
@@ -347,7 +300,7 @@ data = {a: ${123}, b: ${"123"}};
t = Template(
"""
<%!
- class Foo(object):
+ class Foo:
foo = True
def __str__(self):
return "this is a"
diff --git a/test/test_inheritance.py b/test/test_inheritance.py
index e8ed74e..7217e33 100644
--- a/test/test_inheritance.py
+++ b/test/test_inheritance.py
@@ -1,6 +1,5 @@
import unittest
-from mako import compat
from mako import lookup
from test.util import result_lines
@@ -257,22 +256,13 @@ ${next.body()}
""",
)
- if compat.py3k:
- assert result_lines(
- collection.get_template("index").render_unicode(x=5, y=10)
- ) == [
- "this is the base.",
- "pageargs: (type: <class 'dict'>) [('x', 5), ('y', 10)]",
- "print 5, 10, 7",
- ]
- else:
- assert result_lines(
- collection.get_template("index").render_unicode(x=5, y=10)
- ) == [
- "this is the base.",
- "pageargs: (type: <type 'dict'>) [('x', 5), ('y', 10)]",
- "print 5, 10, 7",
- ]
+ assert result_lines(
+ collection.get_template("index").render_unicode(x=5, y=10)
+ ) == [
+ "this is the base.",
+ "pageargs: (type: <class 'dict'>) [('x', 5), ('y', 10)]",
+ "print 5, 10, 7",
+ ]
def test_pageargs_2(self):
collection = lookup.TemplateLookup()
diff --git a/test/test_lexer.py b/test/test_lexer.py
index 9807961..2dbd924 100644
--- a/test/test_lexer.py
+++ b/test/test_lexer.py
@@ -25,13 +25,12 @@ def repr_arg(x):
def _as_unicode(arg):
- if isinstance(arg, compat.string_types):
- return compat.text_type(arg)
- elif isinstance(arg, dict):
- return dict((_as_unicode(k), _as_unicode(v)) for k, v in arg.items())
+ if isinstance(arg, dict):
+ return dict((k, _as_unicode(v)) for k, v in arg.items())
else:
return arg
+
Node = None
TemplateNode = None
ControlLine = None
@@ -59,7 +58,7 @@ for cls in list(parsetree.__dict__.values()):
exec(
(
"""
-class %s(object):
+class %s:
def __init__(self, *args):
self.args = [_as_unicode(arg) for arg in args]
def __repr__(self):
@@ -247,7 +246,7 @@ class LexerTest(TemplateTest):
" % more code\n "
"<%illegal compionent>/></>\n"
' <%def name="laal()">def</%def>'
- '\n\n\n ',
+ "\n\n\n ",
(6, 16),
)
],
@@ -515,10 +514,8 @@ class LexerTest(TemplateTest):
),
)
- if compat.py3k:
-
- def test_code(self):
- template = """text
+ def test_code(self):
+ template = """text
<%
print("hi")
for x in range(1,5):
@@ -529,59 +526,25 @@ more text
import foo
%>
"""
- nodes = Lexer(template).parse()
- self._compare(
- nodes,
- TemplateNode(
- {},
- [
- Text("text\n ", (1, 1)),
- Code(
- '\nprint("hi")\nfor x in range(1,5):\n '
- "print(x)\n \n",
- False,
- (2, 5),
- ),
- Text("\nmore text\n ", (6, 7)),
- Code("\nimport foo\n \n", True, (8, 5)),
- Text("\n", (10, 7)),
- ],
- ),
- )
-
- else:
-
- def test_code(self):
- template = """text
- <%
- print "hi"
- for x in range(1,5):
- print x
- %>
-more text
- <%!
- import foo
- %>
-"""
- nodes = Lexer(template).parse()
- self._compare(
- nodes,
- TemplateNode(
- {},
- [
- Text("text\n ", (1, 1)),
- Code(
- '\nprint "hi"\nfor x in range(1,5):\n '
- "print x\n \n",
- False,
- (2, 5),
- ),
- Text("\nmore text\n ", (6, 7)),
- Code("\nimport foo\n \n", True, (8, 5)),
- Text("\n", (10, 7)),
- ],
- ),
- )
+ nodes = Lexer(template).parse()
+ self._compare(
+ nodes,
+ TemplateNode(
+ {},
+ [
+ Text("text\n ", (1, 1)),
+ Code(
+ '\nprint("hi")\nfor x in range(1,5):\n '
+ "print(x)\n \n",
+ False,
+ (2, 5),
+ ),
+ Text("\nmore text\n ", (6, 7)),
+ Code("\nimport foo\n \n", True, (8, 5)),
+ Text("\n", (10, 7)),
+ ],
+ ),
+ )
def test_code_and_tags(self):
template = """
@@ -741,20 +704,11 @@ more text
)
def test_tricky_code(self):
- if compat.py3k:
- template = """<% print('hi %>') %>"""
- nodes = Lexer(template).parse()
- self._compare(
- nodes,
- TemplateNode({}, [Code("print('hi %>') \n", False, (1, 1))]),
- )
- else:
- template = """<% print 'hi %>' %>"""
- nodes = Lexer(template).parse()
- self._compare(
- nodes,
- TemplateNode({}, [Code("print 'hi %>' \n", False, (1, 1))]),
- )
+ template = """<% print('hi %>') %>"""
+ nodes = Lexer(template).parse()
+ self._compare(
+ nodes, TemplateNode({}, [Code("print('hi %>') \n", False, (1, 1))])
+ )
def test_tricky_code_2(self):
template = """<%
@@ -780,77 +734,42 @@ more text
),
)
- if compat.py3k:
-
- def test_tricky_code_3(self):
- template = """<%
- print('hi')
- # this is a comment
- # another comment
- x = 7 # someone's '''comment
- print('''
- there
- ''')
- # someone else's comment
+ def test_tricky_code_3(self):
+ template = """<%
+ print('hi')
+ # this is a comment
+ # another comment
+ x = 7 # someone's '''comment
+ print('''
+ there
+ ''')
+ # someone else's comment
%> '''and now some text '''"""
- nodes = Lexer(template).parse()
- self._compare(
- nodes,
- TemplateNode(
- {},
- [
- Code(
- """
+ nodes = Lexer(template).parse()
+ self._compare(
+ nodes,
+ TemplateNode(
+ {},
+ [
+ Code(
+ """
print('hi')
# this is a comment
# another comment
x = 7 # someone's '''comment
print('''
- there
- ''')
+ there
+ ''')
# someone else's comment
""",
- False,
- (1, 1),
- ),
- Text(" '''and now some text '''", (10, 3)),
- ],
- ),
- )
-
- else:
-
- def test_tricky_code_3(self):
- template = """<%
- print 'hi'
- # this is a comment
- # another comment
- x = 7 # someone's '''comment
- print '''
- there
- '''
- # someone else's comment
-%> '''and now some text '''"""
- nodes = Lexer(template).parse()
- self._compare(
- nodes,
- TemplateNode(
- {},
- [
- Code(
- """\nprint 'hi'\n# this is a comment\n"""
- """# another comment\nx = 7 """
- """# someone's '''comment\nprint '''\n """
- """there\n '''\n# someone else's """
- """comment\n\n""",
- False,
- (1, 1),
- ),
- Text(" '''and now some text '''", (10, 3)),
- ],
- ),
- )
+ False,
+ (1, 1),
+ ),
+ Text(" '''and now some text '''", (10, 3)),
+ ],
+ ),
+ )
def test_tricky_code_4(self):
template = """<% foo = "\\"\\\\" %>"""
diff --git a/test/test_pygen.py b/test/test_pygen.py
index daa76de..b8c11db 100644
--- a/test/test_pygen.py
+++ b/test/test_pygen.py
@@ -1,6 +1,6 @@
+from io import StringIO
import unittest
-from mako.compat import StringIO
from mako.pygen import adjust_whitespace
from mako.pygen import PythonPrinter
from test import eq_
diff --git a/test/test_template.py b/test/test_template.py
index f9727be..4b0d271 100644
--- a/test/test_template.py
+++ b/test/test_template.py
@@ -3,11 +3,9 @@
import os
import unittest
-from mako import compat
from mako import exceptions
from mako import runtime
from mako import util
-from mako.compat import u
from mako.ext.preprocessors import convert_comments
from mako.lookup import TemplateLookup
from mako.template import ModuleInfo
@@ -17,14 +15,13 @@ from test import assert_raises
from test import assert_raises_message
from test import eq_
from test import module_base
-from test import requires_python_2
from test import template_base
from test import TemplateTest
from test.util import flatten_result
from test.util import result_lines
-class ctx(object):
+class ctx:
def __init__(self, a, b):
pass
@@ -51,34 +48,23 @@ class EncodingTest(TemplateTest):
except:
# <h3>Exception: <span style="color:red">Foobar</span></h3>
markup = html_error_template().render(full=False, css=False)
- if compat.py3k:
- assert (
- '<span style="color:red">Foobar</span></h3>'.encode(
- "ascii"
- )
- not in markup
- )
- assert (
- "&lt;span style=&#34;color:red&#34;"
- "&gt;Foobar&lt;/span&gt;".encode("ascii") in markup
- )
- else:
- assert (
- '<span style="color:red">Foobar</span></h3>' not in markup
- )
- assert (
- "&lt;span style=&#34;color:red&#34;"
- "&gt;Foobar&lt;/span&gt;" in markup
- )
+ assert (
+ '<span style="color:red">Foobar</span></h3>'.encode("ascii")
+ not in markup
+ )
+ assert (
+ "&lt;span style=&#34;color:red&#34;"
+ "&gt;Foobar&lt;/span&gt;".encode("ascii") in markup
+ )
def test_unicode(self):
self._do_memory_test(
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
),
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -87,12 +73,12 @@ class EncodingTest(TemplateTest):
def test_encoding_doesnt_conflict(self):
self._do_memory_test(
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
),
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -101,14 +87,14 @@ class EncodingTest(TemplateTest):
)
def test_unicode_arg(self):
- val = u(
+ val = (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
)
self._do_memory_test(
"${val}",
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -119,7 +105,7 @@ class EncodingTest(TemplateTest):
def test_unicode_file(self):
self._do_file_test(
"unicode.html",
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -129,7 +115,7 @@ class EncodingTest(TemplateTest):
def test_unicode_file_code(self):
self._do_file_test(
"unicode_code.html",
- u("""hi, drôle de petite voix m’a réveillé."""),
+ ("""hi, drôle de petite voix m’a réveillé."""),
filters=flatten_result,
)
@@ -139,19 +125,16 @@ class EncodingTest(TemplateTest):
output_encoding="utf-8",
default_filters=["decode.utf8"],
)
- if compat.py3k:
- template = lookup.get_template("/chs_unicode_py3k.html")
- else:
- template = lookup.get_template("/chs_unicode.html")
+ template = lookup.get_template("/chs_unicode_py3k.html")
eq_(
flatten_result(template.render_unicode(name="毛泽东")),
- u("毛泽东 是 新中国的主席<br/> Welcome 你 to 北京."),
+ ("毛泽东 是 新中国的主席<br/> Welcome 你 to 北京."),
)
def test_unicode_bom(self):
self._do_file_test(
"bom.html",
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -160,7 +143,7 @@ class EncodingTest(TemplateTest):
self._do_file_test(
"bommagic.html",
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -175,14 +158,14 @@ class EncodingTest(TemplateTest):
)
def test_unicode_memory(self):
- val = u(
+ val = (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
)
self._do_memory_test(
("## -*- coding: utf-8 -*-\n" + val).encode("utf-8"),
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -190,14 +173,14 @@ class EncodingTest(TemplateTest):
)
def test_unicode_text(self):
- val = u(
+ val = (
"<%text>Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »</%text>"
)
self._do_memory_test(
("## -*- coding: utf-8 -*-\n" + val).encode("utf-8"),
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -205,7 +188,7 @@ class EncodingTest(TemplateTest):
)
def test_unicode_text_ccall(self):
- val = u(
+ val = (
"""
<%def name="foo()">
${capture(caller.body)}
@@ -218,7 +201,7 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
)
self._do_memory_test(
("## -*- coding: utf-8 -*-\n" + val).encode("utf-8"),
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -227,43 +210,26 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
)
def test_unicode_literal_in_expr(self):
- if compat.py3k:
- self._do_memory_test(
- u(
- "## -*- coding: utf-8 -*-\n"
- '${"Alors vous imaginez ma surprise, au lever du jour, '
- "quand une drôle de petite voix m’a réveillé. "
- "Elle disait: "
- '« S’il vous plaît… dessine-moi un mouton! »"}\n'
- ).encode("utf-8"),
- u(
- "Alors vous imaginez ma surprise, au lever du jour, "
- "quand une drôle de petite voix m’a réveillé. "
- "Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
- ),
- filters=lambda s: s.strip(),
- )
- else:
- self._do_memory_test(
- u(
- "## -*- coding: utf-8 -*-\n"
- '${u"Alors vous imaginez ma surprise, au lever du jour, '
- "quand une drôle de petite voix m’a réveillé. "
- "Elle disait: « S’il vous plaît… dessine-moi un "
- 'mouton! »"}'
- ).encode("utf-8"),
- u(
- "Alors vous imaginez ma surprise, au lever du jour, "
- "quand une drôle de petite voix m’a réveillé. "
- "Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
- ),
- filters=lambda s: s.strip(),
- )
+ self._do_memory_test(
+ (
+ "## -*- coding: utf-8 -*-\n"
+ '${"Alors vous imaginez ma surprise, au lever du jour, '
+ "quand une drôle de petite voix m’a réveillé. "
+ "Elle disait: "
+ '« S’il vous plaît… dessine-moi un mouton! »"}\n'
+ ).encode("utf-8"),
+ (
+ "Alors vous imaginez ma surprise, au lever du jour, "
+ "quand une drôle de petite voix m’a réveillé. "
+ "Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
+ ),
+ filters=lambda s: s.strip(),
+ )
def test_unicode_literal_in_expr_file(self):
self._do_file_test(
"unicode_expr.html",
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, "
"quand une drôle de petite voix m’a réveillé. "
"Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
@@ -272,85 +238,49 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
)
def test_unicode_literal_in_code(self):
- if compat.py3k:
- self._do_memory_test(
- u(
- """## -*- coding: utf-8 -*-
- <%
- context.write("Alors vous imaginez ma surprise, au """
- """lever du jour, quand une drôle de petite voix m’a """
- """réveillé. Elle disait: """
- """« S’il vous plaît… dessine-moi un mouton! »")
- %>
- """
- ).encode("utf-8"),
- u(
- "Alors vous imaginez ma surprise, au lever du jour, "
- "quand une drôle de petite voix m’a réveillé. "
- "Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
- ),
- filters=lambda s: s.strip(),
- )
- else:
- self._do_memory_test(
- u(
- """## -*- coding: utf-8 -*-
- <%
- context.write(u"Alors vous imaginez ma surprise, """
- """au lever du jour, quand une drôle de petite voix """
- """m’a réveillé. Elle disait: « S’il vous plaît… """
- """dessine-moi un mouton! »")
- %>
- """
- ).encode("utf-8"),
- u(
- "Alors vous imaginez ma surprise, au lever du jour, "
- "quand une drôle de petite voix m’a réveillé. "
- "Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
- ),
- filters=lambda s: s.strip(),
- )
+ self._do_memory_test(
+ (
+ """## -*- coding: utf-8 -*-
+ <%
+ context.write("Alors vous imaginez ma surprise, au """
+ """lever du jour, quand une drôle de petite voix m’a """
+ """réveillé. Elle disait: """
+ """« S’il vous plaît… dessine-moi un mouton! »")
+ %>
+ """
+ ).encode("utf-8"),
+ (
+ "Alors vous imaginez ma surprise, au lever du jour, "
+ "quand une drôle de petite voix m’a réveillé. "
+ "Elle disait: « S’il vous plaît… dessine-moi un mouton! »"
+ ),
+ filters=lambda s: s.strip(),
+ )
def test_unicode_literal_in_controlline(self):
- if compat.py3k:
- self._do_memory_test(
- u(
- """## -*- coding: utf-8 -*-
- <%
- x = "drôle de petite voix m’a réveillé."
- %>
- % if x=="drôle de petite voix m’a réveillé.":
- hi, ${x}
- % endif
- """
- ).encode("utf-8"),
- u("""hi, drôle de petite voix m’a réveillé."""),
- filters=lambda s: s.strip(),
- )
- else:
- self._do_memory_test(
- u(
- """## -*- coding: utf-8 -*-
- <%
- x = u"drôle de petite voix m’a réveillé."
- %>
- % if x==u"drôle de petite voix m’a réveillé.":
- hi, ${x}
- % endif
- """
- ).encode("utf-8"),
- u("""hi, drôle de petite voix m’a réveillé."""),
- filters=lambda s: s.strip(),
- )
+ self._do_memory_test(
+ (
+ """## -*- coding: utf-8 -*-
+ <%
+ x = "drôle de petite voix m’a réveillé."
+ %>
+ % if x=="drôle de petite voix m’a réveillé.":
+ hi, ${x}
+ % endif
+ """
+ ).encode("utf-8"),
+ ("""hi, drôle de petite voix m’a réveillé."""),
+ filters=lambda s: s.strip(),
+ )
def test_unicode_literal_in_tag(self):
self._do_file_test(
"unicode_arguments.html",
[
- u("x is: drôle de petite voix m’a réveillé"),
- u("x is: drôle de petite voix m’a réveillé"),
- u("x is: drôle de petite voix m’a réveillé"),
- u("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
],
filters=result_lines,
)
@@ -358,116 +288,66 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
self._do_memory_test(
util.read_file(self._file_path("unicode_arguments.html")),
[
- u("x is: drôle de petite voix m’a réveillé"),
- u("x is: drôle de petite voix m’a réveillé"),
- u("x is: drôle de petite voix m’a réveillé"),
- u("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
+ ("x is: drôle de petite voix m’a réveillé"),
],
filters=result_lines,
)
def test_unicode_literal_in_def(self):
- if compat.py3k:
- self._do_memory_test(
- u(
- """## -*- coding: utf-8 -*-
- <%def name="bello(foo, bar)">
- Foo: ${ foo }
- Bar: ${ bar }
- </%def>
- <%call expr="bello(foo='árvíztűrő tükörfúrógép', """
- """bar='ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP')">
- </%call>"""
- ).encode("utf-8"),
- u(
- """Foo: árvíztűrő tükörfúrógép """
- """Bar: ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"""
- ),
- filters=flatten_result,
- )
-
- self._do_memory_test(
- u(
- "## -*- coding: utf-8 -*-\n"
- """<%def name="hello(foo='árvíztűrő tükörfúrógép', """
- """bar='ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP')">\n"""
- "Foo: ${ foo }\n"
- "Bar: ${ bar }\n"
- "</%def>\n"
- "${ hello() }"
- ).encode("utf-8"),
- u(
- """Foo: árvíztűrő tükörfúrógép Bar: """
- """ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"""
- ),
- filters=flatten_result,
- )
- else:
- self._do_memory_test(
- u(
- """## -*- coding: utf-8 -*-
- <%def name="bello(foo, bar)">
- Foo: ${ foo }
- Bar: ${ bar }
- </%def>
- <%call expr="bello(foo=u'árvíztűrő tükörfúrógép', """
- """bar=u'ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP')">
- </%call>"""
- ).encode("utf-8"),
- u(
- """Foo: árvíztűrő tükörfúrógép Bar: """
- """ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"""
- ),
- filters=flatten_result,
- )
+ self._do_memory_test(
+ (
+ """## -*- coding: utf-8 -*-
+ <%def name="bello(foo, bar)">
+ Foo: ${ foo }
+ Bar: ${ bar }
+ </%def>
+ <%call expr="bello(foo='árvíztűrő tükörfúrógép', """
+ """bar='ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP')">
+ </%call>"""
+ ).encode("utf-8"),
+ (
+ """Foo: árvíztűrő tükörfúrógép """
+ """Bar: ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"""
+ ),
+ filters=flatten_result,
+ )
- self._do_memory_test(
- u(
- """## -*- coding: utf-8 -*-
- <%def name="hello(foo=u'árvíztűrő tükörfúrógép', """
- """bar=u'ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP')">
- Foo: ${ foo }
- Bar: ${ bar }
- </%def>
- ${ hello() }"""
- ).encode("utf-8"),
- u(
- """Foo: árvíztűrő tükörfúrógép Bar: """
- """ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"""
- ),
- filters=flatten_result,
- )
+ self._do_memory_test(
+ (
+ "## -*- coding: utf-8 -*-\n"
+ """<%def name="hello(foo='árvíztűrő tükörfúrógép', """
+ """bar='ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP')">\n"""
+ "Foo: ${ foo }\n"
+ "Bar: ${ bar }\n"
+ "</%def>\n"
+ "${ hello() }"
+ ).encode("utf-8"),
+ (
+ """Foo: árvíztűrő tükörfúrógép Bar: """
+ """ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"""
+ ),
+ filters=flatten_result,
+ )
def test_input_encoding(self):
"""test the 'input_encoding' flag on Template, and that unicode
objects arent double-decoded"""
- if compat.py3k:
- self._do_memory_test(
- u("hello ${f('śląsk')}"),
- u("hello śląsk"),
- input_encoding="utf-8",
- template_args={"f": lambda x: x},
- )
-
- self._do_memory_test(
- u("## -*- coding: utf-8 -*-\nhello ${f('śląsk')}"),
- u("hello śląsk"),
- template_args={"f": lambda x: x},
- )
- else:
- self._do_memory_test(
- u("hello ${f(u'śląsk')}"),
- u("hello śląsk"),
- input_encoding="utf-8",
- template_args={"f": lambda x: x},
- )
+ self._do_memory_test(
+ ("hello ${f('śląsk')}"),
+ ("hello śląsk"),
+ input_encoding="utf-8",
+ template_args={"f": lambda x: x},
+ )
- self._do_memory_test(
- u("## -*- coding: utf-8 -*-\nhello ${f(u'śląsk')}"),
- u("hello śląsk"),
- template_args={"f": lambda x: x},
- )
+ self._do_memory_test(
+ ("## -*- coding: utf-8 -*-\nhello ${f('śląsk')}"),
+ ("hello śląsk"),
+ template_args={"f": lambda x: x},
+ )
def test_raw_strings(self):
"""test that raw strings go straight thru with default_filters
@@ -476,7 +356,7 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
"""
self._do_memory_test(
- u("## -*- coding: utf-8 -*-\nhello ${x}"),
+ ("## -*- coding: utf-8 -*-\nhello ${x}"),
"hello śląsk",
default_filters=[],
template_args={"x": "śląsk"},
@@ -487,19 +367,19 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
# now, the way you *should* be doing it....
self._do_memory_test(
- u("## -*- coding: utf-8 -*-\nhello ${x}"),
- u("hello śląsk"),
- template_args={"x": u("śląsk")},
+ ("## -*- coding: utf-8 -*-\nhello ${x}"),
+ ("hello śląsk"),
+ template_args={"x": ("śląsk")},
)
def test_encoding(self):
self._do_memory_test(
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
),
- u(
+ (
"Alors vous imaginez ma surprise, au lever du jour, quand "
"une drôle de petite voix m’a réveillé. Elle disait: "
"« S’il vous plaît… dessine-moi un mouton! »"
@@ -510,13 +390,13 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
def test_encoding_errors(self):
self._do_memory_test(
- u(
+ (
"""KGB (transliteration of "КГБ") is the Russian-language """
"""abbreviation for Committee for State Security, """
"""(Russian: Комит́ет Госуд́арственной Безоп́асности """
"""(help·info); Komitet Gosudarstvennoy Bezopasnosti)"""
),
- u(
+ (
"""KGB (transliteration of "КГБ") is the Russian-language """
"""abbreviation for Committee for State Security, """
"""(Russian: Комит́ет Госуд́арственной Безоп́асности """
@@ -533,75 +413,13 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
filesystem_checks=True,
output_encoding="utf-8",
)
- if compat.py3k:
- template = lookup.get_template("/read_unicode_py3k.html")
- else:
- template = lookup.get_template("/read_unicode.html")
+ template = lookup.get_template("/read_unicode_py3k.html")
# TODO: I've no idea what encoding this file is, Python 3.1.2
# won't read the file even with open(...encoding='utf-8') unless
# errors is specified. or if there's some quirk in 3.1.2
# since I'm pretty sure this test worked with py3k when I wrote it.
template.render(path=self._file_path("internationalization.html"))
- @requires_python_2
- def test_bytestring_passthru(self):
- self._do_file_test(
- "chs_utf8.html",
- "毛泽东 是 新中国的主席<br/> Welcome 你 to 北京. Welcome 你 to 北京.",
- default_filters=[],
- disable_unicode=True,
- output_encoding=None,
- template_args={"name": "毛泽东"},
- filters=flatten_result,
- unicode_=False,
- )
-
- self._do_file_test(
- "chs_utf8.html",
- "毛泽东 是 新中国的主席<br/> Welcome 你 to 北京. Welcome 你 to 北京.",
- disable_unicode=True,
- output_encoding=None,
- template_args={"name": "毛泽东"},
- filters=flatten_result,
- unicode_=False,
- )
-
- template = self._file_template(
- "chs_utf8.html", output_encoding=None, disable_unicode=True
- )
- self.assertRaises(
- UnicodeDecodeError, template.render_unicode, name="毛泽东"
- )
-
- template = Template(
- "${'Alors vous imaginez ma surprise, au lever"
- " du jour, quand une drôle de petite voix m’a "
- "réveillé. Elle disait: « S’il vous plaît… "
- "dessine-moi un mouton! »'}",
- output_encoding=None,
- disable_unicode=True,
- input_encoding="utf-8",
- )
- assert (
- template.render() == "Alors vous imaginez ma surprise, "
- "au lever du jour, quand une drôle de petite "
- "voix m’a réveillé. Elle disait: « S’il vous "
- "plaît… dessine-moi un mouton! »"
- )
- template = Template(
- "${'Alors vous imaginez ma surprise, au "
- "lever du jour, quand une drôle de petite "
- "voix m’a réveillé. Elle disait: « S’il "
- "vous plaît… dessine-moi un mouton! »'}",
- input_encoding="utf8",
- output_encoding="utf8",
- disable_unicode=False,
- default_filters=[],
- )
- # raises because expression contains an encoded bytestring which cannot
- # be decoded
- self.assertRaises(UnicodeDecodeError, template.render)
-
class PageArgsTest(TemplateTest):
def test_basic(self):
@@ -1094,7 +912,7 @@ class ReservedNameTest(TemplateTest):
exceptions.NameConflictError,
r"Reserved words passed to render\(\): %s" % name,
Template("x").render,
- **{name: "foo"}
+ **{name: "foo"},
)
def test_names_in_template(self):
@@ -1361,13 +1179,13 @@ class RichTracebackTest(TemplateTest):
if memory:
if syntax:
- source = u(
+ source = (
'## coding: utf-8\n<% print "m’a réveillé. '
"Elle disait: « S’il vous plaît… dessine-moi "
"un mouton! » %>"
)
else:
- source = u(
+ source = (
'## coding: utf-8\n<% print u"m’a réveillé. '
"Elle disait: « S’il vous plaît… dessine-moi un "
'mouton! »" + str(5/0) %>'
@@ -1817,7 +1635,7 @@ class LexerTest(TemplateTest):
def _fixture(self):
from mako.parsetree import TemplateNode, Text
- class MyLexer(object):
+ class MyLexer:
encoding = "ascii"
def __init__(self, *arg, **kw):
diff --git a/test/test_tgplugin.py b/test/test_tgplugin.py
index df95d00..d69ddf9 100644
--- a/test/test_tgplugin.py
+++ b/test/test_tgplugin.py
@@ -1,4 +1,3 @@
-from mako import compat
from mako.ext.turbogears import TGPlugin
from test import template_base
from test import TemplateTest
@@ -48,5 +47,5 @@ class TestTGPlugin(TemplateTest):
"this is index"
]
assert result_lines(
- tl.render({}, template=compat.u("/index.html"))
+ tl.render({}, template=("/index.html"))
) == ["this is index"]
diff --git a/test/test_util.py b/test/test_util.py
index 319a8c4..78096c1 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -7,7 +7,6 @@ import unittest
from mako import compat
from mako import exceptions
from mako import util
-from mako.compat import u
from test import assert_raises_message
from test import eq_
from test import skip_if
@@ -30,7 +29,7 @@ class UtilTest(unittest.TestCase):
eq_(buf.getvalue(), "string c string d")
def test_fast_buffer_encoded(self):
- s = u("drôl m’a rée « S’il")
+ s = ("drôl m’a rée « S’il")
buf = util.FastEncodingBuffer(encoding="utf-8")
buf.write(s[0:10])
buf.write(s[10:])
@@ -39,7 +38,7 @@ class UtilTest(unittest.TestCase):
def test_read_file(self):
fn = os.path.join(os.path.dirname(__file__), "test_util.py")
data = util.read_file(fn, "rb")
- assert "test_util" in str(data) # str() for py3k
+ assert b"test_util" in data
@skip_if(lambda: compat.pypy, "Pypy does this differently")
def test_load_module(self):