File: test_plugins.py

package info (click to toggle)
python-flake8 7.1.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,212 kB
  • sloc: python: 6,592; sh: 21; makefile: 19
file content (298 lines) | stat: -rw-r--r-- 7,028 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""Integration tests for plugin loading."""
from __future__ import annotations

import sys

import pytest

from flake8.main.cli import main
from flake8.main.options import register_default_options
from flake8.main.options import stage1_arg_parser
from flake8.options import aggregator
from flake8.options import config
from flake8.options.manager import OptionManager
from flake8.plugins import finder


class ExtensionTestPlugin:
    """Extension test plugin."""

    def __init__(self, tree):
        """Construct an instance of test plugin."""

    def run(self):
        """Do nothing."""

    @classmethod
    def add_options(cls, parser):
        """Register options."""
        parser.add_option("--anopt")


class ReportTestPlugin:
    """Report test plugin."""

    def __init__(self, tree):
        """Construct an instance of test plugin."""

    def run(self):
        """Do nothing."""


@pytest.fixture
def local_config(tmp_path):
    cfg_s = f"""\
[flake8:local-plugins]
extension =
    XE = {ExtensionTestPlugin.__module__}:{ExtensionTestPlugin.__name__}
report =
    XR = {ReportTestPlugin.__module__}:{ReportTestPlugin.__name__}
"""
    cfg = tmp_path.joinpath("tox.ini")
    cfg.write_text(cfg_s)

    return str(cfg)


def test_enable_local_plugin_from_config(local_config):
    """App can load a local plugin from config file."""
    cfg, cfg_dir = config.load_config(local_config, [], isolated=False)
    opts = finder.parse_plugin_options(
        cfg,
        cfg_dir,
        enable_extensions=None,
        require_plugins=None,
    )
    plugins = finder.find_plugins(cfg, opts)
    loaded_plugins = finder.load_plugins(plugins, opts)

    (custom_extension,) = (
        loaded
        for loaded in loaded_plugins.checkers.tree
        if loaded.entry_name == "XE"
    )
    custom_report = loaded_plugins.reporters["XR"]

    assert custom_extension.obj is ExtensionTestPlugin
    assert custom_report.obj is ReportTestPlugin


def test_local_plugin_can_add_option(local_config):
    """A local plugin can add a CLI option."""

    argv = ["--config", local_config, "--anopt", "foo"]

    stage1_parser = stage1_arg_parser()
    stage1_args, rest = stage1_parser.parse_known_args(argv)

    cfg, cfg_dir = config.load_config(
        config=stage1_args.config, extra=[], isolated=False
    )

    opts = finder.parse_plugin_options(
        cfg,
        cfg_dir,
        enable_extensions=None,
        require_plugins=None,
    )
    plugins = finder.find_plugins(cfg, opts)
    loaded_plugins = finder.load_plugins(plugins, opts)

    option_manager = OptionManager(
        version="123",
        plugin_versions="",
        parents=[stage1_parser],
        formatter_names=[],
    )
    register_default_options(option_manager)
    option_manager.register_plugins(loaded_plugins)

    args = aggregator.aggregate_options(option_manager, cfg, cfg_dir, argv)

    assert args.extended_default_select == ["XE", "C90", "F", "E", "W"]
    assert args.anopt == "foo"


class AlwaysErrors:
    def __init__(self, tree):
        pass

    def run(self):
        yield 1, 0, "ABC123 error", type(self)


class AlwaysErrorsDisabled(AlwaysErrors):
    off_by_default = True


def test_plugin_gets_enabled_by_default(tmp_path, capsys):
    cfg_s = f"""\
[flake8:local-plugins]
extension =
    ABC = {AlwaysErrors.__module__}:{AlwaysErrors.__name__}
"""
    cfg = tmp_path.joinpath("tox.ini")
    cfg.write_text(cfg_s)

    t_py = tmp_path.joinpath("t.py")
    t_py.touch()

    assert main((str(t_py), "--config", str(cfg))) == 1
    out, err = capsys.readouterr()
    assert out == f"{t_py}:1:1: ABC123 error\n"
    assert err == ""


def test_plugin_off_by_default(tmp_path, capsys):
    cfg_s = f"""\
