| 1 |
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html |
| 2 |
# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE |
| 3 |
# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt |
| 4 |
|
| 5 |
# pylint: disable=redefined-outer-name |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import warnings |
| 10 |
from contextlib import redirect_stdout |
| 11 |
from io import StringIO |
| 12 |
from json import dumps |
| 13 |
from pathlib import Path |
| 14 |
from typing import TYPE_CHECKING, TextIO |
| 15 |
|
| 16 |
import pytest |
| 17 |
|
| 18 |
from pylint import checkers |
| 19 |
from pylint.interfaces import HIGH |
| 20 |
from pylint.lint import PyLinter |
| 21 |
from pylint.message.message import Message |
| 22 |
from pylint.reporters import BaseReporter, MultiReporter |
| 23 |
from pylint.reporters.text import ParseableTextReporter, TextReporter |
| 24 |
from pylint.typing import FileItem, MessageLocationTuple |
| 25 |
|
| 26 |
if TYPE_CHECKING: |
| 27 |
from pylint.reporters.ureports.nodes import Section |
| 28 |
|
| 29 |
|
| 30 |
@pytest.fixture(scope="module") |
| 31 |
def reporter() -> type[TextReporter]: |
| 32 |
return TextReporter |
| 33 |
|
| 34 |
|
| 35 |
@pytest.fixture(scope="module") |
| 36 |
def disable() -> list[str]: |
| 37 |
return ["I"] |
| 38 |
|
| 39 |
|
| 40 |
def test_template_option(linter: PyLinter) -> None: |
| 41 |
output = StringIO() |
| 42 |
linter.reporter.out = output |
| 43 |
linter.config.msg_template = "{msg_id}:{line:03d}" |
| 44 |
linter.open() |
| 45 |
linter.set_current_module("0123") |
| 46 |
linter.add_message("C0301", line=1, args=(1, 2)) |
| 47 |
linter.add_message("line-too-long", line=2, args=(3, 4)) |
| 48 |
assert output.getvalue() == "************* Module 0123\nC0301:001\nC0301:002\n" |
| 49 |
|
| 50 |
|
| 51 |
def test_template_option_default(linter: PyLinter) -> None: |
| 52 |
"""Test the default msg-template setting.""" |
| 53 |
output = StringIO() |
| 54 |
linter.reporter.out = output |
| 55 |
linter.open() |
| 56 |
linter.set_current_module("my_module") |
| 57 |
linter.add_message("C0301", line=1, args=(1, 2)) |
| 58 |
linter.add_message("line-too-long", line=2, args=(3, 4)) |
| 59 |
|
| 60 |
out_lines = output.getvalue().split("\n") |
| 61 |
assert out_lines[1] == "my_module:1:0: C0301: Line too long (1/2) (line-too-long)" |
| 62 |
assert out_lines[2] == "my_module:2:0: C0301: Line too long (3/4) (line-too-long)" |
| 63 |
|
| 64 |
|
| 65 |
def test_template_option_end_line(linter: PyLinter) -> None: |
| 66 |
"""Test the msg-template option with end_line and end_column.""" |
| 67 |
output = StringIO() |
| 68 |
linter.reporter.out = output |
| 69 |
linter.config.msg_template = ( |
| 70 |
"{path}:{line}:{column}:{end_line}:{end_column}: {msg_id}: {msg} ({symbol})" |
| 71 |
) |
| 72 |
linter.open() |
| 73 |
linter.set_current_module("my_mod") |
| 74 |
linter.add_message("C0301", line=1, args=(1, 2)) |
| 75 |
linter.add_message( |
| 76 |
"line-too-long", line=2, end_lineno=2, end_col_offset=4, args=(3, 4) |
| 77 |
) |
| 78 |
|
| 79 |
out_lines = output.getvalue().split("\n") |
| 80 |
assert out_lines[1] == "my_mod:1:0::: C0301: Line too long (1/2) (line-too-long)" |
| 81 |
assert out_lines[2] == "my_mod:2:0:2:4: C0301: Line too long (3/4) (line-too-long)" |
| 82 |
|
| 83 |
|
| 84 |
def test_template_option_non_existing(linter: PyLinter) -> None: |
| 85 |
"""Test the msg-template option with non-existent options. |
| 86 |
This makes sure that this option remains backwards compatible as new |
| 87 |
parameters do not break on previous versions. |
| 88 |
""" |
| 89 |
output = StringIO() |
| 90 |
linter.reporter.out = output |
| 91 |
linter.config.msg_template = "{path}:{line}:{categ}:({a_second_new_option:03d})" |
| 92 |
linter.open() |
| 93 |
with pytest.warns(UserWarning) as records: |
| 94 |
linter.set_current_module("my_mod") |
| 95 |
assert len(records) == 2 |
| 96 |
assert "Don't recognize the argument 'categ'" in records[0].message.args[0] |
| 97 |
assert ( |
| 98 |
"Don't recognize the argument 'a_second_new_option'" |
| 99 |
in records[1].message.args[0] |
| 100 |
) |
| 101 |
|
| 102 |
linter.add_message("C0301", line=1, args=(1, 2)) |
| 103 |
linter.add_message( |
| 104 |
"line-too-long", line=2, end_lineno=2, end_col_offset=4, args=(3, 4) |
| 105 |
) |
| 106 |
|
| 107 |
out_lines = output.getvalue().split("\n") |
| 108 |
assert out_lines[1] == "my_mod:1::()" |
| 109 |
assert out_lines[2] == "my_mod:2::()" |
| 110 |
|
| 111 |
|
| 112 |
def test_template_option_with_header(linter: PyLinter) -> None: |
| 113 |
output = StringIO() |
| 114 |
linter.reporter.out = output |
| 115 |
linter.config.msg_template = '{{ "Category": "{category}" }}' |
| 116 |
linter.open() |
| 117 |
linter.set_current_module("my_mod") |
| 118 |
|
| 119 |
linter.add_message("C0301", line=1, args=(1, 2)) |
| 120 |
linter.add_message( |
| 121 |
"line-too-long", line=2, end_lineno=2, end_col_offset=4, args=(3, 4) |
| 122 |
) |
| 123 |
|
| 124 |
out_lines = output.getvalue().split("\n") |
| 125 |
assert out_lines[1] == '{ "Category": "convention" }' |
| 126 |
assert out_lines[2] == '{ "Category": "convention" }' |
| 127 |
|
| 128 |
|
| 129 |
def test_parseable_output_deprecated() -> None: |
| 130 |
with warnings.catch_warnings(record=True) as cm: |
| 131 |
warnings.simplefilter("always") |
| 132 |
ParseableTextReporter() |
| 133 |
|
| 134 |
assert len(cm) == 1 |
| 135 |
assert isinstance(cm[0].message, DeprecationWarning) |
| 136 |
|
| 137 |
|
| 138 |
def test_parseable_output_regression() -> None: |
| 139 |
output = StringIO() |
| 140 |
with warnings.catch_warnings(record=True): |
| 141 |
warnings.simplefilter("ignore", category=DeprecationWarning) |
| 142 |
linter = PyLinter(reporter=ParseableTextReporter()) |
| 143 |
|
| 144 |
checkers.initialize(linter) |
| 145 |
linter.config.persistent = 0 |
| 146 |
linter.reporter.out = output |
| 147 |
linter.set_option("output-format", "parseable") |
| 148 |
linter.open() |
| 149 |
linter.set_current_module("0123") |
| 150 |
linter.add_message("line-too-long", line=1, args=(1, 2)) |
| 151 |
assert ( |
| 152 |
output.getvalue() == "************* Module 0123\n" |
| 153 |
"0123:1: [C0301(line-too-long), ] " |
| 154 |
"Line too long (1/2)\n" |
| 155 |
) |
| 156 |
|
| 157 |
|
| 158 |
class NopReporter(BaseReporter): |
| 159 |
name = "nop-reporter" |
| 160 |
extension = "" |
| 161 |
|
| 162 |
def __init__(self, output: TextIO | None = None) -> None: |
| 163 |
super().__init__(output) |
| 164 |
print("A NopReporter was initialized.", file=self.out) |
| 165 |
|
| 166 |
def writeln(self, string: str = "") -> None: |
| 167 |
pass |
| 168 |
|
| 169 |
def _display(self, layout: Section) -> None: |
| 170 |
pass |
| 171 |
|
| 172 |
|
| 173 |
def test_multi_format_output(tmp_path: Path) -> None: |
| 174 |
text = StringIO(newline=None) |
| 175 |
json = tmp_path / "somefile.json" |
| 176 |
|
| 177 |
source_file = tmp_path / "somemodule.py" |
| 178 |
source_file.write_text('NOT_EMPTY = "This module is not empty"\n') |
| 179 |
dumps(str(source_file)) |
| 180 |
|
| 181 |
nop_format = NopReporter.__module__ + "." + NopReporter.__name__ |
| 182 |
formats = ",".join(["json2:" + str(json), "text", nop_format]) |
| 183 |
|
| 184 |
with redirect_stdout(text): |
| 185 |
linter = PyLinter() |
| 186 |
linter.load_default_plugins() |
| 187 |
linter.set_option("persistent", False) |
| 188 |
linter.set_option("reports", True) |
| 189 |
linter.set_option("score", True) |
| 190 |
linter.set_option("score", True) |
| 191 |
linter.set_option("output-format", formats) |
| 192 |
|
| 193 |
assert linter.reporter.linter is linter |
| 194 |
with pytest.raises(NotImplementedError): |
| 195 |
linter.reporter.out = text |
| 196 |
|
| 197 |
linter.open() |
| 198 |
linter.check_single_file_item( |
| 199 |
FileItem("somemodule", str(source_file), "somemodule") |
| 200 |
) |
| 201 |
linter.add_message("line-too-long", line=1, args=(1, 2)) |
| 202 |
linter.generate_reports() |
| 203 |
linter.reporter.writeln("direct output") |
| 204 |
|
| 205 |
# Ensure the output files are flushed and closed |
| 206 |
assert isinstance(linter.reporter, MultiReporter) |
| 207 |
linter.reporter.close_output_files() |
| 208 |
del linter.reporter |
| 209 |
|
| 210 |
with open(json, encoding="utf-8") as f: |
| 211 |
assert '"messageId": "C0114"' in f.read() |
| 212 |
|
| 213 |
assert ( |
| 214 |
text.getvalue() == "A NopReporter was initialized.\n" |
| 215 |
"************* Module somemodule\n" |
| 216 |
f"{source_file}:1:0: C0114: Missing module docstring (missing-module-docstring)\n" |
| 217 |
f"{source_file}:1:0: C0301: Line too long (1/2) (line-too-long)\n" |
| 218 |
"\n" |
| 219 |
"\n" |
| 220 |
"Report\n" |
| 221 |
"======\n" |
| 222 |
"1 statements analysed.\n" |
| 223 |
"\n" |
| 224 |
"Statistics by type\n" |
| 225 |
"------------------\n" |
| 226 |
"\n" |
| 227 |
"+---------+-------+-----------+-----------+------------+---------+\n" |
| 228 |
"|type |number |old number |difference |%documented |%badname |\n" |
| 229 |
"+=========+=======+===========+===========+============+=========+\n" |
| 230 |
"|module |1 |NC |NC |0.00 |0.00 |\n" |
| 231 |
"+---------+-------+-----------+-----------+------------+---------+\n" |
| 232 |
"|class |0 |NC |NC |0 |0 |\n" |
| 233 |
"+---------+-------+-----------+-----------+------------+---------+\n" |
| 234 |
"|method |0 |NC |NC |0 |0 |\n" |
| 235 |
"+---------+-------+-----------+-----------+------------+---------+\n" |
| 236 |
"|function |0 |NC |NC |0 |0 |\n" |
| 237 |
"+---------+-------+-----------+-----------+------------+---------+\n" |
| 238 |
"\n" |
| 239 |
"\n" |
| 240 |
"\n" |
| 241 |
"3 lines have been analyzed\n" |
| 242 |
"\n" |
| 243 |
"Raw metrics\n" |
| 244 |
"-----------\n" |
| 245 |
"\n" |
| 246 |
"+----------+-------+------+---------+-----------+\n" |
| 247 |
"|type |number |% |previous |difference |\n" |
| 248 |
"+==========+=======+======+=========+===========+\n" |
| 249 |
"|code |2 |66.67 |NC |NC |\n" |
| 250 |
"+----------+-------+------+---------+-----------+\n" |
| 251 |
"|docstring |0 |0.00 |NC |NC |\n" |
| 252 |
"+----------+-------+------+---------+-----------+\n" |
| 253 |
"|comment |0 |0.00 |NC |NC |\n" |
| 254 |
"+----------+-------+------+---------+-----------+\n" |
| 255 |
"|empty |1 |33.33 |NC |NC |\n" |
| 256 |
"+----------+-------+------+---------+-----------+\n" |
| 257 |
"\n" |
| 258 |
"\n" |
| 259 |
"\n" |
| 260 |
"Duplication\n" |
| 261 |
"-----------\n" |
| 262 |
"\n" |
| 263 |
"+-------------------------+------+---------+-----------+\n" |
| 264 |
"| |now |previous |difference |\n" |
| 265 |
"+=========================+======+=========+===========+\n" |
| 266 |
"|nb duplicated lines |0 |NC |NC |\n" |
| 267 |
"+-------------------------+------+---------+-----------+\n" |
| 268 |
"|percent duplicated lines |0.000 |NC |NC |\n" |
| 269 |
"+-------------------------+------+---------+-----------+\n" |
| 270 |
"\n" |
| 271 |
"\n" |
| 272 |
"\n" |
| 273 |
"Messages by category\n" |
| 274 |
"--------------------\n" |
| 275 |
"\n" |
| 276 |
"+-----------+-------+---------+-----------+\n" |
| 277 |
"|type |number |previous |difference |\n" |
| 278 |
"+===========+=======+=========+===========+\n" |
| 279 |
"|convention |2 |NC |NC |\n" |
| 280 |
"+-----------+-------+---------+-----------+\n" |
| 281 |
"|refactor |0 |NC |NC |\n" |
| 282 |
"+-----------+-------+---------+-----------+\n" |
| 283 |
"|warning |0 |NC |NC |\n" |
| 284 |
"+-----------+-------+---------+-----------+\n" |
| 285 |
"|error |0 |NC |NC |\n" |
| 286 |
"+-----------+-------+---------+-----------+\n" |
| 287 |
"\n" |
| 288 |
"\n" |
| 289 |
"\n" |
| 290 |
"Messages\n" |
| 291 |
"--------\n" |
| 292 |
"\n" |
| 293 |
"+-------------------------+------------+\n" |
| 294 |
"|message id |occurrences |\n" |
| 295 |
"+=========================+============+\n" |
| 296 |
"|missing-module-docstring |1 |\n" |
| 297 |
"+-------------------------+------------+\n" |
| 298 |
"|line-too-long |1 |\n" |
| 299 |
"+-------------------------+------------+\n" |
| 300 |
"\n" |
| 301 |
"\n" |
| 302 |
"\n" |
| 303 |
"\n" |
| 304 |
"-----------------------------------\n" |
| 305 |
"Your code has been rated at 0.00/10\n" |
| 306 |
"\n" |
| 307 |
"direct output\n" |
| 308 |
) |
| 309 |
|
| 310 |
|
| 311 |
def test_multi_reporter_independant_messages() -> None: |
| 312 |
"""Messages should not be modified by multiple reporters.""" |
| 313 |
check_message = "Not modified" |
| 314 |
|
| 315 |
class ReporterModify(BaseReporter): |
| 316 |
def handle_message(self, msg: Message) -> None: |
| 317 |
msg.msg = "Modified message" |
| 318 |
|
| 319 |
def writeln(self, string: str = "") -> None: |
| 320 |
pass |
| 321 |
|
| 322 |
def _display(self, layout: Section) -> None: |
| 323 |
pass |
| 324 |
|
| 325 |
class ReporterCheck(BaseReporter): |
| 326 |
def handle_message(self, msg: Message) -> None: |
| 327 |
assert ( |
| 328 |
msg.msg == check_message |
| 329 |
), "Message object should not be changed by other reporters." |
| 330 |
|
| 331 |
def writeln(self, string: str = "") -> None: |
| 332 |
pass |
| 333 |
|
| 334 |
def _display(self, layout: Section) -> None: |
| 335 |
pass |
| 336 |
|
| 337 |
multi_reporter = MultiReporter([ReporterModify(), ReporterCheck()], lambda: None) |
| 338 |
|
| 339 |
message = Message( |
| 340 |
symbol="missing-docstring", |
| 341 |
msg_id="C0123", |
| 342 |
location=MessageLocationTuple("abspath", "path", "module", "obj", 1, 2, 1, 3), |
| 343 |
msg=check_message, |
| 344 |
confidence=HIGH, |
| 345 |
) |
| 346 |
|
| 347 |
multi_reporter.handle_message(message) |
| 348 |
|
| 349 |
assert ( |
| 350 |
message.msg == check_message |
| 351 |
), "Message object should not be changed by reporters." |
| 352 |
|
| 353 |
|
| 354 |
def test_display_results_is_renamed() -> None: |
| 355 |
class CustomReporter(TextReporter): |
| 356 |
def _display(self, layout: Section) -> None: |
| 357 |
return None |
| 358 |
|
| 359 |
reporter = CustomReporter() |
| 360 |
with pytest.raises(AttributeError) as exc: |
| 361 |
# pylint: disable=no-member |
| 362 |
reporter.display_results() # type: ignore[attr-defined] |
| 363 |
assert "no attribute 'display_results'" in str(exc) |