summaryrefslogtreecommitdiff
path: root/tests/test_similar.py
blob: 0f2ec242ce734cdffd67ed26c3b8f565b198eef5 (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
# 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 os
import re
import warnings
from io import StringIO
from os.path import abspath, dirname, join
from typing import TextIO

import pytest

from pylint.reporters.text import TextReporter
from pylint.testutils._run import _Run as Run
from pylint.testutils.utils import _patch_streams

HERE = abspath(dirname(__file__))
DATA = join(HERE, "regrtest_data", "duplicate_code")
CLEAN_PATH = re.escape(dirname(dirname(__file__)) + os.path.sep)


class TestSimilarCodeChecker:
    def _runtest(self, args: list[str], code: int) -> None:
        """Runs the tests and sees if output code is as expected."""
        out = StringIO()
        pylint_code = self._run_pylint(args, out=out)
        output = out.getvalue()
        msg = f"expected output status {code}, got {pylint_code}"
        if output is not None:
            msg = f"{msg}. Below pylint output: \n{output}"
        assert pylint_code == code, msg

    @staticmethod
    def _run_pylint(args: list[str], out: TextIO) -> int:
        """Runs pylint with a patched output."""
        args += [
            "--persistent=no",
            "--enable=astroid-error",
            # Enable functionality that will build another ast
            "--ignore-imports=y",
            "--ignore-signatures=y",
        ]
        with _patch_streams(out):
            with pytest.raises(SystemExit) as cm:
                with warnings.catch_warnings():
                    warnings.simplefilter("ignore")
                    Run(args)
            return int(cm.value.code)

    @staticmethod
    def _clean_paths(output: str) -> str:
        """Normalize path to the tests directory."""
        output = re.sub(CLEAN_PATH, "", output, flags=re.MULTILINE)
        return output.replace("\\", "/")

    def _test_output(self, args: list[str], expected_output: str) -> None:
        """Tests if the output of a pylint run is as expected."""
        out = StringIO()
        self._run_pylint(args, out=out)
        actual_output = self._clean_paths(out.getvalue())
        actual_output_stripped = actual_output.strip()
        expected_output = self._clean_paths(expected_output)
        assert expected_output.strip() in actual_output_stripped
        assert "Fatal error" not in actual_output_stripped

    def test_duplicate_code_raw_strings_all(self) -> None:
        """Test similar lines in 3 similar files."""
        path = join(DATA, "raw_strings_all")
        expected_output = "Similar lines in 2 files"
        self._test_output(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            expected_output=expected_output,
        )

    def test_duplicate_code_raw_strings_disable_file(self) -> None:
        """Tests disabling duplicate-code at the file level in a single file."""
        path = join(DATA, "raw_strings_disable_file")
        expected_output = "Similar lines in 2 files"
        self._test_output(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            expected_output=expected_output,
        )

    def test_duplicate_code_raw_strings_disable_file_double(self) -> None:
        """Tests disabling duplicate-code at the file level in two files."""
        path = join(DATA, "raw_strings_disable_file_double")
        self._runtest(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            code=0,
        )

    def test_duplicate_code_raw_strings_disable_line_two(self) -> None:
        """Tests disabling duplicate-code at a line at the begin of a piece of similar code."""
        path = join(DATA, "raw_strings_disable_line_begin")
        expected_output = "Similar lines in 2 files"
        self._test_output(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            expected_output=expected_output,
        )

    def test_duplicate_code_raw_strings_disable_line_disable_all(self) -> None:
        """Tests disabling duplicate-code with all similar lines disabled per line."""
        path = join(DATA, "raw_strings_disable_line_disable_all")
        self._runtest(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            code=0,
        )

    def test_duplicate_code_raw_strings_disable_line_midle(self) -> None:
        """Tests disabling duplicate-code at a line in the middle of a piece of similar code."""
        path = join(DATA, "raw_strings_disable_line_middle")
        self._runtest(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            code=0,
        )

    def test_duplicate_code_raw_strings_disable_line_end(self) -> None:
        """Tests disabling duplicate-code at a line at the end of a piece of similar code."""
        path = join(DATA, "raw_strings_disable_line_end")
        expected_output = "Similar lines in 2 files"
        self._test_output(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            expected_output=expected_output,
        )

    def test_duplicate_code_raw_strings_disable_scope(self) -> None:
        """Tests disabling duplicate-code at an inner scope level."""
        path = join(DATA, "raw_strings_disable_scope")
        expected_output = "Similar lines in 2 files"
        self._test_output(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            expected_output=expected_output,
        )

    def test_duplicate_code_raw_strings_disable_scope_double(self) -> None:
        """Tests disabling duplicate-code at an inner scope level in two files."""
        path = join(DATA, "raw_strings_disable_scope_double")
        self._runtest(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            code=0,
        )

    def test_duplicate_code_raw_strings_disable_scope_function(self) -> None:
        """Tests disabling duplicate-code at an inner scope level with another scope with
        similarity."""
        path = join(DATA, "raw_strings_disable_scope_second_function")
        expected_output = "Similar lines in 2 files"
        self._test_output(
            [
                path,
                "--disable=all",
                "--enable=duplicate-code",
                "--ignore-imports=no",
                "--ignore-signatures=no",
                "--min-similarity-lines=4",
            ],
            expected_output=expected_output,
        )

    def test_ignore_imports(self) -> None:
        """Tests enabling ignore-imports works correctly."""
        path = join(DATA, "ignore_imports")
        self._runtest(
            [path, "-e=duplicate-code", "-d=unused-import,C", "--ignore-imports=y"],
            code=0,
        )

    @staticmethod
    def test_useless_suppression() -> None:
        """Tests that duplicate code and useless-suppression work well together."""
        path = join(DATA, "useless_suppression")
        pylint_output = StringIO()
        reporter = TextReporter(pylint_output)
        runner = Run(
            [
                path,
                "-e=duplicate-code, useless-suppression",
                "-d=missing-module-docstring, unused-import",
            ],
            reporter=reporter,
            exit=False,
        )
        assert not runner.linter.stats.by_msg