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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
|
"""Tests for applying noqa directives and the IgnoreMask."""
import logging
import pytest
from sqlfluff.core import FluffConfig, Linter
from sqlfluff.core.errors import SQLBaseError, SQLParseError
from sqlfluff.core.rules.noqa import IgnoreMask, NoQaDirective
# noqa tests require a rule_set, therefore we construct dummy rule set for glob matching.
dummy_rule_map = Linter().get_rulepack().reference_map
class DummyLintError(SQLBaseError):
"""Fake lint error used by tests, similar to SQLLintError."""
def __init__(self, line_no: int, code: str = "LT01"):
self._code = code
super().__init__(line_no=line_no)
def test__linter__raises_malformed_noqa():
"""A badly formatted noqa gets raised as a parsing error."""
lntr = Linter(dialect="ansi")
result = lntr.lint_string_wrapped("select 1 --noqa missing semicolon")
with pytest.raises(SQLParseError):
result.check_tuples()
@pytest.mark.parametrize(
"input,expected",
[
("", None),
("noqa", NoQaDirective(0, 0, None, None, "noqa")),
("noqa?", SQLParseError),
("noqa:", NoQaDirective(0, 0, None, None, "noqa:")),
(
"noqa:LT01,LT02",
NoQaDirective(0, 0, ("LT01", "LT02"), None, "noqa:LT01,LT02"),
),
(
"noqa: enable=LT01",
NoQaDirective(0, 0, ("LT01",), "enable", "noqa: enable=LT01"),
),
(
"noqa: disable=CP01",
NoQaDirective(0, 0, ("CP01",), "disable", "noqa: disable=CP01"),
),
(
"noqa: disable=all",
NoQaDirective(0, 0, None, "disable", "noqa: disable=all"),
),
("noqa: disable", SQLParseError),
(
"Inline comment before inline ignore -- noqa:LT01,LT02",
NoQaDirective(0, 0, ("LT01", "LT02"), None, "noqa:LT01,LT02"),
),
# Test selection with rule globs
(
"noqa:L04*",
NoQaDirective(
0,
0,
(
"AM04", # L044 is an alias of AM04
"CP04", # L040 is an alias of CP04
"CV04", # L047 is an alias of CV04
"CV05", # L049 is an alias of CV05
"JJ01", # L046 is an alias of JJ01
"LT01", # L048 is an alias of LT01
"LT10", # L041 is an alias of LT10
"ST02", # L043 is an alias of ST02
"ST03", # L045 is an alias of ST03
"ST05", # L042 is an alias of ST05
),
None,
"noqa:L04*",
),
),
# Test selection with aliases.
(
"noqa:L002",
NoQaDirective(0, 0, ("LT02",), None, "noqa:L002"),
),
# Test selection with alias globs.
(
"noqa:L00*",
NoQaDirective(
0,
0,
("LT01", "LT02", "LT03", "LT12"),
None,
"noqa:L00*",
),
),
# Test selection with names.
(
"noqa:capitalisation.keywords",
NoQaDirective(0, 0, ("CP01",), None, "noqa:capitalisation.keywords"),
),
# Test selection with groups.
(
"noqa:capitalisation",
NoQaDirective(
0,
0,
("CP01", "CP02", "CP03", "CP04", "CP05"),
None,
"noqa:capitalisation",
),
),
],
)
def test_parse_noqa(input, expected):
"""Test correct of "noqa" comments."""
result = IgnoreMask._parse_noqa(input, 0, 0, reference_map=dummy_rule_map)
if not isinstance(expected, type):
assert result == expected
else:
# With exceptions, just check the type, not the contents.
assert isinstance(result, expected)
def test_parse_noqa_no_dups():
"""Test overlapping glob expansions don't return duplicate rules in noqa."""
result = IgnoreMask._parse_noqa(
comment="noqa:L0*5,L01*", line_no=0, line_pos=0, reference_map=dummy_rule_map
)
assert len(result.rules) == len(set(result.rules))
@pytest.mark.parametrize(
"noqa,violations,expected,used_noqas",
[
[
[],
[DummyLintError(1)],
[
0,
],
[],
],
[
[dict(comment="noqa: LT01", line_no=1)],
[DummyLintError(1)],
[],
[0],
],
[
[dict(comment="noqa: LT01", line_no=2)],
[DummyLintError(1)],
[0],
[],
],
[
[dict(comment="noqa: LT02", line_no=1)],
[DummyLintError(1)],
[0],
[],
],
[
[dict(comment="noqa: enable=LT01", line_no=1)],
[DummyLintError(1)],
[0],
[],
],
[
[dict(comment="noqa: disable=LT01", line_no=1)],
[DummyLintError(1)],
[],
[0],
],
[
[
dict(comment="noqa: disable=LT01", line_no=2),
dict(comment="noqa: enable=LT01", line_no=4),
],
[DummyLintError(1)],
[0],
[], # The disable wasn't used, neither was the enable.
],
[
[
dict(comment="noqa: disable=LT01", line_no=2),
dict(comment="noqa: enable=LT01", line_no=4),
],
[DummyLintError(2)],
[],
[0, 1], # Both were used.
],
[
[
dict(comment="noqa: disable=LT01", line_no=2),
dict(comment="noqa: enable=LT01", line_no=4),
],
[DummyLintError(3)],
[],
[0, 1], # Both were used.
],
[
[
dict(comment="noqa: disable=LT01", line_no=2),
dict(comment="noqa: enable=LT01", line_no=4),
],
[DummyLintError(4)],
[0],
[1], # The enable was matched, but the disable wasn't used.
],
[
[
dict(comment="noqa: disable=all", line_no=2),
dict(comment="noqa: enable=all", line_no=4),
],
[DummyLintError(1)],
[0],
# TODO: This is an odd edge case, where we drop out in our
# evaluation too early so see whether the "enable" is ever
# matched. In this case _both_ are effectively unused, because
# we never evaluate the last one. For a first pass I think this
# might be an acceptable edge case.
[],
],
[
[
dict(comment="noqa: disable=all", line_no=2),
dict(comment="noqa: enable=all", line_no=4),
],
[DummyLintError(2)],
[],
[0, 1], # Both were used.
],
[
[
dict(comment="noqa: disable=all", line_no=2),
dict(comment="noqa: enable=all", line_no=4),
],
[DummyLintError(3)],
[],
[0, 1], # Both were used.
],
[
[
dict(comment="noqa: disable=all", line_no=2),
dict(comment="noqa: enable=all", line_no=4),
],
[DummyLintError(4)],
[0],
[1], # The enable was matched, but the disable wasn't used.
],
[
[
dict(comment="noqa: disable=LT01", line_no=2),
dict(comment="noqa: enable=all", line_no=4),
],
[
DummyLintError(2, code="LT01"),
DummyLintError(2, code="LT02"),
DummyLintError(4, code="LT01"),
DummyLintError(4, code="LT02"),
],
[1, 2, 3],
[0, 1], # The enable matched. The disable also matched rules.
],
[
[
dict(comment="noqa: disable=all", line_no=2),
dict(comment="noqa: enable=LT01", line_no=4),
],
[
DummyLintError(2, code="LT01"),
DummyLintError(2, code="LT02"),
DummyLintError(4, code="LT01"),
DummyLintError(4, code="LT02"),
],
[2],
[0, 1], # The enable matched the disable. The disable also matched
],
[
[
dict(
comment="Inline comment before inline ignore -- noqa: LT02",
line_no=1,
)
],
[DummyLintError(1)],
[0],
[],
],
[
[
dict(
comment="Inline comment before inline ignore -- noqa: LT02",
line_no=1,
),
dict(
comment="Inline comment before inline ignore -- noqa: LT02",
line_no=2,
),
],
[
DummyLintError(1),
DummyLintError(2),
],
[0, 1],
[], # Neither used because wrong code.
],
[
[
dict(
comment="Inline comment before inline ignore -- noqa: L01*",
line_no=1,
),
],
[
DummyLintError(1),
],
[0],
[], # Neither used because wrong code.
],
[
[
dict(
comment="Inline comment before inline ignore -- noqa: LT*",
line_no=1,
),
],
[
DummyLintError(1),
],
[],
[0], # Matched indirectly
],
],
ids=[
"1_violation_no_ignore",
"1_violation_ignore_specific_line",
"1_violation_ignore_different_specific_line",
"1_violation_ignore_different_specific_rule",
"1_violation_ignore_enable_this_range",
"1_violation_ignore_disable_this_range",
"1_violation_line_1_ignore_disable_specific_2_3",
"1_violation_line_2_ignore_disable_specific_2_3",
"1_violation_line_3_ignore_disable_specific_2_3",
"1_violation_line_4_ignore_disable_specific_2_3",
"1_violation_line_1_ignore_disable_all_2_3",
"1_violation_line_2_ignore_disable_all_2_3",
"1_violation_line_3_ignore_disable_all_2_3",
"1_violation_line_4_ignore_disable_all_2_3",
"4_violations_two_types_disable_specific_enable_all",
"4_violations_two_types_disable_all_enable_specific",
"1_violations_comment_inline_ignore",
"2_violations_comment_inline_ignore",
"1_violations_comment_inline_glob_ignore_unmatch",
"1_violations_comment_inline_glob_ignore_match",
],
)
def test_linted_file_ignore_masked_violations(
noqa: dict, violations: list[SQLBaseError], expected, used_noqas
):
"""Test that _ignore_masked_violations() correctly filters violations."""
ignore_mask = [
IgnoreMask._parse_noqa(reference_map=dummy_rule_map, line_pos=0, **c)
for c in noqa
]
result = IgnoreMask(ignore_mask).ignore_masked_violations(violations)
expected_violations = [v for i, v in enumerate(violations) if i in expected]
assert expected_violations == result
# Check whether "used" evaluation works
expected_used = [ignore_mask[i] for i, _ in enumerate(noqa) if i in used_noqas]
actually_used = [i for i in ignore_mask if i.used]
assert actually_used == expected_used
def test_linter_noqa():
"""Test "noqa" feature at the higher "Linter" level."""
lntr = Linter(
config=FluffConfig(
overrides={
"dialect": "bigquery", # Use bigquery to allow hash comments.
"rules": "AL02, LT04",
}
)
)
sql = """
SELECT
col_a a,
col_b b, --noqa: disable=AL02
col_c c,
col_d d, --noqa: enable=AL02
col_e e,
col_f f,
col_g g, --noqa
col_h h,
col_i i, --noqa:AL02
col_j j,
col_k k, --noqa:AL03
col_l l,
col_m m,
col_n n, --noqa: disable=all
col_o o,
col_p p, --noqa: enable=all
col_q q, --Inline comment --noqa: AL02
col_r r, /* Block comment */ --noqa: AL02
col_s s # hash comment --noqa: AL02
-- We trigger both AL02 (implicit aliasing)
-- and LT04 (leading commas) here to
-- test glob ignoring of multiple rules.
, col_t t --noqa: L01*
, col_u u -- Some comment --noqa: L01*
, col_v v -- We can ignore both AL02 and LT04 -- noqa: L01[29]
FROM foo
"""
result = lntr.lint_string(sql)
violations = result.get_violations()
assert {3, 6, 7, 8, 10, 12, 13, 14, 15, 18} == {v.line_no for v in violations}
def test_linter_noqa_with_templating():
"""Similar to test_linter_noqa, but uses templating (Jinja)."""
lntr = Linter(
config=FluffConfig(
overrides={
"dialect": "bigquery", # Use bigquery to allow hash comments.
"templater": "jinja",
"rules": "LT05",
}
)
)
sql = "\n"
'"{%- set a_var = ["1", "2"] -%}\n'
"SELECT\n"
" this_is_just_a_very_long_line_for_demonstration_purposes_of_a_bug_involving_"
"templated_sql_files, --noqa: LT05\n"
" this_is_not_so_big a, --Inline comment --noqa: AL02\n"
" this_is_not_so_big b, /* Block comment */ --noqa: AL02\n"
" this_is_not_so_big c, # hash comment --noqa: AL02\n"
" this_is_just_a_very_long_line_for_demonstration_purposes_of_a_bug_involving_"
"templated_sql_files, --noqa: L01*\n"
"FROM\n"
" a_table\n"
" "
result = lntr.lint_string(sql)
assert not result.get_violations()
def test_linter_noqa_template_errors():
"""Similar to test_linter_noqa, but uses templating (Jinja)."""
lntr = Linter(
config=FluffConfig(
overrides={
"templater": "jinja",
"dialect": "ansi",
}
)
)
sql = """select * --noqa: TMP
from raw
where
balance_date >= {{ execution_date - macros.timedelta() }} --noqa: TMP
"""
result = lntr.lint_string(sql)
assert not result.get_violations()
@pytest.mark.parametrize("disable_noqa", [True, False])
@pytest.mark.parametrize(
"sql", ["SELEC * FROM foo -- noqa: PRS\n", "{% if 1 > '2' %} -- noqa: TMP\n"]
)
def test_linter_noqa_prs(sql, disable_noqa, caplog):
"""Test "noqa" feature to ignore PRS or TMP at the higher "Linter" level.
Because templating and parsing failures prevent a fully formed parse tree
to be formed the rely on slightly different routines to ensure ignores are
still applied.
"""
lntr = Linter(
config=FluffConfig(
overrides={
"disable_noqa": disable_noqa,
"dialect": "ansi",
}
)
)
with caplog.at_level(logging.DEBUG, logger="sqlfluff.linter"):
result = lntr.lint_string(sql)
violations = result.get_violations()
# In both the templating fail and parsing fail cases, the failures should be
# ignored because of the inline ignore, _unless_ `disable_noqa`` is set.
if disable_noqa:
assert violations
else:
assert not violations
def test_linter_noqa_tmp():
"""Test "noqa" feature to ignore TMP at the higher "Linter" level."""
lntr = Linter(
config=FluffConfig(
overrides={
"exclude_rules": "LT13",
"dialect": "ansi",
}
)
)
sql = """
SELECT {{ col_a }} AS a -- noqa: TMP,PRS
FROM foo;
"""
result = lntr.lint_string(sql)
print(result.tree.stringify())
violations = result.get_violations()
assert not violations
def test_linter_noqa_disable():
"""Test "noqa" comments can be disabled via the config."""
lntr_noqa_enabled = Linter(
config=FluffConfig(
overrides={
"rules": "AL02",
"dialect": "ansi",
}
)
)
lntr_noqa_disabled = Linter(
config=FluffConfig(
overrides={
"disable_noqa": True,
"rules": "AL02",
"dialect": "ansi",
}
)
)
# This query raises AL02, but it is being suppressed by the inline noqa comment.
# We can ignore this comment by setting disable_noqa = True in the config
# or by using the --disable-noqa flag in the CLI.
sql = """
SELECT col_a a --noqa: AL02
FROM foo
"""
# Verify that noqa works as expected with disable_noqa = False (default).
result_noqa_enabled = lntr_noqa_enabled.lint_string(sql)
violations_noqa_enabled = result_noqa_enabled.get_violations()
assert len(violations_noqa_enabled) == 0
# Verify that noqa comment is ignored with disable_noqa = True.
result_noqa_disabled = lntr_noqa_disabled.lint_string(sql)
violations_noqa_disabled = result_noqa_disabled.get_violations()
assert len(violations_noqa_disabled) == 1
assert violations_noqa_disabled[0].rule.code == "AL02"
def test_linter_disable_noqa_except():
"""Test "noqa" comments can be disabled via the config."""
lntr_disable_noqa_except_al02 = Linter(
config=FluffConfig(
overrides={
"disable_noqa_except": "AL02",
"rules": "AL02, CP01",
"dialect": "ansi",
}
)
)
lntr_disable_noqa_except_core = Linter(
config=FluffConfig(
overrides={
"disable_noqa_except": "core",
"rules": "AL02, CP01",
"dialect": "ansi",
}
)
)
# This query raises AL02 and CP01 but it is being suppressed by the inline noqa
# comments. We can partially ignore these comment by setting
# disable_noqa_except = rule_list in the config or by using the
# --disable-noqa-except option in the CLI.
sql = """
SELECT
col_a a, --noqa: AL02
col_b b --noqa: aliasing
from foo; --noqa: CP01
"""
# Verify that noqa comment is ignored with
# disable_noqa_except = AL02 (base rule name).
result_disable_noqa_except_al02 = lntr_disable_noqa_except_al02.lint_string(sql)
violations_disable_noqa_except_al02 = (
result_disable_noqa_except_al02.get_violations()
)
assert len(violations_disable_noqa_except_al02) == 1
assert violations_disable_noqa_except_al02[0].rule.code == "CP01"
# Verify that noqa works as expected with disable_noqa_except = core (rule alias).
result_disable_noqa_except_core = lntr_disable_noqa_except_core.lint_string(sql)
violations_disable_noqa_except_core = (
result_disable_noqa_except_core.get_violations()
)
assert len(violations_disable_noqa_except_core) == 0
|