Skip to content

Commit 5899e7d

Browse files
authoredApr 7, 2021
Merge pull request #1307 from PyCQA/pre-commit-ci-update-config
[pre-commit.ci] pre-commit autoupdate
2 parents 1623a8e + 3f10c04 commit 5899e7d

9 files changed

+94
-78
lines changed
 

‎.pre-commit-config.yaml

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
exclude: ^tests/fixtures/example-code/
22
repos:
33
- repo: https://github.com/pre-commit/pre-commit-hooks
4-
rev: v2.3.0
4+
rev: v3.4.0
55
hooks:
66
- id: check-yaml
77
- id: debug-statements
@@ -26,7 +26,7 @@ repos:
2626
- id: pyupgrade
2727
args: [--py36-plus]
2828
- repo: https://github.com/pre-commit/mirrors-mypy
29-
rev: v0.720
29+
rev: v0.812
3030
hooks:
3131
- id: mypy
3232
exclude: ^(docs/|example-plugin/|tests/fixtures)

‎src/flake8/checker.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,7 @@
4040

4141
def _multiprocessing_is_fork(): # type () -> bool
4242
"""Class state is only preserved when using the `fork` strategy."""
43-
return (
44-
multiprocessing
45-
# https://github.com/python/typeshed/pull/3415
46-
and multiprocessing.get_start_method() == "fork" # type: ignore
47-
)
43+
return multiprocessing and multiprocessing.get_start_method() == "fork"
4844

4945

