summaryrefslogtreecommitdiff
path: root/tests/checkers/unittest_unicode/unittest_bad_chars.py
blob: 7746ce4ae727267db55c606ea00ca89a62c64e63 (plain)
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
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt

# pylint: disable=redefined-outer-name

from __future__ import annotations

import itertools
from collections.abc import Callable
from pathlib import Path
from typing import cast

import astroid
import pytest
from astroid import AstroidBuildingError, nodes

import pylint.checkers.unicode
import pylint.interfaces
import pylint.testutils

from . import CODEC_AND_MSG, FakeNode


@pytest.fixture()
def bad_char_file_generator(tmp_path: Path) -> Callable[[str, bool, str], Path]:
    """Generates a test file for bad chars.

    The generator also ensures that file generated is correct
    """

    def encode_without_bom(string: str, encoding: str) -> bytes:
        return pylint.checkers.unicode._encode_without_bom(string, encoding)

    # All lines contain a not extra checked invalid character
    lines = (
        "# Example File containing bad ASCII",
        "# invalid char backspace: \b",
        "# Bad carriage-return \r # not at the end",
        "# Invalid char sub: \x1A",
        "# Invalid char esc: \x1B",
    )

    def _bad_char_file_generator(
        codec: str, add_invalid_bytes: bool, line_ending: str
    ) -> Path:
        byte_suffix = b""
        if add_invalid_bytes:
            if codec == "utf-8":
                byte_suffix = b"BAD:\x80abc"
            elif codec == "utf-16":
                byte_suffix = b"BAD:\n"  # Generates Truncated Data
            else:
                byte_suffix = b"BAD:\xc3\x28 "
            byte_suffix = encode_without_bom(" foobar ", codec) + byte_suffix

        line_ending_encoded = encode_without_bom(line_ending, codec)

        # Start content with BOM / codec definition and two empty lines
        content = f"# coding: {codec} \n # \n ".encode(codec)

        # Generate context with the given codec and line ending
        for lineno, line in enumerate(lines):
            byte_line = encode_without_bom(line, codec)
            byte_line += byte_suffix + line_ending_encoded
            content += byte_line

            # Directly test the generated content
            if not add_invalid_bytes:
                # Test that the content is correct and gives no errors
                try:
                    byte_line.decode(codec, "strict")
                except UnicodeDecodeError as e:
                    raise ValueError(
                        f"Line {lineno} did raise unexpected error: {byte_line!r}\n{e}"
                    ) from e
            else:
                try:
                    # But if there was a byte_suffix we expect an error
                    # because that is what we want to test for
                    byte_line.decode(codec, "strict")
                except UnicodeDecodeError:
                    ...
                else:
                    raise ValueError(
                        f"Line {lineno} did not raise decode error: {byte_line!r}"
                    )

        file = tmp_path / "bad_chars.py"
        file.write_bytes(content)
        return file

    return _bad_char_file_generator


