1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
|
"""Tests for the BaseGrammar and it's methods.
NOTE: All of these tests depend somewhat on the KeywordSegment working as planned.
"""
import pytest
from sqlfluff.core.dialects.base import Dialect
from sqlfluff.core.errors import SQLParseError
from sqlfluff.core.parser import (
CodeSegment,
KeywordSegment,
StringParser,
SymbolSegment,
WhitespaceSegment,
)
from sqlfluff.core.parser.context import ParseContext
from sqlfluff.core.parser.lexer import RegexLexer
from sqlfluff.core.parser.match_algorithms import (
greedy_match,
next_ex_bracket_match,
next_match,
resolve_bracket,
trim_to_terminator,
)
# NB: All of these tests depend somewhat on the KeywordSegment working as planned
@pytest.fixture(scope="function")
def test_dialect():
"""A stripped back test dialect for testing brackets."""
test_dialect = Dialect("test", root_segment_name="FileSegment")
test_dialect.bracket_sets("bracket_pairs").update(
[("round", "StartBracketSegment", "EndBracketSegment", True)]
)
test_dialect.set_lexer_matchers(
[
RegexLexer("whitespace", r"[^\S\r\n]+", WhitespaceSegment),
RegexLexer(
"code", r"[0-9a-zA-Z_]+", CodeSegment, segment_kwargs={"type": "code"}
),
]
)
test_dialect.add(
StartBracketSegment=StringParser("(", SymbolSegment, type="start_bracket"),
EndBracketSegment=StringParser(")", SymbolSegment, type="end_bracket"),
)
# Return the expanded copy.
return test_dialect.expand()
def make_result_tuple(result_slice, matcher_keywords, test_segments):
"""Make a comparison tuple for test matching."""
# No result slice means no match.
if not result_slice:
return ()
return tuple(
(
KeywordSegment(elem.raw, pos_marker=elem.pos_marker)
if elem.raw in matcher_keywords
else elem
)
for elem in test_segments[result_slice]
)
@pytest.mark.parametrize(
"matcher_keywords,result_slice,winning_matcher",
[
# Basic version, we should find bar first
(["bar", "foo"], slice(0, 1), "bar"),
# Look ahead for foo
(["foo"], slice(2, 3), "foo"),
# Duplicate matchers
(["foo", "foo"], slice(2, 3), "foo"),
(["sadkjfhas", "asefaslf"], slice(0, 0), None),
],
)
def test__parser__algorithms__next_match(
matcher_keywords,
result_slice,
winning_matcher,
test_segments,
):
"""Test the `next_match()` method."""
# Make the string parsers for testing.
matchers = [StringParser(keyword, KeywordSegment) for keyword in matcher_keywords]
# Fetch the matching keyword from above (because it will have the same position)
if winning_matcher:
winning_matcher = matchers[matcher_keywords.index(winning_matcher)]
ctx = ParseContext(dialect=None)
match, matcher = next_match(
test_segments,
0,
matchers,
ctx,
)
# Check the right matcher was successful.
if winning_matcher:
assert matcher is winning_matcher
else:
# If no designated winning matcher, assert that it wasn't successful.
assert matcher is None
assert not match
assert match.matched_slice == result_slice
@pytest.mark.parametrize(
"raw_segments,result_slice,error",
[
(["(", "a", ")", " ", "foo"], slice(0, 3), None),
(["(", "a", "(", "b", ")", "(", "c", ")", "d", ")", "e"], slice(0, 10), None),
# This should error because we try to close a square bracket
# inside a round one.
(["(", "a", "]", "b", ")", "e"], None, SQLParseError),
# This should error because we never find the end.
(["(", "a", " ", "b", " ", "e"], None, SQLParseError),
],
)
def test__parser__algorithms__resolve_bracket(
raw_segments, result_slice, error, generate_test_segments
):
"""Test the `resolve_bracket()` method."""
test_segments = generate_test_segments(raw_segments)
start_bracket = StringParser("(", SymbolSegment, type="start_bracket")
end_bracket = StringParser(")", SymbolSegment, type="end_bracket")
start_sq_bracket = StringParser("[", SymbolSegment, type="start_square_bracket")
end_sq_bracket = StringParser("]", SymbolSegment, type="end_square_bracket")
ctx = ParseContext(dialect=None)
# For this test case we assert that the first segment is the initial match.
first_match = start_bracket.match(test_segments, 0, ctx)
assert first_match
args = (test_segments,)
kwargs = dict(
opening_match=first_match,
opening_matcher=start_bracket,
start_brackets=[start_bracket, start_sq_bracket],
end_brackets=[end_bracket, end_sq_bracket],
bracket_persists=[True, False],
parse_context=ctx,
)
# If an error is defined, check that it is raised.
if error:
with pytest.raises(error):
resolve_bracket(*args, **kwargs)
else:
result = resolve_bracket(*args, **kwargs)
assert result
assert result.matched_slice == result_slice
@pytest.mark.parametrize(
"raw_segments,target_word,result_slice",
[
([], "foo", slice(0, 0)),
(["(", "foo", ")", " ", "foo"], "foo", slice(4, 5)),
(["a", " ", "foo", " ", "foo"], "foo", slice(2, 3)),
(["foo", " ", "foo", " ", "foo"], "foo", slice(0, 1)),
# Error case, unexpected closing bracket.
# NOTE: This should never normally happen, but we should
# be prepared in case it does so that we return appropriately.
(["a", " ", ")", " ", "foo"], "foo", slice(0, 0)),
],
)
def test__parser__algorithms__next_ex_bracket_match(
raw_segments, target_word, result_slice, generate_test_segments, test_dialect
):
"""Test the `next_ex_bracket_match()` method."""
test_segments = generate_test_segments(raw_segments)
target = StringParser(target_word, KeywordSegment)
ctx = ParseContext(dialect=test_dialect)
result, _, _ = next_ex_bracket_match(
test_segments,
0,
matchers=[target],
parse_context=ctx,
)
assert result.matched_slice == result_slice
@pytest.mark.parametrize(
"raw_segments,target_words,inc_term,result_slice",
[
(["a", "b", " ", "c", "d", " ", "e"], ["e", "c"], False, slice(0, 2)),
(["a", "b", " ", "c", "d", " ", "e"], ["e", "c"], True, slice(0, 4)),
# NOTE: Because "b" is_alpha, it needs whitespace before it to match.
(["a", "b", " ", "b"], ["b"], True, slice(0, 4)),
(["a", "b", " ", "b"], ["b"], False, slice(0, 2)),
(["a", "b", "c", " ", "b"], ["b"], False, slice(0, 3)),
],
)
def test__parser__algorithms__greedy_match(
raw_segments,
target_words,
inc_term,
result_slice,
generate_test_segments,
test_dialect,
):
"""Test the `greedy_match()` method."""
test_segments = generate_test_segments(raw_segments)
matchers = [StringParser(word, KeywordSegment) for word in target_words]
ctx = ParseContext(dialect=test_dialect)
match = greedy_match(
segments=test_segments,
idx=0,
parse_context=ctx,
matchers=matchers,
include_terminator=inc_term,
)
assert match
assert match.matched_slice == result_slice
@pytest.mark.parametrize(
"raw_segments,target_words,expected_result",
[
# Terminators mid sequence.
(["a", "b", " ", "c", "d", " ", "e"], ["e", "c"], 2),
# Initial terminators.
(["a", "b", " ", "c", "d", " ", "e"], ["a", "e"], 0),
# No terminators.
(["a", "b", " ", "c", "d", " ", "e"], ["x", "y"], 7),
# No sequence.
([], ["x", "y"], 0),
],
)
def test__parser__algorithms__trim_to_terminator(
raw_segments,
target_words,
expected_result,
generate_test_segments,
test_dialect,
):
"""Test the `trim_to_terminator()` method."""
test_segments = generate_test_segments(raw_segments)
matchers = [StringParser(word, KeywordSegment) for word in target_words]
ctx = ParseContext(dialect=test_dialect)
assert (
trim_to_terminator(
segments=test_segments,
idx=0,
parse_context=ctx,
terminators=matchers,
)
== expected_result
)
|