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__rules__user_rules():
"""Test that can safely add user rules."""
# Set up a linter with the user rule
linter = Linter(user_rules=[Rule_T042], dialect="ansi")
# Make sure the new one is in there.
assert RuleTuple("T042", "", "A dummy rule.", ("all",), ()) in linter.rule_tuples()
# Instantiate a second linter and check it's NOT in there.
# This tests that copying and isolation works.
linter = Linter(dialect="ansi")
assert not any(rule[0] == "T042" for rule in linter.rule_tuples()) | Test that can safely add user rules. | test__rules__user_rules | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test__rules__rule_selection(rules, exclude_rules, resulting_codes):
"""Test that rule selection works by various means."""
class Rule_T010(BaseRule):
"""Fake Basic Rule."""
groups = ("all", "test")
name = "fake_basic"
aliases = ("fb1", "foo") # NB: Foo is a group on another rule.
crawl_behaviour = RootOnlyCrawler()
def _eval(self, **kwargs):
pass
class Rule_T011(Rule_T010):
"""Fake Basic Rule.
NOTE: We inherit crawl behaviour and _eval from above.
"""
groups = ("all", "test", "foo")
name = "fake_other"
aliases = ("fb2",)
class Rule_T012(Rule_T010):
"""Fake Basic Rule.
NOTE: We inherit crawl behaviour and _eval from above.
"""
# NB: "fake_other" is the name of another rule.
groups = ("all", "foo", "fake_other")
# No aliases, Name collides with the alias of another rule.
name = "fake_again"
aliases = ()
cfg = FluffConfig(
overrides={"rules": rules, "exclude_rules": exclude_rules, "dialect": "ansi"}
)
linter = Linter(config=cfg, user_rules=[Rule_T010, Rule_T011, Rule_T012])
# Get the set of selected codes:
selected_codes = set(tpl[0] for tpl in linter.rule_tuples())
# Check selected rules
assert selected_codes == resulting_codes | Test that rule selection works by various means. | test__rules__rule_selection | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test__rules__filter_unparsable():
"""Test that rules that handle their own crawling respect unparsable."""
# Set up a linter with the user rule
linter = Linter(user_rules=[Rule_T002], dialect="ansi", rules=["T002"])
# Lint a simple parsable file and check we do get issues
# It's parsable, so we should get issues.
res = linter.lint_string("SELECT 1")
assert any(v.rule_code() == "T002" for v in res.violations)
# Lint an unparsable file. Check we don't get any violations.
# It's not parsable so we shouldn't get issues.
res = linter.lint_string("asd asdf sdfg")
assert not any(v.rule_code() == "T002" for v in res.violations) | Test that rules that handle their own crawling respect unparsable. | test__rules__filter_unparsable | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test__rules__result_unparsable():
"""Test that the linter won't allow rules which make the file unparsable."""
# Set up a linter with the user rule
linter = Linter(user_rules=[Rule_T003], dialect="ansi", rules=["T003"])
# Lint a simple parsable file and check we do get issues
# It's parsable, so we should get issues.
raw_sql = "SELECT 1 FROM a"
with fluff_log_catcher(logging.WARNING, "sqlfluff") as caplog:
res = linter.lint_string(raw_sql, fix=True)
# Check we got the warning.
assert "would result in an unparsable file" in caplog.text
# Check we get the violation.
assert any(v.rule_code() == "T003" for v in res.violations)
# The resulting file should be _the same_ because it would have resulted
# in an unparsable file if applied.
assert res.tree.raw == raw_sql | Test that the linter won't allow rules which make the file unparsable. | test__rules__result_unparsable | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test__rules__runaway_fail_catch(sql_query, check_tuples):
"""Test that we catch runaway rules."""
runaway_limit = 5
# Set up the config to only use the rule we are testing.
cfg = FluffConfig(
overrides={"rules": "T001", "runaway_limit": runaway_limit, "dialect": "ansi"}
)
# Lint it using the current config (while in fix mode)
linter = Linter(config=cfg, user_rules=[Rule_T001])
# In theory this step should result in an infinite
# loop, but the loop limit should catch it.
result = linter.lint_string(sql_query, fix=True)
# When the linter hits the runaway limit, it returns the original SQL tree.
assert result.tree.raw == sql_query
# Check the issues found.
assert result.check_tuples() == check_tuples | Test that we catch runaway rules. | test__rules__runaway_fail_catch | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rules_cannot_be_instantiated_without_declared_configs():
"""Ensure that new rules must be instantiated with config values."""
class Rule_NewRule_ZZ99(BaseRule):
"""Testing Rule."""
config_keywords = ["case_sensitive"]
new_rule = Rule_NewRule_ZZ99(code="L000", description="", case_sensitive=False)
assert new_rule.case_sensitive is False
# Error is thrown since "case_sensitive" is defined in class,
# but not upon instantiation
with pytest.raises(ValueError):
new_rule = Rule_NewRule_ZZ99(code="L000", description="") | Ensure that new rules must be instantiated with config values. | test_rules_cannot_be_instantiated_without_declared_configs | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rules_legacy_doc_decorators(caplog):
"""Ensure that the deprecated decorators can still be imported but do nothing."""
with fluff_log_catcher(logging.WARNING, "sqlfluff") as caplog:
@document_fix_compatible
@document_groups
@document_configuration
class Rule_NewRule_ZZ99(BaseRule):
"""Untouched Text."""
pass
# Check they didn't do anything to the docstring.
assert Rule_NewRule_ZZ99.__doc__ == """Untouched Text."""
# Check there are warnings.
print("Records:")
for record in caplog.records:
print(record)
assert "uses the @document_fix_compatible decorator" in caplog.text
assert "uses the @document_groups decorator" in caplog.text
assert "uses the @document_configuration decorator" in caplog.text | Ensure that the deprecated decorators can still be imported but do nothing. | test_rules_legacy_doc_decorators | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rules_configs_are_dynamically_documented():
"""Ensure that rule configurations are added to the class docstring."""
class RuleWithConfig_ZZ99(BaseRule):
"""A new rule with configuration."""
config_keywords = ["unquoted_identifiers_policy"]
print(f"RuleWithConfig_ZZ99.__doc__: {RuleWithConfig_ZZ99.__doc__!r}")
assert "unquoted_identifiers_policy" in RuleWithConfig_ZZ99.__doc__
class RuleWithoutConfig_ZZ99(BaseRule):
"""A new rule without configuration."""
pass
print(f"RuleWithoutConfig_ZZ99.__doc__: {RuleWithoutConfig_ZZ99.__doc__!r}")
assert "Configuration" not in RuleWithoutConfig_ZZ99.__doc__ | Ensure that rule configurations are added to the class docstring. | test_rules_configs_are_dynamically_documented | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rules_name_validation():
"""Ensure that rule names are validated."""
with pytest.raises(SQLFluffUserError) as exc_info:
class RuleWithoutBadName_ZZ99(BaseRule):
"""A new rule without configuration."""
name = "MY-KEBAB-CASE-NAME"
assert "Tried to define rule with unexpected name" in exc_info.value.args[0]
assert "MY-KEBAB-CASE-NAME" in exc_info.value.args[0] | Ensure that rule names are validated. | test_rules_name_validation | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rule_exception_is_caught_to_validation():
"""Assert that a rule that throws an exception returns it as a validation."""
std_rule_set = get_ruleset()
@std_rule_set.register
class Rule_T000(BaseRule):
"""Rule that throws an exception."""
groups = ("all",)
crawl_behaviour = RootOnlyCrawler()
def _eval(self, segment, parent_stack, **kwargs):
raise Exception("Catch me or I'll deny any linting results from you")
linter = Linter(
config=FluffConfig(overrides=dict(rules="T000", dialect="ansi")),
user_rules=[Rule_T000],
)
assert linter.lint_string("select 1").check_tuples() == [("T000", 1, 1)] | Assert that a rule that throws an exception returns it as a validation. | test_rule_exception_is_caught_to_validation | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rule_must_belong_to_all_group():
"""Assert correct 'groups' config for rule."""
std_rule_set = get_ruleset()
with pytest.raises(AssertionError):
@std_rule_set.register
class Rule_T000(BaseRule):
"""Badly configured rule, no groups attribute."""
def _eval(self, **kwargs):
pass
with pytest.raises(AssertionError):
@std_rule_set.register
class Rule_T001(BaseRule):
"""Badly configured rule, no 'all' group."""
groups = ()
def _eval(self, **kwargs):
pass | Assert correct 'groups' config for rule. | test_rule_must_belong_to_all_group | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_std_rule_import_fail_bad_naming():
"""Check that rule import from file works."""
assert get_rules_from_path(
rules_path="test/fixtures/rules/custom/*.py",
base_module="test.fixtures.rules.custom",
) == [Rule_L000, Rule_S000]
with pytest.raises(AttributeError) as e:
get_rules_from_path(
rules_path="test/fixtures/rules/custom/bad_rule_name/*.py",
base_module="test.fixtures.rules.custom.bad_rule_name",
)
e.match("Rule classes must be named in the format of") | Check that rule import from file works. | test_std_rule_import_fail_bad_naming | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rule_set_return_informative_error_when_rule_not_registered():
"""Assert that a rule that throws an exception returns it as a validation."""
cfg = FluffConfig(overrides={"dialect": "ansi"})
with pytest.raises(ValueError) as e:
get_rule_from_set("L000", config=cfg)
e.match("'L000' not in") | Assert that a rule that throws an exception returns it as a validation. | test_rule_set_return_informative_error_when_rule_not_registered | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_rules__lint_result_repr(lint_result, expected):
"""Test that repr(LintResult) works as expected."""
assert repr(lint_result) == expected | Test that repr(LintResult) works as expected. | test_rules__lint_result_repr | python | sqlfluff/sqlfluff | test/core/rules/rules_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/rules_test.py | MIT |
def test_slices_all(input, expected):
"""Test the "all()" function."""
assert input.all(lambda s: "abc" in s.raw) == expected | Test the "all()" function. | test_slices_all | python | sqlfluff/sqlfluff | test/core/rules/functional/raw_file_slices_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/raw_file_slices_test.py | MIT |
def test_slices_any(input, expected):
"""Test the "any()" function."""
assert input.any(lambda s: "abc" in s.raw) == expected | Test the "any()" function. | test_slices_any | python | sqlfluff/sqlfluff | test/core/rules/functional/raw_file_slices_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/raw_file_slices_test.py | MIT |
def test_segments_add(lhs, rhs, expected):
"""Verify addition of Segments objects with themselves and lists."""
result = lhs + rhs
assert isinstance(result, segments.Segments)
assert result == expected | Verify addition of Segments objects with themselves and lists. | test_segments_add | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_all(input, expected):
"""Test the "all()" function."""
assert input.all(lambda s: s.raw[-1] <= "2") == expected | Test the "all()" function. | test_segments_all | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_any(input, expected):
"""Test the "any()" function."""
assert input.any(lambda s: s.raw[-1] <= "2") == expected | Test the "any()" function. | test_segments_any | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_reversed():
"""Test the "reversed()" function."""
assert segments.Segments(seg1, seg2).reversed() == segments.Segments(seg2, seg1) | Test the "reversed()" function. | test_segments_reversed | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_raw_slices_no_templated_file():
"""Test that raw_slices() fails if TemplatedFile not provided."""
with pytest.raises(ValueError):
segments.Segments(seg1).raw_slices | Test that raw_slices() fails if TemplatedFile not provided. | test_segments_raw_slices_no_templated_file | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_first_no_predicate():
"""Test the "first()" function with no predicate."""
assert segments.Segments(seg1, seg2).first() == segments.Segments(seg1) | Test the "first()" function with no predicate. | test_segments_first_no_predicate | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_first_with_predicate():
"""Test the "first()" function with a predicate."""
assert segments.Segments(seg1, seg2).first(sp.is_meta()) == segments.Segments() | Test the "first()" function with a predicate. | test_segments_first_with_predicate | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_last():
"""Test the "last()" function."""
assert segments.Segments(seg1, seg2).last() == segments.Segments(seg2) | Test the "last()" function. | test_segments_last | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_apply():
"""Test the "apply()" function."""
assert segments.Segments(seg1, seg2).apply(lambda s: s.raw[-1]) == ["1", "2"] | Test the "apply()" function. | test_segments_apply | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_apply_functions(function, expected):
"""Test the "apply()" function with the "get_name()" function."""
assert segments.Segments(seg1, seg2).apply(function) == expected | Test the "apply()" function with the "get_name()" function. | test_segments_apply_functions | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segment_predicates_and():
"""Test the "and_()" function."""
assert segments.Segments(seg1, seg2).select(
select_if=sp.and_(sp.is_raw(), lambda s: s.raw[-1] == "1")
) == segments.Segments(seg1)
assert (
segments.Segments(seg1, seg2).select(
select_if=sp.and_(sp.is_raw(), lambda s: s.raw[-1] == "3")
)
== segments.Segments()
) | Test the "and_()" function. | test_segment_predicates_and | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def test_segments_recursive_crawl():
"""Test the "recursive_crawl()" function."""
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)
functional_tree = segments.Segments(parsed.root_variant().tree)
assert len(functional_tree.recursive_crawl("common_table_expression")) == 1
assert len(functional_tree.recursive_crawl("table_reference")) == 3 | Test the "recursive_crawl()" function. | test_segments_recursive_crawl | python | sqlfluff/sqlfluff | test/core/rules/functional/segments_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/core/rules/functional/segments_test.py | MIT |
def logging_cleanup():
"""This gracefully handles logging issues at session teardown.
Removes handlers from all loggers. Autouse applies this to all
tests in this file (i.e. all the cli command tests), which should
be all of the test cases where `set_logging_level` is called.
https://github.com/sqlfluff/sqlfluff/issues/3702
https://github.com/pytest-dev/pytest/issues/5502#issuecomment-1190557648
"""
yield
# NOTE: This is a teardown function so the clearup code
# comes _after_ the yield.
# Get only the sqlfluff loggers (which we set in set_logging_level)
loggers = [
logger
for logger in logging.Logger.manager.loggerDict.values()
if isinstance(logger, logging.Logger) and logger.name.startswith("sqlfluff")
]
for logger in loggers:
if not hasattr(logger, "handlers"):
continue
for handler in logger.handlers[:]:
logger.removeHandler(handler) | This gracefully handles logging issues at session teardown.
Removes handlers from all loggers. Autouse applies this to all
tests in this file (i.e. all the cli command tests), which should
be all of the test cases where `set_logging_level` is called.
https://github.com/sqlfluff/sqlfluff/issues/3702
https://github.com/pytest-dev/pytest/issues/5502#issuecomment-1190557648 | logging_cleanup | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def contains_ansi_escape(s: str) -> bool:
"""Does the string contain ANSI escape codes (e.g. color)?"""
return re_ansi_escape.search(s) is not None | Does the string contain ANSI escape codes (e.g. color)? | contains_ansi_escape | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_directed():
"""Basic checking of lint functionality."""
result = invoke_assert_code(
ret_code=1,
args=[
lint,
[
"--disable-progress-bar",
"test/fixtures/linter/indentation_error_simple.sql",
],
],
)
# We should get a readout of what the error was
check_a = "L: 2 | P: 1 | LT02"
# NB: Skip the number at the end because it's configurable
check_b = "ndentation"
assert check_a in result.stdout
assert check_b in result.stdout
# Finally check the WHOLE output to make sure that unexpected newlines are not
# added. The replace command just accounts for cross platform testing.
assert result.stdout.replace("\\", "/").startswith(expected_output) | Basic checking of lint functionality. | test__cli__command_directed | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_dialect():
"""Check the script raises the right exception on an unknown dialect."""
# The dialect is unknown should be a non-zero exit code
invoke_assert_code(
ret_code=2,
args=[
lint,
[
"-n",
"--dialect",
"faslkjh",
"test/fixtures/linter/indentation_error_simple.sql",
],
],
) | Check the script raises the right exception on an unknown dialect. | test__cli__command_dialect | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_no_dialect(command):
"""Check the script raises the right exception no dialect."""
# The dialect is unknown should be a non-zero exit code
result = invoke_assert_code(
ret_code=2,
args=[
command,
["-"],
],
cli_input="SELECT 1",
)
assert "User Error" in result.stderr
assert "No dialect was specified" in result.stderr
# No traceback should be in the output
assert "Traceback (most recent call last)" not in result.stderr | Check the script raises the right exception no dialect. | test__cli__command_no_dialect | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_parse_error_dialect_explicit_warning():
"""Check parsing error raises the right warning."""
# For any parsing error there should be a non-zero exit code
# and a human-readable warning should be displayed.
# Dialect specified as commandline option.
invoke_assert_code(
ret_code=1,
args=[
parse,
[
"-n",
"--dialect",
"postgres",
"test/fixtures/cli/fail_many.sql",
],
],
assert_stdout_contains=(
"WARNING: Parsing errors found and dialect is set to 'postgres'. "
"Have you configured your dialect correctly?"
),
) | Check parsing error raises the right warning. | test__cli__command_parse_error_dialect_explicit_warning | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_parse_error_dialect_implicit_warning():
"""Check parsing error raises the right warning."""
# For any parsing error there should be a non-zero exit code
# and a human-readable warning should be displayed.
# Dialect specified in .sqlfluff config.
invoke_assert_code(
ret_code=1,
args=[
# Config sets dialect to tsql
parse,
[
"-n",
"--config",
"test/fixtures/cli/extra_configs/.sqlfluff",
"test/fixtures/cli/fail_many.sql",
],
],
assert_stdout_contains=(
"WARNING: Parsing errors found and dialect is set to 'tsql'. "
"Have you configured your dialect correctly?"
),
) | Check parsing error raises the right warning. | test__cli__command_parse_error_dialect_implicit_warning | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_dialect_legacy():
"""Check the script raises the right exception on a legacy dialect."""
invoke_assert_code(
ret_code=2,
args=[
lint,
[
"-n",
"--dialect",
"exasol_fs",
"test/fixtures/linter/indentation_error_simple.sql",
],
],
assert_stdout_contains="Please use the 'exasol' dialect instead.",
) | Check the script raises the right exception on a legacy dialect. | test__cli__command_dialect_legacy | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_extra_config_fail():
"""Check the script raises the right exception non-existent extra config path."""
invoke_assert_code(
ret_code=2,
args=[
lint,
[
"--config",
"test/fixtures/cli/extra_configs/.sqlfluffsdfdfdfsfd",
"test/fixtures/cli/extra_config_tsql.sql",
],
],
assert_stdout_contains=(
"Extra config path 'test/fixtures/cli/extra_configs/.sqlfluffsdfdfdfsfd' "
"does not exist."
),
) | Check the script raises the right exception non-existent extra config path. | test__cli__command_extra_config_fail | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_stdin_filename_config(
command, stdin_filepath, ret_code, stdout, stderr
):
"""Check the script picks up the config from the indicated path."""
invoke_assert_code(
ret_code=ret_code,
args=[
command,
[
"--stdin-filename",
stdin_filepath,
"-",
],
],
cli_input=stdin_cli_input,
assert_stdout_contains=stdout,
assert_stderr_contains=stderr,
) | Check the script picks up the config from the indicated path. | test__cli__command_stdin_filename_config | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_stdin(command):
"""Check basic commands on a simple script using stdin.
The subprocess command should exit without errors, as no issues should be found.
"""
with open("test/fixtures/cli/passing_a.sql") as test_file:
sql = test_file.read()
invoke_assert_code(args=[lint, ("--dialect=ansi",) + command], cli_input=sql) | Check basic commands on a simple script using stdin.
The subprocess command should exit without errors, as no issues should be found. | test__cli__command_lint_stdin | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_empty_stdin():
"""Check linting an empty file raises no exceptions.
https://github.com/sqlfluff/sqlfluff/issues/4807
"""
invoke_assert_code(args=[lint, ("-d", "ansi", "-")], cli_input="") | Check linting an empty file raises no exceptions.
https://github.com/sqlfluff/sqlfluff/issues/4807 | test__cli__command_lint_empty_stdin | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_render_stdin():
"""Check render on a simple script using stdin."""
with open("test/fixtures/cli/passing_a.sql") as test_file:
sql = test_file.read()
invoke_assert_code(
args=[render, ("--dialect=ansi", "-")],
cli_input=sql,
# Check we get back out the same file we input.
assert_stdout_contains=sql,
) | Check render on a simple script using stdin. | test__cli__command_render_stdin | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_parse(command):
"""Check basic commands on a more complicated script."""
invoke_assert_code(args=command) | Check basic commands on a more complicated script. | test__cli__command_lint_parse | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_parse_with_retcode(command, ret_code):
"""Check commands expecting a non-zero ret code."""
invoke_assert_code(ret_code=ret_code, args=command) | Check commands expecting a non-zero ret code. | test__cli__command_lint_parse_with_retcode | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_warning_explicit_file_ignored():
"""Check ignoring file works when file is in an ignore directory."""
runner = CliRunner()
result = runner.invoke(
lint, ["test/fixtures/linter/sqlfluffignore/path_b/query_c.sql"]
)
assert result.exit_code == 0
assert (
"Exact file path test/fixtures/linter/sqlfluffignore/path_b/query_c.sql "
"was given but it was ignored"
) in result.stdout.strip() | Check ignoring file works when file is in an ignore directory. | test__cli__command_lint_warning_explicit_file_ignored | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_skip_ignore_files():
"""Check "ignore file" is skipped when --disregard-sqlfluffignores flag is set."""
runner = CliRunner()
result = runner.invoke(
lint,
[
"test/fixtures/linter/sqlfluffignore/path_b/query_c.sql",
"--disregard-sqlfluffignores",
],
)
assert result.exit_code == 1
assert "LT12" in result.stdout.strip() | Check "ignore file" is skipped when --disregard-sqlfluffignores flag is set. | test__cli__command_lint_skip_ignore_files | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_ignore_local_config():
"""Test that --ignore-local_config ignores .sqlfluff file as expected."""
runner = CliRunner()
# First we test that not including the --ignore-local-config includes
# .sqlfluff file, and therefore the lint doesn't raise AL02
result = runner.invoke(
lint,
[
"test/fixtures/cli/ignore_local_config/ignore_local_config_test.sql",
],
)
assert result.exit_code == 0
assert "AL02" not in result.stdout.strip()
# Then repeat the same lint but this time ignoring the .sqlfluff file.
# We should see AL02 raised.
result = runner.invoke(
lint,
[
"--ignore-local-config",
"--dialect=ansi",
"test/fixtures/cli/ignore_local_config/ignore_local_config_test.sql",
],
)
assert result.exit_code == 1
assert "AL02" in result.stdout.strip() | Test that --ignore-local_config ignores .sqlfluff file as expected. | test__cli__command_lint_ignore_local_config | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_warning():
"""Test that configuring warnings works.
For this test the warnings are configured using
inline config in the file. That's more for simplicity
however the code paths should be the same if it's
configured in a file.
"""
runner = CliRunner()
result = runner.invoke(
lint,
[
"test/fixtures/cli/warning_a.sql",
],
)
# Because we're only warning. The command should pass.
assert result.exit_code == 0
# The output should still say PASS.
assert "PASS" in result.stdout.strip()
# But should also contain the warnings.
# NOTE: Not including the whole description because it's too long.
assert (
"L: 4 | P: 9 | LT01 | WARNING: Expected single whitespace"
in result.stdout.strip()
) | Test that configuring warnings works.
For this test the warnings are configured using
inline config in the file. That's more for simplicity
however the code paths should be the same if it's
configured in a file. | test__cli__command_lint_warning | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_warning_name_rule():
"""Test that configuring warnings works.
For this test the warnings are configured using
inline config in the file. That's more for simplicity
however the code paths should be the same if it's
configured in a file.
"""
runner = CliRunner()
result = runner.invoke(
lint,
[
"test/fixtures/cli/warning_name_a.sql",
],
)
# Because we're only warning. The command should pass.
assert result.exit_code == 0
# The output should still say PASS.
assert "PASS" in result.stdout.strip()
# But should also contain the warnings.
# NOTE: Not including the whole description because it's too long.
assert (
"L: 4 | P: 9 | LT01 | WARNING: Expected single whitespace"
in result.stdout.strip()
) | Test that configuring warnings works.
For this test the warnings are configured using
inline config in the file. That's more for simplicity
however the code paths should be the same if it's
configured in a file. | test__cli__command_lint_warning_name_rule | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_versioning():
"""Check version command."""
# Get the package version info
pkg_version = sqlfluff.__version__
# Get the version info from the config file
with open("pyproject.toml", "r") as config_file:
config = tomllib.loads(config_file.read())
config_version = config["project"]["version"]
assert pkg_version == config_version
# Get the version from the cli
runner = CliRunner()
result = runner.invoke(version)
assert result.exit_code == 0
# We need to strip to remove the newline characters
assert result.stdout.strip() == pkg_version | Check version command. | test__cli__command_versioning | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_version():
"""Just check version command for exceptions."""
# Get the package version info
pkg_version = sqlfluff.__version__
runner = CliRunner()
result = runner.invoke(version)
assert result.exit_code == 0
assert pkg_version in result.stdout
# Check a verbose version
result = runner.invoke(version, ["-v"])
assert result.exit_code == 0
assert pkg_version in result.stdout | Just check version command for exceptions. | test__cli__command_version | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_rules():
"""Check rules command for exceptions."""
invoke_assert_code(args=[rules]) | Check rules command for exceptions. | test__cli__command_rules | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_dialects():
"""Check dialects command for exceptions."""
invoke_assert_code(args=[dialects]) | Check dialects command for exceptions. | test__cli__command_dialects | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def generic_roundtrip_test(
source_file,
rulestring,
final_exit_code=0,
check=False,
fix_input=None,
fix_exit_code=0,
input_file_encoding="utf-8",
output_file_encoding=None,
):
"""A test for roundtrip testing, take a file buffer, lint, fix and lint.
This is explicitly different from the linter version of this, in that
it uses the command line rather than the direct api.
"""
filename = "testing.sql"
# Lets get the path of a file to use
tempdir_path = tempfile.mkdtemp()
filepath = os.path.join(tempdir_path, filename)
# Open the example file and write the content to it
with open(filepath, mode="w", encoding=input_file_encoding) as dest_file:
for line in source_file:
dest_file.write(line)
status = os.stat(filepath)
assert stat.S_ISREG(status.st_mode)
old_mode = stat.S_IMODE(status.st_mode)
# Check that we first detect the issue
invoke_assert_code(
ret_code=1,
args=[lint, ["--dialect=ansi", "--rules", rulestring, filepath]],
)
# Fix the file (in force mode)
if check:
fix_args = ["--rules", rulestring, "--check", filepath]
else:
fix_args = ["--rules", rulestring, filepath]
fix_args.append("--dialect=ansi")
invoke_assert_code(
ret_code=fix_exit_code, args=[fix, fix_args], cli_input=fix_input
)
# Now lint the file and check for exceptions
invoke_assert_code(
ret_code=final_exit_code,
args=[lint, ["--dialect=ansi", "--rules", rulestring, filepath]],
)
# Check the output file has the correct encoding after fix
if output_file_encoding:
with open(filepath, mode="rb") as f:
data = f.read()
assert chardet.detect(data)["encoding"] == output_file_encoding
# Also check the file mode was preserved.
status = os.stat(filepath)
assert stat.S_ISREG(status.st_mode)
new_mode = stat.S_IMODE(status.st_mode)
assert new_mode == old_mode
shutil.rmtree(tempdir_path) | A test for roundtrip testing, take a file buffer, lint, fix and lint.
This is explicitly different from the linter version of this, in that
it uses the command line rather than the direct api. | generic_roundtrip_test | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command__fix(rule, fname):
"""Test the round trip of detecting, fixing and then not detecting the rule."""
with open(fname) as test_file:
generic_roundtrip_test(test_file, rule) | Test the round trip of detecting, fixing and then not detecting the rule. | test__cli__command__fix | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__fix_error_handling_behavior(sql, fix_args, fixed, exit_code, tmpdir):
"""Tests how "fix" behaves wrt parse errors, exit code, etc."""
if not isinstance(sql, list):
sql = [sql]
if not isinstance(fixed, list):
fixed = [fixed]
assert len(sql) == len(fixed)
tmp_path = pathlib.Path(str(tmpdir))
for idx, this_sql in enumerate(sql):
filepath = tmp_path / f"testing{idx + 1}.sql"
filepath.write_text(textwrap.dedent(this_sql))
with tmpdir.as_cwd():
with pytest.raises(SystemExit) as e:
fix(
fix_args
# Use the short dialect option
+ ["-d", "ansi"]
)
assert exit_code == e.value.code
for idx, this_fixed in enumerate(fixed):
fixed_path = tmp_path / f"testing{idx + 1}FIXED.sql"
if this_fixed is not None:
assert textwrap.dedent(this_fixed) == fixed_path.read_text()
else:
# A None value indicates "sqlfluff fix" should have skipped any
# fixes for this file. To confirm this, we verify that the output
# file WAS NOT EVEN CREATED.
assert not fixed_path.is_file() | Tests how "fix" behaves wrt parse errors, exit code, etc. | test__cli__fix_error_handling_behavior | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_fix_even_unparsable(
method: str, fix_even_unparsable: bool, monkeypatch, tmpdir
):
"""Test the fix_even_unparsable option works from cmd line and config."""
sql_filename = "fix_even_unparsable.sql"
sql_path = str(tmpdir / sql_filename)
with open(sql_path, "w") as f:
print(
"""SELECT my_col
FROM my_schema.my_table
where processdate ! 3
""",
file=f,
)
options = [
"--dialect",
"ansi",
"--fixed-suffix=FIXED",
sql_path,
]
if method == "command-line":
if fix_even_unparsable:
options.append("--FIX-EVEN-UNPARSABLE")
else:
assert method == "config-file"
with open(str(tmpdir / ".sqlfluff"), "w") as f:
print(
f"[sqlfluff]\nfix_even_unparsable = {fix_even_unparsable}",
file=f,
)
# TRICKY: Switch current directory to the one with the SQL file. Otherwise,
# the setting doesn't work. That's because SQLFluff reads it in
# sqlfluff.cli.commands.fix(), prior to reading any file-specific settings
# (down in sqlfluff.core.linter.Linter._load_raw_file_and_config()).
monkeypatch.chdir(str(tmpdir))
invoke_assert_code(
ret_code=0 if fix_even_unparsable else 1,
args=[
fix,
options,
],
)
fixed_path = str(tmpdir / "fix_even_unparsableFIXED.sql")
if fix_even_unparsable:
with open(fixed_path, "r") as f:
fixed_sql = f.read()
assert (
fixed_sql
== """SELECT my_col
FROM my_schema.my_table
WHERE processdate ! 3
"""
)
else:
assert not os.path.isfile(fixed_path) | Test the fix_even_unparsable option works from cmd line and config. | test_cli_fix_even_unparsable | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_fix_stdin(stdin, rules, stdout):
"""Check stdin input for fix works."""
result = invoke_assert_code(
args=[
fix,
("-", "--rules", rules, "--disable-progress-bar", "--dialect=ansi"),
],
cli_input=stdin,
)
assert result.stdout == stdout
assert result.stderr == "" | Check stdin input for fix works. | test__cli__command_fix_stdin | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_format_stdin(stdin, stdout):
"""Check stdin input for fix works."""
result = invoke_assert_code(
args=[
cli_format,
("-", "--disable-progress-bar", "--dialect=ansi"),
],
cli_input=stdin,
)
assert result.stdout == stdout | Check stdin input for fix works. | test__cli__command_format_stdin | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_fix_stdin_logging_to_stderr(monkeypatch):
"""Check that logging goes to stderr when stdin is passed to fix."""
perfect_sql = "select col from table"
class MockLinter(sqlfluff.core.Linter):
@classmethod
def lint_fix_parsed(cls, *args, **kwargs):
cls._warn_unfixable("<FAKE CODE>")
return super().lint_fix_parsed(*args, **kwargs)
monkeypatch.setattr(sqlfluff.cli.commands, "Linter", MockLinter)
result = invoke_assert_code(
args=[fix, ("-", "--rules=LT02", "--dialect=ansi")],
cli_input=perfect_sql,
)
assert result.stdout == perfect_sql
assert "<FAKE CODE>" in result.stderr | Check that logging goes to stderr when stdin is passed to fix. | test__cli__command_fix_stdin_logging_to_stderr | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_fix_stdin_safety():
"""Check edge cases regarding safety when fixing stdin."""
perfect_sql = "select col from table"
# just prints the very same thing
result = invoke_assert_code(
args=[fix, ("-", "--disable-progress-bar", "--dialect=ansi")],
cli_input=perfect_sql,
)
assert result.stdout.strip() == perfect_sql
assert result.stderr == "" | Check edge cases regarding safety when fixing stdin. | test__cli__command_fix_stdin_safety | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_fix_stdin_error_exit_code(
sql, exit_code, params, assert_stderr_contains
):
"""Check that the CLI fails nicely if fixing a templated stdin."""
invoke_assert_code(
ret_code=exit_code,
args=[fix, ((params,) if params else ()) + ("--dialect=ansi", "-")],
cli_input=sql,
assert_stderr_contains=assert_stderr_contains,
) | Check that the CLI fails nicely if fixing a templated stdin. | test__cli__command_fix_stdin_error_exit_code | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command__fix_check(rule, fname, prompt, exit_code, fix_exit_code):
"""Round trip test, using the prompts."""
with open(fname) as test_file:
generic_roundtrip_test(
test_file,
rule,
check=True,
final_exit_code=exit_code,
fix_input=prompt,
fix_exit_code=fix_exit_code,
) | Round trip test, using the prompts. | test__cli__command__fix_check | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_parse_serialize_from_stdin(serialize, write_file, tmp_path):
"""Check that the parser serialized output option is working.
This tests both output to stdout and output to file.
Not going to test for the content of the output as that is subject to change.
"""
cmd_args = ("-", "--format", serialize, "--dialect=ansi")
if write_file:
target_file = os.path.join(tmp_path, write_file + "." + serialize)
cmd_args += ("--write-output", target_file)
result = invoke_assert_code(
args=[parse, cmd_args],
cli_input="select * from tbl",
)
if write_file:
with open(target_file, "r") as payload_file:
result_payload = payload_file.read()
else:
result_payload = result.stdout
if serialize == "json":
result = json.loads(result_payload)
elif serialize == "yaml":
result = yaml.safe_load(result_payload)
else:
raise Exception
result = result[0] # only one file
assert result["filepath"] == "stdin" | Check that the parser serialized output option is working.
This tests both output to stdout and output to file.
Not going to test for the content of the output as that is subject to change. | test__cli__command_parse_serialize_from_stdin | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_serialize_from_stdin(
serialize, sql, rules, expected, exit_code
):
"""Check an explicit serialized return value for a single error."""
result = invoke_assert_code(
args=[
lint,
(
"-",
"--rules",
rules,
"--format",
serialize,
"--disable-progress-bar",
"--dialect=ansi",
),
],
cli_input=sql,
ret_code=exit_code,
)
if serialize == "json":
result = json.loads(result.stdout)
# Drop any timing section (because it's less determinate)
for record in result:
if "timings" in record:
del record["timings"]
assert result == expected
elif serialize == "yaml":
result = yaml.safe_load(result.stdout)
# Drop any timing section (because it's less determinate)
for record in result:
if "timings" in record:
del record["timings"]
assert result == expected
elif serialize == "none":
assert result.stdout == ""
else:
raise Exception | Check an explicit serialized return value for a single error. | test__cli__command_lint_serialize_from_stdin | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_fail_nice_not_found(command):
"""Check commands fail as expected when then don't find files."""
invoke_assert_code(
args=command,
ret_code=2,
assert_stderr_contains=(
"User Error: Specified path does not exist. Check it/they "
"exist(s): this_file_does_not_exist.sql"
),
) | Check commands fail as expected when then don't find files. | test__cli__command_fail_nice_not_found | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_nocolor(isatty, should_strip_ansi, capsys, tmpdir):
"""Test the --nocolor option prevents color output."""
# Patch these two functions to make it think every output stream is a TTY.
# In spite of this, the output should not contain ANSI color codes because
# we specify "--nocolor" below.
isatty.return_value = True
should_strip_ansi.return_value = False
fpath = "test/fixtures/linter/indentation_errors.sql"
output_file = str(tmpdir / "result.txt")
cmd_args = [
"--verbose",
"--nocolor",
"--dialect",
"ansi",
"--disable-progress-bar",
fpath,
"--write-output",
output_file,
]
with pytest.raises(SystemExit):
lint(cmd_args)
out = capsys.readouterr()[0]
assert not contains_ansi_escape(out)
with open(output_file, "r") as f:
file_contents = f.read()
assert not contains_ansi_escape(file_contents) | Test the --nocolor option prevents color output. | test__cli__command_lint_nocolor | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_serialize_multiple_files(serialize, write_file, tmp_path):
"""Test the output formats for multiple files.
This tests runs both stdout checking and file checking.
"""
fpath1 = "test/fixtures/linter/indentation_errors.sql"
fpath2 = "test/fixtures/linter/multiple_sql_errors.sql"
cmd_args = (
fpath1,
fpath2,
"--format",
serialize,
"--disable-progress-bar",
)
if write_file:
ext = {
"human": ".txt",
"yaml": ".yaml",
}
target_file = os.path.join(tmp_path, write_file + ext.get(serialize, ".json"))
cmd_args += ("--write-output", target_file)
# note the file is in here twice. two files = two payloads.
result = invoke_assert_code(
args=[lint, cmd_args],
ret_code=1,
)
# NOTE: The "none" serializer doesn't write a file even if specified.
if write_file and serialize != "none":
with open(target_file, "r") as payload_file:
result_payload = payload_file.read()
else:
result_payload = result.stdout
# Print for debugging.
payload_length = len(result_payload.split("\n"))
print("=== BEGIN RESULT OUTPUT")
print(result_payload)
print("=== END RESULT OUTPUT")
print("Result length:", payload_length)
if serialize == "human":
assert payload_length == 25 if write_file else 34
elif serialize == "none":
assert payload_length == 1 # There will be a single newline.
elif serialize == "json":
result = json.loads(result_payload)
assert len(result) == 2
elif serialize == "yaml":
result = yaml.safe_load(result_payload)
assert len(result) == 2
elif serialize == "github-annotation":
result = json.loads(result_payload)
filepaths = {r["file"] for r in result}
assert len(filepaths) == 2
elif serialize == "github-annotation-native":
result = result_payload.split("\n")
# SQLFluff produces trailing newline
if result[-1] == "":
del result[-1]
assert len(result) == 16
else:
raise Exception | Test the output formats for multiple files.
This tests runs both stdout checking and file checking. | test__cli__command_lint_serialize_multiple_files | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_serialize_github_annotation():
"""Test format of github-annotation output."""
fpath = "test/fixtures/linter/identifier_capitalisation.sql"
result = invoke_assert_code(
args=[
lint,
(
fpath,
"--format",
"github-annotation",
"--annotation-level",
"warning",
"--disable-progress-bar",
),
],
ret_code=1,
)
result = json.loads(result.stdout)
assert result == [
{
"annotation_level": "warning",
# Normalise paths to control for OS variance
"file": os.path.normpath(
"test/fixtures/linter/identifier_capitalisation.sql"
),
"start_line": 3,
"end_line": 3,
"message": "RF02: Unqualified reference 'foo' found in select with more "
"than one referenced table/view.",
"start_column": 5,
"end_column": 8,
"title": "SQLFluff",
},
{
"annotation_level": "warning",
# Normalise paths to control for OS variance
"file": os.path.normpath(
"test/fixtures/linter/identifier_capitalisation.sql"
),
"start_line": 4,
"end_line": 4,
"message": "LT02: Expected indent of 8 spaces.",
"start_column": 1,
"end_column": 5,
"title": "SQLFluff",
},
{
"annotation_level": "warning",
# Normalise paths to control for OS variance
"file": os.path.normpath(
"test/fixtures/linter/identifier_capitalisation.sql"
),
"start_line": 4,
"end_line": 4,
"message": "AL02: Implicit/explicit aliasing of columns.",
"start_column": 5,
"end_column": 8,
"title": "SQLFluff",
},
{
"annotation_level": "warning",
# Normalise paths to control for OS variance
"file": os.path.normpath(
"test/fixtures/linter/identifier_capitalisation.sql"
),
"start_line": 4,
"end_line": 4,
"message": "CP02: Unquoted identifiers must be consistently lower case.",
"start_column": 5,
"end_column": 8,
"title": "SQLFluff",
},
{
# Warnings should come through as notices.
"annotation_level": "notice",
# Normalise paths to control for OS variance
"file": os.path.normpath(
"test/fixtures/linter/identifier_capitalisation.sql"
),
"start_line": 5,
"end_line": 5,
"message": "CP01: Keywords must be consistently lower case.",
"start_column": 1,
"end_column": 5,
"title": "SQLFluff",
},
{
"annotation_level": "warning",
# Normalise paths to control for OS variance
"file": os.path.normpath(
"test/fixtures/linter/identifier_capitalisation.sql"
),
"start_line": 5,
"end_line": 5,
"message": "CP02: Unquoted identifiers must be consistently lower case.",
"start_column": 12,
"end_column": 16,
"title": "SQLFluff",
},
{
"annotation_level": "warning",
# Normalise paths to control for OS variance
"file": os.path.normpath(
"test/fixtures/linter/identifier_capitalisation.sql"
),
"start_line": 5,
"end_line": 5,
"message": "CP02: Unquoted identifiers must be consistently lower case.",
"start_column": 18,
"end_column": 22,
"title": "SQLFluff",
},
] | Test format of github-annotation output. | test__cli__command_lint_serialize_github_annotation | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_serialize_github_annotation_native(
filename, expected_output
):
"""Test format of github-annotation output."""
# Normalise paths to control for OS variance
fpath_normalised = os.path.normpath(filename)
result = invoke_assert_code(
args=[
lint,
(
filename,
"--format",
"github-annotation-native",
"--annotation-level",
"error",
"--disable-progress-bar",
),
],
ret_code=1,
)
assert result.stdout == expected_output.format(filename=fpath_normalised) | Test format of github-annotation output. | test__cli__command_lint_serialize_github_annotation_native | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__command_lint_serialize_annotation_level_error_failure_equivalent(
serialize,
):
"""Test format of github-annotation output."""
fpath = "test/fixtures/linter/identifier_capitalisation.sql"
result_error = invoke_assert_code(
args=[
lint,
(
fpath,
"--format",
serialize,
"--annotation-level",
"error",
"--disable-progress-bar",
),
],
ret_code=1,
)
result_failure = invoke_assert_code(
args=[
lint,
(
fpath,
"--format",
serialize,
"--annotation-level",
"failure",
"--disable-progress-bar",
),
],
ret_code=1,
)
assert result_error.stdout == result_failure.stdout | Test format of github-annotation output. | test__cli__command_lint_serialize_annotation_level_error_failure_equivalent | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test___main___help():
"""Test that the CLI can be access via __main__."""
# nonzero exit is good enough
subprocess.check_output(
[sys.executable, "-m", "sqlfluff", "--help"], env=os.environ
) | Test that the CLI can be access via __main__. | test___main___help | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_encoding(encoding_in, encoding_out):
"""Check the encoding of the test file remains the same after fix is applied."""
with open("test/fixtures/linter/indentation_errors.sql", "r") as testfile:
generic_roundtrip_test(
testfile,
"LT01",
input_file_encoding=encoding_in,
output_file_encoding=encoding_out,
) | Check the encoding of the test file remains the same after fix is applied. | test_encoding | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_encoding(encoding, method, expect_success, tmpdir):
"""Try loading a utf-8-SIG encoded file using the correct encoding via the cli."""
sql_path = "test/fixtures/cli/encoding_test.sql"
if method == "command-line":
options = [sql_path, "--encoding", encoding]
else:
assert method == "config-file"
with open(str(tmpdir / ".sqlfluff"), "w") as f:
print(f"[sqlfluff]\ndialect=ansi\nencoding = {encoding}", file=f)
shutil.copy(sql_path, tmpdir)
options = [str(tmpdir / "encoding_test.sql")]
result = invoke_assert_code(
ret_code=1,
args=[
lint,
options,
],
)
raw_stdout = repr(result.stdout)
# Incorrect encoding raises parsing and lexer errors.
success1 = r"L: 1 | P: 1 | LXR |" not in raw_stdout
success2 = r"L: 1 | P: 1 | PRS |" not in raw_stdout
assert success1 == expect_success
assert success2 == expect_success | Try loading a utf-8-SIG encoded file using the correct encoding via the cli. | test_cli_encoding | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_no_disable_noqa_flag():
"""Test that unset --disable-noqa flag respects inline noqa comments."""
invoke_assert_code(
ret_code=0,
args=[
lint,
["test/fixtures/cli/disable_noqa_test.sql"],
],
) | Test that unset --disable-noqa flag respects inline noqa comments. | test_cli_no_disable_noqa_flag | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_disable_noqa_flag():
"""Test that --disable-noqa flag ignores inline noqa comments."""
invoke_assert_code(
ret_code=1,
args=[
lint,
[
"test/fixtures/cli/disable_noqa_test.sql",
"--disable-noqa",
],
],
# Linting error is raised even though it is inline ignored.
assert_stdout_contains=r"L: 6 | P: 11 | CP01 |",
) | Test that --disable-noqa flag ignores inline noqa comments. | test_cli_disable_noqa_flag | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_disable_noqa_except_flag():
"""Test that --disable-noqa-except flag ignores inline noqa comments."""
result = invoke_assert_code(
ret_code=1,
args=[
lint,
[
"test/fixtures/cli/disable_noqa_test.sql",
"--disable-noqa-except",
"CP01",
],
],
# Linting error is raised even though it is inline ignored.
assert_stdout_contains=r"L: 8 | P: 5 | CP03 |",
)
assert r"L: 6 | P: 11 | CP01 |" not in result.stdout | Test that --disable-noqa-except flag ignores inline noqa comments. | test_cli_disable_noqa_except_flag | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_disable_noqa_except_non_rules_flag():
"""Test that --disable-noqa-except flag ignores all inline noqa comments."""
invoke_assert_code(
ret_code=1,
args=[
lint,
[
"test/fixtures/cli/disable_noqa_test.sql",
"--disable-noqa-except",
"None",
],
],
# Linting error is raised even though it is inline ignored.
assert_stdout_contains=r"L: 6 | P: 11 | CP01 |",
) | Test that --disable-noqa-except flag ignores all inline noqa comments. | test_cli_disable_noqa_except_non_rules_flag | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_warn_unused_noqa_flag():
"""Test that --warn-unused-ignores flag works."""
invoke_assert_code(
# Return value should still be success.
ret_code=0,
args=[
lint,
[
"test/fixtures/cli/disable_noqa_test.sql",
"--warn-unused-ignores",
],
],
# Warning shown.
assert_stdout_contains=(
r"L: 5 | P: 18 | NOQA | WARNING: Unused noqa: 'noqa: CP01'"
),
) | Test that --warn-unused-ignores flag works. | test_cli_warn_unused_noqa_flag | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_get_default_config():
"""`nocolor` and `verbose` values loaded from config if not specified via CLI."""
config = get_config(
"test/fixtures/config/toml/pyproject.toml",
True,
nocolor=None,
verbose=None,
require_dialect=False,
)
assert config.get("nocolor") is True
assert config.get("verbose") == 2 | `nocolor` and `verbose` values loaded from config if not specified via CLI. | test_cli_get_default_config | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_lint_disabled_progress_bar(
self, mock_disable_progress_bar: MagicMock
) -> None:
"""When progress bar is disabled, nothing should be printed into output."""
result = invoke_assert_code(
args=[
lint,
[
"--disable-progress-bar",
"test/fixtures/linter/passing.sql",
],
],
)
raw_stderr = repr(result.stderr)
assert "\rpath test/fixtures/linter/passing.sql:" not in raw_stderr
assert "\rparsing: 0it" not in raw_stderr
assert "\r\rlint by rules:" not in raw_stderr | When progress bar is disabled, nothing should be printed into output. | test_cli_lint_disabled_progress_bar | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_lint_enabled_progress_bar(
self, mock_disable_progress_bar: MagicMock
) -> None:
"""When progress bar is enabled, there should be some tracks in output."""
result = invoke_assert_code(
args=[
lint,
[
"test/fixtures/linter/passing.sql",
],
],
)
raw_stderr = repr(result.stderr)
assert r"\rlint by rules:" in raw_stderr
assert r"\rrule LT01:" in raw_stderr
assert r"\rrule CV05:" in raw_stderr | When progress bar is enabled, there should be some tracks in output. | test_cli_lint_enabled_progress_bar | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_lint_enabled_progress_bar_multiple_paths(
self, mock_disable_progress_bar: MagicMock
) -> None:
"""When progress bar is enabled, there should be some tracks in output."""
result = invoke_assert_code(
ret_code=1,
args=[
lint,
[
"test/fixtures/linter/passing.sql",
"test/fixtures/linter/indentation_errors.sql",
],
],
)
normalised_stderr = repr(result.stderr.replace("\\", "/"))
assert r"\rfile test/fixtures/linter/passing.sql:" in normalised_stderr
assert (
r"\rfile test/fixtures/linter/indentation_errors.sql:" in normalised_stderr
)
assert r"\rlint by rules:" in normalised_stderr
assert r"\rrule LT01:" in normalised_stderr
assert r"\rrule CV05:" in normalised_stderr | When progress bar is enabled, there should be some tracks in output. | test_cli_lint_enabled_progress_bar_multiple_paths | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test_cli_lint_enabled_progress_bar_multiple_files(
self, mock_disable_progress_bar: MagicMock
) -> None:
"""When progress bar is enabled, there should be some tracks in output."""
result = invoke_assert_code(
args=[
lint,
[
"test/fixtures/linter/multiple_files",
],
],
)
raw_stderr = repr(result.stderr)
sep = os.sep
if sys.platform == "win32":
sep *= 2
assert (
r"\rfile test/fixtures/linter/multiple_files/passing.1.sql:".replace(
"/", sep
)
in raw_stderr
)
assert (
r"\rfile test/fixtures/linter/multiple_files/passing.2.sql:".replace(
"/", sep
)
in raw_stderr
)
assert (
r"\rfile test/fixtures/linter/multiple_files/passing.3.sql:".replace(
"/", sep
)
in raw_stderr
)
assert r"\rlint by rules:" in raw_stderr
assert r"\rrule LT01:" in raw_stderr
assert r"\rrule CV05:" in raw_stderr | When progress bar is enabled, there should be some tracks in output. | test_cli_lint_enabled_progress_bar_multiple_files | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__fix_multiple_errors_no_show_errors():
"""Test the fix output."""
invoke_assert_code(
ret_code=1,
args=[
fix,
[
"--check", # Run in check mode to get the confirmation.
"--disable-progress-bar",
"test/fixtures/linter/multiple_sql_errors.sql",
],
],
assert_stdout_contains=multiple_expected_output,
) | Test the fix output. | test__cli__fix_multiple_errors_no_show_errors | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__fix_multiple_errors_quiet_force():
"""Test the fix --quiet option with --force."""
invoke_assert_code(
ret_code=0,
args=[
fix,
[
"--disable-progress-bar",
"test/fixtures/linter/multiple_sql_errors.sql",
"--quiet",
"-x",
"_fix",
],
],
assert_stdout_contains=(
"""== [test/fixtures/linter/multiple_sql_errors.sql] FIXED
2 fixable linting violations found"""
),
) | Test the fix --quiet option with --force. | test__cli__fix_multiple_errors_quiet_force | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__fix_multiple_errors_quiet_check():
"""Test the fix --quiet option without --force."""
invoke_assert_code(
ret_code=0,
args=[
fix,
[
"--disable-progress-bar",
"test/fixtures/linter/multiple_sql_errors.sql",
"--check", # Run in check mode to get the confirmation.
"--quiet",
"-x",
"_fix",
],
# Test with the confirmation step.
"y",
],
assert_stdout_contains=(
"""2 fixable linting violations found
Are you sure you wish to attempt to fix these? [Y/n] ...
== [test/fixtures/linter/multiple_sql_errors.sql] FIXED
All Finished"""
),
) | Test the fix --quiet option without --force. | test__cli__fix_multiple_errors_quiet_check | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__fix_multiple_errors_show_errors():
"""Test the fix --show-lint-violations option."""
result = invoke_assert_code(
ret_code=1,
args=[
fix,
[
"--disable-progress-bar",
"--show-lint-violations",
"test/fixtures/linter/multiple_sql_errors.sql",
"--check", # Run in check mode to get the confirmation.
],
],
)
# We should get a readout of what the error was
check_a = "4 unfixable linting violations found"
assert check_a in result.stdout
# Finally check the WHOLE output to make sure that unexpected newlines are not
# added. The replace command just accounts for cross platform testing.
assert "L: 12 | P: 1 | LT02 | Expected indent of 4 spaces." in result.stdout
assert (
"L: 36 | P: 9 | RF02 | Unqualified reference 'package_id' found in "
"select with more than" in result.stdout
)
assert (
"L: 45 | P: 17 | RF02 | Unqualified reference 'owner_type' found in "
"select with more than" in result.stdout
)
assert (
"L: 45 | P: 50 | RF02 | Unqualified reference 'app_key' found in "
"select with more than one" in result.stdout
)
assert (
"L: 42 | P: 45 | RF02 | Unqualified reference 'owner_id' found in "
"select with more than" in result.stdout
) | Test the fix --show-lint-violations option. | test__cli__fix_multiple_errors_show_errors | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__fix_show_parse_errors():
"""Test the fix --show-lint-violations option with parser error."""
result = invoke_assert_code(
ret_code=1,
args=[
fix,
[
"--show-lint-violations",
"test/fixtures/linter/parse_lex_error.sql",
],
],
)
check_a = "1 templating/parsing errors found"
assert check_a not in result.stderr
assert (
"L: 9 | P: 21 | PRS | Couldn't find closing bracket for opening bracket."
in result.stdout
)
assert "L: 9 | P: 22 | LXR | Unable to lex characters: " in result.stdout
# Calling without show-lint-violations
result = invoke_assert_code(
ret_code=1,
args=[
fix,
[
"test/fixtures/linter/parse_lex_error.sql",
],
],
)
assert check_a in result.stderr
assert (
"L: 9 | P: 21 | PRS | Couldn't find closing bracket for opening bracket."
not in result.stdout
)
assert "L: 9 | P: 22 | LXR | Unable to lex characters: " not in result.stdout | Test the fix --show-lint-violations option with parser error. | test__cli__fix_show_parse_errors | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__multiple_files__fix_multiple_errors_show_errors():
"""Basic check of lint ensures with multiple files, filenames are listed."""
sql_path = "test/fixtures/linter/multiple_sql_errors.sql"
indent_path = "test/fixtures/linter/indentation_errors.sql"
result = invoke_assert_code(
ret_code=1,
args=[
fix,
[
"--disable-progress-bar",
"--check", # Run in check mode to get the confirmation.
"--show-lint-violations",
sql_path,
indent_path,
],
],
)
unfixable_error_msg = "==== lint for unfixable violations ===="
assert unfixable_error_msg in result.stdout
indent_pass_msg = f"== [{os.path.normpath(indent_path)}] PASS"
multi_fail_msg = f"== [{os.path.normpath(sql_path)}] FAIL"
unfix_err_log = result.stdout[result.stdout.index(unfixable_error_msg) :]
assert indent_pass_msg in unfix_err_log
assert multi_fail_msg in unfix_err_log
# Assert that they are sorted in alphabetical order
assert unfix_err_log.index(indent_pass_msg) < unfix_err_log.index(multi_fail_msg) | Basic check of lint ensures with multiple files, filenames are listed. | test__cli__multiple_files__fix_multiple_errors_show_errors | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__render_fail():
"""Basic how render fails."""
invoke_assert_code(
ret_code=1,
args=[
render,
[
"test/fixtures/cli/fail_many.sql",
],
],
assert_stdout_contains=(
"L: 3 | P: 8 | TMP | Undefined jinja template " "variable: 'something'"
),
) | Basic how render fails. | test__cli__render_fail | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__render_pass():
"""Basic how render works."""
invoke_assert_code(
ret_code=0,
args=[
render,
[
"test/fixtures/templater/jinja_a/jinja.sql",
],
],
assert_stdout_contains="SELECT 56 FROM sch1.tbl2",
) | Basic how render works. | test__cli__render_pass | python | sqlfluff/sqlfluff | test/cli/commands_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/commands_test.py | MIT |
def test__cli__helpers__wrap_elem(in_str, length, res):
"""Test wrapping."""
str_list = wrap_elem(in_str, length)
assert str_list == res | Test wrapping. | test__cli__helpers__wrap_elem | python | sqlfluff/sqlfluff | test/cli/helpers_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/helpers_test.py | MIT |
def test__cli__helpers__wrap_field_a():
"""Test simple wrapping."""
dct = wrap_field("abc", "How Now Brown Cow", width=40)
assert dct["label_list"] == ["abc"]
assert dct["val_list"] == ["How Now Brown Cow"]
assert "sep_char" in dct
assert dct["lines"] == 1
assert dct["label_width"] == 3 | Test simple wrapping. | test__cli__helpers__wrap_field_a | python | sqlfluff/sqlfluff | test/cli/helpers_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/helpers_test.py | MIT |
def test__cli__helpers__wrap_field_b():
"""Test simple wrapping with overlap avoidance."""
dct = wrap_field("abc", "How Now Brown Cow", width=23)
assert dct["label_list"] == ["abc"]
assert dct["val_list"] == ["How Now Brown Cow"]
assert dct["label_width"] == 3 | Test simple wrapping with overlap avoidance. | test__cli__helpers__wrap_field_b | python | sqlfluff/sqlfluff | test/cli/helpers_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/helpers_test.py | MIT |
def test__cli__helpers__wrap_field_c():
"""Test simple wrapping."""
dct = wrap_field("how now brn cow", "How Now Brown Cow", width=25)
assert dct["label_list"] == ["how now", "brn cow"]
assert dct["label_width"] == 7
assert dct["val_list"] == ["How Now Brown", "Cow"]
assert dct["lines"] == 2 | Test simple wrapping. | test__cli__helpers__wrap_field_c | python | sqlfluff/sqlfluff | test/cli/helpers_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/helpers_test.py | MIT |
def test__cli__helpers__pad_line():
"""Test line padding."""
assert pad_line("abc", 5) == "abc "
assert pad_line("abcdef", 10, align="right") == " abcdef" | Test line padding. | test__cli__helpers__pad_line | python | sqlfluff/sqlfluff | test/cli/helpers_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/helpers_test.py | MIT |
def test_cli__helpers__lazy_sequence():
"""Test the LazySequence."""
getter_run = False
def _get_sequence():
nonlocal getter_run
getter_run = True
return [1, 2, 3]
seq = LazySequence(_get_sequence)
# Check the sequence isn't called on instantiation.
assert not getter_run
# Fetch an item...
assert seq[2] == 3
# .. and that now it has run.
assert getter_run
# Check other methods work
assert len(seq) == 3 | Test the LazySequence. | test_cli__helpers__lazy_sequence | python | sqlfluff/sqlfluff | test/cli/helpers_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/helpers_test.py | MIT |
def escape_ansi(line):
"""Remove ANSI color codes for testing."""
ansi_escape = re.compile("\u001b\\[[0-9]+(;[0-9]+)?m")
return ansi_escape.sub("", line) | Remove ANSI color codes for testing. | escape_ansi | python | sqlfluff/sqlfluff | test/cli/formatters_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/formatters_test.py | MIT |
def test__cli__formatters__filename_nocol(tmpdir):
"""Test formatting filenames."""
formatter = OutputStreamFormatter(
FileOutput(FluffConfig(require_dialect=False), str(tmpdir / "out.txt")), False
)
res = formatter.format_filename("blahblah", success=True)
assert escape_ansi(res) == "== [blahblah] PASS" | Test formatting filenames. | test__cli__formatters__filename_nocol | python | sqlfluff/sqlfluff | test/cli/formatters_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/formatters_test.py | MIT |
def test__cli__formatters__violation(tmpdir):
"""Test formatting violations.
NB Position is 1 + start_pos.
"""
s = RawSegment(
"foobarbar",
PositionMarker(
slice(10, 19),
slice(10, 19),
TemplatedFile.from_string(" \n\n foobarbar"),
),
)
r = RuleGhost("A", "some-name", "DESC")
v = SQLLintError(description=r.description, segment=s, rule=r)
formatter = OutputStreamFormatter(
FileOutput(FluffConfig(require_dialect=False), str(tmpdir / "out.txt")), False
)
f = formatter.format_violation(v)
# Position is 3, 3 because foobarbar is on the third
# line (i.e. it has two newlines preceding it) and
# it's at the third position in that line (i.e. there
# are two characters between it and the preceding
# newline).
assert escape_ansi(f) == "L: 3 | P: 3 | A | DESC [some-name]" | Test formatting violations.
NB Position is 1 + start_pos. | test__cli__formatters__violation | python | sqlfluff/sqlfluff | test/cli/formatters_test.py | https://github.com/sqlfluff/sqlfluff/blob/master/test/cli/formatters_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.