class TestBadCharsChecker(pylint.testutils.CheckerTestCase):
    CHECKER_CLASS = pylint.checkers.unicode.UnicodeChecker

    checker: pylint.checkers.unicode.UnicodeChecker

    @pytest.mark.parametrize(
        "codec_and_msg, line_ending, add_invalid_bytes",
        [
            pytest.param(
                codec_and_msg,
                line_ending[0],
                suffix[0],
                id=f"{codec_and_msg[0]}_{line_ending[1]}_{suffix[1]}",
            )
            for codec_and_msg, line_ending, suffix in itertools.product(
                CODEC_AND_MSG,
                (("\n", "linux"), ("\r\n", "windows")),
                ((False, "valid_line"), (True, "not_decode_able_line")),
            )
            # Only utf8 can drop invalid lines
            if codec_and_msg[0].startswith("utf") or not suffix[0]
        ],
    )
    def test_find_bad_chars(
        self,
        bad_char_file_generator: Callable[[str, bool, str], Path],
        codec_and_msg: tuple[str, tuple[pylint.testutils.MessageTest]],
        line_ending: str,
        add_invalid_bytes: bool,
    ) -> None:
        """All combinations of bad characters that are accepted by Python at the moment
        are tested in all possible combinations of
          - line ending
          - encoding
          - including not encode-able byte (or not)
        """
        codec, start_msg = codec_and_msg

        start_lines = 2

        file = bad_char_file_generator(codec, add_invalid_bytes, line_ending)

        try:
            # We need to use ast from file as only this function reads bytes and not
            # string
            module = astroid.MANAGER.ast_from_string(file)
        except AstroidBuildingError:
            # pylint: disable-next=redefined-variable-type
            module = cast(nodes.Module, FakeNode(file.read_bytes()))

        expected = [
            *start_msg,
            pylint.testutils.MessageTest(
                msg_id="invalid-character-backspace",
                line=2 + start_lines,
                end_line=2 + start_lines,
                # node=module,
                args=None,
                confidence=pylint.interfaces.HIGH,
                col_offset=27,
                end_col_offset=28,
            ),
            pylint.testutils.MessageTest(
                msg_id="invalid-character-carriage-return",
                line=3 + start_lines,
                end_line=3 + start_lines,
                # node=module,
                args=None,
                confidence=pylint.interfaces.HIGH,
                col_offset=23,
                end_col_offset=24,
            ),
            pylint.testutils.MessageTest(
                msg_id="invalid-character-sub",
                line=4 + start_lines,
                end_line=4 + start_lines,
                # node=module,
                args=None,
                confidence=pylint.interfaces.HIGH,
                col_offset=21,
                end_col_offset=22,
            ),
            pylint.testutils.MessageTest(
                msg_id="invalid-character-esc",
                line=5 + start_lines,
                end_line=5 + start_lines,
                # node=module,
                args=None,
                confidence=pylint.interfaces.HIGH,
                col_offset=21,
                end_col_offset=22,
            ),
        ]
        with self.assertAddsMessages(*expected):
            self.checker.process_module(module)

    @pytest.mark.parametrize(
        "codec_and_msg, char, msg_id",
        [
            pytest.param(
                codec_and_msg,
                char_msg[0],
                char_msg[1],
                id=f"{char_msg[1]}_{codec_and_msg[0]}",
            )
            for codec_and_msg, char_msg in itertools.product(
                CODEC_AND_MSG,
                (
                    ("\0", "invalid-character-nul"),
                    ("\N{ZERO WIDTH SPACE}", "invalid-character-zero-width-space"),
                ),
            )
            # Only utf contains zero width space
            if (
                char_msg[0] != "\N{ZERO WIDTH SPACE}"
                or codec_and_msg[0].startswith("utf")
            )
        ],
    )
    def test_bad_chars_that_would_currently_crash_python(
        self,
        char: str,
        msg_id: str,
        codec_and_msg: tuple[str, tuple[pylint.testutils.MessageTest]],
    ) -> None:
        """Special test for a file containing chars that lead to
        Python or Astroid crashes (which causes Pylint to exit early)
        """
        codec, start_msg = codec_and_msg
        # Create file that will fail loading in astroid.
        # We still want to check this, in case this behavior changes
        content = f"# # coding: {codec}\n# file containing {char} <-\n"
        module = FakeNode(content.encode(codec))

        expected = [
            *start_msg,
            pylint.testutils.MessageTest(
                msg_id=msg_id,
                line=2,
                end_line=2,
                # node=module,
                args=None,
                confidence=pylint.interfaces.HIGH,
                col_offset=19,
                end_col_offset=20,
            ),
        ]

        with self.assertAddsMessages(*expected):
            self.checker.process_module(cast(nodes.Module, module))

    @pytest.mark.parametrize(
        "char, msg, codec",
        [
            pytest.param(
                char.unescaped,
                char.human_code(),
                codec_and_msg[0],
                id=f"{char.name}_{codec_and_msg[0]}",
            )
            for char, codec_and_msg in itertools.product(
                pylint.checkers.unicode.BAD_CHARS, CODEC_AND_MSG
            )
            # Only utf contains zero width space
            if (
                char.unescaped != "\N{ZERO WIDTH SPACE}"
                or codec_and_msg[0].startswith("utf")
            )
        ],
    )
    def test___check_invalid_chars(self, char: str, msg: str, codec: str) -> None:
        """Check function should deliver correct column no matter which codec we used."""
        with self.assertAddsMessages(
            pylint.testutils.MessageTest(
                msg_id=msg,
                line=55,
                args=None,
                confidence=pylint.interfaces.HIGH,
                end_line=55,
                col_offset=5,
                end_col_offset=6,
            )
        ):
            self.checker._check_invalid_chars(f"#234{char}".encode(codec), 55, codec)