File: test_file_processor.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 (392 lines) | stat: -rw-r--r-- 12,259 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
"""Tests for the FileProcessor class."""
from __future__ import annotations

import ast
import tokenize
from unittest import mock

import pytest

from flake8 import processor


def test_read_lines_splits_lines(default_options):
    """Verify that read_lines splits the lines of the file."""
    file_processor = processor.FileProcessor(__file__, default_options)
    lines = file_processor.lines
    assert len(lines) > 5
    assert lines[0].strip() == '"""Tests for the FileProcessor class."""'


def _lines_from_file(tmpdir, contents, options):
    f = tmpdir.join("f.py")
    # be careful to write the bytes exactly to avoid newline munging
    f.write_binary(contents)
    return processor.FileProcessor(f.strpath, options).lines


def test_read_lines_universal_newlines(tmpdir, default_options):
    r"""Verify that line endings are translated to \n."""
    lines = _lines_from_file(
        tmpdir, b"# coding: utf-8\r\nx = 1\r\n", default_options
    )
    assert lines == ["# coding: utf-8\n", "x = 1\n"]


def test_read_lines_incorrect_utf_16(tmpdir, default_options):
    """Verify that an incorrectly encoded file is read as latin-1."""
    lines = _lines_from_file(
        tmpdir, b"# coding: utf16\nx = 1\n", default_options
    )
    assert lines == ["# coding: utf16\n", "x = 1\n"]


def test_read_lines_unknown_encoding(tmpdir, default_options):
    """Verify that an unknown encoding is still read as latin-1."""
    lines = _lines_from_file(
        tmpdir, b"# coding: fake-encoding\nx = 1\n", default_options
    )
    assert lines == ["# coding: fake-encoding\n", "x = 1\n"]


@pytest.mark.parametrize(
    "first_line",
    [
        '\xEF\xBB\xBF"""Module docstring."""\n',
        '\uFEFF"""Module docstring."""\n',
    ],
)
def test_strip_utf_bom(first_line, default_options):
    r"""Verify that we strip '\xEF\xBB\xBF' from the first line."""
    lines = [first_line]
    file_processor = processor.FileProcessor("-", default_options, lines[:])
    assert file_processor.lines != lines
    assert file_processor.lines[0] == '"""Module docstring."""\n'


@pytest.mark.parametrize(
    "lines, expected",
    [
        (['\xEF\xBB\xBF"""Module docstring."""\n'], False),
        (['\uFEFF"""Module docstring."""\n'], False),
        (["#!/usr/bin/python", "# flake8 is great", "a = 1"], False),
        (["#!/usr/bin/python", "# flake8: noqa", "a = 1"], True),
        (["#!/usr/bin/python", "# flake8:noqa", "a = 1"], True),
        (["# flake8: noqa", "#!/usr/bin/python", "a = 1"], True),
        (["# flake8:noqa", "#!/usr/bin/python", "a = 1"], True),
        (["#!/usr/bin/python", "a = 1", "# flake8: noqa"], True),
        (["#!/usr/bin/python", "a = 1", "# flake8:noqa"], True),
        (["#!/usr/bin/python", "a = 1  # flake8: noqa"], False),
        (["#!/usr/bin/python", "a = 1  # flake8:noqa"], False),
    ],
)
def test_should_ignore_file(lines, expected, default_options):
    """Verify that we ignore a file if told to."""
    file_processor = processor.FileProcessor("-", default_options, lines)
    assert file_processor.should_ignore_file() is expected


def test_should_ignore_file_to_handle_disable_noqa(default_options):
    """Verify that we ignore a file if told to."""
    lines = ["# flake8: noqa"]
    file_processor = processor.FileProcessor("-", default_options, lines)
    assert file_processor.should_ignore_file() is True
    default_options.disable_noqa = True
    file_processor = processor.FileProcessor("-", default_options, lines)
    assert file_processor.should_ignore_file() is False


@mock.patch("flake8.utils.stdin_get_value")
def test_read_lines_from_stdin(stdin_get_value, default_options):
    """Verify that we use our own utility function to retrieve stdin."""
    stdin_get_value.return_value = ""
    processor.FileProcessor("-", default_options)
    stdin_get_value.assert_called_once_with()


