code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test__helpers_dict__nested_combine_copy_effect():
"""Verify that nested_combine effectively copies dicts.
In particular it's important that even nested dicts are fully
isolated, as if not true it can create some very difficult to
trace bugs.
"""
# Set up the original dicts.
a = {"a": {"b": {"c": 123, "d": 456}}}
b = {"a": {"b": {"c": 234, "e": 567}}, "f": {"g": {"h": "i"}}}
r = nested_combine(a, b)
# After combination, edit both some of the inputs and one of the outputs.
a["a"]["b"]["d"] = 999
b["f"]["g"]["h"] = "j"
r["a"]["b"]["e"] = 888
# Check that editing the result didn't change the input:
assert b["a"]["b"]["e"] == 567 # and not 888
# Check that editing the input didn't change the result:
assert r["a"]["b"]["d"] == 456 # and not 999
assert r["f"]["g"]["h"] == "i" # and not "j" | Verify that nested_combine effectively copies dicts.
In particular it's important that even nested dicts are fully
isolated, as if not true it can create some very difficult to
trace bugs. | test__helpers_dict__nested_combine_copy_effect | python | sqlfluff/sqlfluff | test/core/helpers/dict_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/dict_test.py | MIT |
def test__helpers_dict__dict_diff():
"""Test diffs between two config dicts."""
a = {"a": {"b": {"c": 123, "d": 456, "f": 6}}}
b = {"b": {"b": {"c": 123, "d": 456}}}
c = {"a": {"b": {"c": 234, "e": 456, "f": 6}}}
assert dict_diff(a, b) == a
assert dict_diff(a, c) == {"a": {"b": {"c": 123, "d": 456}}}
assert dict_diff(c, a) == {"a": {"b": {"c": 234, "e": 456}}} | Test diffs between two config dicts. | test__helpers_dict__dict_diff | python | sqlfluff/sqlfluff | test/core/helpers/dict_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/dict_test.py | MIT |
def test__config__iter_records_from_nested_dict():
"""Test conversion from nested dict to records."""
c = iter_records_from_nested_dict({"a": {"b": {"c": 123, "d": 456}, "f": 6}})
assert list(c) == [
(("a", "b", "c"), 123),
(("a", "b", "d"), 456),
(("a", "f"), 6),
] | Test conversion from nested dict to records. | test__config__iter_records_from_nested_dict | python | sqlfluff/sqlfluff | test/core/helpers/dict_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/dict_test.py | MIT |
def test__config__from_strings():
"""Test loading config from multiple strings."""
strings = [
"[sqlfluff]\ndialect=mysql\ntesting_val=foobar",
"[sqlfluff]\ndialect=postgres\ntesting_val2=bar",
"[sqlfluff]\ndialect=mysql\ntesting_val=foo",
]
cfg = FluffConfig.from_strings(*strings)
assert cfg.get("dialect") == "mysql"
assert cfg.get("testing_val2") == "bar"
assert cfg.get("testing_val") == "foo" | Test loading config from multiple strings. | test__config__from_strings | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__nested_config_tests():
"""Test linting with overridden config in nested paths.
This looks like a linter test but it's actually a config
test.
"""
lntr = Linter(
# Exclude CP02 in overrides (similar to cli --exclude-rules)
config=FluffConfig(overrides=dict(exclude_rules="CP02", dialect="ansi"))
)
lnt = lntr.lint_path("test/fixtures/config/inheritance_b")
violations = lnt.check_tuples_by_path()
for k in violations:
if k.endswith("nested\\example.sql"):
# CP01 is enabled in the .sqlfluff file and not excluded.
assert ("CP01", 1, 4) in violations[k]
# LT02 is enabled in the .sqlfluff file and not excluded.
assert ("LT02", 1, 1) in violations[k]
# CP02 is enabled in the .sqlfluff file but excluded by the
# override above.
assert "CP02" not in [c[0] for c in violations[k]]
elif k.endswith("inheritance_b\\example.sql"):
# CP01 is enabled because while disabled in the tox.ini file,
# the exclude-rules option is overridden by the override above
# which effectively sets the exclude to CP02 and in effect
# re-enables CP01.
# This may seem counter-intuitive but is in line with current
# documentation on how to use `rules` and `exclude-rules`.
# https://docs.sqlfluff.com/en/latest/perma/rule_disabling.html
assert ("CP01", 1, 4) in violations[k]
# CP02 is disabled because of the override above.
assert "CP02" not in [c[0] for c in violations[k]]
# LT02 is disabled because it is not in the `rules` of tox.ini
assert "LT02" not in [c[0] for c in violations[k]] | Test linting with overridden config in nested paths.
This looks like a linter test but it's actually a config
test. | test__config__nested_config_tests | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__templater_selection(templater_name, templater_class, raises_error):
"""Test template selection by name."""
if raises_error:
with pytest.raises(SQLFluffUserError):
FluffConfig(overrides={"dialect": "ansi", "templater": templater_name})
else:
cfg = FluffConfig(overrides={"dialect": "ansi", "templater": templater_name})
assert cfg.get_templater().__class__ is templater_class
assert cfg._configs["core"]["templater_obj"].__class__ is templater_class | Test template selection by name. | test__config__templater_selection | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__glob_exclude_config_tests():
"""Test linting with a glob pattern in exclude_rules.
This looks like a linter test but it's actually a config
test.
"""
lntr = Linter(config=FluffConfig.from_path("test/fixtures/config/glob_exclude"))
lnt = lntr.lint_path("test/fixtures/config/glob_exclude/test.sql")
violations = lnt.check_tuples_by_path()
for k in violations:
assert ("AM04", 12, 1) in violations[k]
assert "RF02" not in [c[0] for c in violations[k]]
assert "LT13" not in [c[0] for c in violations[k]]
assert "AM05" not in [c[0] for c in violations[k]]
assert "CV06" not in [c[0] for c in violations[k]] | Test linting with a glob pattern in exclude_rules.
This looks like a linter test but it's actually a config
test. | test__config__glob_exclude_config_tests | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__glob_include_config_tests():
"""Test linting with a glob pattern in rules.
This looks like a linter test but it's actually a config
test.
"""
lntr = Linter(config=FluffConfig.from_path("test/fixtures/config/glob_include"))
lnt = lntr.lint_path("test/fixtures/config/glob_include/test.sql")
violations = lnt.check_tuples_by_path()
for k in violations:
assert ("LT13", 1, 1) in violations[k]
assert ("AM05", 14, 1) in violations[k]
assert ("CV06", 14, 9) in violations[k]
assert ("RF02", 12, 8) in violations[k]
assert "AM04" not in [c[0] for c in violations[k]] | Test linting with a glob pattern in rules.
This looks like a linter test but it's actually a config
test. | test__config__glob_include_config_tests | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__rules_set_to_none():
"""Test linting when rules are set to 'None'.
Ensure that all rules are still run.
"""
lntr = Linter(
config=FluffConfig.from_path("test/fixtures/config/rules_set_to_none")
)
lnt = lntr.lint_path("test/fixtures/config/rules_set_to_none/test.sql")
violations = lnt.check_tuples_by_path()
for k in violations:
assert ("LT13", 1, 1) in violations[k]
assert ("AM04", 12, 1) in violations[k]
assert ("CP01", 12, 10) in violations[k] | Test linting when rules are set to 'None'.
Ensure that all rules are still run. | test__config__rules_set_to_none | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__rules_group_with_exclude():
"""Test linting when a rules group is selected and rules are excluded."""
lntr = Linter(
config=FluffConfig.from_path("test/fixtures/config/rules_group_with_exclude")
)
lnt = lntr.lint_path("test/fixtures/config/rules_group_with_exclude/test.sql")
violations = lnt.check_tuples_by_path()
for k in violations:
assert ("CP01", 15, 1) in violations[k]
assert "LT04" not in [c[0] for c in violations[k]] | Test linting when a rules group is selected and rules are excluded. | test__config__rules_group_with_exclude | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__get_section():
"""Test FluffConfig.get_section method."""
cfg = FluffConfig(config_b)
assert cfg.get_section("core").get("rules", None) == "LT03"
assert cfg.get_section(["layout", "type", "comma"]) == {
"line_position": "trailing",
"spacing_before": "touch",
}
assert cfg.get_section("non_existent") is None | Test FluffConfig.get_section method. | test__config__get_section | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__get():
"""Test FluffConfig.get method."""
cfg = FluffConfig(config_b)
assert cfg.get("rules") == "LT03"
assert cfg.get("rulez") is None
assert cfg.get("rulez", section="core", default=123) == 123
assert (
cfg.get("line_position", section=["layout", "type", "comma"], default=None)
== "trailing"
)
assert (
cfg.get("line_position", section=["layout", "type", "ASDFSDG007"], default=None)
is None
) | Test FluffConfig.get method. | test__config__get | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__from_kwargs():
"""Test from_kwargs method of FluffConfig."""
# Instantiate config object.
cfg = FluffConfig.from_kwargs(
dialect="snowflake",
rules=["LT01", "LT02"],
exclude_rules=["CP01", "AL01"],
)
# Verify we can later retrieve the config values.
assert cfg.get("dialect") == "snowflake"
assert cfg.get("rules") == "LT01,LT02"
assert cfg.get("exclude_rules") == "CP01,AL01" | Test from_kwargs method of FluffConfig. | test__config__from_kwargs | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__from_string():
"""Test from_string method of FluffConfig."""
with open(
os.path.join("test", "fixtures", "config", "inheritance_a", ".sqlfluff")
) as f:
config_string = f.read()
cfg = FluffConfig.from_string(config_string)
# Verify we can later retrieve the config values.
assert cfg.get("testing_val") == "foobar"
assert cfg.get("dialect") == "mysql" | Test from_string method of FluffConfig. | test__config__from_string | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config_missing_dialect():
"""Verify an exception is thrown if no dialect was specified."""
with pytest.raises(SQLFluffUserError) as e:
FluffConfig.from_kwargs()
assert "must configure a dialect" in str(e.value) | Verify an exception is thrown if no dialect was specified. | test__config_missing_dialect | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__validate_configs_indirect():
"""Test _validate_configs method of FluffConfig indirectly."""
# Instantiate config object.
with pytest.raises(SQLFluffUserError):
FluffConfig(
configs={
"core": {"dialect": "ansi"},
# This is a known removed value.
"rules": {"L003": {"lint_templated_tokens": True}},
}
) | Test _validate_configs method of FluffConfig indirectly. | test__config__validate_configs_indirect | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__validate_configs_inline_layout(raw_sql):
"""Test _validate_configs method of FluffConfig when used on a file.
This test covers both the validation of inline config
directives but also the validation of layout configs.
"""
# Instantiate config object.
cfg = FluffConfig(configs={"core": {"dialect": "ansi"}})
# Try to process an invalid inline config. Make sure we get an error.
with pytest.raises(SQLFluffUserError):
cfg.process_raw_file_for_config(raw_sql, "test.sql") | Test _validate_configs method of FluffConfig when used on a file.
This test covers both the validation of inline config
directives but also the validation of layout configs. | test__config__validate_configs_inline_layout | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__config__warn_unknown_rule():
"""Test warnings when rules are unknown."""
lntr = Linter(config=FluffConfig(config_c))
with fluff_log_catcher(logging.WARNING, "sqlfluff.rules") as caplog:
lntr.get_rulepack()
# Check we get a warning on the unrecognised rule.
assert (
"Rule configuration contain a section for unexpected rule 'NOT_A_RULE'."
) in caplog.text
# Check we get a warning for the deprecated rule.
assert (
"Rule configuration contain a section for unexpected rule 'L001'."
) in caplog.text
# Check we get a hint for the matched rule.
assert "match for rule LT01 with name 'layout.spacing'" in caplog.text
# Check we get a warning for the group name.
assert (
"Rule configuration contain a section for unexpected rule 'layout'."
) in caplog.text
# Check we get a hint for the matched rule group.
# NOTE: We don't check the set explicitly because we can't assume ordering.
assert ("The reference was found as a match for multiple rules: {") in caplog.text
assert ("LT01") in caplog.text
assert ("LT02") in caplog.text | Test warnings when rules are unknown. | test__config__warn_unknown_rule | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__process_inline_config():
"""Test the processing of inline in-file configuration directives."""
cfg = FluffConfig(config_b)
assert cfg.get("rules") == "LT03"
cfg.process_inline_config("-- sqlfluff:rules:LT02", "test.sql")
assert cfg.get("rules") == "LT02"
assert cfg.get("tab_space_size", section="indentation") == 4
cfg.process_inline_config("-- sqlfluff:indentation:tab_space_size:20", "test.sql")
assert cfg.get("tab_space_size", section="indentation") == 20
assert cfg.get("dialect") == "ansi"
assert cfg.get("dialect_obj").name == "ansi"
cfg.process_inline_config("-- sqlfluff:dialect:postgres", "test.sql")
assert cfg.get("dialect") == "postgres"
assert cfg.get("dialect_obj").name == "postgres"
assert cfg.get("rulez") is None
cfg.process_inline_config("-- sqlfluff:rulez:LT06", "test.sql")
assert cfg.get("rulez") == "LT06"
# Check that Windows paths don't get mangled
cfg.process_inline_config("-- sqlfluff:jinja:my_path:c:\\foo", "test.sql")
assert cfg.get("my_path", section="jinja") == "c:\\foo"
# Check that JSON objects are not mangled
cfg.process_inline_config('-- sqlfluff:jinja:my_dict:{"k":"v"}', "test.sql")
assert cfg.get("my_dict", section="jinja") == '{"k":"v"}'
# Check that JSON arrays are not mangled
cfg.process_inline_config('-- sqlfluff:jinja:my_dict:[{"k":"v"}]', "test.sql")
assert cfg.get("my_dict", section="jinja") == '[{"k":"v"}]' | Test the processing of inline in-file configuration directives. | test__process_inline_config | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__process_raw_file_for_config(raw_sql):
"""Test the processing of a file inline directives."""
cfg = FluffConfig(config_b)
# verify initial attributes based on the preloaded configuration
assert cfg.get("max_line_length") == 80
assert cfg.get("rules") == "LT03"
assert cfg.get("exclude_rules") is None
# internal list attributes should have corresponding exploded list values
assert cfg.get("rule_allowlist") == ["LT03"]
assert cfg.get("rule_denylist") == []
cfg.process_raw_file_for_config(raw_sql, "test.sql")
# verify overrides based on the file inline directives
assert cfg.get("max_line_length") == 25
assert cfg.get("rules") == "LT05,LT06"
assert cfg.get("exclude_rules") == "LT01,LT02"
# internal list attributes should have overridden exploded list values
assert cfg.get("rule_allowlist") == ["LT05", "LT06"]
assert cfg.get("rule_denylist") == ["LT01", "LT02"] | Test the processing of a file inline directives. | test__process_raw_file_for_config | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__api__immutable_config():
"""Tests that a config is not mutated when parsing."""
config = FluffConfig.from_path(
"test/fixtures/api/config_path_test/extra_configs/.sqlfluff"
)
assert config.get("dialect") == "ansi"
sqlfluff.parse(
"-- sqlfluff:dialect: postgres\nSELECT * FROM table1\n", config=config
)
assert config.get("dialect") == "ansi" | Tests that a config is not mutated when parsing. | test__api__immutable_config | python | sqlfluff/sqlfluff | test/core/config/fluffconfig_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/fluffconfig_test.py | MIT |
def test__validate_configs_direct():
"""Test validate methods directly."""
# Make sure there _are_ removed configs.
assert REMOVED_CONFIGS
# Make sure all raise an error if validated
for k in REMOVED_CONFIGS:
print(k)
if k.translation_func and k.new_path:
config = records_to_nested_dict([(k.old_path, "foo")])
validate_config_dict_for_removed(config, "<test>")
print(config)
new_records = list(iter_records_from_nested_dict(config))
# There should only be one
assert len(new_records) == 1
# And it should be the reassigned one
assert new_records[0][0] == k.new_path
# Really we should check that it's output here, but logging config
# seems to make that hard.
else:
config = records_to_nested_dict([(k.old_path, "foo")])
with pytest.raises(SQLFluffUserError) as excinfo:
validate_config_dict_for_removed(config, "<test>")
assert "set an outdated config" in str(excinfo.value)
assert k.warning in str(excinfo.value) | Test validate methods directly. | test__validate_configs_direct | python | sqlfluff/sqlfluff | test/core/config/validate_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/validate_test.py | MIT |
def test__validate_configs_precedence_same_file():
"""Test _validate_configs method of FluffConfig where there's a conflict."""
# Check with a known conflicted value
old_key = ("rules", "LT03", "operator_new_lines")
new_key = ("layout", "type", "binary_operator", "line_position")
# Check it's still conflicted.
assert any(
k.old_path == old_key and k.new_path == new_key for k in REMOVED_CONFIGS
), (
"This test depends on this key still being removed. Update the test to "
"one that is if this one isn't."
)
# Test config
config = records_to_nested_dict([(new_key, "foo"), (old_key, "foo")])
# Before validation
assert config == {
"rules": {"LT03": {"operator_new_lines": "foo"}},
"layout": {"type": {"binary_operator": {"line_position": "foo"}}},
}
validate_config_dict_for_removed(config, "<test>")
# Check we only get the new key after validation
assert config == {"layout": {"type": {"binary_operator": {"line_position": "foo"}}}} | Test _validate_configs method of FluffConfig where there's a conflict. | test__validate_configs_precedence_same_file | python | sqlfluff/sqlfluff | test/core/config/validate_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/validate_test.py | MIT |
def test__validate_layouts(config_dict, config_warning):
"""Test the layout validation checks."""
with pytest.raises(SQLFluffUserError) as excinfo:
_validate_layout_config(config_dict, "<test>")
assert "set an invalid `layout` option" in str(excinfo.value)
assert config_warning in str(excinfo.value) | Test the layout validation checks. | test__validate_layouts | python | sqlfluff/sqlfluff | test/core/config/validate_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/validate_test.py | MIT |
def mock_xdg_home(monkeypatch):
"""Sets the XDG_CONFIG_HOME variable."""
monkeypatch.setenv("XDG_CONFIG_HOME", "~/.config/my/special/path") | Sets the XDG_CONFIG_HOME variable. | mock_xdg_home | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_file_dir():
"""Test loading config from a directory path."""
cfg = load_config_at_path(
os.path.join("test", "fixtures", "config", "inheritance_a")
)
assert cfg == config_a | Test loading config from a directory path. | test__config__load_file_dir | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_from_string():
"""Test loading config from a string."""
# Load a string
with open(
os.path.join("test", "fixtures", "config", "inheritance_a", ".sqlfluff")
) as f:
config_string = f.read()
cfg = load_config_string(config_string)
assert cfg == config_a | Test loading config from a string. | test__config__load_from_string | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_file_f():
"""Test loading config from a file path."""
cfg = load_config_at_path(
os.path.join("test", "fixtures", "config", "inheritance_a", "testing.sql")
)
assert cfg == config_a | Test loading config from a file path. | test__config__load_file_f | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_file_missing_extra():
"""Test loading config from a file path if extra path is not found."""
with pytest.raises(SQLFluffUserError):
load_config_up_to_path(
os.path.join("test", "fixtures", "config", "inheritance_a", "testing.sql"),
extra_config_path="non/existent/path",
) | Test loading config from a file path if extra path is not found. | test__config__load_file_missing_extra | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_nested():
"""Test nested overwrite and order of precedence of config files."""
cfg = load_config_up_to_path(
os.path.join(
"test", "fixtures", "config", "inheritance_a", "nested", "blah.sql"
),
extra_config_path=os.path.join(
"test",
"fixtures",
"config",
"inheritance_a",
"extra",
"this_can_have_any_name.cfg",
),
)
assert cfg == {
"core": {
# Outer .sqlfluff defines dialect & testing_val and not overridden.
"dialect": "mysql",
"testing_val": "foobar",
# tesing_int is defined in many. Inner pyproject.toml takes precedence.
"testing_int": 1,
# testing_bar is defined only in setup.cfg
"testing_bar": 7.698,
},
# bar is defined in a few, but the extra_config takes precedence.
"bar": {"foo": "foobarextra"},
# fnarr is defined in a few. Inner tox.ini takes precedence.
"fnarr": {"fnarr": {"foo": "foobar"}},
} | Test nested overwrite and order of precedence of config files. | test__config__load_nested | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def change_dir(path):
"""Set the current working directory to `path` for the duration of the context."""
original_dir = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(original_dir) | Set the current working directory to `path` for the duration of the context. | change_dir | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_parent():
"""Test that config is loaded from parent directory of current working directory."""
with change_dir(
os.path.join("test", "fixtures", "config", "inheritance_a", "nested")
):
cfg = load_config_up_to_path("blah.sql")
assert cfg == {
"core": {
"dialect": "mysql",
"testing_val": "foobar",
"testing_int": 1,
"testing_bar": 7.698,
},
"bar": {"foo": "foobar"},
"fnarr": {"fnarr": {"foo": "foobar"}},
} | Test that config is loaded from parent directory of current working directory. | test__config__load_parent | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_toml():
"""Test loading config from a pyproject.toml file."""
cfg = load_config_file(
os.path.join("test", "fixtures", "config", "toml"),
"pyproject.toml",
)
assert cfg == {
"core": {
"nocolor": True,
"verbose": 2,
"testing_int": 5,
"testing_bar": 7.698,
"testing_bool": False,
"testing_arr": ["a", "b", "c"],
"rules": ["LT03", "LT09"],
"testing_inline_table": {"x": 1},
},
"bar": {"foo": "foobar"},
"fnarr": {"fnarr": {"foo": "foobar"}},
"rules": {"capitalisation.keywords": {"capitalisation_policy": "upper"}},
} | Test loading config from a pyproject.toml file. | test__config__load_toml | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_placeholder_cfg():
"""Test loading a sqlfluff configuration file for placeholder templater."""
cfg = load_config_file(
os.path.join("test", "fixtures", "config", "placeholder"),
".sqlfluff-placeholder",
)
assert cfg == {
"core": {
"testing_val": "foobar",
"testing_int": 4,
},
"bar": {"foo": "barbar"},
"templater": {
"placeholder": {
"param_style": "flyway_var",
"flyway:database": "test_db",
}
},
} | Test loading a sqlfluff configuration file for placeholder templater. | test__config__load_placeholder_cfg | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def path_exists(check_path):
"""Patch for os.path.exists which depends on test parameters.
Returns:
True, unless `default_exists` is `False` and the path passed to
the function is the default config path, or unless `xdg_exists`
is `False` and the path passed is the XDG config path.
"""
resolved_path = os.path.expanduser(check_path)
if (
resolved_path == os.path.expanduser("~/.config/sqlfluff")
and not default_exists
):
return False
if resolved_path == os.path.expanduser(xdg_config_path) and not xdg_exists:
return False
return True | Patch for os.path.exists which depends on test parameters.
Returns:
True, unless `default_exists` is `False` and the path passed to
the function is the default config path, or unless `xdg_exists`
is `False` and the path passed is the XDG config path. | test__config__get_user_config_dir_path.path_exists | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__get_user_config_dir_path(
mock_listdir,
mock_path_exists,
mock_xdg_home,
sys_platform,
xdg_exists,
default_exists,
resolved_config_path,
paths_checked,
):
"""Test loading config from user appdir."""
xdg_home = os.environ.get("XDG_CONFIG_HOME")
assert xdg_home, "XDG HOME should be set by the mock. Something has gone wrong."
xdg_config_path = xdg_home + "/sqlfluff"
def path_exists(check_path):
"""Patch for os.path.exists which depends on test parameters.
Returns:
True, unless `default_exists` is `False` and the path passed to
the function is the default config path, or unless `xdg_exists`
is `False` and the path passed is the XDG config path.
"""
resolved_path = os.path.expanduser(check_path)
if (
resolved_path == os.path.expanduser("~/.config/sqlfluff")
and not default_exists
):
return False
if resolved_path == os.path.expanduser(xdg_config_path) and not xdg_exists:
return False
return True
mock_path_exists.side_effect = path_exists
# Get the config path as though we are on macOS.
resolved_path = _get_user_config_dir_path(sys_platform)
assert os.path.expanduser(resolved_path) == os.path.expanduser(resolved_config_path)
mock_path_exists.assert_has_calls(
[call(os.path.expanduser(path)) for path in paths_checked]
) | Test loading config from user appdir. | test__config__get_user_config_dir_path | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__load_user_appdir_config(mock_load_config, mock_path_exists):
"""Test _load_user_appdir_config.
NOTE: We mock `load_config_at_path()` so we can be really focussed with this test
and also not need to actually interact with local home directories.
"""
mock_load_config.side_effect = lambda x: {}
mock_path_exists.side_effect = lambda x: True
_load_user_appdir_config()
# It will check that the default config path exists...
mock_path_exists.assert_has_calls([call(os.path.expanduser("~/.config/sqlfluff"))])
# ...and assuming it does, it will try and load config files at that path.
mock_load_config.assert_has_calls([call(os.path.expanduser("~/.config/sqlfluff"))]) | Test _load_user_appdir_config.
NOTE: We mock `load_config_at_path()` so we can be really focussed with this test
and also not need to actually interact with local home directories. | test__config__load_user_appdir_config | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def test__config__toml_list_config():
"""Test Parsing TOML list of values."""
loaded_config = load_config_file(
os.path.join("test", "fixtures", "config", "toml"),
"pyproject.toml",
)
loaded_config["core"]["dialect"] = "ansi"
cfg = FluffConfig(loaded_config)
# Verify we can later retrieve the config values.
assert cfg.get("dialect") == "ansi"
assert cfg.get("rules") == ["LT03", "LT09"] | Test Parsing TOML list of values. | test__config__toml_list_config | python | sqlfluff/sqlfluff | test/core/config/loader_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/config/loader_test.py | MIT |
def raw_segments(generate_test_segments):
"""Construct a list of raw segments as a fixture."""
return generate_test_segments(["foobar", ".barfoo"]) | Construct a list of raw segments as a fixture. | raw_segments | python | sqlfluff/sqlfluff | test/core/linter/fix_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/fix_test.py | MIT |
def test__rules_base_segments_compute_anchor_edit_info(raw_segments):
"""Test BaseSegment.compute_anchor_edit_info()."""
# Construct a fix buffer, intentionally with:
# - one duplicate.
# - two different incompatible fixes on the same segment.
fixes = [
LintFix.replace(raw_segments[0], [raw_segments[0].edit(raw="a")]),
LintFix.replace(raw_segments[0], [raw_segments[0].edit(raw="a")]),
LintFix.replace(raw_segments[0], [raw_segments[0].edit(raw="b")]),
]
anchor_info_dict = compute_anchor_edit_info(fixes)
# Check the target segment is the only key we have.
assert list(anchor_info_dict.keys()) == [raw_segments[0].uuid]
anchor_info = anchor_info_dict[raw_segments[0].uuid]
# Check that the duplicate as been deduplicated.
# i.e. this isn't 3.
assert anchor_info.replace == 2
# Check the fixes themselves.
# NOTE: There's no duplicated first fix.
assert anchor_info.fixes == [
LintFix.replace(raw_segments[0], [raw_segments[0].edit(raw="a")]),
LintFix.replace(raw_segments[0], [raw_segments[0].edit(raw="b")]),
]
# Check the first replace
assert anchor_info._first_replace == LintFix.replace(
raw_segments[0], [raw_segments[0].edit(raw="a")]
) | Test BaseSegment.compute_anchor_edit_info(). | test__rules_base_segments_compute_anchor_edit_info | python | sqlfluff/sqlfluff | test/core/linter/fix_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/fix_test.py | MIT |
def test__fix__generate_source_patches(tree, templated_file, expected_result, caplog):
"""Test generate_source_patches.
This is part of fix_string().
"""
with caplog.at_level(logging.DEBUG, logger="sqlfluff.linter"):
result = generate_source_patches(tree, templated_file)
assert result == expected_result | Test generate_source_patches.
This is part of fix_string(). | test__fix__generate_source_patches | python | sqlfluff/sqlfluff | test/core/linter/fix_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/fix_test.py | MIT |
def normalise_paths(paths):
"""Test normalising paths.
NB Paths on difference platforms might look different, so this
makes them comparable.
"""
return {pth.replace("/", ".").replace("\\", ".") for pth in paths} | Test normalising paths.
NB Paths on difference platforms might look different, so this
makes them comparable. | normalise_paths | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__skip_large_bytes(filesize, raises_skip):
"""Test extracting paths from a file path."""
config = FluffConfig(
overrides={"large_file_skip_byte_limit": filesize, "dialect": "ansi"}
)
# First check the function directly
if raises_skip:
with pytest.raises(SQLFluffSkipFile) as excinfo:
Linter.load_raw_file_and_config(
"test/fixtures/linter/indentation_errors.sql", config
)
assert "Skipping" in str(excinfo.value)
assert f"over the limit of {filesize}" in str(excinfo.value)
# If NOT raises, then we'll catch the raise an error and the test will fail.
# Then check that it either is or isn't linted appropriately via lint_paths.
lntr = Linter(config)
result = lntr.lint_paths(
("test/fixtures/linter/indentation_errors.sql",),
)
if raises_skip:
assert not result.get_violations()
else:
assert result.get_violations()
# Same again via parse_path, which is the other entry point.
result = list(
lntr.parse_path(
"test/fixtures/linter/indentation_errors.sql",
)
)
if raises_skip:
assert not result
else:
assert result | Test extracting paths from a file path. | test__linter__skip_large_bytes | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__lint_string_vs_file(path):
"""Test the linter finds the same things on strings and files."""
with open(path) as f:
sql_str = f.read()
lntr = Linter(dialect="ansi")
assert (
lntr.lint_string(sql_str).check_tuples() == lntr.lint_path(path).check_tuples()
) | Test the linter finds the same things on strings and files. | test__linter__lint_string_vs_file | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__get_violations_filter_rules(rules, num_violations):
"""Test filtering violations by which rules were violated."""
lntr = Linter(dialect="ansi")
lint_result = lntr.lint_string("select a, b FROM tbl c order BY d")
assert len(lint_result.get_violations(rules=rules)) == num_violations | Test filtering violations by which rules were violated. | test__linter__get_violations_filter_rules | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_result__sum_dicts():
"""Test the summing of dictionaries in the linter."""
i = {}
a = dict(a=3, b=123, f=876.321)
b = dict(a=19, b=321.0, g=23478)
r = dict(a=22, b=444.0, f=876.321, g=23478)
assert sum_dicts(a, b) == r
# Check the identity too
assert sum_dicts(r, i) == r | Test the summing of dictionaries in the linter. | test__linter__linting_result__sum_dicts | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_result__combine_dicts():
"""Test the combination of dictionaries in the linter."""
a = dict(a=3, b=123, f=876.321)
b = dict(h=19, i=321.0, j=23478)
r = dict(z=22)
assert combine_dicts(a, b, r) == dict(
a=3, b=123, f=876.321, h=19, i=321.0, j=23478, z=22
) | Test the combination of dictionaries in the linter. | test__linter__linting_result__combine_dicts | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_result_check_tuples():
"""Test that a LintingResult can partition violations by the source files."""
lntr = Linter()
result = lntr.lint_paths(
(
"test/fixtures/linter/comma_errors.sql",
"test/fixtures/linter/whitespace_errors.sql",
)
)
check_tuples = result.check_tuples()
isinstance(check_tuples, list)
assert check_tuples == [
("LT09", 2, 1),
("LT04", 4, 5),
("LT02", 5, 1),
("LT04", 5, 1),
("LT02", 6, 1),
("AL02", 6, 5),
("LT01", 6, 6),
("CP01", 8, 1),
("LT09", 1, 1),
("LT01", 2, 9),
("LT01", 3, 12),
("LT02", 4, 1),
("CP01", 6, 10),
] | Test that a LintingResult can partition violations by the source files. | test__linter__linting_result_check_tuples | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_result_check_tuples_by_path():
"""Test that a LintingResult can partition violations by the source files."""
lntr = Linter()
result = lntr.lint_paths(
(
"test/fixtures/linter/comma_errors.sql",
"test/fixtures/linter/whitespace_errors.sql",
)
)
check_tuples = result.check_tuples_by_path()
isinstance(check_tuples, dict)
# Normalise the paths in the keys.
check_tuples = {k.replace("\\", "/"): v for k, v in check_tuples.items()}
assert check_tuples == {
"test/fixtures/linter/comma_errors.sql": [
("LT09", 2, 1),
("LT04", 4, 5),
("LT02", 5, 1),
("LT04", 5, 1),
("LT02", 6, 1),
("AL02", 6, 5),
("LT01", 6, 6),
("CP01", 8, 1),
],
"test/fixtures/linter/whitespace_errors.sql": [
("LT09", 1, 1),
("LT01", 2, 9),
("LT01", 3, 12),
("LT02", 4, 1),
("CP01", 6, 10),
],
} | Test that a LintingResult can partition violations by the source files. | test__linter__linting_result_check_tuples_by_path | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_result_stats(path, stats):
"""Test that a LintingResult can get the right stats with multiple files.
https://github.com/sqlfluff/sqlfluff/issues/5673
"""
lntr = Linter()
result = lntr.lint_paths((f"test/fixtures/linter/exit_codes/{path}",))
# NOTE: We're using fake return codes for testing purposes.
assert result.stats(111, 222) == stats | Test that a LintingResult can get the right stats with multiple files.
https://github.com/sqlfluff/sqlfluff/issues/5673 | test__linter__linting_result_stats | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_result_get_violations(processes):
"""Test that we can get violations from a LintingResult."""
lntr = Linter()
result = lntr.lint_paths(
(
"test/fixtures/linter/comma_errors.sql",
"test/fixtures/linter/whitespace_errors.sql",
),
processes=processes,
)
all([isinstance(v, SQLLintError) for v in result.get_violations()]) | Test that we can get violations from a LintingResult. | test__linter__linting_result_get_violations | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_parallel_thread(force_error, monkeypatch):
"""Run linter in parallel mode using threads.
Similar to test__linter__linting_result_get_violations but uses a thread
pool of 1 worker to test parallel mode without subprocesses. This lets the
tests capture code coverage information for the backend parts of parallel
execution without having to jump through hoops.
"""
if not force_error:
monkeypatch.setattr(Linter, "allow_process_parallelism", False)
else:
def _create_pool(*args, **kwargs):
class ErrorPool:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def imap_unordered(self, *args, **kwargs):
yield runner.DelayedException(ValueError())
return ErrorPool()
monkeypatch.setattr(runner.MultiProcessRunner, "_create_pool", _create_pool)
config = FluffConfig(overrides={"dialect": "ansi"})
output_stream = make_output_stream(config, None, os.devnull)
lntr = Linter(
formatter=OutputStreamFormatter(output_stream, False, verbosity=0),
dialect="ansi",
)
result = lntr.lint_paths(
# NOTE: Lint more than one file to make sure we enabled the multithreaded
# code path.
(
"test/fixtures/linter/comma_errors.sql",
"test/fixtures/linter/whitespace_errors.sql",
),
processes=2,
)
all([isinstance(v, SQLLintError) for v in result.get_violations()]) | Run linter in parallel mode using threads.
Similar to test__linter__linting_result_get_violations but uses a thread
pool of 1 worker to test parallel mode without subprocesses. This lets the
tests capture code coverage information for the backend parts of parallel
execution without having to jump through hoops. | test__linter__linting_parallel_thread | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test_lint_path_parallel_wrapper_exception(patched_lint):
"""Tests the error catching behavior of _lint_path_parallel_wrapper().
Test on MultiThread runner because otherwise we have pickling issues.
"""
patched_lint.side_effect = ValueError("Something unexpected happened")
for result in runner.MultiThreadRunner(
Linter(), FluffConfig(overrides={"dialect": "ansi"}), processes=1
).run(
["test/fixtures/linter/passing.sql"],
fix=False,
):
assert isinstance(result, runner.DelayedException)
with pytest.raises(ValueError):
result.reraise() | Tests the error catching behavior of _lint_path_parallel_wrapper().
Test on MultiThread runner because otherwise we have pickling issues. | test_lint_path_parallel_wrapper_exception | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__get_runner_processes(
patched_cpu_count, mock_cpu, in_processes, exp_processes
):
"""Test that get_runner handles processes correctly."""
# Make the mocked cpu count a really high value which is
# unlikely to collide with the real value.
patched_cpu_count.return_value = mock_cpu
_, return_processes = get_runner(
linter=Linter(),
config=FluffConfig(overrides={"dialect": "ansi"}),
processes=in_processes,
)
assert return_processes == exp_processes | Test that get_runner handles processes correctly. | test__linter__get_runner_processes | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__linting_unexpected_error_handled_gracefully(
patched_lint, patched_logger
):
"""Test that an unexpected internal error returns the issue-surfacing file."""
patched_lint.side_effect = Exception("Something unexpected happened")
lntr = Linter()
lntr.lint_paths(("test/fixtures/linter/passing.sql",))
assert (
"Unable to lint test/fixtures/linter/passing.sql due to an internal error."
# NB: Replace is to handle windows-style paths.
in patched_logger.warning.call_args[0][0].replace("\\", "/")
and "Exception: Something unexpected happened"
in patched_logger.warning.call_args[0][0]
) | Test that an unexpected internal error returns the issue-surfacing file. | test__linter__linting_unexpected_error_handled_gracefully | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__empty_file():
"""Test linter behaves nicely with an empty string.
Much of this test is about making sure that ParsedString is
instantiated appropriately.
"""
lntr = Linter(dialect="ansi")
# Make sure no exceptions raised and no violations found in empty file.
parsed = lntr.parse_string("")
# There should still be a parsed variant
assert parsed.parsed_variants
assert len(parsed.parsed_variants) == 1
root_variant = parsed.parsed_variants[0]
# That root variant should still have a templated file and a parsed tree
# (although that parsed tree will likely just be an end of file marker).
assert root_variant.templated_file
assert root_variant.tree
# No violations
assert not parsed.violations | Test linter behaves nicely with an empty string.
Much of this test is about making sure that ParsedString is
instantiated appropriately. | test__linter__empty_file | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__parse_fail():
"""Test linter behaves as expected with an unparsable string.
Much of this test is about making sure that ParsedString is
instantiated appropriately.
"""
lntr = Linter(dialect="ansi")
# Try and parse something which obviously isn't SQL
parsed = lntr.parse_string("THIS IS NOT SQL")
# There should still be a parsed variant
assert parsed.parsed_variants
assert len(parsed.parsed_variants) == 1
root_variant = parsed.parsed_variants[0]
# That root variant should still have a templated file and a parsed tree...
assert root_variant.templated_file
assert root_variant.tree
# ...but that tree should contain an unparsable segment.
assert "unparsable" in root_variant.tree.type_set()
# There *should* be violations because there should be a parsing fail.
assert parsed.violations
assert any(isinstance(v, SQLParseError) for v in parsed.violations) | Test linter behaves as expected with an unparsable string.
Much of this test is about making sure that ParsedString is
instantiated appropriately. | test__linter__parse_fail | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__templating_fail():
"""Test linter behaves as expected with invalid jinja template.
Much of this test is about making sure that ParsedString is
instantiated appropriately.
"""
lntr = Linter(dialect="ansi")
# Try and parse something which breaks Jinja templating.
parsed = lntr.parse_string("{% if foo %}")
# For a templating fail, there won't be a parsed variant.
assert not parsed.parsed_variants
# There *should* be violations because there should be a templating fail.
assert parsed.violations
assert any(isinstance(v, SQLTemplaterError) for v in parsed.violations) | Test linter behaves as expected with invalid jinja template.
Much of this test is about making sure that ParsedString is
instantiated appropriately. | test__linter__templating_fail | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__mask_templated_violations(
path, rules, ignore_templated_areas, check_tuples
):
"""Test linter masks files properly around templated content.
NOTE: this also tests deduplication of fixes which have the same
source position. i.e. `LintedFile.deduplicate_in_source_space()`.
"""
lntr = Linter(
config=FluffConfig(
overrides={
"rules": rules,
"ignore_templated_areas": ignore_templated_areas,
"dialect": "ansi",
}
)
)
linted = lntr.lint_path(path=path)
assert linted.check_tuples() == check_tuples | Test linter masks files properly around templated content.
NOTE: this also tests deduplication of fixes which have the same
source position. i.e. `LintedFile.deduplicate_in_source_space()`. | test__linter__mask_templated_violations | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__linter__encoding(fname, config_encoding, lexerror):
"""Test linter deals with files with different encoding."""
lntr = Linter(
config=FluffConfig(
overrides={
"rules": "LT01",
"encoding": config_encoding,
"dialect": "ansi",
}
)
)
result = lntr.lint_paths((fname,))
assert lexerror == (SQLLexError in [type(v) for v in result.get_violations()]) | Test linter deals with files with different encoding. | test__linter__encoding | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test_delayed_exception():
"""Test that DelayedException stores and reraises a stored exception."""
ve = ValueError()
de = runner.DelayedException(ve)
with pytest.raises(ValueError):
de.reraise() | Test that DelayedException stores and reraises a stored exception. | test_delayed_exception | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test__attempt_to_change_templater_warning():
"""Test warning when changing templater in .sqlfluff file in subdirectory."""
initial_config = FluffConfig(
configs={"core": {"templater": "jinja", "dialect": "ansi"}}
)
lntr = Linter(config=initial_config)
updated_config = FluffConfig(
configs={"core": {"templater": "python", "dialect": "ansi"}}
)
with fluff_log_catcher(logging.WARNING, "sqlfluff.linter") as caplog:
lntr.render_string(
in_str="select * from table",
fname="test.sql",
config=updated_config,
encoding="utf-8",
)
assert "Attempt to set templater to " in caplog.text | Test warning when changing templater in .sqlfluff file in subdirectory. | test__attempt_to_change_templater_warning | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test_advanced_api_methods():
"""Test advanced API methods on segments."""
# These aren't used by the simple API, which returns
# a simple JSON representation of the parse tree, but
# are available for advanced API usage and within rules.
sql = """
WITH cte AS (
SELECT * FROM tab_a
)
SELECT
cte.col_a,
tab_b.col_b
FROM cte
INNER JOIN tab_b;
"""
linter = Linter(dialect="ansi")
parsed = linter.parse_string(sql)
# CTEDefinitionSegment.get_identifier
cte_segment = next(parsed.tree.recursive_crawl("common_table_expression"))
assert cte_segment.get_identifier().raw == "cte"
# BaseFileSegment.get_table_references & StatementSegment.get_table_references
assert parsed.tree.get_table_references() == {"tab_a", "tab_b"} | Test advanced API methods on segments. | test_advanced_api_methods | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test_normalise_newlines():
"""Test normalising newlines to unix-style line endings."""
in_str = "SELECT\r\n foo\n FROM \r \n\r bar;"
out_str = "SELECT\n foo\n FROM \n \n\n bar;"
assert out_str == Linter._normalise_newlines(in_str) | Test normalising newlines to unix-style line endings. | test_normalise_newlines | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def test_unparsable_fix_output(fix_even_unparsable):
"""Tests functionality and logging output with unparsable sections.
NOTE: While we cover different paths, the result for this test is the
same for both values of `fix_even_unparsable`. We probably need a better
test case at some point so that we can actually see the difference.
"""
config = FluffConfig(
overrides={"fix_even_unparsable": fix_even_unparsable, "dialect": "ansi"}
)
linter = Linter(config=config)
# Attempt to fix it, capturing the logging output.
with fluff_log_catcher(logging.WARNING, "sqlfluff.linter") as caplog:
result = linter.lint_paths(
("test/fixtures/linter/parse_error_2.sql",),
fix=True,
apply_fixes=True,
fixed_file_suffix=f"_{fix_even_unparsable}_fix",
fix_even_unparsable=fix_even_unparsable,
)
# Assert that it parsed (i.e. we found a select_statement), but with an
# unparsable section in there too.
assert result.tree
assert "select_statement" in result.tree.descendant_type_set
assert "unparsable" in result.tree.descendant_type_set
# We should still find linting issues too
assert result.check_tuples(raise_on_non_linting_violations=False) == [
("CP01", 2, 7), # `a as b` - capitalisation of AS
("AL03", 3, 5), # 42 is an expression without an alias
# The unparsable section is (wrongly) detected as an indentation issue.
("LT02", 4, 1),
("CP01", 5, 1), # `from` is uncapitalised
]
# We should make sure that the warning that asks users to report a bug is
# NOT present. i.e. the warning which could happen in `lint_fix_parsed()`.`
assert "Please report this as a bug" not in caplog.text
# Also not the `fix not applied`. The one in `_warn_unfixable()`
assert "it would re-cause the same error" not in caplog.text
# In fact, there shouldn't be any warnings at all.
assert not caplog.text.strip()
# In both cases, the final capitalisation and the `a as b` sections should have
# been fixed (because they aren't in the unparsable section).
assert "from cte" not in result.tree.raw
assert "FROM cte" in result.tree.raw
assert "a as b" not in result.tree.raw
assert "a AS b" in result.tree.raw
# Check whether the file was persisted. If `fix_even_unparsable` was set, then
# there should be a file, and it should have the fixes from above in it. If not
# then there should be no fixed file, as the persist will have been aborted due
# to the parsing issues.
predicted_fix_path = (
f"test/fixtures/linter/parse_error_2_{fix_even_unparsable}_fix.sql"
)
if fix_even_unparsable:
with open(predicted_fix_path, "r") as f:
fixed_sql = f.read()
assert result.tree.raw == fixed_sql
else:
with pytest.raises(FileNotFoundError):
open(predicted_fix_path, "r") | Tests functionality and logging output with unparsable sections.
NOTE: While we cover different paths, the result for this test is the
same for both values of `fix_even_unparsable`. We probably need a better
test case at some point so that we can actually see the difference. | test_unparsable_fix_output | python | sqlfluff/sqlfluff | test/core/linter/linter_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linter_test.py | MIT |
def normalise_paths(paths):
"""Test normalising paths.
NB Paths on difference platforms might look different, so this
makes them comparable.
"""
return {pth.replace("/", ".").replace("\\", ".") for pth in paths} | Test normalising paths.
NB Paths on difference platforms might look different, so this
makes them comparable. | normalise_paths | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__dir():
"""Test extracting paths from directories."""
paths = paths_from_path("test/fixtures/lexer")
assert normalise_paths(paths) == {
"test.fixtures.lexer.block_comment.sql",
"test.fixtures.lexer.inline_comment.sql",
"test.fixtures.lexer.basic.sql",
} | Test extracting paths from directories. | test__linter__path_from_paths__dir | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__default():
"""Test .sql files are found by default."""
paths = normalise_paths(paths_from_path("test/fixtures/linter"))
assert "test.fixtures.linter.passing.sql" in paths
assert "test.fixtures.linter.passing_cap_extension.SQL" in paths
assert "test.fixtures.linter.discovery_file.txt" not in paths | Test .sql files are found by default. | test__linter__path_from_paths__default | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__exts():
"""Test configuration of file discovery."""
paths = normalise_paths(
paths_from_path("test/fixtures/linter", target_file_exts=[".txt", ".txt.j2"])
)
assert "test.fixtures.linter.passing.sql" not in paths
assert "test.fixtures.linter.passing_cap_extension.SQL" not in paths
assert "test.fixtures.linter.discovery_file.txt" in paths
assert "test.fixtures.linter.discovery_file.txt.j2" in paths | Test configuration of file discovery. | test__linter__path_from_paths__exts | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__file():
"""Test extracting paths from a file path."""
paths = paths_from_path("test/fixtures/linter/indentation_errors.sql")
assert normalise_paths(paths) == {"test.fixtures.linter.indentation_errors.sql"} | Test extracting paths from a file path. | test__linter__path_from_paths__file | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__not_exist():
"""Test that the right errors are raise when a file doesn't exist."""
with pytest.raises(SQLFluffUserError):
paths_from_path("asflekjfhsakuefhse") | Test that the right errors are raise when a file doesn't exist. | test__linter__path_from_paths__not_exist | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__not_exist_ignore():
"""Test extracting paths from a file path."""
paths = paths_from_path("asflekjfhsakuefhse", ignore_non_existent_files=True)
assert len(paths) == 0 | Test extracting paths from a file path. | test__linter__path_from_paths__not_exist_ignore | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__explicit_ignore():
"""Test ignoring files that were passed explicitly."""
paths = paths_from_path(
"test/fixtures/linter/sqlfluffignore/path_a/query_a.sql",
ignore_non_existent_files=True,
ignore_files=True,
working_path="test/fixtures/linter/sqlfluffignore/",
)
assert len(paths) == 0 | Test ignoring files that were passed explicitly. | test__linter__path_from_paths__explicit_ignore | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__sqlfluffignore_current_directory():
"""Test that .sqlfluffignore in the current directory is read when dir given."""
oldcwd = os.getcwd()
try:
os.chdir("test/fixtures/linter/sqlfluffignore")
paths = paths_from_path(
"path_a/",
ignore_non_existent_files=True,
ignore_files=True,
working_path="test/fixtures/linter/sqlfluffignore/",
)
assert len(paths) == 0
finally:
os.chdir(oldcwd) | Test that .sqlfluffignore in the current directory is read when dir given. | test__linter__path_from_paths__sqlfluffignore_current_directory | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__dot():
"""Test extracting paths from a dot."""
# Use set theory to check that we get AT LEAST these files
assert normalise_paths(paths_from_path(".")) >= {
"test.fixtures.lexer.block_comment.sql",
"test.fixtures.lexer.inline_comment.sql",
"test.fixtures.lexer.basic.sql",
} | Test extracting paths from a dot. | test__linter__path_from_paths__dot | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__ignore(path):
"""Test extracting paths from a dot."""
# We should only get query_b, because of the sqlfluffignore files.
assert normalise_paths(paths_from_path(path)) == {
"test.fixtures.linter.sqlfluffignore.path_b.query_b.sql"
} | Test extracting paths from a dot. | test__linter__path_from_paths__ignore | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__path_from_paths__specific_bad_ext():
"""Test we get no match if a path with the wrong extension is passed."""
assert paths_from_path("README.md") == [] | Test we get no match if a path with the wrong extension is passed. | test__linter__path_from_paths__specific_bad_ext | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linter__load_specs_from_lines(lines):
"""Test the unhappy path of _load_specs_from_lines.
This is typically if we pass something un-iterable,
or an invalid pattern
"""
with pytest.raises(SQLFluffUserError):
_load_specs_from_lines(lines, "<test>") | Test the unhappy path of _load_specs_from_lines.
This is typically if we pass something un-iterable,
or an invalid pattern | test__linter__load_specs_from_lines | python | sqlfluff/sqlfluff | test/core/linter/discovery_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/discovery_test.py | MIT |
def test__linted_file__build_up_fixed_source_string(
source_slices, source_patches, raw_source_string, expected_result, caplog
):
"""Test _build_up_fixed_source_string.
This is part of fix_string().
"""
with caplog.at_level(logging.DEBUG, logger="sqlfluff.linter"):
result = LintedFile._build_up_fixed_source_string(
source_slices, source_patches, raw_source_string
)
assert result == expected_result | Test _build_up_fixed_source_string.
This is part of fix_string(). | test__linted_file__build_up_fixed_source_string | python | sqlfluff/sqlfluff | test/core/linter/linted_file_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linted_file_test.py | MIT |
def test__linted_file__slice_source_file_using_patches(
source_patches, source_only_slices, raw_source_string, expected_result, caplog
):
"""Test _slice_source_file_using_patches.
This is part of fix_string().
"""
with caplog.at_level(logging.DEBUG, logger="sqlfluff.linter"):
result = LintedFile._slice_source_file_using_patches(
source_patches, source_only_slices, raw_source_string
)
assert result == expected_result | Test _slice_source_file_using_patches.
This is part of fix_string(). | test__linted_file__slice_source_file_using_patches | python | sqlfluff/sqlfluff | test/core/linter/linted_file_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linted_file_test.py | MIT |
def test_safe_create_replace_file(case, tmp_path):
"""Test creating or updating .sql files, various content and encoding."""
p = tmp_path / case["fname"]
if case["existing"]:
p.write_text(case["existing"])
try:
LintedFile._safe_create_replace_file(
str(p), str(p), case["update"], case["encoding"]
)
except Exception:
pass
actual = p.read_text(encoding=case["encoding"])
assert case["expected"] == actual | Test creating or updating .sql files, various content and encoding. | test_safe_create_replace_file | python | sqlfluff/sqlfluff | test/core/linter/linted_file_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/linter/linted_file_test.py | MIT |
def test_object_ref_matches_table(possible_references, targets, result):
"""Test object_ref_matches_table()."""
assert reference.object_ref_matches_table(possible_references, targets) == result | Test object_ref_matches_table(). | test_object_ref_matches_table | python | sqlfluff/sqlfluff | test/core/rules/reference_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/reference_test.py | MIT |
def test_rules_crawlers(CrawlerType, crawler_kwargs, raw_sql_in, target_raws_out):
"""Test Crawlers."""
cfg = FluffConfig(overrides={"dialect": "ansi"})
linter = Linter(config=cfg)
root = linter.parse_string(raw_sql_in).tree
root_context = RuleContext(
dialect=cfg.get("dialect_obj"),
fix=True,
templated_file=TemplatedFile(raw_sql_in, "<test-case>"),
path=None,
segment=root,
config=cfg,
)
crawler = CrawlerType(**crawler_kwargs)
result_raws = [context.segment.raw for context in crawler.crawl(root_context)]
assert result_raws == target_raws_out | Test Crawlers. | test_rules_crawlers | python | sqlfluff/sqlfluff | test/core/rules/crawlers_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/crawlers_test.py | MIT |
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() | A badly formatted noqa gets raised as a parsing error. | test__linter__raises_malformed_noqa | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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) | Test correct of "noqa" comments. | test_parse_noqa | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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)) | Test overlapping glob expansions don't return duplicate rules in noqa. | test_parse_noqa_no_dups | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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 | Test that _ignore_masked_violations() correctly filters violations. | test_linted_file_ignore_masked_violations | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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} | Test "noqa" feature at the higher "Linter" level. | test_linter_noqa | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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() | Similar to test_linter_noqa, but uses templating (Jinja). | test_linter_noqa_with_templating | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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() | Similar to test_linter_noqa, but uses templating (Jinja). | test_linter_noqa_template_errors | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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 | 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. | test_linter_noqa_prs | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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 | Test "noqa" feature to ignore TMP at the higher "Linter" level. | test_linter_noqa_tmp | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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" | Test "noqa" comments can be disabled via the config. | test_linter_noqa_disable | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
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 | Test "noqa" comments can be disabled via the config. | test_linter_disable_noqa_except | python | sqlfluff/sqlfluff | test/core/rules/noqa_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/noqa_test.py | MIT |
def test_content_count(content, min_count):
"""Test docstring have specific content."""
for plugin_rules in get_plugin_manager().hook.get_rules():
for rule in plugin_rules:
if rule._check_docstring is True:
assert len(content.findall(rule.__doc__)) >= min_count, (
f"{rule.__name__} content {content} does not occur at least "
f"{min_count} times"
) | Test docstring have specific content. | test_content_count | python | sqlfluff/sqlfluff | test/core/rules/docstring_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/docstring_test.py | MIT |
def test_keyword_anti_before_best():
"""Test docstring anti pattern before best pattern."""
for plugin_rules in get_plugin_manager().hook.get_rules():
for rule in plugin_rules:
if rule._check_docstring is True:
best_match = KEYWORD_BEST.search(rule.__doc__)
anti_match = KEYWORD_ANTI.search(rule.__doc__)
assert best_match
assert anti_match
best_pos = best_match.start()
anti_pos = anti_match.start()
assert anti_pos < best_pos, (
f"{rule.__name__} keyword {KEYWORD_BEST} appears before "
f"{KEYWORD_ANTI}"
) | Test docstring anti pattern before best pattern. | test_keyword_anti_before_best | python | sqlfluff/sqlfluff | test/core/rules/docstring_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/docstring_test.py | MIT |
def test_backtick_replace():
"""Test replacing docstring double backticks for lint results."""
sql = """
SELECT
DISTINCT(a),
b
FROM foo
"""
result = lint(sql, rules=["ST08"])
# ST08 docstring looks like:
# ``DISTINCT`` used with parentheses.
# Check the double bacticks (``) get replaced by a single quote (').
assert result[0]["description"] == "'DISTINCT' used with parentheses." | Test replacing docstring double backticks for lint results. | test_backtick_replace | python | sqlfluff/sqlfluff | test/core/rules/docstring_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/docstring_test.py | MIT |
def _eval(self, context):
"""Stars make newlines."""
if context.segment.is_type("whitespace"):
return LintResult(
anchor=context.segment,
fixes=[
LintFix.replace(
context.segment, [WhitespaceSegment(context.segment.raw + " ")]
)
],
) | Stars make newlines. | _eval | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def _eval(self, context):
"""Stars make newlines."""
violations = []
for seg in context.segment.raw_segments:
if seg.is_code:
violations.append(LintResult(anchor=seg, description="TESTING"))
return violations | Stars make newlines. | _eval | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def _eval(self, context):
"""Triple any numeric literals."""
return LintResult(
anchor=context.segment,
fixes=[
LintFix.replace(
context.segment,
[
context.segment,
WhitespaceSegment(context.segment.raw + " "),
context.segment,
WhitespaceSegment(context.segment.raw + " "),
context.segment,
],
)
],
) | Triple any numeric literals. | _eval | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.