summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFederico Caselli <cfederico87@gmail.com>2021-10-25 15:45:42 -0400
committersqla-tester <sqla-tester@sqlalchemy.org>2021-10-25 15:45:42 -0400
commit6055be01a1357ec3c13937c3aab28360b5e80ea3 (patch)
treeb846c03c14e14c597fcb7c57f51698c6868a9c25
parent03c65d63d1df5835695a96ab7909e7086ba3dcf3 (diff)
downloadmako-6055be01a1357ec3c13937c3aab28360b5e80ea3.tar.gz
update black and format
Closes: #342 Pull-request: https://github.com/sqlalchemy/mako/pull/342 Pull-request-sha: 21a068103481410cf4856fb07c19146dc684d460 Change-Id: I9027433ec23ee19c9d9a47015e0327acf409e2d8
-rw-r--r--.github/workflows/run-on-pr.yaml7
-rw-r--r--.pre-commit-config.yaml5
-rw-r--r--examples/bench/basic.py121
-rw-r--r--examples/bench/django/templatetags/bench.py5
-rw-r--r--examples/wsgi/run_wsgi.py52
-rw-r--r--mako/codegen.py10
-rw-r--r--mako/exceptions.py3
-rw-r--r--mako/lexer.py15
-rw-r--r--mako/lookup.py8
-rw-r--r--mako/parsetree.py6
-rw-r--r--mako/pygen.py4
-rw-r--r--mako/pyparser.py2
-rw-r--r--mako/runtime.py21
-rw-r--r--mako/template.py22
-rw-r--r--test/__init__.py9
-rw-r--r--test/ext/test_babelplugin.py4
-rw-r--r--test/ext/test_linguaplugin.py4
-rw-r--r--test/templates/foo/modtest.html.py17
-rw-r--r--test/templates/subdir/foo/modtest.html.py19
-rw-r--r--test/test_ast.py2
-rw-r--r--test/test_exceptions.py34
-rw-r--r--test/test_filters.py2
-rw-r--r--test/test_template.py21
-rw-r--r--test/test_tgplugin.py6
-rw-r--r--test/test_util.py2
-rw-r--r--tox.ini5
26 files changed, 229 insertions, 177 deletions
diff --git a/.github/workflows/run-on-pr.yaml b/.github/workflows/run-on-pr.yaml
index b916836..9b8b545 100644
--- a/.github/workflows/run-on-pr.yaml
+++ b/.github/workflows/run-on-pr.yaml
@@ -10,7 +10,7 @@ on:
jobs:
run-test:
- name: ${{ matrix.python-version }}-${{ matrix.os }}
+ name: ${{ matrix.python-version }}-${{ matrix.os }}-${{matrix.tox-env}}
runs-on: ${{ matrix.os }}
strategy:
# run this job using this matrix
@@ -19,6 +19,9 @@ jobs:
- "ubuntu-latest"
python-version:
- "3.10"
+ tox-env:
+ - ""
+ - "-e pep8"
fail-fast: false
@@ -40,4 +43,4 @@ jobs:
pip list
- name: Run tests
- run: tox \ No newline at end of file
+ run: tox ${{ matrix.tox-env }}
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index ffacfe7..9fd0eee 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -2,13 +2,12 @@
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/python/black
- rev: 19.3b0
+ rev: 21.9b0
hooks:
- id: black
- args: [-l 79]
- repo: https://github.com/sqlalchemyorg/zimports
- rev: v0.4.0
+ rev: v0.4.1
hooks:
- id: zimports
diff --git a/examples/bench/basic.py b/examples/bench/basic.py
index 15482f6..fc36527 100644
--- a/examples/bench/basic.py
+++ b/examples/bench/basic.py
@@ -1,11 +1,11 @@
# basic.py - basic benchmarks adapted from Genshi
# Copyright (C) 2006 Edgewall Software
# All rights reserved.
-#
+#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
-#
+#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
@@ -15,7 +15,7 @@
# 3. The name of the author may not be used to endorse or promote
# products derived from this software without specific prior
# written permission.
-#
+#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@@ -33,68 +33,102 @@ import sys
import timeit
-__all__ = ['mako', 'mako_inheritance', 'jinja2', 'jinja2_inheritance',
- 'cheetah', 'django', 'myghty', 'genshi', 'kid']
+__all__ = [
+ "mako",
+ "mako_inheritance",
+ "jinja2",
+ "jinja2_inheritance",
+ "cheetah",
+ "django",
+ "myghty",
+ "genshi",
+ "kid",
+]
# Templates content and constants
-TITLE = 'Just a test'
-USER = 'joe'
-ITEMS = ['Number %d' % num for num in range(1, 15)]
+TITLE = "Just a test"
+USER = "joe"
+ITEMS = ["Number %d" % num for num in range(1, 15)]
+
def genshi(dirname, verbose=False):
from genshi.template import TemplateLoader
+
loader = TemplateLoader([dirname], auto_reload=False)
- template = loader.load('template.html')
+ template = loader.load("template.html")
+
def render():
data = dict(title=TITLE, user=USER, items=ITEMS)
- return template.generate(**data).render('xhtml')
+ return template.generate(**data).render("xhtml")
if verbose:
print(render())
return render
+
def myghty(dirname, verbose=False):
from myghty import interp
+
interpreter = interp.Interpreter(component_root=dirname)
+
def render():
data = dict(title=TITLE, user=USER, items=ITEMS)
buffer = StringIO()
- interpreter.execute("template.myt", request_args=data, out_buffer=buffer)
+ interpreter.execute(
+ "template.myt", request_args=data, out_buffer=buffer
+ )
return buffer.getvalue()
+
if verbose:
print(render())
return render
+
def mako(dirname, verbose=False):
from mako.template import Template
from mako.lookup import TemplateLookup
+
lookup = TemplateLookup(directories=[dirname], filesystem_checks=False)
- template = lookup.get_template('template.html')
+ template = lookup.get_template("template.html")
+
def render():
return template.render(title=TITLE, user=USER, list_items=ITEMS)
+
if verbose:
print(template.code + " " + render())
return render
+
+
mako_inheritance = mako
+
def jinja2(dirname, verbose=False):
from jinja2 import Environment, FileSystemLoader
+
env = Environment(loader=FileSystemLoader(dirname))
- template = env.get_template('template.html')
+ template = env.get_template("template.html")
+
def render():
return template.render(title=TITLE, user=USER, list_items=ITEMS)
+
if verbose:
print(render())
return render
+
+
jinja2_inheritance = jinja2
+
def cheetah(dirname, verbose=False):
from Cheetah.Template import Template
- filename = os.path.join(dirname, 'template.tmpl')
+
+ filename = os.path.join(dirname, "template.tmpl")
template = Template(file=filename)
+
def render():
- template.__dict__.update({'title': TITLE, 'user': USER,
- 'list_items': ITEMS})
+ template.__dict__.update(
+ {"title": TITLE, "user": USER, "list_items": ITEMS}
+ )
return template.respond()
if verbose:
@@ -103,30 +137,37 @@ def cheetah(dirname, verbose=False):
print(render())
return render
+
def django(dirname, verbose=False):
from django.conf import settings
- settings.configure(TEMPLATE_DIRS=[os.path.join(dirname, 'templates')])
+
+ settings.configure(TEMPLATE_DIRS=[os.path.join(dirname, "templates")])
from django import template, templatetags
from django.template import loader
- templatetags.__path__.append(os.path.join(dirname, 'templatetags'))
- tmpl = loader.get_template('template.html')
+
+ templatetags.__path__.append(os.path.join(dirname, "templatetags"))
+ tmpl = loader.get_template("template.html")
def render():
- data = {'title': TITLE, 'user': USER, 'items': ITEMS}
+ data = {"title": TITLE, "user": USER, "items": ITEMS}
return tmpl.render(template.Context(data))
if verbose:
print(render())
return render
+
def kid(dirname, verbose=False):
import kid
+
kid.path = kid.TemplatePath([dirname])
- template = kid.Template(file='template.kid')
+ template = kid.Template(file="template.kid")
+
def render():
- template = kid.Template(file='template.kid',
- title=TITLE, user=USER, items=ITEMS)
- return template.serialize(output='xhtml')
+ template = kid.Template(
+ file="template.kid", title=TITLE, user=USER, items=ITEMS
+ )
+ return template.serialize(output="xhtml")
if verbose:
print(render())
@@ -138,42 +179,46 @@ def run(engines, number=2000, verbose=False):
for engine in engines:
dirname = os.path.join(basepath, engine)
if verbose:
- print('%s:' % engine.capitalize())
- print('--------------------------------------------------------')
+ print("%s:" % engine.capitalize())
+ print("--------------------------------------------------------")
else:
- sys.stdout.write('%s:' % engine.capitalize())
- t = timeit.Timer(setup='from __main__ import %s; render = %s(r"%s", %s)'
- % (engine, engine, dirname, verbose),
- stmt='render()')
+ sys.stdout.write("%s:" % engine.capitalize())
+ t = timeit.Timer(
+ setup='from __main__ import %s; render = %s(r"%s", %s)'
+ % (engine, engine, dirname, verbose),
+ stmt="render()",
+ )
time = t.timeit(number=number) / number
if verbose:
- print('--------------------------------------------------------')
- print('%.2f ms' % (1000 * time))
+ print("--------------------------------------------------------")
+ print("%.2f ms" % (1000 * time))
if verbose:
- print('--------------------------------------------------------')
+ print("--------------------------------------------------------")
-if __name__ == '__main__':
- engines = [arg for arg in sys.argv[1:] if arg[0] != '-']
+if __name__ == "__main__":
+ engines = [arg for arg in sys.argv[1:] if arg[0] != "-"]
if not engines:
engines = __all__
- verbose = '-v' in sys.argv
+ verbose = "-v" in sys.argv
- if '-p' in sys.argv:
+ if "-p" in sys.argv:
try:
import hotshot, hotshot.stats
+
prof = hotshot.Profile("template.prof")
benchtime = prof.runcall(run, engines, number=100, verbose=verbose)
stats = hotshot.stats.load("template.prof")
except ImportError:
import cProfile, pstats
+
stmt = "run(%r, number=%r, verbose=%r)" % (engines, 1000, verbose)
cProfile.runctx(stmt, globals(), {}, "template.prof")
stats = pstats.Stats("template.prof")
stats.strip_dirs()
- stats.sort_stats('time', 'calls')
+ stats.sort_stats("time", "calls")
stats.print_stats()
else:
run(engines, verbose=verbose)
diff --git a/examples/bench/django/templatetags/bench.py b/examples/bench/django/templatetags/bench.py
index 7bf0abc..1f67937 100644
--- a/examples/bench/django/templatetags/bench.py
+++ b/examples/bench/django/templatetags/bench.py
@@ -3,6 +3,9 @@ from django.utils.html import escape
register = Library()
+
def greeting(name):
- return 'Hello, %s!' % escape(name)
+ return "Hello, %s!" % escape(name)
+
+
greeting = register.simple_tag(greeting)
diff --git a/examples/wsgi/run_wsgi.py b/examples/wsgi/run_wsgi.py
index d013074..a98f6c6 100644
--- a/examples/wsgi/run_wsgi.py
+++ b/examples/wsgi/run_wsgi.py
@@ -3,56 +3,56 @@ import cgi, re, os, posixpath, mimetypes
from mako.lookup import TemplateLookup
from mako import exceptions
-root = './'
+root = "./"
port = 8000
lookup = TemplateLookup(
- directories=[root + 'templates', root + 'htdocs'],
- filesystem_checks=True,
- module_directory='./modules',
- # even better would be to use 'charset' in start_response
- output_encoding='ascii',
- encoding_errors='replace'
- )
+ directories=[root + "templates", root + "htdocs"],
+ filesystem_checks=True,
+ module_directory="./modules",
+ # even better would be to use 'charset' in start_response
+ output_encoding="ascii",
+ encoding_errors="replace",
+)
+
def serve(environ, start_response):
"""serves requests using the WSGI callable interface."""
fieldstorage = cgi.FieldStorage(
- fp = environ['wsgi.input'],
- environ = environ,
- keep_blank_values = True
+ fp=environ["wsgi.input"], environ=environ, keep_blank_values=True
)
d = dict([(k, getfield(fieldstorage[k])) for k in fieldstorage])
- uri = environ.get('PATH_INFO', '/')
+ uri = environ.get("PATH_INFO", "/")
if not uri:
- uri = '/index.html'
+ uri = "/index.html"
else:
- uri = re.sub(r'^/$', '/index.html', uri)
+ uri = re.sub(r"^/$", "/index.html", uri)
- if re.match(r'.*\.html$', uri):
+ if re.match(r".*\.html$", uri):
try:
template = lookup.get_template(uri)
except exceptions.TopLevelLookupException:
start_response("404 Not Found", [])
return [str.encode("Cant find template '%s'" % uri)]
- start_response("200 OK", [('Content-type','text/html')])
+ start_response("200 OK", [("Content-type", "text/html")])
try:
return [template.render(**d)]
except:
return [exceptions.html_error_template().render()]
else:
- u = re.sub(r'^\/+', '', uri)
+ u = re.sub(r"^\/+", "", uri)
filename = os.path.join(root, u)
if os.path.isfile(filename):
- start_response("200 OK", [('Content-type',guess_type(uri))])
- return [open(filename, 'rb').read()]
+ start_response("200 OK", [("Content-type", guess_type(uri))])
+ return [open(filename, "rb").read()]
else:
start_response("404 Not Found", [])
return [str.encode("File not found: '%s'" % filename)]
-
+
+
def getfield(f):
"""convert values from cgi.Field objects to plain values."""
if isinstance(f, list):
@@ -60,8 +60,10 @@ def getfield(f):
else:
return f.value
+
extensions_map = mimetypes.types_map.copy()
+
def guess_type(path):
"""return a mimetype for the given path based on file extension."""
base, ext = posixpath.splitext(path)
@@ -71,10 +73,12 @@ def guess_type(path):
if ext in extensions_map:
return extensions_map[ext]
else:
- return 'text/html'
-
-if __name__ == '__main__':
+ return "text/html"
+
+
+if __name__ == "__main__":
import wsgiref.simple_server
- server = wsgiref.simple_server.make_server('', port, serve)
+
+ server = wsgiref.simple_server.make_server("", port, serve)
print("Server listening on port %d" % port)
server.serve_forever()
diff --git a/mako/codegen.py b/mako/codegen.py
index 7f1c8c3..c897f0f 100644
--- a/mako/codegen.py
+++ b/mako/codegen.py
@@ -43,7 +43,7 @@ def compile( # noqa
reserved_names=frozenset(),
):
"""Generate module source code given a parsetree node,
- uri, and optional source filename"""
+ uri, and optional source filename"""
buf = util.FastEncodingBuffer()
@@ -99,7 +99,7 @@ class _CompileContext:
class _GenerateRenderMethod:
"""A template visitor object which generates the
- full module source for a template.
+ full module source for a template.
"""
@@ -702,7 +702,7 @@ class _GenerateRenderMethod:
toplevel=False,
):
"""write a post-function decorator to replace a rendering
- callable with a cached version of itself."""
+ callable with a cached version of itself."""
self.printer.writeline("__M_%s = %s" % (name, name))
cachekey = node_or_pagetag.parsed_attributes.get(
@@ -1084,7 +1084,7 @@ class _Identifiers:
def branch(self, node, **kwargs):
"""create a new Identifiers for a new Node, with
- this Identifiers as the parent."""
+ this Identifiers as the parent."""
return _Identifiers(self.compiler, node, self, **kwargs)
@@ -1109,7 +1109,7 @@ class _Identifiers:
def check_declared(self, node):
"""update the state of this Identifiers with the undeclared
- and declared identifiers of the given node."""
+ and declared identifiers of the given node."""
for ident in node.undeclared_identifiers():
if ident != "context" and ident not in self.declared.union(
diff --git a/mako/exceptions.py b/mako/exceptions.py
index ec2de81..a0a5fec 100644
--- a/mako/exceptions.py
+++ b/mako/exceptions.py
@@ -139,8 +139,7 @@ class RichTraceback:
@property
def reverse_traceback(self):
- """Return the same data as traceback, except in reverse order.
- """
+ """Return the same data as traceback, except in reverse order."""
return list(self._get_reformatted_records(self.reverse_records))
diff --git a/mako/lexer.py b/mako/lexer.py
index 306ae4b..953c0a0 100644
--- a/mako/lexer.py
+++ b/mako/lexer.py
@@ -176,8 +176,8 @@ class Lexer:
def decode_raw_stream(self, text, decode_raw, known_encoding, filename):
"""given string/unicode or bytes/string, determine encoding
- from magic encoding comment, return body as unicode
- or raw if decode_raw=False
+ from magic encoding comment, return body as unicode
+ or raw if decode_raw=False
"""
if isinstance(text, str):
@@ -312,7 +312,7 @@ class Lexer:
if not match:
raise exceptions.SyntaxException(
"Unclosed tag: <%%%s>" % self.tag[-1].keyword,
- **self.exception_kwargs
+ **self.exception_kwargs,
)
self.append_node(parsetree.Text, match.group(1))
return self.match_tag_end()
@@ -434,7 +434,7 @@ class Lexer:
if not m2:
raise exceptions.SyntaxException(
"Invalid control line: '%s'" % text,
- **self.exception_kwargs
+ **self.exception_kwargs,
)
isend, keyword = m2.group(1, 2)
isend = isend is not None
@@ -442,15 +442,14 @@ class Lexer:
if isend:
if not len(self.control_line):
raise exceptions.SyntaxException(
- "No starting keyword '%s' for '%s'"
- % (keyword, text),
- **self.exception_kwargs
+ "No starting keyword '%s' for '%s'" % (keyword, text),
+ **self.exception_kwargs,
)
elif self.control_line[-1].keyword != keyword:
raise exceptions.SyntaxException(
"Keyword '%s' doesn't match keyword '%s'"
% (text, self.control_line[-1].keyword),
- **self.exception_kwargs
+ **self.exception_kwargs,
)
self.append_node(parsetree.ControlLine, keyword, isend, text)
else:
diff --git a/mako/lookup.py b/mako/lookup.py
index 06dee89..17cef8e 100644
--- a/mako/lookup.py
+++ b/mako/lookup.py
@@ -30,7 +30,7 @@ class TemplateCollection:
:class:`.TemplateCollection` is an abstract class,
with the usual default implementation being :class:`.TemplateLookup`.
- """
+ """
def has_template(self, uri):
"""Return ``True`` if this :class:`.TemplateLookup` is
@@ -64,7 +64,7 @@ class TemplateCollection:
def filename_to_uri(self, uri, filename):
"""Convert the given ``filename`` to a URI relative to
- this :class:`.TemplateCollection`."""
+ this :class:`.TemplateCollection`."""
return uri
@@ -274,7 +274,7 @@ class TemplateLookup(TemplateCollection):
def filename_to_uri(self, filename):
"""Convert the given ``filename`` to a URI relative to
- this :class:`.TemplateCollection`."""
+ this :class:`.TemplateCollection`."""
try:
return self._uri_cache[filename]
@@ -285,7 +285,7 @@ class TemplateLookup(TemplateCollection):
def _relativeize(self, filename):
"""Return the portion of a filename that is 'relative'
- to the directories in this lookup.
+ to the directories in this lookup.
"""
diff --git a/mako/parsetree.py b/mako/parsetree.py
index 7ec0c1c..c1629d9 100644
--- a/mako/parsetree.py
+++ b/mako/parsetree.py
@@ -106,11 +106,13 @@ class ControlLine(Node):
"""return true if the given keyword is a ternary keyword
for this ControlLine"""
- return keyword in {
+ cases = {
"if": {"else", "elif"},
"try": {"except", "finally"},
"for": {"else"},
- }.get(self.keyword, [])
+ }
+
+ return keyword in cases.get(self.keyword, set())
def __repr__(self):
return "ControlLine(%r, %r, %r, %r)" % (
diff --git a/mako/pygen.py b/mako/pygen.py
index bf8811c..46b0b52 100644
--- a/mako/pygen.py
+++ b/mako/pygen.py
@@ -107,9 +107,7 @@ class PythonPrinter:
# module wont compile.
if len(self.indent_detail) == 0:
# TODO: no coverage here
- raise exceptions.MakoException(
- "Too many whitespace closures"
- )
+ raise exceptions.MakoException("Too many whitespace closures")
self.indent_detail.pop()
if line is None:
diff --git a/mako/pyparser.py b/mako/pyparser.py
index c626622..2a1ba5f 100644
--- a/mako/pyparser.py
+++ b/mako/pyparser.py
@@ -161,7 +161,7 @@ class FindIdentifiers(_ast_util.NodeVisitor):
"names must be explicitly declared. Please use the "
"form 'from <modulename> import <name1>, <name2>, "
"...' instead.",
- **self.exception_kwargs
+ **self.exception_kwargs,
)
else:
self._add_declared(name.name)
diff --git a/mako/runtime.py b/mako/runtime.py
index 28186a9..f5dbe1a 100644
--- a/mako/runtime.py
+++ b/mako/runtime.py
@@ -24,7 +24,7 @@ class Context:
See :ref:`runtime_toplevel` for detail on the usage of
:class:`.Context`.
- """
+ """
def __init__(self, buffer, **data):
self._buffer_stack = [buffer]
@@ -339,8 +339,7 @@ class LoopContext:
return bool(self.index % 2)
def cycle(self, *values):
- """Cycle through values as the loop progresses.
- """
+ """Cycle through values as the loop progresses."""
if not values:
raise ValueError("You must provide values to cycle through")
return values[self.index % len(values)]
@@ -363,19 +362,19 @@ class _NSAttr:
class Namespace:
"""Provides access to collections of rendering methods, which
- can be local, from other templates, or from imported modules.
+ can be local, from other templates, or from imported modules.
- To access a particular rendering method referenced by a
- :class:`.Namespace`, use plain attribute access:
+ To access a particular rendering method referenced by a
+ :class:`.Namespace`, use plain attribute access:
- .. sourcecode:: mako
+ .. sourcecode:: mako
- ${some_namespace.foo(x, y, z)}
+ ${some_namespace.foo(x, y, z)}
- :class:`.Namespace` also contains several built-in attributes
- described here.
+ :class:`.Namespace` also contains several built-in attributes
+ described here.
- """
+ """
def __init__(
self,
diff --git a/mako/template.py b/mako/template.py
index df2a7ac..bbbe73c 100644
--- a/mako/template.py
+++ b/mako/template.py
@@ -483,17 +483,17 @@ class ModuleTemplate(Template):
"""A Template which is constructed given an existing Python module.
- e.g.::
+ e.g.::
- t = Template("this is a template")
- f = file("mymodule.py", "w")
- f.write(t.code)
- f.close()
+ t = Template("this is a template")
+ f = file("mymodule.py", "w")
+ f.write(t.code)
+ f.close()
- import mymodule
+ import mymodule
- t = ModuleTemplate(mymodule)
- print(t.render())
+ t = ModuleTemplate(mymodule)
+ print(t.render())
"""
@@ -579,7 +579,7 @@ class ModuleInfo:
memory, provides reverse lookups of template source, module
source code based on a module's identifier.
- """
+ """
_modules = weakref.WeakValueDictionary()
@@ -642,9 +642,7 @@ class ModuleInfo:
elif self.module._source_encoding and not isinstance(
self.template_source, str
):
- return self.template_source.decode(
- self.module._source_encoding
- )
+ return self.template_source.decode(self.module._source_encoding)
else:
return self.template_source
diff --git a/test/__init__.py b/test/__init__.py
index 6c5047a..9b85cdf 100644
--- a/test/__init__.py
+++ b/test/__init__.py
@@ -102,9 +102,10 @@ def raises(except_cls, message=None):
success = False
except except_cls as e:
if message:
- assert re.search(
- message, str(e), re.UNICODE
- ), "%r !~ %s" % (message, e)
+ assert re.search(message, str(e), re.UNICODE), "%r !~ %s" % (
+ message,
+ e,
+ )
print(str(e).encode("utf-8"))
success = True
@@ -168,7 +169,7 @@ def requires_no_pygments_exceptions(fn):
class PlainCacheImpl(CacheImpl):
"""Simple memory cache impl so that tests which
- use caching can run without beaker. """
+ use caching can run without beaker."""
def __init__(self, cache):
self.cache = cache
diff --git a/test/ext/test_babelplugin.py b/test/ext/test_babelplugin.py
index bf21aa2..a69d884 100644
--- a/test/ext/test_babelplugin.py
+++ b/test/ext/test_babelplugin.py
@@ -105,7 +105,7 @@ class ExtractMakoTestCase(TemplateTest):
message = next(
extract(mako_tmpl, set(["_", None]), [], {"encoding": "utf-8"})
)
- assert message == (1, "_", u"K\xf6ln", [])
+ assert message == (1, "_", "K\xf6ln", [])
@skip()
def test_extract_cp1251(self):
@@ -117,4 +117,4 @@ class ExtractMakoTestCase(TemplateTest):
extract(mako_tmpl, set(["_", None]), [], {"encoding": "cp1251"})
)
# "test" in Rusian. File encoding is cp1251 (aka "windows-1251")
- assert message == (1, "_", u"\u0442\u0435\u0441\u0442", [])
+ assert message == (1, "_", "\u0442\u0435\u0441\u0442", [])
diff --git a/test/ext/test_linguaplugin.py b/test/ext/test_linguaplugin.py
index f505759..53d7073 100644
--- a/test/ext/test_linguaplugin.py
+++ b/test/ext/test_linguaplugin.py
@@ -55,9 +55,9 @@ class ExtractMakoTestCase(TemplateTest):
("Goodbye, really!", None),
("P.S. byebye", None),
("Top", None),
- (u"foo", None),
+ ("foo", None),
("hoho", None),
- (u"bar", None),
+ ("bar", None),
("Inside a p tag", None),
("Later in a p tag", None),
("No action at a distance.", None),
diff --git a/test/templates/foo/modtest.html.py b/test/templates/foo/modtest.html.py
index e6fc8d8..7a73e55 100644
--- a/test/templates/foo/modtest.html.py
+++ b/test/templates/foo/modtest.html.py
@@ -1,25 +1,24 @@
from mako import runtime, filters, cache
+
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1267565427.7968459
-_template_filename='/Users/classic/dev/mako/test/templates/modtest.html'
-_template_uri='/modtest.html'
-_template_cache=cache.Cache(__name__, _modified_time)
-_source_encoding=None
+_template_filename = "/Users/classic/dev/mako/test/templates/modtest.html"
+_template_uri = "/modtest.html"
+_template_cache = cache.Cache(__name__, _modified_time)
+_source_encoding = None
_exports = []
-def render_body(context,**pageargs):
+def render_body(context, **pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
__M_writer = context.writer()
# SOURCE LINE 1
- __M_writer('this is a test')
- return ''
+ __M_writer("this is a test")
+ return ""
finally:
context.caller_stack._pop_frame()
-
-
diff --git a/test/templates/subdir/foo/modtest.html.py b/test/templates/subdir/foo/modtest.html.py
index b0f50c7..8b3a73b 100644
--- a/test/templates/subdir/foo/modtest.html.py
+++ b/test/templates/subdir/foo/modtest.html.py
@@ -1,25 +1,26 @@
from mako import runtime, filters, cache
+
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1267565427.799504
-_template_filename='/Users/classic/dev/mako/test/templates/subdir/modtest.html'
-_template_uri='/subdir/modtest.html'
-_template_cache=cache.Cache(__name__, _modified_time)
-_source_encoding=None
+_template_filename = (
+ "/Users/classic/dev/mako/test/templates/subdir/modtest.html"
+)
+_template_uri = "/subdir/modtest.html"
+_template_cache = cache.Cache(__name__, _modified_time)
+_source_encoding = None
_exports = []
-def render_body(context,**pageargs):
+def render_body(context, **pageargs):
context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
__M_writer = context.writer()
# SOURCE LINE 1
- __M_writer('this is a test')
- return ''
+ __M_writer("this is a test")
+ return ""
finally:
context.caller_stack._pop_frame()
-
-
diff --git a/test/test_ast.py b/test/test_ast.py
index daa7c6e..0f30c5a 100644
--- a/test/test_ast.py
+++ b/test/test_ast.py
@@ -234,7 +234,7 @@ import x as bar
exceptions.CompileException,
ast.PythonCode,
code,
- **exception_kwargs
+ **exception_kwargs,
)
def test_python_fragment(self):
diff --git a/test/test_exceptions.py b/test/test_exceptions.py
index b0e2bb1..dc3b735 100644
--- a/test/test_exceptions.py
+++ b/test/test_exceptions.py
@@ -77,13 +77,12 @@ ${'привет'}
except exceptions.CompileException:
html_error = exceptions.html_error_template().render()
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
- )
+ "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
assert (
"".encode(sys.getdefaultencoding(), "htmlentityreplace")
@@ -111,13 +110,12 @@ ${'привет'}
except exceptions.CompileException:
html_error = exceptions.html_error_template().render()
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
- )
+ "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
assert (
"${&#39;привет&#39;}".encode(
sys.getdefaultencoding(), "htmlentityreplace"
@@ -154,9 +152,7 @@ ${'привет'}
raise RuntimeError("日本")
except:
html_error = exceptions.html_error_template().render()
- assert (
- "RuntimeError: 日本".encode("ascii", "ignore") in html_error
- )
+ assert "RuntimeError: 日本".encode("ascii", "ignore") in html_error
@requires_pygments_14
def test_format_exceptions_pygments(self):
@@ -208,7 +204,7 @@ ${foobar}
@requires_pygments_14
def test_utf8_format_exceptions_pygments(self):
"""test that htmlentityreplace formatting is applied to
- exceptions reported with format_exceptions=True"""
+ exceptions reported with format_exceptions=True"""
l = TemplateLookup(format_exceptions=True)
l.put_string(
@@ -222,7 +218,7 @@ ${foobar}
@requires_no_pygments_exceptions
def test_utf8_format_exceptions_no_pygments(self):
"""test that htmlentityreplace formatting is applied to
- exceptions reported with format_exceptions=True"""
+ exceptions reported with format_exceptions=True"""
l = TemplateLookup(format_exceptions=True)
l.put_string(
diff --git a/test/test_filters.py b/test/test_filters.py
index 4def5f8..7aa7662 100644
--- a/test/test_filters.py
+++ b/test/test_filters.py
@@ -74,7 +74,7 @@ class FilterTest(TemplateTest):
)
eq_(
- flatten_result(t.render(bar=u"酒吧bar")),
+ flatten_result(t.render(bar="酒吧bar")),
"http://example.com/?bar=%E9%85%92%E5%90%A7bar&v=1",
)
diff --git a/test/test_template.py b/test/test_template.py
index 715bc4c..f2ca6b4 100644
--- a/test/test_template.py
+++ b/test/test_template.py
@@ -332,7 +332,7 @@ quand une drôle de petite voix m’a réveillé. Elle disait:
def test_input_encoding(self):
"""test the 'input_encoding' flag on Template, and that unicode
- objects arent double-decoded"""
+ objects arent double-decoded"""
self._do_memory_test(
("hello ${f('śląsk')}"),
@@ -927,15 +927,18 @@ class ControlTest(TemplateTest):
%endfor
"""
)
- assert result_lines(
- t.render(
- y=[
- {"test": "one"},
- {"foo": "bar"},
- {"foo": "bar", "test": "two"},
- ]
+ assert (
+ result_lines(
+ t.render(
+ y=[
+ {"test": "one"},
+ {"foo": "bar"},
+ {"foo": "bar", "test": "two"},
+ ]
+ )
)
- ) == ["yes x has test", "no x does not have test", "yes x has test"]
+ == ["yes x has test", "no x does not have test", "yes x has test"]
+ )
def test_blank_control_1(self):
self._do_memory_test(
diff --git a/test/test_tgplugin.py b/test/test_tgplugin.py
index d69ddf9..9b8055f 100644
--- a/test/test_tgplugin.py
+++ b/test/test_tgplugin.py
@@ -46,6 +46,6 @@ class TestTGPlugin(TemplateTest):
assert result_lines(tl.render({}, template="/index.html")) == [
"this is index"
]
- assert result_lines(
- tl.render({}, template=("/index.html"))
- ) == ["this is index"]
+ assert result_lines(tl.render({}, template=("/index.html"))) == [
+ "this is index"
+ ]
diff --git a/test/test_util.py b/test/test_util.py
index 78096c1..2646300 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -29,7 +29,7 @@ class UtilTest(unittest.TestCase):
eq_(buf.getvalue(), "string c string d")
def test_fast_buffer_encoded(self):
- s = ("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:])
diff --git a/tox.ini b/tox.ini
index 2478967..d8edd3c 100644
--- a/tox.ini
+++ b/tox.ini
@@ -30,4 +30,7 @@ deps=
pydocstyle<4.0.0
# used by flake8-rst-docstrings
pygments
-commands = flake8 ./mako/ ./test/ setup.py --exclude test/templates,test/foo {posargs}
+ black==21.9b0
+commands =
+ flake8 ./mako/ ./test/ setup.py --exclude test/templates,test/foo {posargs}
+ black --check .