[flake8:local-plugins]
extension =
    ABC = {AlwaysErrorsDisabled.__module__}:{AlwaysErrorsDisabled.__name__}
"""
    cfg = tmp_path.joinpath("tox.ini")
    cfg.write_text(cfg_s)

    t_py = tmp_path.joinpath("t.py")
    t_py.touch()

    cmd = (str(t_py), "--config", str(cfg))

    assert main(cmd) == 0
    out, err = capsys.readouterr()
    assert out == err == ""

    assert main((*cmd, "--enable-extension=ABC")) == 1
    out, err = capsys.readouterr()
    assert out == f"{t_py}:1:1: ABC123 error\n"
    assert err == ""


def yields_physical_line(physical_line):
    yield 0, f"T001 {physical_line!r}"


def test_physical_line_plugin_multiline_string(tmpdir, capsys):
    cfg_s = f"""\
[flake8:local-plugins]
extension =
    T = {yields_physical_line.__module__}:{yields_physical_line.__name__}
"""

    cfg = tmpdir.join("tox.ini")
    cfg.write(cfg_s)

    src = '''\
x = "foo" + """
bar
"""
'''
    t_py = tmpdir.join("t.py")
    t_py.write_binary(src.encode())

    with tmpdir.as_cwd():
        assert main(("t.py", "--config", str(cfg))) == 1

    expected = '''\
t.py:1:1: T001 'x = "foo" + """\\n'
t.py:2:1: T001 'bar\\n'
t.py:3:1: T001 '"""\\n'
'''
    out, err = capsys.readouterr()
    assert out == expected


def test_physical_line_plugin_multiline_fstring(tmpdir, capsys):
    cfg_s = f"""\
[flake8:local-plugins]
extension =
    T = {yields_physical_line.__module__}:{yields_physical_line.__name__}
"""

    cfg = tmpdir.join("tox.ini")
    cfg.write(cfg_s)

    src = '''\
y = 1
x = f"""
hello {y}
"""
'''
    t_py = tmpdir.join("t.py")
    t_py.write_binary(src.encode())

    with tmpdir.as_cwd():
        assert main(("t.py", "--config", str(cfg))) == 1

    expected = '''\
t.py:1:1: T001 'y = 1\\n'
t.py:2:1: T001 'x = f"""\\n'
t.py:3:1: T001 'hello {y}\\n'
t.py:4:1: T001 '"""\\n'
'''
    out, err = capsys.readouterr()
    assert out == expected


def yields_logical_line(logical_line):
    yield 0, f"T001 {logical_line!r}"


def test_logical_line_plugin(tmpdir, capsys):
    cfg_s = f"""\
[flake8]
extend-ignore = F
[flake8:local-plugins]
extension =
    T = {yields_logical_line.__module__}:{yields_logical_line.__name__}
"""

    cfg = tmpdir.join("tox.ini")
    cfg.write(cfg_s)

    src = """\
f'hello world'
"""
    t_py = tmpdir.join("t.py")
    t_py.write_binary(src.encode())

    with tmpdir.as_cwd():
        assert main(("t.py", "--config", str(cfg))) == 1

    expected = """\
t.py:1:1: T001 "f'xxxxxxxxxxx'"
"""
    out, err = capsys.readouterr()
    assert out == expected


def test_escaping_of_fstrings_in_string_redacter(tmpdir, capsys):
    cfg_s = f"""\
[flake8]
extend-ignore = F
[flake8:local-plugins]
extension =
    T = {yields_logical_line.__module__}:{yields_logical_line.__name__}
"""

    cfg = tmpdir.join("tox.ini")
    cfg.write(cfg_s)

    src = """\
f'{{"{hello}": "{world}"}}'
"""
    t_py = tmpdir.join("t.py")
    t_py.write_binary(src.encode())

    with tmpdir.as_cwd():
        assert main(("t.py", "--config", str(cfg))) == 1

    if sys.version_info >= (3, 12):  # pragma: >=3.12 cover
        expected = """\
t.py:1:1: T001 "f'xxx{hello}xxxx{world}xxx'"
"""
    else:  # pragma: <3.12 cover
        expected = """\
t.py:1:1: T001 "f'xxxxxxxxxxxxxxxxxxxxxxxx'"
"""
    out, err = capsys.readouterr()
    assert out == expected