@mock.patch("flake8.utils.stdin_get_value")
def test_stdin_filename_attribute(stdin_get_value, default_options):
    """Verify that we update the filename attribute."""
    stdin_get_value.return_value = ""
    file_processor = processor.FileProcessor("-", default_options)
    assert file_processor.filename == "stdin"


@mock.patch("flake8.utils.stdin_get_value")
def test_read_lines_uses_display_name(stdin_get_value, default_options):
    """Verify that when processing stdin we use a display name if present."""
    default_options.stdin_display_name = "display_name.py"
    stdin_get_value.return_value = ""
    file_processor = processor.FileProcessor("-", default_options)
    assert file_processor.filename == "display_name.py"


@mock.patch("flake8.utils.stdin_get_value")
def test_read_lines_ignores_empty_display_name(
    stdin_get_value,
    default_options,
):
    """Verify that when processing stdin we use a display name if present."""
    stdin_get_value.return_value = ""
    default_options.stdin_display_name = ""
    file_processor = processor.FileProcessor("-", default_options)
    assert file_processor.filename == "stdin"


def test_noqa_line_for(default_options):
    """Verify we grab the correct line from the cached lines."""
    file_processor = processor.FileProcessor(
        "-",
        default_options,
        lines=[
            "Line 1\n",
            "Line 2\n",
            "Line 3\n",
        ],
    )

    for i in range(1, 4):
        assert file_processor.noqa_line_for(i) == f"Line {i}\n"


def test_noqa_line_for_continuation(default_options):
    """Verify that the correct "line" is retrieved for continuation."""
    src = '''\
from foo \\
    import bar  # 2

x = """
hello
world
"""  # 7
'''
    lines = src.splitlines(True)
    file_processor = processor.FileProcessor("-", default_options, lines=lines)

    assert file_processor.noqa_line_for(0) is None

    l_1_2 = "from foo \\\n    import bar  # 2\n"
    assert file_processor.noqa_line_for(1) == l_1_2
    assert file_processor.noqa_line_for(2) == l_1_2

    assert file_processor.noqa_line_for(3) == "\n"

    l_4_7 = 'x = """\nhello\nworld\n"""  # 7\n'
    for i in (4, 5, 6, 7):
        assert file_processor.noqa_line_for(i) == l_4_7

    assert file_processor.noqa_line_for(8) is None


def test_noqa_line_for_no_eol_at_end_of_file(default_options):
    """Verify that we properly handle noqa line at the end of the file."""
    src = "from foo \\\nimport bar"  # no end of file newline
    lines = src.splitlines(True)
    file_processor = processor.FileProcessor("-", default_options, lines=lines)

    l_1_2 = "from foo \\\nimport bar"
    assert file_processor.noqa_line_for(1) == l_1_2
    assert file_processor.noqa_line_for(2) == l_1_2


def test_next_line(default_options):
    """Verify we update the file_processor state for each new line."""
    file_processor = processor.FileProcessor(
        "-",
        default_options,
        lines=[
            "Line 1",
            "Line 2",
            "Line 3",
        ],
    )

    for i in range(1, 4):
        assert file_processor.next_line() == f"Line {i}"
        assert file_processor.line_number == i


@pytest.mark.parametrize(
    "params, args, expected_kwargs",
    [
        (
            {"blank_before": True, "blank_lines": True},
            {},
            {"blank_before": 0, "blank_lines": 0},
        ),
        (
            {"noqa": True, "fake": True},
            {"fake": "foo"},
            {"noqa": False},
        ),
        (
            {"blank_before": True, "blank_lines": True, "noqa": True},
            {"blank_before": 10, "blank_lines": 5, "noqa": True},
            {},
        ),
        ({}, {"fake": "foo"}, {}),
        ({"non-existent": False}, {"fake": "foo"}, {}),
    ],
)
def test_keyword_arguments_for(params, args, expected_kwargs, default_options):
    """Verify the keyword args are generated properly."""
    file_processor = processor.FileProcessor(
        "-",
        default_options,
        lines=[
            "Line 1",
        ],
    )
    ret = file_processor.keyword_arguments_for(params, args)

    assert ret == expected_kwargs


