Skip to content

Commit 9fb7764

Browse files
committed
style: ruff format
1 parent d1c443a commit 9fb7764

14 files changed

Lines changed: 285 additions & 220 deletions

django_coverage_plugin/plugin.py

Lines changed: 30 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
class DjangoTemplatePluginException(Exception):
1919
"""Used for any errors from the plugin itself."""
20+
2021
pass
2122

2223

@@ -42,6 +43,7 @@ def check_debug():
4243
# I _think_ this check is all that's needed and the 3 "hasattr" checks
4344
# below can be removed, but it's not clear how to verify that
4445
from django.apps import apps
46+
4547
if not apps.ready:
4648
return False
4749

@@ -58,13 +60,9 @@ def check_debug():
5860

5961
for engine in django.template.engines.all():
6062
if not isinstance(engine, django.template.backends.django.DjangoTemplates):
61-
raise DjangoTemplatePluginException(
62-
"Can't use non-Django templates."
63-
)
63+
raise DjangoTemplatePluginException("Can't use non-Django templates.")
6464
if not engine.engine.debug:
65-
raise DjangoTemplatePluginException(
66-
"Template debugging must be enabled in settings."
67-
)
65+
raise DjangoTemplatePluginException("Template debugging must be enabled in settings.")
6866

6967
return True
7068

@@ -112,16 +110,15 @@ class DjangoTemplatePlugin(
112110
coverage.plugin.CoveragePlugin,
113111
coverage.plugin.FileTracer,
114112
):
115-
116113
def __init__(self, options):
117114
extensions = options.get("template_extensions", "html,htm,txt")
118115
self.extensions = [e.strip() for e in extensions.split(",")]
119116

120117
self.debug_checked = False
121118

122-
self.django_template_dir = os.path.normcase(os.path.realpath(
123-
os.path.dirname(django.template.__file__)
124-
))
119+
self.django_template_dir = os.path.normcase(
120+
os.path.realpath(os.path.dirname(django.template.__file__))
121+
)
125122

126123
self.source_map = {}
127124

@@ -130,11 +127,10 @@ def __init__(self, options):
130127
def sys_info(self):
131128
return [
132129
("django_template_dir", self.django_template_dir),
133-
("environment", sorted(
134-
("{} = {}".format(k, v))
135-
for k, v in os.environ.items()
136-
if "DJANGO" in k
137-
)),
130+
(
131+
"environment",
132+
sorted(("{} = {}".format(k, v)) for k, v in os.environ.items() if "DJANGO" in k),
133+
),
138134
]
139135

140136
def configure(self, config):
@@ -159,7 +155,7 @@ def find_executable_files(self, src_dir):
159155
# funny characters that probably mean they are editor junk.
160156
rx = r"^[^.#~!$@%^&*()+=,]+\.(" + "|".join(self.extensions) + r")$"
161157

162-
for (dirpath, dirnames, filenames) in os.walk(src_dir):
158+
for dirpath, dirnames, filenames in os.walk(src_dir):
163159
if dirpath == self.html_report_dir:
164160
# Don't confuse the HTML report with HTML templates.
165161
continue
@@ -196,7 +192,7 @@ def line_number_range(self, frame):
196192
if 0:
197193
dump_frame(frame, label="line_number_range")
198194

199-
render_self = frame.f_locals['self']
195+
render_self = frame.f_locals["self"]
200196
if isinstance(render_self, (NodeList, Template)):
201197
return -1, -1
202198

@@ -226,13 +222,11 @@ def line_number_range(self, frame):
226222
filename = filename_for_frame(frame)
227223
line_map = self.get_line_map(filename)
228224
start = get_line_number(line_map, s_start)
229-
end = get_line_number(line_map, s_end-1)
225+
end = get_line_number(line_map, s_end - 1)
230226
if start < 0 or end < 0:
231227
start, end = -1, -1
232228
if SHOW_TRACING:
233-
print("line_number_range({}) -> {}".format(
234-
filename, (start, end)
235-
))
229+
print("line_number_range({}) -> {}".format(filename, (start, end)))
236230
return start, end
237231

