summaryrefslogtreecommitdiff
path: root/tests/checkers/unittest_non_ascii_name.py
blob: 0741a9fb081a3c84a9c50ddb82218b3b0f89c6df (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
280
281
282
283
284
285
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt

from __future__ import annotations

import sys
from collections.abc import Iterable

import astroid
import pytest
from astroid import nodes

import pylint.checkers.non_ascii_names
import pylint.interfaces
import pylint.testutils


class TestNonAsciiChecker(pylint.testutils.CheckerTestCase):
    CHECKER_CLASS = pylint.checkers.non_ascii_names.NonAsciiNameChecker
    checker: pylint.checkers.non_ascii_names.NonAsciiNameChecker

    @pytest.mark.skipif(
        sys.version_info < (3, 8), reason="requires python3.8 or higher"
    )
    def test_kwargs_and_position_only(self) -> None:
        """Even the new position only and keyword only should be found."""
        node = astroid.extract_node(
            """
                def name(
                    ok,
                    not_økay,
                    not_okay_defaułt=None,
                    /,
                    p_or_kw_okay=None,
                    p_or_kw_not_økay=None,
                    *,
                    kw_arg_okay,
                    kw_arg_not_økay,
                ):
                    ...
            """
        )
        assert isinstance(node, nodes.FunctionDef)
        arguments = node.args

        posargs = list(arguments.posonlyargs)
        args = list(arguments.args)
        kwargs = list(arguments.kwonlyargs)

        with self.assertAddsMessages(
            pylint.testutils.MessageTest(
                msg_id="non-ascii-name",
                node=posargs[1],
                args=("Argument", "not_økay"),
                confidence=pylint.interfaces.HIGH,
            ),
            pylint.testutils.MessageTest(
                msg_id="non-ascii-name",
                node=posargs[2],
                args=("Argument", "not_okay_defaułt"),
                confidence=pylint.interfaces.HIGH,
            ),
            pylint.testutils.MessageTest(
                msg_id="non-ascii-name",
                node=args[1],
                args=("Argument", "p_or_kw_not_økay"),
                confidence=pylint.interfaces.HIGH,
            ),
            pylint.testutils.MessageTest(
                msg_id="non-ascii-name",
                node=kwargs[1],
                args=("Argument", "kw_arg_not_økay"),
                confidence=pylint.interfaces.HIGH,
            ),
            ignore_position=True,
        ):
            self.checker.visit_functiondef(node)

    @pytest.mark.parametrize(
        "code, assign_type",
        [
            pytest.param(
                """
                try:
                    ...
                except ValueError as łol: #@
                    ...
                """,
                "Variable",
                id="try-except",
            ),
            pytest.param(
                """
                class FooBar:
                    łol = "test" #@
                """,
                "Attribute",
                id="class_attribute",
            ),
            pytest.param(
                """
                łol = "test" #@
                """,
                "Variable",
                id="global_assign",
            ),
            pytest.param(
                """
                def foobar():
                    łol="test"  #@
                """,
                "Variable",
                id="function_variable",
            ),
            pytest.param(
                """
                for łol in os.listdir("."):  #@
                    ...
                """,
                "Variable",
                id="for_loop_variable",
            ),
            pytest.param(
                """
                [łoł
                    for łol in os.listdir(".")  #@
                ]
                """,
                "Variable",
                id="inline_for_loop_variable",
            ),
        ],
    )
    def test_assignname(
        self,
        code: str,
        assign_type: str,
    ) -> None:
        """Variables defined no matter where, should be checked for non ascii."""
        assign_node = astroid.extract_node(code)

        if not isinstance(assign_node, nodes.AssignName):
            # For some elements we can't directly extract the assign
            # node, so we have to manually look in the children for it
            for child in assign_node.get_children():
                if isinstance(child, nodes.AssignName):
                    assign_node = child
                    break

        # Just to make sure we found the correct node
        assert isinstance(assign_node, nodes.AssignName)

        with self.assertAddsMessages(
            pylint.testutils.MessageTest(
                msg_id="non-ascii-name",
                node=assign_node,
                args=(assign_type, "łol"),
                confidence=pylint.interfaces.HIGH,
            ),
            ignore_position=True,
        ):
            self.checker.visit_assignname(assign_node)

    @pytest.mark.parametrize(
        "import_statement, wrong_name",
        [
            pytest.param("import fürimma", "fürimma", id="bad_single_main_module"),
            pytest.param(
                "import fürimma as okay",
                None,
                id="bad_single_main_module_with_okay_alias",
            ),
            pytest.param(
                "import fürimma, pathlib",
                "fürimma",
                id="bad_single_main_module_with_stdlib_import",
            ),
            pytest.param(
                "import pathlib, os, foobar, fürimma",
                "fürimma",
                id="stdlib_with_bad_single_main_module",
            ),
            pytest.param(
                "import pathlib, os, foobar, sys as systëm",
                "systëm",
                id="stdlib_with_bad_alias",
            ),
            pytest.param(
                "import fürimma as okay, pathlib",
                None,
                id="bad_single_main_module_with_okay_alias_with_stdlib_import",
            ),
            pytest.param(
                "import fürimma.submodule", "fürimma.submodule", id="bad_main_module"
            ),
            pytest.param(
                "import fürimma.submodule as submodule",
                None,
                id="bad_main_module_with_okay_alias",
            ),
            pytest.param(
                "import main_module.fürimma", "main_module.fürimma", id="bad_submodule"
            ),
            pytest.param(
                "import main_module.fürimma as okay",
                None,
                id="bad_submodule_with_okay_alias",
            ),
            pytest.param(
                "import main_module.fürimma as not_økay",
                "not_økay",
                id="bad_submodule_with_bad_alias",
            ),
            pytest.param(
                "from foo.bar import function", None, id="from_okay_module_import_okay"
            ),
            pytest.param(
                "from foo.bär import function", None, id="from_bad_module_import_okay"
            ),
            pytest.param(
                "from foo.bar import functiøn",
                "functiøn",
                id="from_okay_module_import_bad",
            ),
            pytest.param(
                "from foo.bar import functiøn as function",
                None,
                id="from_okay_module_import_bad_as_good",
            ),
            pytest.param(
                "from foo.bär import functiøn as function",
                None,
                id="from_bad_module_import_bad_as_good",
            ),
            pytest.param(
                "from foo.bar import functiøn as føl",
                "føl",
                id="from_okay_module_import_bad_as_bad",
            ),
            pytest.param(
                "from foo.bar import functiøn as good, bäd",
                "bäd",
                id="from_okay_module_import_bad_as_good_and_bad",
            ),
            pytest.param(
                "from foo.bar import functiøn as good, bäd",
                "bäd",
                id="from_okay_module_import_bad_as_good_and_bad",
            ),
            pytest.param(
                "from foo.bar import functiøn as good, *",
                # We still have functiøn within our namespace and could detect this
                # But to do this properly we would need to check all `*` imports
                # -> Too much effort!
                "functiøn",
                id="from_okay_module_import_bad_as_good_and_star",
                marks=pytest.mark.xfail(
                    reason="We don't know what is imported when using star"
                ),
            ),
        ],
    )
    def test_check_import(self, import_statement: str, wrong_name: str | None) -> None:
        """We expect that for everything that user can change there is a message."""
        node = astroid.extract_node(f"{import_statement} #@")

        expected_msgs: Iterable[pylint.testutils.MessageTest] = tuple()

        if wrong_name:
            expected_msgs = (
                pylint.testutils.MessageTest(
                    msg_id="non-ascii-module-import",
                    node=node,
                    args=("Module", wrong_name),
                    confidence=pylint.interfaces.HIGH,
                ),
            )
        with self.assertAddsMessages(*expected_msgs, ignore_position=True):
            if import_statement.startswith("from"):
                assert isinstance(node, nodes.ImportFrom)
                self.checker.visit_importfrom(node)
            else:
                assert isinstance(node, nodes.Import)
                self.checker.visit_import(node)