def test_keyword_arguments_for_does_not_handle_attribute_errors(
    default_options,
):
    """Verify we re-raise AttributeErrors."""
    file_processor = processor.FileProcessor(
        "-",
        default_options,
        lines=[
            "Line 1",
        ],
    )

    with pytest.raises(AttributeError):
        file_processor.keyword_arguments_for({"fake": True}, {})


def test_processor_split_line(default_options):
    file_processor = processor.FileProcessor(
        "-",
        default_options,
        lines=[
            'x = """\n',
            "contents\n",
            '"""\n',
        ],
    )
    token = tokenize.TokenInfo(
        3,
        '"""\ncontents\n"""',
        (1, 4),
        (3, 3),
        'x = """\ncontents\n"""\n',
    )
    expected = [('x = """\n', 1, True), ("contents\n", 2, True)]
    assert file_processor.multiline is False
    actual = [
        (line, file_processor.line_number, file_processor.multiline)
        for line in file_processor.multiline_string(token)
    ]
    assert file_processor.multiline is False
    assert expected == actual
    assert file_processor.line_number == 3


def test_build_ast(default_options):
    """Verify the logic for how we build an AST for plugins."""
    file_processor = processor.FileProcessor(
        "-", default_options, lines=["a = 1\n"]
    )

    module = file_processor.build_ast()
    assert isinstance(module, ast.Module)


def test_next_logical_line_updates_the_previous_logical_line(default_options):
    """Verify that we update our tracking of the previous logical line."""
    file_processor = processor.FileProcessor(
        "-", default_options, lines=["a = 1\n"]
    )

    file_processor.indent_level = 1
    file_processor.logical_line = "a = 1"
    assert file_processor.previous_logical == ""
    assert file_processor.previous_indent_level == 0

    file_processor.next_logical_line()
    assert file_processor.previous_logical == "a = 1"
    assert file_processor.previous_indent_level == 1


def test_visited_new_blank_line(default_options):
    """Verify we update the number of blank lines seen."""
    file_processor = processor.FileProcessor(
        "-", default_options, lines=["a = 1\n"]
    )

    assert file_processor.blank_lines == 0
    file_processor.visited_new_blank_line()
    assert file_processor.blank_lines == 1


@pytest.mark.parametrize(
    "string, expected",
    [
        ('""', '""'),
        ("''", "''"),
        ('"a"', '"x"'),
        ("'a'", "'x'"),
        ('"x"', '"x"'),
        ("'x'", "'x'"),
        ('"abcdef"', '"xxxxxx"'),
        ("'abcdef'", "'xxxxxx'"),
        ('""""""', '""""""'),
        ("''''''", "''''''"),
        ('"""a"""', '"""x"""'),
        ("'''a'''", "'''x'''"),
        ('"""x"""', '"""x"""'),
        ("'''x'''", "'''x'''"),
        ('"""abcdef"""', '"""xxxxxx"""'),
        ("'''abcdef'''", "'''xxxxxx'''"),
        ('"""xxxxxx"""', '"""xxxxxx"""'),
        ("'''xxxxxx'''", "'''xxxxxx'''"),
    ],
)
def test_mutate_string(string, expected, default_options):
    """Verify we appropriately mutate the string to sanitize it."""
    actual = processor.mutate_string(string)
    assert expected == actual


@pytest.mark.parametrize(
    "string, expected",
    [
        ("    ", 4),
        ("      ", 6),
        ("\t", 8),
        ("\t\t", 16),
        ("       \t", 8),
        ("        \t", 16),
    ],
)
def test_expand_indent(string, expected):
    """Verify we correctly measure the amount of indentation."""
    actual = processor.expand_indent(string)
    assert expected == actual


@pytest.mark.parametrize(
    "current_count, token_text, expected",
    [
        (0, "(", 1),
        (0, "[", 1),
        (0, "{", 1),
        (1, ")", 0),
        (1, "]", 0),
        (1, "}", 0),
        (10, "+", 10),
    ],
)
def test_count_parentheses(current_count, token_text, expected):
    """Verify our arithmetic is correct."""
    assert processor.count_parentheses(current_count, token_text) == expected


def test_nonexistent_file(default_options):
    """Verify that FileProcessor raises IOError when a file does not exist."""
    with pytest.raises(IOError):
        processor.FileProcessor("foobar.py", default_options)