238232
# --- FileTracer helpers
@@ -251,9 +245,9 @@ def get_line_map(self, filename):
251245
"""
252246
if filename not in self.source_map:
253247
template_source = read_template_source(filename)
254-
if 0: # change to see the template text
248+
if 0: # change to see the template text
255249
for i in range(0, len(template_source), 10):
256-
print("%3d: %r" % (i, template_source[i:i+10]))
250+
print("%3d: %r" % (i, template_source[i : i + 10]))
257251
self.source_map[filename] = make_line_map(template_source)
258252
return self.source_map[filename]
259253

@@ -292,7 +286,8 @@ def lines(self):
292286
for token in tokens:
293287
if SHOW_PARSING:
294288
print(
295-
"%10s %2d: %r" % (
289+
"%10s %2d: %r"
290+
% (
296291
token.token_type.capitalize(),
297292
token.lineno,
298293
token.contents,
@@ -352,11 +347,9 @@ def lines(self):
352347
# When a tag is not at the start of a line, the preceding
353348
# TEXT token ends with whitespace and no newline.
354349
# That partial line is not executable content.
355-
if num_lines > 0 and (
356-
lines[-1].isspace() and not lines[-1].endswith(("\n", "\r"))
357-
):
350+
if num_lines > 0 and (lines[-1].isspace() and not lines[-1].endswith(("\n", "\r"))):
358351
num_lines -= 1
359-
source_lines.update(range(lineno, lineno+num_lines))
352+
source_lines.update(range(lineno, lineno + num_lines))
360353

361354
if SHOW_PARSING:
362355
print(f"\t\t\tNow source_lines is: {source_lines!r}")
@@ -388,19 +381,21 @@ def get_line_number(line_map, offset):
388381
def dump_frame(frame, label=""):
389382
"""Dump interesting information about this frame."""
390383
locals = dict(frame.f_locals)
391-
self = locals.get('self', None)
392-
context = locals.get('context', None)
384+
self = locals.get("self", None)
385+
context = locals.get("context", None)
393386
if "__builtins__" in locals:
394387
del locals["__builtins__"]
395388

396389
if label:
397390
label = " ( %s ) " % label
398391
print("-- frame --%s---------------------" % label)
399-
print("{}:{}:{}".format(
400-
os.path.basename(frame.f_code.co_filename),
401-
frame.f_lineno,
402-
type(self),
403-
))
392+
print(
393+
"{}:{}:{}".format(
394+
os.path.basename(frame.f_code.co_filename),
395+
frame.f_lineno,
396+
type(self),
397+
)
398+
)
404399
print(locals)
405400
if self:
406401
print("self:", self.__dict__)

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,7 @@ filterwarnings = [
6262
fragment_directory = "scriv.d"
6363
output_file = "README.rst"
6464
rst_header_chars = "-."
65+
66+
[tool.ruff]
67+
target-version = "py310" # Can't use [project]
68+
line-length = 100

tests/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,5 @@ def index(request):
1717

1818

1919
urlpatterns = [
20-
re_path(r'^home$', index, name='index'),
20+
re_path(r"^home$", index, name="index"),
2121
]

tests/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def set_warnings():
2828
"ignore",
2929
category=UserWarning,
3030
message=r"Overriding setting DATABASES can lead to unexpected behavior.",
31-
)
31+
)
3232

3333
# Django has warnings like RemovedInDjango40Warning. We use features that are going to be
3434
# deprecated, so we don't need to see those warnings. But the specific warning classes change

tests/plugin_test.py

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,34 +23,36 @@
2323
def get_test_settings():
2424
"""Create a dict full of default Django settings for the tests."""
2525
the_settings = {
26-
'CACHES': {
27-
'default': {
28-
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
26+
"CACHES": {
27+
"default": {
28+
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
2929
},
3030
},
31-
'DATABASES': {
32-
'default': {
33-
'ENGINE': 'django.db.backends.sqlite3',
34-
'NAME': ':memory:',
31+
"DATABASES": {
32+
"default": {
33+
"ENGINE": "django.db.backends.sqlite3",
34+
"NAME": ":memory:",
3535
}
3636
},
37-
'ROOT_URLCONF': 'tests',
37+
"ROOT_URLCONF": "tests",
3838
}
3939

40-
the_settings.update({
41-
'TEMPLATES': [
42-
{
43-
'BACKEND': 'django.template.backends.django.DjangoTemplates',
44-
'DIRS': ['templates'], # where the tests put things.
45-
'OPTIONS': {
46-
'debug': True,
47-
'loaders': [
48-
'django.template.loaders.filesystem.Loader',
49-
]
40+
the_settings.update(
41+
{
42+
"TEMPLATES": [
43+
{
44+
"BACKEND": "django.template.backends.django.DjangoTemplates",
45+
"DIRS": ["templates"], # where the tests put things.
46+
"OPTIONS": {
47+
"debug": True,
48+
"loaders": [
49+
"django.template.loaders.filesystem.Loader",
50+
],
51+
},
5052
},
51-
},
52-
],
53-
})
53+
],
54+
}
55+
)
5456

5557
return the_settings
5658

@@ -85,9 +87,7 @@ def make_template(self, text, name=None):
8587
template_path = self._path(self.template_file)
8688
return os.path.abspath(self.make_file(template_path, text))
8789

88-
def run_django_coverage(
89-
self, name=None, text=None, context=None, options=None, using=None
90-
):
90+
def run_django_coverage(self, name=None, text=None, context=None, options=None, using=None):
9191
"""Run a template under coverage.
9292
9393
The data context is `context` if provided, else {}.
@@ -105,10 +105,11 @@ def run_django_coverage(
105105
use_real_context = False
106106

107107
if options is None:
108-
options = {'source': ["."]}
108+
options = {"source": ["."]}
109109

110110
if using:
111111
from django.template import engines
112+
112113
engine = engines[using]
113114
if text is not None:
114115
tem = engine.from_string(text)
@@ -134,7 +135,7 @@ def run_django_coverage(
134135
self.cov.stop()
135136
self.cov.save()
136137
# Warning! Accessing secret internals!
137-
if hasattr(self.cov, 'plugins'):
138+
if hasattr(self.cov, "plugins"):
138139
plugins = self.cov.plugins
139140
else:
140141
plugins = self.cov._plugins
@@ -191,14 +192,16 @@ def assert_analysis(self, executable, missing=None, name=None):
191192
executable,
192193
actual_executable,
193194
"Executable lines aren't as expected: {!r} != {!r}".format(
194-
executable, actual_executable,
195+
executable,
196+
actual_executable,
195197
),
196198
)
197199
self.assertEqual(
198200
missing or [],
199201
actual_missing,
200202
"Missing lines aren't as expected: {!r} != {!r}".format(
201-
missing, actual_missing,
203+
missing,
204+
actual_missing,
202205
),
203206
)
204207

@@ -239,6 +242,7 @@ def assert_coverage_warnings(self, *msgs, min_cov=None):
239242
return
240243
elif coverage.version_info >= (6, 0):
241244
import coverage.exceptions as cov_exc
245+
242246
ctxmgr = self.assertWarns(cov_exc.CoverageWarning)
243247
else:
244248
ctxmgr = contextlib.nullcontext()
@@ -280,4 +284,5 @@ def squashed(s):
280284

281285
class PluginDisabled(Exception):
282286
"""Raised if we find that our plugin has been disabled."""
287+
283288
pass

tests/test_engines.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,40 +13,40 @@ def setUp(self):
1313
super().setUp()
1414

1515
engine = {
16-
'NAME': 'other',
17-
'BACKEND': 'django.template.backends.django.DjangoTemplates',
18-
'DIRS': ['templates2'], # where the tests put things.
19-
'OPTIONS': {
20-
'debug': True,
16+
"NAME": "other",
17+
"BACKEND": "django.template.backends.django.DjangoTemplates",
18+
"DIRS": ["templates2"], # where the tests put things.
19+
"OPTIONS": {
20+
"debug": True,
2121
},
2222
}
23-
modified_settings = modify_settings(TEMPLATES={'append': [engine]})
23+
modified_settings = modify_settings(TEMPLATES={"append": [engine]})
2424
modified_settings.enable()
2525
self.addCleanup(modified_settings.disable)
2626

27-
self.template_directory = 'templates2'
27+
self.template_directory = "templates2"
2828

2929
def test_file_template(self):
30-
self.make_template('Hello')
31-
text = self.run_django_coverage(using='other')
32-
self.assertEqual(text, 'Hello')
30+
self.make_template("Hello")
31+
text = self.run_django_coverage(using="other")
32+
self.assertEqual(text, "Hello")
3333
self.assert_analysis([1])
3434

3535
def test_string_template(self):
3636
with self.assert_no_data():
37-
text = self.run_django_coverage(text='Hello', using='other')
38-
self.assertEqual(text, 'Hello')
37+
text = self.run_django_coverage(text="Hello", using="other")
38+
self.assertEqual(text, "Hello")
3939

4040
def test_third_engine_not_debug(self):
4141
engine3 = {
42-
'NAME': 'notdebug',
43-
'BACKEND': 'django.template.backends.django.DjangoTemplates',
44-
'DIRS': ['templates3'], # where the tests put things.
42+
"NAME": "notdebug",
43+
"BACKEND": "django.template.backends.django.DjangoTemplates",
44+
"DIRS": ["templates3"], # where the tests put things.
4545
}
46-
modified_settings = modify_settings(TEMPLATES={'append': [engine3]})
46+
modified_settings = modify_settings(TEMPLATES={"append": [engine3]})
4747
modified_settings.enable()
4848
self.addCleanup(modified_settings.disable)
4949

50-
self.make_template('Hello')
50+
self.make_template("Hello")
5151
with self.assert_plugin_disabled("Template debugging must be enabled in settings."):
5252
self.run_django_coverage()

0 commit comments

Comments
 (0)