5046
class Manager:
@@ -396,7 +392,7 @@ def report(
396392

397393
# If we're recovering from a problem in _make_processor, we will not
398394
# have this attribute.
399-
if hasattr(self, "processor"):
395+
if hasattr(self, "processor") and self.processor is not None:
400396
line = self.processor.noqa_line_for(line_number)
401397
else:
402398
line = None
@@ -407,6 +403,7 @@ def report(
407403
def run_check(self, plugin, **arguments):
408404
"""Run the check in a single plugin."""
409405
LOG.debug("Running %r with %r", plugin, arguments)
406+
assert self.processor is not None
410407
try:
411408
self.processor.keyword_arguments_for(
412409
plugin["parameters"], arguments
@@ -467,6 +464,7 @@ def _extract_syntax_information(exception):
467464

468465
def run_ast_checks(self) -> None:
469466
"""Run all checks expecting an abstract syntax tree."""
467+
assert self.processor is not None
470468
try:
471469
ast = self.processor.build_ast()
472470
except (ValueError, SyntaxError, TypeError) as e:
@@ -494,6 +492,7 @@ def run_ast_checks(self) -> None:
494492

495493
def run_logical_checks(self):
496494
"""Run all checks expecting a logical line."""
495+
assert self.processor is not None
497496
comments, logical_line, mapping = self.processor.build_logical_line()
498497
if not mapping:
499498
return
@@ -522,6 +521,7 @@ def run_physical_checks(self, physical_line):
522521
523522
A single physical check may return multiple errors.
524523
"""
524+
assert self.processor is not None
525525
for plugin in self.checks["physical_line_plugins"]:
526526
self.processor.update_checker_state_for(plugin)
527527
result = self.run_check(plugin, physical_line=physical_line)
@@ -554,6 +554,7 @@ def process_tokens(self):
554554
Instead of using this directly, you should use
555555
:meth:`flake8.checker.FileChecker.run_checks`.
556556
"""
557+
assert self.processor is not None
557558
parens = 0
558559
statistics = self.statistics
559560
file_processor = self.processor
@@ -577,6 +578,7 @@ def process_tokens(self):
577578

578579
def run_checks(self):
579580
"""Run checks against the file."""
581+
assert self.processor is not None
580582
try:
581583
self.process_tokens()
582584
self.run_ast_checks()
@@ -594,6 +596,7 @@ def run_checks(self):
594596

595597
def handle_newline(self, token_type):
596598
"""Handle the logic when encountering a newline token."""
599+
assert self.processor is not None
597600
if token_type == tokenize.NEWLINE:
598601
self.run_logical_checks()
599602
self.processor.reset_blank_before()
@@ -608,6 +611,7 @@ def check_physical_eol(
608611
self, token: processor._Token, prev_physical: str
609612
) -> None:
610613
"""Run physical checks if and only if it is at the end of the line."""
614+
assert self.processor is not None
611615
# a newline token ends a single physical line.
612616
if processor.is_eol_token(token):
613617
# if the file does not end with a newline, the NEWLINE

‎src/flake8/main/application.py

+29-8
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def __init__(self, program="flake8", version=flake8.__version__):
4444
#: The timestamp when the Application instance was instantiated.
4545
self.start_time = time.time()
4646
#: The timestamp when the Application finished reported errors.
47-
self.end_time: float = None
47+
self.end_time: Optional[float] = None
4848
#: The name of the program being run
4949
self.program = program
5050
#: The version of the program being run
@@ -63,24 +63,26 @@ def __init__(self, program="flake8", version=flake8.__version__):
6363
options.register_default_options(self.option_manager)
6464

6565
#: The instance of :class:`flake8.plugins.manager.Checkers`
66-
self.check_plugins: plugin_manager.Checkers = None
66+
self.check_plugins: Optional[plugin_manager.Checkers] = None
6767
#: The instance of :class:`flake8.plugins.manager.ReportFormatters`
68-
self.formatting_plugins: plugin_manager.ReportFormatters = None
68+
self.formatting_plugins: Optional[
69+
plugin_manager.ReportFormatters
70+
] = None
6971
#: The user-selected formatter from :attr:`formatting_plugins`
70-
self.formatter: BaseFormatter = None
72+
self.formatter: Optional[BaseFormatter] = None
7173
#: The :class:`flake8.style_guide.StyleGuideManager` built from the
7274
#: user's options
73-
self.guide: style_guide.StyleGuideManager = None
75+
self.guide: Optional[style_guide.StyleGuideManager] = None
7476
#: The :class:`flake8.checker.Manager` that will handle running all of
7577
#: the checks selected by the user.
76-
self.file_checker_manager: checker.Manager = None
78+
self.file_checker_manager: Optional[checker.Manager] = None
7779

7880
#: The user-supplied options parsed into an instance of
7981
#: :class:`argparse.Namespace`
80-
self.options: argparse.Namespace = None
82+
self.options: Optional[argparse.Namespace] = None
8183
#: The left over arguments that were not parsed by
8284
#: :attr:`option_manager`
83-
self.args: List[str] = None
85+
self.args: Optional[List[str]] = None
8486
#: The number of errors, warnings, and other messages after running
8587
#: flake8 and taking into account ignored errors and lines.
8688
self.result_count = 0
@@ -128,6 +130,7 @@ def exit(self) -> None:
128130
This should be the last thing called on the application instance. It
129131
will check certain options and exit appropriately.
130132
"""
133+
assert self.options is not None
131134
if self.options.count:
132135
print(self.result_count)
133136

@@ -162,8 +165,10 @@ def find_plugins(self, config_finder: config.ConfigFileFinder) -> None:
162165

163166
def register_plugin_options(self) -> None:
164167
"""Register options provided by plugins to our option manager."""
168+
assert self.check_plugins is not None
165169
self.check_plugins.register_options(self.option_manager)
166170
self.check_plugins.register_plugin_versions(self.option_manager)
171+
assert self.formatting_plugins is not None
167172
self.formatting_plugins.register_options(self.option_manager)
168173

169174
def parse_configuration_and_cli(
@@ -190,15 +195,18 @@ def parse_configuration_and_cli(
190195
if not self.parsed_diff:
191196
self.exit()
192197

198+
assert self.check_plugins is not None
193199
self.check_plugins.provide_options(
194200
self.option_manager, self.options, self.args
195201
)
202+
assert self.formatting_plugins is not None
196203
self.formatting_plugins.provide_options(
197204
self.option_manager, self.options, self.args
198205
)
199206

200207
def formatter_for(self, formatter_plugin_name):
201208
"""Retrieve the formatter class by plugin name."""
209+
assert self.formatting_plugins is not None
202210
default_formatter = self.formatting_plugins["default"]
203211
formatter_plugin = self.formatting_plugins.get(formatter_plugin_name)
204212
if formatter_plugin is None:
@@ -214,6 +222,7 @@ def make_formatter(
214222
self, formatter_class: Optional[Type["BaseFormatter"]] = None
215223
) -> None:
216224
"""Initialize a formatter based on the parsed options."""
225+
assert self.options is not None
217226
format_plugin = self.options.format
218227
if 1 <= self.options.quiet < 2:
219228
format_plugin = "quiet-filename"
@@ -227,6 +236,8 @@ def make_formatter(
227236

228237
def make_guide(self) -> None:
229238
"""Initialize our StyleGuide."""
239+
assert self.formatter is not None
240+
assert self.options is not None
230241
self.guide = style_guide.StyleGuideManager(
231242
self.options, self.formatter
232243
)
@@ -252,6 +263,7 @@ def run_checks(self, files: Optional[List[str]] = None) -> None:
252263
:param list files:
253264
List of filenames to process
254265
"""
266+
assert self.file_checker_manager is not None
255267
if self.running_against_diff:
256268
files = sorted(self.parsed_diff)
257269
self.file_checker_manager.start(files)
@@ -267,9 +279,12 @@ def run_checks(self, files: Optional[List[str]] = None) -> None:
267279

268280
def report_benchmarks(self):
269281
"""Aggregate, calculate, and report benchmarks for this run."""
282+
assert self.options is not None
270283
if not self.options.benchmark:
271284
return
272285

286+
assert self.file_checker_manager is not None
287+
assert self.end_time is not None
273288
time_elapsed = self.end_time - self.start_time
274289
statistics = [("seconds elapsed", time_elapsed)]
275290
add_statistic = statistics.append
@@ -280,6 +295,7 @@ def report_benchmarks(self):
280295
per_second_description = f"{statistic} processed per second"
281296
add_statistic((per_second_description, int(value / time_elapsed)))
282297

298+
assert self.formatter is not None
283299
self.formatter.show_benchmarks(statistics)
284300

285301
def report_errors(self) -> None:
@@ -289,6 +305,7 @@ def report_errors(self) -> None:
289305
number of errors, warnings, and other messages found.
290306
"""
291307
LOG.info("Reporting errors")
308+
assert self.file_checker_manager is not None
292309
results = self.file_checker_manager.report()
293310
self.total_result_count, self.result_count = results
294311
LOG.info(
@@ -299,9 +316,12 @@ def report_errors(self) -> None:
299316

300317
def report_statistics(self):
301318
"""Aggregate and report statistics from this run."""
319+
assert self.options is not None
302320
if not self.options.statistics:
303321
return
304322

323+
assert self.formatter is not None
324+
assert self.guide is not None
305325
self.formatter.show_statistics(self.guide.stats)
306326

307327
def initialize(self, argv: List[str]) -> None:
@@ -332,6 +352,7 @@ def initialize(self, argv: List[str]) -> None:
332352

333353
def report(self):
334354
"""Report errors, statistics, and benchmarks."""
355+
assert self.formatter is not None
335356
self.formatter.start()
336357
self.report_errors()
337358
self.report_statistics()

‎src/flake8/plugins/manager.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,9 @@ def _load_local_plugins(self, local_plugins):
251251
for plugin_str in local_plugins:
252252
name, _, entry_str = plugin_str.partition("=")
253253
name, entry_str = name.strip(), entry_str.strip()
254-
entry_point = importlib_metadata.EntryPoint(name, entry_str, None)
254+
entry_point = importlib_metadata.EntryPoint(
255+
name, entry_str, self.namespace
256+
)
255257
self._load_plugin_from_entrypoint(entry_point, local=True)
256258

257259
def _load_entrypoint_plugins(self):

‎src/flake8/style_guide.py

+13-14
Original file line numberDiff line numberDiff line change
@@ -54,20 +54,19 @@ def find_noqa(physical_line: str) -> Optional[Match[str]]:
5454
return defaults.NOQA_INLINE_REGEXP.search(physical_line)
5555

5656

57-
_Violation = collections.namedtuple(
58-
"Violation",
59-
[
60-
"code",
61-
"filename",
62-
"line_number",
63-
"column_number",
64-
"text",
65-
"physical_line",
66-
],
67-
)
68-
69-
70-
class Violation(_Violation):
57+
class Violation(
58+
collections.namedtuple(
59+
"Violation",
60+
[
61+
"code",
62+
"filename",
63+
"line_number",
64+
"column_number",
65+
"text",
66+
"physical_line",
67+
],
68+
)
69+
):
7170
"""Class representing a violation reported by Flake8."""
7271

7372
def is_inline_ignored(self, disable_noqa: bool) -> bool:

‎src/flake8/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def parse_comma_separated_list(
5757
return [item for item in item_gen if item]
5858

5959

60-
_Token = collections.namedtuple("Token", ("tp", "src"))
60+
_Token = collections.namedtuple("_Token", ("tp", "src"))
6161
_CODE, _FILE, _COLON, _COMMA, _WS = "code", "file", "colon", "comma", "ws"
6262
_EOF = "eof"
6363
_FILE_LIST_TOKEN_TYPES = [

‎tests/integration/test_plugins.py

+4
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ def test_enable_local_plugin_from_config():
4141
app = application.Application()
4242
app.initialize(['flake8', '--config', LOCAL_PLUGIN_CONFIG])
4343

44+
assert app.check_plugins is not None
4445
assert app.check_plugins['XE'].plugin is ExtensionTestPlugin
46+
assert app.formatting_plugins is not None
4547
assert app.formatting_plugins['XR'].plugin is ReportTestPlugin
4648

4749

@@ -51,6 +53,7 @@ def test_local_plugin_can_add_option():
5153
app.initialize(
5254
['flake8', '--config', LOCAL_PLUGIN_CONFIG, '--anopt', 'foo'])
5355

56+
assert app.options is not None
5457
assert app.options.anopt == 'foo'
5558

5659

@@ -59,4 +62,5 @@ def test_enable_local_plugin_at_non_installed_path():
5962
app = application.Application()
6063
app.initialize(['flake8', '--config', LOCAL_PLUGIN_PATH_CONFIG])
6164

65+
assert app.check_plugins is not None
6266
assert app.check_plugins['XE'].plugin.name == 'ExtensionTestPlugin2'

‎tests/unit/test_exceptions.py

+28-42
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,34 @@
11
"""Tests for the flake8.exceptions module."""
22
import pickle
33

4-
from flake8 import exceptions
5-
6-
7-
class _ExceptionTest:
8-
def test_pickleable(self):
9-
"""Test that the exception is round-trip pickleable."""
10-
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
11-
new_err = pickle.loads(pickle.dumps(self.err, protocol=proto))
12-
assert str(self.err) == str(new_err)
13-
orig_e = self.err.original_exception
14-
new_e = new_err.original_exception
15-
assert (type(orig_e), orig_e.args) == (type(new_e), new_e.args)
16-
17-
18-
class TestFailedToLoadPlugin(_ExceptionTest):
19-
"""Tests for the FailedToLoadPlugin exception."""
20-
21-
err = exceptions.FailedToLoadPlugin(
22-
plugin_name='plugin_name',
23-
exception=ValueError('boom!'),
24-
)
25-
26-
27-
class TestInvalidSyntax(_ExceptionTest):
28-
"""Tests for the InvalidSyntax exception."""
29-
30-
err = exceptions.InvalidSyntax(exception=ValueError('Unexpected token: $'))
31-
32-
33-
class TestPluginRequestedUnknownParameters(_ExceptionTest):
34-
"""Tests for the PluginRequestedUnknownParameters exception."""
35-
36-
err = exceptions.PluginRequestedUnknownParameters(
37-
plugin={'plugin_name': 'plugin_name'},
38-
exception=ValueError('boom!'),
39-
)
4+
import pytest
405

6+
from flake8 import exceptions
417

42-
class TestPluginExecutionFailed(_ExceptionTest):
43-
"""Tests for the PluginExecutionFailed exception."""
448

45-
err = exceptions.PluginExecutionFailed(
46-
plugin={'plugin_name': 'plugin_name'},
47-
exception=ValueError('boom!'),
48-
)
9+
@pytest.mark.parametrize(
10+
'err',
11+
(
12+
exceptions.FailedToLoadPlugin(
13+
plugin_name='plugin_name',
14+
exception=ValueError('boom!'),
15+
),
16+
exceptions.InvalidSyntax(exception=ValueError('Unexpected token: $')),
17+
exceptions.PluginRequestedUnknownParameters(
18+
plugin={'plugin_name': 'plugin_name'},
19+
exception=ValueError('boom!'),
20+
),
21+
exceptions.PluginExecutionFailed(
22+
plugin={'plugin_name': 'plugin_name'},
23+
exception=ValueError('boom!'),
24+
)
25+
),
26+
)
27+
def test_pickleable(err):
28+
"""Ensure that our exceptions can cross pickle boundaries."""
29+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
30+
new_err = pickle.loads(pickle.dumps(err, protocol=proto))
31+
assert str(err) == str(new_err)
32+
orig_e = err.original_exception
33+
new_e = new_err.original_exception
34+
assert (type(orig_e), orig_e.args) == (type(new_e), new_e.args)

‎tests/unit/test_plugin_manager.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ def test_calls_entrypoints_creates_plugins_automaticaly(entry_points_mck):
1818
"""Verify that we create Plugins on instantiation."""
1919
entry_points_mck.return_value = {
2020
'testing.entrypoints': [
21-
importlib_metadata.EntryPoint('T100', '', None),
22-
importlib_metadata.EntryPoint('T200', '', None),
21+
importlib_metadata.EntryPoint('T100', '', 'testing.entrypoints'),
22+
importlib_metadata.EntryPoint('T200', '', 'testing.entrypoints'),
2323
],
2424
}
2525
plugin_mgr = manager.PluginManager(namespace='testing.entrypoints')
@@ -36,8 +36,8 @@ def test_handles_mapping_functions_across_plugins(entry_points_mck):
3636
"""Verify we can use the PluginManager call functions on all plugins."""
3737
entry_points_mck.return_value = {
3838
'testing.entrypoints': [
39-
importlib_metadata.EntryPoint('T100', '', None),
40-
importlib_metadata.EntryPoint('T200', '', None),
39+
importlib_metadata.EntryPoint('T100', '', 'testing.entrypoints'),
40+
importlib_metadata.EntryPoint('T200', '', 'testing.entrypoints'),
4141
],
4242
}
4343
plugin_mgr = manager.PluginManager(namespace='testing.entrypoints')

0 commit comments

Comments
 (0)
Please sign in to comment.