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__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
Test the `resolve_bracket()` method.
test__parser__algorithms__resolve_bracket
python
sqlfluff/sqlfluff
test/core/parser/match_algorithms_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/match_algorithms_test.py
MIT
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
Test the `next_ex_bracket_match()` method.
test__parser__algorithms__next_ex_bracket_match
python
sqlfluff/sqlfluff
test/core/parser/match_algorithms_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/match_algorithms_test.py
MIT
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
Test the `greedy_match()` method.
test__parser__algorithms__greedy_match
python
sqlfluff/sqlfluff
test/core/parser/match_algorithms_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/match_algorithms_test.py
MIT
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 )
Test the `trim_to_terminator()` method.
test__parser__algorithms__trim_to_terminator
python
sqlfluff/sqlfluff
test/core/parser/match_algorithms_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/match_algorithms_test.py
MIT
def fresh_ansi_dialect(): """Expand the ansi dialect for use.""" return dialect_selector("ansi")
Expand the ansi dialect for use.
fresh_ansi_dialect
python
sqlfluff/sqlfluff
test/core/parser/conftest.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/conftest.py
MIT
def test_segments(generate_test_segments): """A preset list of segments for testing. Includes a templated segment for completeness. """ main_list = generate_test_segments(["bar", " \t ", "foo", "baar", " \t "]) ts = TemplateSegment( pos_marker=main_list[-1].get_end_point_marker(), source_str="{# comment #}", block_type="comment", ) return main_list + (ts,)
A preset list of segments for testing. Includes a templated segment for completeness.
test_segments
python
sqlfluff/sqlfluff
test/core/parser/conftest.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/conftest.py
MIT
def test_markers__infer_next_position(raw, start_pos, end_pos): """Test that we can correctly infer positions from strings.""" assert end_pos == PositionMarker.infer_next_position(raw, *start_pos)
Test that we can correctly infer positions from strings.
test_markers__infer_next_position
python
sqlfluff/sqlfluff
test/core/parser/markers_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/markers_test.py
MIT
def test_markers__setting_position_raw(): """Test that we can correctly infer positions from strings & locations.""" templ = TemplatedFile.from_string("foobar") # Check inference in the template assert templ.get_line_pos_of_char_pos(2, source=True) == (1, 3) assert templ.get_line_pos_of_char_pos(2, source=False) == (1, 3) # Now check it passes through pos = PositionMarker(slice(2, 5), slice(2, 5), templ) # Can we infer positions correctly? assert pos.working_loc == (1, 3) # Check other marker properties work too (i.e. source properties) assert pos.line_no == 1 assert pos.line_pos == 3 # i.e. 2 + 1 (for 1-indexed)
Test that we can correctly infer positions from strings & locations.
test_markers__setting_position_raw
python
sqlfluff/sqlfluff
test/core/parser/markers_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/markers_test.py
MIT
def test_markers__setting_position_working(): """Test that we can correctly set positions manually.""" templ = TemplatedFile.from_string("foobar") pos = PositionMarker(slice(2, 5), slice(2, 5), templ, 4, 4) # Can we don't infer when we're explicitly told. assert pos.working_loc == (4, 4)
Test that we can correctly set positions manually.
test_markers__setting_position_working
python
sqlfluff/sqlfluff
test/core/parser/markers_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/markers_test.py
MIT
def test_markers__comparison(): """Test that we can correctly compare markers.""" templ = TemplatedFile.from_string("abc") # Make position markers for each of a, b & c # NOTE: We're not explicitly setting the working location, we # rely here on the marker inferring that correctly itself. a_pos = PositionMarker(slice(0, 1), slice(0, 1), templ) b_pos = PositionMarker(slice(1, 2), slice(1, 2), templ) c_pos = PositionMarker(slice(2, 3), slice(2, 3), templ) all_pos = (a_pos, b_pos, c_pos) # Check equality assert all(p == p for p in all_pos) # Check inequality assert a_pos != b_pos and a_pos != c_pos and b_pos != c_pos # Check less than assert a_pos < b_pos and b_pos < c_pos assert not c_pos < a_pos # Check greater than assert c_pos > a_pos and c_pos > b_pos assert not a_pos > c_pos # Check less than or equal assert all(a_pos <= p for p in all_pos) # Check greater than or equal assert all(c_pos >= p for p in all_pos)
Test that we can correctly compare markers.
test_markers__comparison
python
sqlfluff/sqlfluff
test/core/parser/markers_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/markers_test.py
MIT
def test__parser__repr(): """Test the __repr__ method of the parsers.""" # For the string parser note the uppercase template. assert repr(StringParser("foo", KeywordSegment)) == "<StringParser: 'FOO'>" # NOTE: For MultiStringParser we only test with one element here # because for more than one, the order is unpredictable. assert ( repr(MultiStringParser(["a"], KeywordSegment)) == "<MultiStringParser: {'A'}>" ) # For the typed & regex parser it's case sensitive (although lowercase # by convention). assert repr(TypedParser("foo", KeywordSegment)) == "<TypedParser: 'foo'>" assert repr(RegexParser(r"fo|o", KeywordSegment)) == "<RegexParser: 'fo|o'>"
Test the __repr__ method of the parsers.
test__parser__repr
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__typedparser__match(generate_test_segments): """Test the match method of TypedParser.""" parser = TypedParser("single_quote", ExampleSegment) ctx = ParseContext(dialect=None) # NOTE: The second element of the sequence has single quotes # and the test fixture will set the type accordingly. segments = generate_test_segments(["foo", "'bar'"]) result1 = parser.match(segments, 0, ctx) assert not result1 result2 = parser.match(segments, 1, ctx) assert result2 assert result2.matched_slice == slice(1, 2) assert result2.matched_class is ExampleSegment
Test the match method of TypedParser.
test__parser__typedparser__match
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__typedparser__simple(): """Test the simple method of TypedParser.""" parser = TypedParser("single_quote", ExampleSegment) ctx = ParseContext(dialect=None) assert parser.simple(ctx) == (frozenset(), frozenset(["single_quote"]))
Test the simple method of TypedParser.
test__parser__typedparser__simple
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__stringparser__match(generate_test_segments): """Test the match method of StringParser.""" parser = StringParser("foo", ExampleSegment, type="test") ctx = ParseContext(dialect=None) segments = generate_test_segments(["foo", "bar", "foo"]) result1 = parser.match(segments, 0, ctx) assert result1 assert result1.matched_slice == slice(0, 1) assert result1.matched_class is ExampleSegment assert result1.segment_kwargs == {"instance_types": ("test",)} result2 = parser.match(segments, 1, ctx) assert not result2 result3 = parser.match(segments, 2, ctx) assert result3 assert result3.matched_slice == slice(2, 3) assert result3.matched_class is ExampleSegment assert result3.segment_kwargs == {"instance_types": ("test",)}
Test the match method of StringParser.
test__parser__stringparser__match
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__stringparser__simple(): """Test the simple method of StringParser.""" parser = StringParser("foo", ExampleSegment) ctx = ParseContext(dialect=None) assert parser.simple(ctx) == (frozenset(["FOO"]), frozenset())
Test the simple method of StringParser.
test__parser__stringparser__simple
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__regexparser__match(generate_test_segments): """Test the match method of RegexParser.""" parser = RegexParser(r"b.r", ExampleSegment) ctx = ParseContext(dialect=None) segments = generate_test_segments(["foo", "bar", "boo"]) assert not parser.match(segments, 0, ctx) assert not parser.match(segments, 2, ctx) result = parser.match(segments, 1, ctx) assert result assert result.matched_slice == slice(1, 2) assert result.matched_class is ExampleSegment
Test the match method of RegexParser.
test__parser__regexparser__match
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__regexparser__simple(): """Test the simple method of RegexParser.""" parser = RegexParser(r"b.r", ExampleSegment) ctx = ParseContext(dialect=None) assert parser.simple(ctx) is None
Test the simple method of RegexParser.
test__parser__regexparser__simple
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__multistringparser__match(generate_test_segments): """Test the match method of MultiStringParser.""" parser = MultiStringParser(["foo", "bar"], ExampleSegment) ctx = ParseContext(dialect=None) segments = generate_test_segments(["foo", "fo", "bar", "boo"]) assert not parser.match(segments, 1, ctx) assert not parser.match(segments, 3, ctx) result1 = parser.match(segments, 0, ctx) assert result1 assert result1.matched_slice == slice(0, 1) assert result1.matched_class is ExampleSegment result2 = parser.match(segments, 2, ctx) assert result2 assert result2.matched_slice == slice(2, 3) assert result2.matched_class is ExampleSegment
Test the match method of MultiStringParser.
test__parser__multistringparser__match
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__multistringparser__simple(): """Test the MultiStringParser matchable.""" parser = MultiStringParser(["foo", "bar"], KeywordSegment) ctx = ParseContext(dialect=None) assert parser.simple(ctx) == (frozenset(["FOO", "BAR"]), frozenset())
Test the MultiStringParser matchable.
test__parser__multistringparser__simple
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__typedparser_rematch(new_type, generate_test_segments): """Test that TypedParser allows rematching. Because the TypedParser looks for types and then changes the type as a result, there is a risk of preventing rematching. This is a problem because we use it when checking that fix edits haven't broken the parse tree. In this example the TypedParser is looking for a "single_quote" type segment, but is due to mutate to an Example segment, which inherits directly from `RawSegment`. Unless the TypedParser steps in, this would apparently present a rematching issue. """ pre_match_types = { "single_quote", "raw", "base", } post_match_types = { # Make sure we got the "example" class "example", # But we *also* get the "single_quote" class. # On the second pass this is the main crux of the test. "single_quote", "raw", "base", } kwargs = {} expected_type = "example" if new_type: post_match_types.add(new_type) kwargs = {"type": new_type} expected_type = new_type segments = generate_test_segments(["'foo'"]) # Check types pre-match assert segments[0].class_types == pre_match_types parser = TypedParser("single_quote", ExampleSegment, **kwargs) # Just check that our assumptions about inheritance are right. assert not ExampleSegment.class_is_type("single_quote") ctx = ParseContext(dialect=None) match1 = parser.match(segments, 0, ctx) assert match1 segments1 = match1.apply(segments) # Check types post-match 1 assert segments1[0].class_types == post_match_types assert segments1[0].get_type() == expected_type assert segments1[0].to_tuple(show_raw=True) == (expected_type, "'foo'") # Do a rematch to check it works. match = parser.match(segments1, 0, ctx) assert match # Check types post-match 2 segments2 = match.apply(segments1) assert segments2[0].class_types == post_match_types assert segments2[0].get_type() == expected_type assert segments2[0].to_tuple(show_raw=True) == (expected_type, "'foo'")
Test that TypedParser allows rematching. Because the TypedParser looks for types and then changes the type as a result, there is a risk of preventing rematching. This is a problem because we use it when checking that fix edits haven't broken the parse tree. In this example the TypedParser is looking for a "single_quote" type segment, but is due to mutate to an Example segment, which inherits directly from `RawSegment`. Unless the TypedParser steps in, this would apparently present a rematching issue.
test__parser__typedparser_rematch
python
sqlfluff/sqlfluff
test/core/parser/parser_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parser_test.py
MIT
def test__parser__helper_trim_non_code_segments( token_list, pre_len, mid_len, post_len, generate_test_segments, ): """Test trim_non_code_segments.""" segments = generate_test_segments(token_list) pre, mid, post = trim_non_code_segments(segments) # Assert lengths assert (len(pre), len(mid), len(post)) == (pre_len, mid_len, post_len) # Assert content assert [elem.raw for elem in pre] == list(token_list[:pre_len]) assert [elem.raw for elem in mid] == list(token_list[pre_len : pre_len + mid_len]) assert [elem.raw for elem in post] == list(token_list[len(segments) - post_len :])
Test trim_non_code_segments.
test__parser__helper_trim_non_code_segments
python
sqlfluff/sqlfluff
test/core/parser/helpers_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/helpers_test.py
MIT
def test__parser__parse_match(test_segments): """Test match method on a real segment.""" ctx = ParseContext(dialect=None) # This should match and have consumed everything, which should # now be part of a BasicSegment. match = BasicSegment.match(test_segments, 0, parse_context=ctx) assert match matched = match.apply(test_segments) assert len(matched) == 1 assert isinstance(matched[0], BasicSegment) assert matched[0].segments[0].type == "raw"
Test match method on a real segment.
test__parser__parse_match
python
sqlfluff/sqlfluff
test/core/parser/parse_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parse_test.py
MIT
def test__parser__parse_error(): """Test that SQLParseError is raised for unparsable section.""" in_str = "SELECT ;" lnt = Linter(dialect="ansi") parsed = lnt.parse_string(in_str) assert len(parsed.violations) == 1 violation = parsed.violations[0] assert isinstance(violation, SQLParseError) assert violation.desc() == "Line 1, Position 1: Found unparsable section: 'SELECT'" # Check that the expected labels work for logging. # TODO: This is more specific that in previous iterations, but we could # definitely make this easier to read. assert ( 'Expected: "<Delimited: ' "[<Ref: 'SelectClauseElementSegment'>]> " "after <WordSegment: ([L: 1, P: 1]) 'SELECT'>. " "Found nothing." ) in parsed.tree.stringify()
Test that SQLParseError is raised for unparsable section.
test__parser__parse_error
python
sqlfluff/sqlfluff
test/core/parser/parse_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parse_test.py
MIT
def test_parse_jinja_macro_exclude(): """Test parsing when excluding macros with unknown tags. This test case has a file which defines the unknown tag `materialization` which would cause a templating error if not excluded. By ignoring that folder we can ensure there are no errors. """ config_path = "test/fixtures/templater/jinja_exclude_macro_path/.sqlfluff" config = FluffConfig.from_path(config_path) linter = Linter(config=config) sql_file_path = "test/fixtures/templater/jinja_exclude_macro_path/jinja.sql" parsed = linter.parse_path(sql_file_path) for parse in parsed: assert parse.violations == []
Test parsing when excluding macros with unknown tags. This test case has a file which defines the unknown tag `materialization` which would cause a templating error if not excluded. By ignoring that folder we can ensure there are no errors.
test_parse_jinja_macro_exclude
python
sqlfluff/sqlfluff
test/core/parser/parse_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/parse_test.py
MIT
def assert_matches(instring, matcher, matchstring): """Assert that a matcher does or doesn't work on a string. The optional `matchstring` argument, which can optionally be None, allows to either test positive matching of a particular string or negative matching (that it explicitly) doesn't match. """ res = matcher.match(instring) # Check we've got the right type assert isinstance(res, LexMatch) if matchstring is None: assert res.forward_string == instring assert res.elements == [] else: assert res.forward_string == instring[len(matchstring) :] assert len(res.elements) == 1 assert res.elements[0].raw == matchstring
Assert that a matcher does or doesn't work on a string. The optional `matchstring` argument, which can optionally be None, allows to either test positive matching of a particular string or negative matching (that it explicitly) doesn't match.
assert_matches
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_obj(raw, res, caplog): """Test the lexer splits as expected in a selection of cases.""" lex = Lexer(config=FluffConfig(overrides={"dialect": "ansi"})) with caplog.at_level(logging.DEBUG): lexing_segments, _ = lex.lex(raw) assert [seg.raw for seg in lexing_segments] == res
Test the lexer splits as expected in a selection of cases.
test__parser__lexer_obj
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_string(raw, res): """Test the StringLexer.""" matcher = StringLexer("dot", ".", CodeSegment) assert_matches(raw, matcher, res)
Test the StringLexer.
test__parser__lexer_string
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_regex(raw, reg, res, caplog): """Test the RegexLexer.""" matcher = RegexLexer("test", reg, CodeSegment) with caplog.at_level(logging.DEBUG): assert_matches(raw, matcher, res)
Test the RegexLexer.
test__parser__lexer_regex
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_lex_match(caplog): """Test the RepeatedMultiMatcher.""" matchers = [ StringLexer("dot", ".", CodeSegment), RegexLexer("test", r"#[^#]*#", CodeSegment), ] with caplog.at_level(logging.DEBUG): res = Lexer.lex_match("..#..#..#", matchers) assert res.forward_string == "#" # Should match right up to the final element assert len(res.elements) == 5 assert res.elements[2].raw == "#..#"
Test the RepeatedMultiMatcher.
test__parser__lexer_lex_match
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_fail(): """Test the how the lexer fails and reports errors.""" lex = Lexer(config=FluffConfig(overrides={"dialect": "ansi"})) _, vs = lex.lex("Select \u0394") assert len(vs) == 1 err = vs[0] assert isinstance(err, SQLLexError) assert err.line_pos == 8
Test the how the lexer fails and reports errors.
test__parser__lexer_fail
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_fail_via_parse(): """Test the how the parser fails and reports errors while lexing.""" lexer = Lexer(config=FluffConfig(overrides={"dialect": "ansi"})) _, vs = lexer.lex("Select \u0394") assert vs assert len(vs) == 1 err = vs[0] assert isinstance(err, SQLLexError) assert err.line_pos == 8
Test the how the parser fails and reports errors while lexing.
test__parser__lexer_fail_via_parse
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_trim_post_subdivide(caplog): """Test a RegexLexer with a trim_post_subdivide function.""" matcher = [ RegexLexer( "function_script_terminator", r";\s+(?!\*)\/(?!\*)|\s+(?!\*)\/(?!\*)", CodeSegment, segment_kwargs={"type": "function_script_terminator"}, subdivider=StringLexer( "semicolon", ";", CodeSegment, segment_kwargs={"type": "semicolon"} ), trim_post_subdivide=RegexLexer( "newline", r"(\n|\r\n)+", NewlineSegment, ), ) ] with caplog.at_level(logging.DEBUG): res = Lexer.lex_match(";\n/\n", matcher) assert res.elements[0].raw == ";" assert res.elements[1].raw == "\n" assert res.elements[2].raw == "/" assert len(res.elements) == 3
Test a RegexLexer with a trim_post_subdivide function.
test__parser__lexer_trim_post_subdivide
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_slicing_calls(case: _LexerSlicingCase): """Test slicing of call blocks. https://github.com/sqlfluff/sqlfluff/issues/4013 """ config = FluffConfig(overrides={"dialect": "ansi"}) templater = JinjaTemplater(override_context=case.context) templated_file, templater_violations = templater.process( in_str=case.in_str, fname="test.sql", config=config, formatter=None ) assert ( not templater_violations ), f"Found templater violations: {templater_violations}" lexer = Lexer(config=config) lexing_segments, lexing_violations = lexer.lex(templated_file) assert not lexing_violations, f"Found templater violations: {lexing_violations}" assert case.expected_segments == [ ( seg.raw, seg.source_str if isinstance(seg, TemplateSegment) else None, seg.block_type if isinstance(seg, TemplateSegment) else None, seg.type, ) for seg in lexing_segments ]
Test slicing of call blocks. https://github.com/sqlfluff/sqlfluff/issues/4013
test__parser__lexer_slicing_calls
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__lexer_slicing_from_template_file(case: _LexerSlicingTemplateFileCase): """Test slicing using a provided TemplateFile. Useful for testing special inputs without having to find a templater to trick and yield the input you want to test. """ config = FluffConfig(overrides={"dialect": "ansi"}) lexer = Lexer(config=config) lexing_segments, lexing_violations = lexer.lex(case.file) assert not lexing_violations, f"Found templater violations: {lexing_violations}" assert case.expected_segments == [ ( seg.raw, seg.source_str if isinstance(seg, TemplateSegment) else None, seg.block_type if isinstance(seg, TemplateSegment) else None, seg.type, ) for seg in lexing_segments ]
Test slicing using a provided TemplateFile. Useful for testing special inputs without having to find a templater to trick and yield the input you want to test.
test__parser__lexer_slicing_from_template_file
python
sqlfluff/sqlfluff
test/core/parser/lexer_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/lexer_test.py
MIT
def test__parser__matchresult2_apply( segment_seed, match_result, match_len, serialised_result, generate_test_segments ): """Test MatchResult.apply(). This includes testing instantiating the MatchResult and whether setting some attributes and not others works as expected. """ input_segments = generate_test_segments(segment_seed) # Test the length attribute. # NOTE: It's not the number of segments we'll return, but the span # of the match in the original sequence. assert len(match_result) == match_len out_segments = match_result.apply(input_segments) serialised = tuple( seg.to_tuple(show_raw=True, include_meta=True) for seg in out_segments ) assert serialised == serialised_result # Test that _every_ segment (including metas) has a position marker already. for seg in out_segments: _recursive_assert_pos(seg)
Test MatchResult.apply(). This includes testing instantiating the MatchResult and whether setting some attributes and not others works as expected.
test__parser__matchresult2_apply
python
sqlfluff/sqlfluff
test/core/parser/match_result_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/match_result_test.py
MIT
def test__parser__raw_get_raw_segments(raw_segments): """Test niche case of calling get_raw_segments on a raw segment.""" for s in raw_segments: assert s.get_raw_segments() == [s]
Test niche case of calling get_raw_segments on a raw segment.
test__parser__raw_get_raw_segments
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_raw_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_raw_test.py
MIT
def test__parser__raw_segments_with_ancestors( raw_segments, DummySegment, DummyAuxSegment ): """Test raw_segments_with_ancestors. This is used in the reflow module to assess parse depth. """ test_seg = DummySegment([DummyAuxSegment(raw_segments[:1]), raw_segments[1]]) # Result should be the same raw segment, but with appropriate parents assert test_seg.raw_segments_with_ancestors == [ ( raw_segments[0], [ PathStep(test_seg, 0, 2, (0, 1)), PathStep(test_seg.segments[0], 0, 1, (0,)), ], ), (raw_segments[1], [PathStep(test_seg, 1, 2, (0, 1))]), ]
Test raw_segments_with_ancestors. This is used in the reflow module to assess parse depth.
test__parser__raw_segments_with_ancestors
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_raw_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_raw_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/parser/segments/conftest.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/conftest.py
MIT
def raw_seg(raw_segments): """Construct a raw segment as a fixture.""" return raw_segments[0]
Construct a raw segment as a fixture.
raw_seg
python
sqlfluff/sqlfluff
test/core/parser/segments/conftest.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/conftest.py
MIT
def DummySegment(): """Construct a raw segment as a fixture.""" class DummySegment(BaseSegment): """A dummy segment for testing with no grammar.""" type = "dummy" return DummySegment
Construct a raw segment as a fixture.
DummySegment
python
sqlfluff/sqlfluff
test/core/parser/segments/conftest.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/conftest.py
MIT
def DummyAuxSegment(): """Construct a raw segment as a fixture.""" class DummyAuxSegment(BaseSegment): """A different dummy segment for testing with no grammar.""" type = "dummy_aux" return DummyAuxSegment
Construct a raw segment as a fixture.
DummyAuxSegment
python
sqlfluff/sqlfluff
test/core/parser/segments/conftest.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/conftest.py
MIT
def test__parser__base_segments_type(DummySegment): """Test the .is_type() method.""" assert BaseSegment.class_is_type("base") assert not BaseSegment.class_is_type("foo") assert not BaseSegment.class_is_type("foo", "bar") assert DummySegment.class_is_type("dummy") assert DummySegment.class_is_type("base") assert DummySegment.class_is_type("base", "foo", "bar")
Test the .is_type() method.
test__parser__base_segments_type
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_class_types(DummySegment): """Test the metaclass ._class_types attribute.""" assert DummySegment._class_types == {"dummy", "base"}
Test the metaclass ._class_types attribute.
test__parser__base_segments_class_types
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_descendant_type_set( raw_segments, DummySegment, DummyAuxSegment ): """Test the .descendant_type_set() method.""" test_seg = DummySegment([DummyAuxSegment(raw_segments)]) assert test_seg.descendant_type_set == {"raw", "base", "dummy_aux"}
Test the .descendant_type_set() method.
test__parser__base_segments_descendant_type_set
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_direct_descendant_type_set( raw_segments, DummySegment, DummyAuxSegment ): """Test the .direct_descendant_type_set() method.""" test_seg = DummySegment([DummyAuxSegment(raw_segments)]) assert test_seg.direct_descendant_type_set == {"base", "dummy_aux"}
Test the .direct_descendant_type_set() method.
test__parser__base_segments_direct_descendant_type_set
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_to_tuple_a(raw_segments, DummySegment, DummyAuxSegment): """Test the .to_tuple() method.""" test_seg = DummySegment([DummyAuxSegment(raw_segments)]) assert test_seg.to_tuple() == ( "dummy", (("dummy_aux", (("raw", ()), ("raw", ()))),), )
Test the .to_tuple() method.
test__parser__base_segments_to_tuple_a
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_to_tuple_b(raw_segments, DummySegment, DummyAuxSegment): """Test the .to_tuple() method.""" test_seg = DummySegment( [DummyAuxSegment(raw_segments + (DummyAuxSegment(raw_segments[:1]),))] ) assert test_seg.to_tuple() == ( "dummy", (("dummy_aux", (("raw", ()), ("raw", ()), ("dummy_aux", (("raw", ()),)))),), )
Test the .to_tuple() method.
test__parser__base_segments_to_tuple_b
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_to_tuple_c(raw_segments, DummySegment, DummyAuxSegment): """Test the .to_tuple() method with show_raw=True.""" test_seg = DummySegment( [DummyAuxSegment(raw_segments + (DummyAuxSegment(raw_segments[:1]),))] ) assert test_seg.to_tuple(show_raw=True) == ( "dummy", ( ( "dummy_aux", ( ("raw", "foobar"), ("raw", ".barfoo"), ("dummy_aux", (("raw", "foobar"),)), ), ), ), )
Test the .to_tuple() method with show_raw=True.
test__parser__base_segments_to_tuple_c
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_as_record_a( raw_segments, DummySegment, DummyAuxSegment ): """Test the .as_record() method. NOTE: In this test, note that there are lists, as some segment types are duplicated within their parent segment. """ test_seg = DummySegment([DummyAuxSegment(raw_segments)]) assert test_seg.as_record() == { "dummy": {"dummy_aux": [{"raw": None}, {"raw": None}]} }
Test the .as_record() method. NOTE: In this test, note that there are lists, as some segment types are duplicated within their parent segment.
test__parser__base_segments_as_record_a
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_as_record_b( raw_segments, DummySegment, DummyAuxSegment ): """Test the .as_record() method. NOTE: In this test, note that there are no lists, every segment type is unique within it's parent segment, and so there is no need. """ test_seg = DummySegment( [DummyAuxSegment(raw_segments[:1] + (DummyAuxSegment(raw_segments[:1]),))] ) assert test_seg.as_record() == { "dummy": {"dummy_aux": {"raw": None, "dummy_aux": {"raw": None}}} }
Test the .as_record() method. NOTE: In this test, note that there are no lists, every segment type is unique within it's parent segment, and so there is no need.
test__parser__base_segments_as_record_b
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_as_record_c( raw_segments, DummySegment, DummyAuxSegment ): """Test the .as_record() method with show_raw=True. NOTE: In this test, note that there are no lists, every segment type is unique within it's parent segment, and so there is no need. """ test_seg = DummySegment( [DummyAuxSegment(raw_segments[:1] + (DummyAuxSegment(raw_segments[:1]),))] ) assert test_seg.as_record(show_raw=True) == { "dummy": {"dummy_aux": {"raw": "foobar", "dummy_aux": {"raw": "foobar"}}} }
Test the .as_record() method with show_raw=True. NOTE: In this test, note that there are no lists, every segment type is unique within it's parent segment, and so there is no need.
test__parser__base_segments_as_record_c
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_count_segments( raw_segments, DummySegment, DummyAuxSegment ): """Test the .count_segments() method.""" test_seg = DummySegment([DummyAuxSegment(raw_segments)]) assert test_seg.count_segments() == 4 assert test_seg.count_segments(raw_only=True) == 2
Test the .count_segments() method.
test__parser__base_segments_count_segments
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser_base_segments_validate_non_code_ends( generate_test_segments, DummySegment, list_in, result ): """Test BaseSegment.validate_non_code_ends().""" if result: # Assert that it _does_ raise an exception. with pytest.raises(AssertionError): # Validation happens on instantiation. seg = DummySegment(segments=generate_test_segments(list_in)) else: # Check that it _doesn't_ raise an exception... seg = DummySegment(segments=generate_test_segments(list_in)) # ...even when explicitly validating. seg.validate_non_code_ends()
Test BaseSegment.validate_non_code_ends().
test__parser_base_segments_validate_non_code_ends
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_path_to(raw_segments, DummySegment, DummyAuxSegment): """Test the .path_to() method.""" test_seg_a = DummyAuxSegment(raw_segments) test_seg_b = DummySegment([test_seg_a]) # With a direct parent/child relationship we only get # one element of path. # NOTE: All the dummy segments return True for .is_code() # so that means the do appear in code_idxs. assert test_seg_b.path_to(test_seg_a) == [PathStep(test_seg_b, 0, 1, (0,))] # With a three segment chain - we get two path elements. assert test_seg_b.path_to(raw_segments[0]) == [ PathStep(test_seg_b, 0, 1, (0,)), PathStep(test_seg_a, 0, 2, (0, 1)), ] assert test_seg_b.path_to(raw_segments[1]) == [ PathStep(test_seg_b, 0, 1, (0,)), PathStep(test_seg_a, 1, 2, (0, 1)), ]
Test the .path_to() method.
test__parser__base_segments_path_to
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_stubs(): """Test stub methods that have no implementation in base class.""" template = TemplatedFile.from_string("foobar") rs1 = RawSegment("foobar", PositionMarker(slice(0, 6), slice(0, 6), template)) base_segment = BaseSegment(segments=[rs1]) with pytest.raises(NotImplementedError): base_segment.edit("foo")
Test stub methods that have no implementation in base class.
test__parser__base_segments_stubs
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_raw(raw_seg): """Test raw segments behave as expected.""" # Check Segment Return assert raw_seg.segments == () assert raw_seg.raw == "foobar" # Check Formatting and Stringification assert str(raw_seg) == repr(raw_seg) == "<CodeSegment: ([L: 1, P: 1]) 'foobar'>" assert ( raw_seg.stringify(ident=1, tabsize=2) == "[L: 1, P: 1] | raw: " " 'foobar'\n" ) # Check tuple assert raw_seg.to_tuple() == ("raw", ()) # Check tuple assert raw_seg.to_tuple(show_raw=True) == ("raw", "foobar")
Test raw segments behave as expected.
test__parser__base_segments_raw
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_base(raw_segments, fresh_ansi_dialect, DummySegment): """Test base segments behave as expected.""" base_seg = DummySegment(raw_segments) # Check we assume the position correctly assert ( base_seg.pos_marker.start_point_marker() == raw_segments[0].pos_marker.start_point_marker() ) assert ( base_seg.pos_marker.end_point_marker() == raw_segments[-1].pos_marker.end_point_marker() ) # Check that we correctly reconstruct the raw assert base_seg.raw == "foobar.barfoo" # Check tuple assert base_seg.to_tuple() == ( "dummy", (raw_segments[0].to_tuple(), raw_segments[1].to_tuple()), ) # Check Formatting and Stringification assert str(base_seg) == repr(base_seg) == "<DummySegment: ([L: 1, P: 1])>" assert base_seg.stringify(ident=1, tabsize=2) == ( "[L: 1, P: 1] | dummy:\n" "[L: 1, P: 1] | raw: " " 'foobar'\n" "[L: 1, P: 7] | raw: " " '.barfoo'\n" )
Test base segments behave as expected.
test__parser__base_segments_base
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_raw_compare(): """Test comparison of raw segments.""" template = TemplatedFile.from_string("foobar") rs1 = RawSegment("foobar", PositionMarker(slice(0, 6), slice(0, 6), template)) rs2 = RawSegment("foobar", PositionMarker(slice(0, 6), slice(0, 6), template)) assert rs1 == rs2
Test comparison of raw segments.
test__parser__base_segments_raw_compare
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_base_compare(DummySegment, DummyAuxSegment): """Test comparison of base segments.""" template = TemplatedFile.from_string("foobar") rs1 = RawSegment("foobar", PositionMarker(slice(0, 6), slice(0, 6), template)) rs2 = RawSegment("foobar", PositionMarker(slice(0, 6), slice(0, 6), template)) ds1 = DummySegment([rs1]) ds2 = DummySegment([rs2]) dsa2 = DummyAuxSegment([rs2]) # Check for equality assert ds1 == ds2 # Check a different match on the same details are not the same assert ds1 != dsa2
Test comparison of base segments.
test__parser__base_segments_base_compare
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_pickle_safe(raw_segments): """Test pickling and unpickling of BaseSegment.""" test_seg = BaseSegment([BaseSegment(raw_segments)]) test_seg.set_as_parent() pickled = pickle.dumps(test_seg) result_seg = pickle.loads(pickled) assert test_seg == result_seg # Check specifically the treatment of the parent position. assert result_seg.segments[0].get_parent()[0] is result_seg
Test pickling and unpickling of BaseSegment.
test__parser__base_segments_pickle_safe
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_copy_isolation(DummySegment, raw_segments): """Test copy isolation in BaseSegment. First on one of the raws and then on the dummy segment. """ # On a raw a_seg = raw_segments[0] a_copy = a_seg.copy() assert a_seg is not a_copy assert a_seg == a_copy assert a_seg.pos_marker is a_copy.pos_marker a_copy.pos_marker = None assert a_copy.pos_marker is None assert a_seg.pos_marker is not None # On a base b_seg = DummySegment(segments=raw_segments) b_copy = b_seg.copy() assert b_seg is not b_copy assert b_seg == b_copy assert b_seg.pos_marker is b_copy.pos_marker b_copy.pos_marker = None assert b_copy.pos_marker is None assert b_seg.pos_marker is not None # On addition to a lint Fix fix = LintFix("replace", a_seg, [b_seg]) for s in fix.edit: assert not s.pos_marker assert b_seg.pos_marker
Test copy isolation in BaseSegment. First on one of the raws and then on the dummy segment.
test__parser__base_segments_copy_isolation
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_parent_ref(DummySegment, raw_segments): """Test getting and setting parents on BaseSegment.""" # Check initially no parent (because not set) assert not raw_segments[0].get_parent() # Add it to a segment (which also sets the parent value) seg = DummySegment(segments=raw_segments) # The DummySegment shouldn't have a parent. assert seg.get_parent() is None assert seg.segments[0].get_parent()[0] is seg assert seg.segments[1].get_parent()[0] is seg # Remove segment from parent, but don't unset. # Should still check an return None. seg_0 = seg.segments[0] seg.segments = seg.segments[1:] assert seg_0 not in seg.segments assert not seg_0.get_parent() # Check the other still works. assert seg.segments[0].get_parent()[0]
Test getting and setting parents on BaseSegment.
test__parser__base_segments_parent_ref
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__raw_segment_raw_normalized(): """Test comparison of raw segments.""" template = TemplatedFile.from_string('"a"""."e"') rs1 = RawSegment( '"a"""', PositionMarker(slice(0, 5), slice(0, 5), template), quoted_value=(r'"((?:[^"]|"")*)"', 1), escape_replacements=[('""', '"')], casefold=str.upper, ) rs2 = RawSegment( ".", PositionMarker(slice(6, 7), slice(6, 7), template), ) rs3 = RawSegment( '"e"', PositionMarker(slice(8, 10), slice(8, 10), template), quoted_value=(r'"((?:[^"]|"")*)"', 1), escape_replacements=[('""', '"')], casefold=str.upper, ) bs1 = BaseSegment( ( rs1, rs2, rs3, ), PositionMarker(slice(0, 10), slice(0, 10), template), ) assert rs1.raw == '"a"""' assert rs1.raw_normalized(False) == 'a"' assert rs1.raw_normalized() == 'A"' assert rs2.raw == "." assert rs2.raw_normalized(False) == "." assert rs2.raw_normalized() == "." assert rs3.raw == '"e"' assert rs3.raw_normalized(False) == "e" assert rs3.raw_normalized() == "E" assert bs1.raw == '"a"""."e"' assert bs1.raw_normalized() == 'A".E'
Test comparison of raw segments.
test__parser__raw_segment_raw_normalized
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_base_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_base_test.py
MIT
def test__parser__base_segments_file(raw_segments): """Test BaseFileSegment to behave as expected.""" base_seg = BaseFileSegment(raw_segments, fname="/some/dir/file.sql") assert base_seg.type == "file" assert base_seg.file_path == "/some/dir/file.sql" assert base_seg.can_start_end_non_code assert base_seg.allow_empty
Test BaseFileSegment to behave as expected.
test__parser__base_segments_file
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_file_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_file_test.py
MIT
def test__parser__core_keyword(raw_segments): """Test the Mystical KeywordSegment.""" # First make a keyword FooKeyword = StringParser("foobar", KeywordSegment, type="bar") # Check it looks as expected assert FooKeyword.template.upper() == "FOOBAR" ctx = ParseContext(dialect=None) # Match it against a list and check it doesn't match assert not FooKeyword.match(raw_segments, 1, parse_context=ctx) # Match it against the final element (returns tuple) m = FooKeyword.match(raw_segments, 0, parse_context=ctx) assert m assert m == MatchResult( matched_slice=slice(0, 1), matched_class=KeywordSegment, segment_kwargs={"instance_types": ("bar",)}, ) segments = m.apply(raw_segments) assert len(segments) == 1 segment = segments[0] assert segment.class_types == { "base", "word", "keyword", "raw", "bar", }
Test the Mystical KeywordSegment.
test__parser__core_keyword
python
sqlfluff/sqlfluff
test/core/parser/segments/segments_common_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/segments/segments_common_test.py
MIT
def structural_parse_mode_test(generate_test_segments, fresh_ansi_dialect): """Test the structural function of a grammar in various parse modes. This helper fixture is designed to modularise grammar tests. """ def _structural_parse_mode_test( test_segment_seeds: List[str], grammar_class: Type[BaseGrammar], grammar_argument_seeds: List[str], grammar_terminator_seeds: List[str], grammar_kwargs: Dict[str, Any], parse_mode: ParseMode, input_slice: slice, output_tuple: Tuple[Any, ...], ): segments = generate_test_segments(test_segment_seeds) # Dialect is required here only to have access to bracket segments. ctx = ParseContext(dialect=fresh_ansi_dialect) # NOTE: We pass terminators using kwargs rather than directly because some # classes don't support it (e.g. Bracketed). if grammar_terminator_seeds: grammar_kwargs["terminators"] = [ StringParser(e, KeywordSegment) for e in grammar_terminator_seeds ] _seq = grammar_class( *(StringParser(e, KeywordSegment) for e in grammar_argument_seeds), parse_mode=parse_mode, **grammar_kwargs, ) _start = input_slice.start or 0 _stop = input_slice.stop or len(segments) _match = _seq.match(segments[:_stop], _start, ctx) # If we're expecting an output tuple, assert the match is truthy. if output_tuple: assert _match _result = tuple( e.to_tuple(show_raw=True, code_only=False, include_meta=True) for e in _match.apply(segments) ) assert _result == output_tuple # Return the function return _structural_parse_mode_test
Test the structural function of a grammar in various parse modes. This helper fixture is designed to modularise grammar tests.
structural_parse_mode_test
python
sqlfluff/sqlfluff
test/core/parser/grammar/conftest.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/conftest.py
MIT
def test_dialect(): """A stripped back test dialect for testing.""" test_dialect = Dialect("test", root_segment_name="FileSegment") 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(FooSegment=StringParser("foo", CodeSegment, type="foo")) # Return the expanded copy. return test_dialect.expand()
A stripped back test dialect for testing.
test_dialect
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_ref_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_ref_test.py
MIT
def test__parser__grammar__ref_eq(): """Test equality of Ref Grammars.""" r1 = Ref("foo") r2 = Ref("foo") assert r1 is not r2 assert r1 == r2 check_list = [1, 2, r2, 3] # Check we can find it in lists assert r1 in check_list # Check we can get it's position assert check_list.index(r1) == 2 # Check we can remove it from a list check_list.remove(r1) assert r1 not in check_list
Test equality of Ref Grammars.
test__parser__grammar__ref_eq
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_ref_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_ref_test.py
MIT
def test__parser__grammar__ref_repr(): """Test the __repr__ method of Ref.""" assert repr(Ref("foo")) == "<Ref: 'foo'>" assert repr(Ref("bar", optional=True)) == "<Ref: 'bar' [opt]>"
Test the __repr__ method of Ref.
test__parser__grammar__ref_repr
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_ref_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_ref_test.py
MIT
def test__parser__grammar_ref_match(generate_test_segments, test_dialect): """Test the Ref grammar match method.""" foo_ref = Ref("FooSegment") test_segments = generate_test_segments(["bar", "foo", "bar"]) ctx = ParseContext(dialect=test_dialect) match = foo_ref.match(test_segments, 1, ctx) assert match == MatchResult( matched_slice=slice(1, 2), matched_class=CodeSegment, segment_kwargs={"instance_types": ("foo",)}, )
Test the Ref grammar match method.
test__parser__grammar_ref_match
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_ref_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_ref_test.py
MIT
def test__parser__grammar_ref_exclude(generate_test_segments, fresh_ansi_dialect): """Test the Ref grammar exclude option with the match method.""" identifier = Ref("NakedIdentifierSegment", exclude=Ref.keyword("ABS")) test_segments = generate_test_segments(["ABS", "ABSOLUTE"]) ctx = ParseContext(dialect=fresh_ansi_dialect) # Assert ABS does not match, due to the exclude assert not identifier.match(test_segments, 0, ctx) # Assert ABSOLUTE does match assert identifier.match(test_segments, 1, ctx)
Test the Ref grammar exclude option with the match method.
test__parser__grammar_ref_exclude
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_ref_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_ref_test.py
MIT
def test__parser__grammar__oneof__copy(): """Test grammar copying.""" bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) g1 = OneOf(fs, bs) # Check copy g2 = g1.copy() assert g1 == g2 assert g1 is not g2 # Check copy insert (start) g3 = g1.copy(insert=[bs], at=0) assert g3 == OneOf(bs, fs, bs) # Check copy insert (mid) g4 = g1.copy(insert=[bs], at=1) assert g4 == OneOf(fs, bs, bs) # Check copy insert (end) g5 = g1.copy(insert=[bs], at=-1) assert g5 == OneOf(fs, bs, bs)
Test grammar copying.
test__parser__grammar__oneof__copy
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_oneof(test_segments, allow_gaps): """Test the OneOf grammar. NOTE: Should behave the same regardless of allow_gaps. """ bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) g = OneOf(fs, bs, allow_gaps=allow_gaps) ctx = ParseContext(dialect=None) # Check directly assert g.match(test_segments, 0, parse_context=ctx) == MatchResult( matched_slice=slice(0, 1), matched_class=KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ) # Check with a bit of whitespace assert not g.match(test_segments, 1, parse_context=ctx)
Test the OneOf grammar. NOTE: Should behave the same regardless of allow_gaps.
test__parser__grammar_oneof
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_oneof_templated(test_segments): """Test the OneOf grammar. NB: Should behave the same regardless of code_only. """ bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) g = OneOf(fs, bs) ctx = ParseContext(dialect=None) # This shouldn't match, but it *ALSO* shouldn't raise an exception. # https://github.com/sqlfluff/sqlfluff/issues/780 assert not g.match(test_segments, 5, parse_context=ctx)
Test the OneOf grammar. NB: Should behave the same regardless of code_only.
test__parser__grammar_oneof_templated
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_oneof_exclude(test_segments): """Test the OneOf grammar exclude option.""" bs = StringParser("bar", KeywordSegment) fs = StringParser("foo", KeywordSegment) g = OneOf(bs, exclude=Sequence(bs, fs)) ctx = ParseContext(dialect=None) # Just against the first alone assert g.match(test_segments[:1], 0, parse_context=ctx) # Now with the bit to exclude included assert not g.match(test_segments, 0, parse_context=ctx)
Test the OneOf grammar exclude option.
test__parser__grammar_oneof_exclude
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_oneof_take_longest_match(test_segments): """Test that the OneOf grammar takes the longest match.""" fooRegex = RegexParser(r"fo{2}", KeywordSegment) baar = StringParser("baar", KeywordSegment) foo = StringParser("foo", KeywordSegment) fooBaar = Sequence( foo, baar, ) ctx = ParseContext(dialect=None) assert fooRegex.match(test_segments, 2, parse_context=ctx).matched_slice == slice( 2, 3 ) # Even if fooRegex comes first, fooBaar # is a longer match and should be taken assert OneOf(fooRegex, fooBaar).match( test_segments, 2, parse_context=ctx ).matched_slice == slice(2, 4)
Test that the OneOf grammar takes the longest match.
test__parser__grammar_oneof_take_longest_match
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_oneof_take_first(test_segments): """Test that the OneOf grammar takes first match in case they are of same length.""" foo1 = StringParser("foo", Example1Segment) foo2 = StringParser("foo", Example2Segment) ctx = ParseContext(dialect=None) # Both segments would match "foo" # so we test that order matters g1 = OneOf(foo1, foo2) result1 = g1.match(test_segments, 2, ctx) # 2 is the index of "foo" # in g1, the Example1Segment is first. assert result1.matched_class is Example1Segment g2 = OneOf(foo2, foo1) result2 = g2.match(test_segments, 2, ctx) # 2 is the index of "foo" # in g2, the Example2Segment is first. assert result2.matched_class is Example2Segment
Test that the OneOf grammar takes first match in case they are of same length.
test__parser__grammar_oneof_take_first
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_anyof_modes( mode, options, terminators, input_slice, kwargs, output_tuple, structural_parse_mode_test, ): """Test the AnyNumberOf grammar with various parse modes. In particular here we're testing the treatment of unparsable sections. """ structural_parse_mode_test( ["a", " ", "b", " ", "c", "d", " ", "d"], AnyNumberOf, options, terminators, kwargs, mode, input_slice, output_tuple, )
Test the AnyNumberOf grammar with various parse modes. In particular here we're testing the treatment of unparsable sections.
test__parser__grammar_anyof_modes
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_anysetof(generate_test_segments): """Test the AnySetOf grammar.""" token_list = ["bar", " \t ", "foo", " \t ", "bar"] segments = generate_test_segments(token_list) bar = StringParser("bar", KeywordSegment) foo = StringParser("foo", KeywordSegment) g = AnySetOf(foo, bar) ctx = ParseContext(dialect=None) # Check it doesn't match if the start is whitespace. assert not g.match(segments, 1, ctx) # Check structure if we start with a match. result = g.match(segments, 0, ctx) assert result == MatchResult( matched_slice=slice(0, 3), child_matches=( MatchResult( slice(0, 1), KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ), MatchResult( slice(2, 3), KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ), # NOTE: The second "bar" isn't included because this # is any *set* of and we've already have "bar" once. ), )
Test the AnySetOf grammar.
test__parser__grammar_anysetof
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_anyof_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_anyof_test.py
MIT
def test__parser__grammar_delimited( min_delimiters, allow_gaps, allow_trailing, token_list, match_len, caplog, generate_test_segments, fresh_ansi_dialect, ): """Test the Delimited grammar when not code_only.""" test_segments = generate_test_segments(token_list) g = Delimited( StringParser("bar", KeywordSegment), delimiter=StringParser(".", SymbolSegment), allow_gaps=allow_gaps, allow_trailing=allow_trailing, min_delimiters=min_delimiters, ) ctx = ParseContext(dialect=fresh_ansi_dialect) with caplog.at_level(logging.DEBUG, logger="sqlfluff.parser"): # Matching with whitespace shouldn't match if we need at least one delimiter m = g.match(test_segments, 0, ctx) assert len(m) == match_len
Test the Delimited grammar when not code_only.
test__parser__grammar_delimited
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_other_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_other_test.py
MIT
def test__parser__grammar_anything_structure( input_tokens, terminators, output_tuple, structural_parse_mode_test ): """Structure tests for the Anything grammar. NOTE: For most greedy semantics we don't instantiate inner brackets, but in the Anything grammar, the assumption is that we're not coming back to these segments later so we take the time to instantiate any bracketed sections. This is to maintain some backward compatibility with previous parsing behaviour. """ structural_parse_mode_test( input_tokens, Anything, [], terminators, {}, ParseMode.STRICT, slice(None, None), output_tuple, )
Structure tests for the Anything grammar. NOTE: For most greedy semantics we don't instantiate inner brackets, but in the Anything grammar, the assumption is that we're not coming back to these segments later so we take the time to instantiate any bracketed sections. This is to maintain some backward compatibility with previous parsing behaviour.
test__parser__grammar_anything_structure
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_other_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_other_test.py
MIT
def test__parser__grammar_anything_match( terminators, match_length, test_segments, fresh_ansi_dialect ): """Test the Anything grammar. NOTE: Anything combined with terminators implements the semantics which used to be implemented by `GreedyUntil`. """ ctx = ParseContext(dialect=fresh_ansi_dialect) terms = [StringParser(kw, KeywordSegment) for kw in terminators] result = Anything(terminators=terms).match(test_segments, 0, parse_context=ctx) assert result.matched_slice == slice(0, match_length) assert result.matched_class is None # We shouldn't have set a class
Test the Anything grammar. NOTE: Anything combined with terminators implements the semantics which used to be implemented by `GreedyUntil`.
test__parser__grammar_anything_match
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_other_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_other_test.py
MIT
def test__parser__grammar_nothing_match(test_segments, fresh_ansi_dialect): """Test the Nothing grammar.""" ctx = ParseContext(dialect=fresh_ansi_dialect) assert not Nothing().match(test_segments, 0, ctx)
Test the Nothing grammar.
test__parser__grammar_nothing_match
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_other_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_other_test.py
MIT
def test__parser__grammar_noncode_match(test_segments, fresh_ansi_dialect): """Test the NonCodeMatcher.""" ctx = ParseContext(dialect=fresh_ansi_dialect) # NonCode Matcher doesn't work with simple assert NonCodeMatcher().simple(ctx) is None # We should match one and only one segment match = NonCodeMatcher().match(test_segments, 1, parse_context=ctx) assert match assert match.matched_slice == slice(1, 2)
Test the NonCodeMatcher.
test__parser__grammar_noncode_match
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_other_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_other_test.py
MIT
def test__parser__grammar_sequence_repr(): """Test the Sequence grammar __repr__ method.""" bar = StringParser("bar", KeywordSegment) assert repr(bar) == "<StringParser: 'BAR'>" foo = StringParser("foo", KeywordSegment) sequence = Sequence(bar, foo) assert ( repr(sequence) == "<Sequence: [<StringParser: 'BAR'>, <StringParser: 'FOO'>]>" )
Test the Sequence grammar __repr__ method.
test__parser__grammar_sequence_repr
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_sequence_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_sequence_test.py
MIT
def test__parser__grammar_sequence_nested_match(test_segments, caplog): """Test the Sequence grammar when nested.""" bar = StringParser("bar", KeywordSegment) foo = StringParser("foo", KeywordSegment) baar = StringParser("baar", KeywordSegment) g = Sequence(Sequence(bar, foo), baar) ctx = ParseContext(dialect=None) # Confirm the structure of the test segments: assert [s.raw for s in test_segments] == ["bar", " \t ", "foo", "baar", " \t ", ""] with caplog.at_level(logging.DEBUG, logger="sqlfluff.parser"): # Matching just the start of the list shouldn't work. result1 = g.match(test_segments[:3], 0, ctx) assert not result1 # Check it returns falsy with caplog.at_level(logging.DEBUG, logger="sqlfluff.parser"): # Matching the whole list should. result2 = g.match(test_segments, 0, ctx) assert result2 # Check it returns truthy assert result2 == MatchResult( matched_slice=slice(0, 4), # NOTE: One of these is space. child_matches=( MatchResult( matched_slice=slice(0, 1), matched_class=KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ), MatchResult( matched_slice=slice(2, 3), matched_class=KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ), MatchResult( matched_slice=slice(3, 4), matched_class=KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ), ), )
Test the Sequence grammar when nested.
test__parser__grammar_sequence_nested_match
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_sequence_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_sequence_test.py
MIT
def test__parser__grammar_sequence_modes( mode, sequence, terminators, input_slice, output_tuple, structural_parse_mode_test, ): """Test the Sequence grammar with various parse modes. In particular here we're testing the treatment of unparsable sections. """ structural_parse_mode_test( ["a", " ", "b", " ", "c", "d", " ", "d"], Sequence, sequence, terminators, {}, mode, input_slice, output_tuple, )
Test the Sequence grammar with various parse modes. In particular here we're testing the treatment of unparsable sections.
test__parser__grammar_sequence_modes
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_sequence_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_sequence_test.py
MIT
def test__parser__grammar_bracketed_modes( input_seed, mode, sequence, kwargs, output_tuple, structural_parse_mode_test, ): """Test the Bracketed grammar with various parse modes.""" structural_parse_mode_test( input_seed, Bracketed, sequence, [], kwargs, mode, slice(None, None), output_tuple, )
Test the Bracketed grammar with various parse modes.
test__parser__grammar_bracketed_modes
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_sequence_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_sequence_test.py
MIT
def test__parser__grammar_bracketed_error_modes( input_seed, mode, sequence, structural_parse_mode_test, ): """Test the Bracketed grammar with various parse modes.""" with pytest.raises(SQLParseError): structural_parse_mode_test( input_seed, Bracketed, sequence, [], {}, mode, slice(None, None), (), )
Test the Bracketed grammar with various parse modes.
test__parser__grammar_bracketed_error_modes
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_sequence_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_sequence_test.py
MIT
def test__parser__grammar_sequence_indent_conditional_match(test_segments, caplog): """Test the Sequence grammar with indents.""" bar = StringParser("bar", KeywordSegment) foo = StringParser("foo", KeywordSegment) # We will assume the default config has indented_joins = False. # We're testing without explicitly setting the `config_type` because # that's the assumed way of using the grammar in practice. g = Sequence( Dedent, Conditional(Indent, indented_joins=False), bar, Conditional(Indent, indented_joins=True), foo, Dedent, ) ctx = ParseContext(dialect=None) with caplog.at_level(logging.DEBUG, logger="sqlfluff.parser"): m = g.match(test_segments, 0, parse_context=ctx) assert m == MatchResult( matched_slice=slice(0, 3), # NOTE: One of these is space. child_matches=( # The two child keywords MatchResult( matched_slice=slice(0, 1), matched_class=KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ), MatchResult( matched_slice=slice(2, 3), matched_class=KeywordSegment, segment_kwargs={"instance_types": ("keyword",)}, ), ), insert_segments=( (0, Dedent), # The starting, unconditional dedent. (0, Indent), # The conditional (activated) Indent. # NOTE: There *isn't* the other Indent. (3, Dedent), # The closing unconditional dedent. # NOTE: This last one is still included even though it's # after the last matched segment. ), )
Test the Sequence grammar with indents.
test__parser__grammar_sequence_indent_conditional_match
python
sqlfluff/sqlfluff
test/core/parser/grammar/grammar_sequence_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/parser/grammar/grammar_sequence_test.py
MIT
def test__parser__helper_get_encoding(fname, config_encoding, result): """Test get_encoding.""" assert ( get_encoding( fname=fname, config_encoding=config_encoding, ) == result )
Test get_encoding.
test__parser__helper_get_encoding
python
sqlfluff/sqlfluff
test/core/helpers/file_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/file_test.py
MIT
def test__config__iter_config_paths(path, working_path, result): """Test that config paths are fetched ordered by priority.""" cfg_paths = iter_intermediate_paths(Path(path), Path(working_path)) assert [str(p) for p in cfg_paths] == [str(Path(p).resolve()) for p in result]
Test that config paths are fetched ordered by priority.
test__config__iter_config_paths
python
sqlfluff/sqlfluff
test/core/helpers/file_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/file_test.py
MIT
def test__config__iter_config_paths_exc_win(): """Test that config path resolution exception handling works on windows.""" cfg_paths = iter_intermediate_paths(Path("J:\\\\"), Path("C:\\\\")) assert list(cfg_paths) == [Path("C:\\\\"), Path("J:\\\\")]
Test that config path resolution exception handling works on windows.
test__config__iter_config_paths_exc_win
python
sqlfluff/sqlfluff
test/core/helpers/file_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/file_test.py
MIT
def test__config__iter_config_paths_exc_unix(): """Test that config path resolution exception handling works on linux.""" cfg_paths = iter_intermediate_paths(Path("/abc/def"), Path("/ghi/jlk")) # NOTE: `/def` doesn't exist, so we'll use it's parent instead because `.is_dir()` # will return false. This should still test the "zero path length" handling routine. assert list(cfg_paths) == [Path("/"), Path("/abc")]
Test that config path resolution exception handling works on linux.
test__config__iter_config_paths_exc_unix
python
sqlfluff/sqlfluff
test/core/helpers/file_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/file_test.py
MIT
def test__helpers_string__findall(mainstr, substr, positions): """Test _findall.""" assert list(findall(substr, mainstr)) == positions
Test _findall.
test__helpers_string__findall
python
sqlfluff/sqlfluff
test/core/helpers/string_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/string_test.py
MIT
def test__helpers_string__split_comma_separated_string(raw_str, expected): """Tests that string and lists are output correctly.""" assert split_comma_separated_string(raw_str) == expected
Tests that string and lists are output correctly.
test__helpers_string__split_comma_separated_string
python
sqlfluff/sqlfluff
test/core/helpers/string_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/string_test.py
MIT
def test__parser__slice_overlaps_result(s1, s2, result): """Test _findall.""" assert slice_overlaps(s1, s2) == result
Test _findall.
test__parser__slice_overlaps_result
python
sqlfluff/sqlfluff
test/core/helpers/slice_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/slice_test.py
MIT
def test__parser__slice_overlaps_error(s1, s2): """Test assertions of slice_overlaps.""" with pytest.raises(AssertionError): slice_overlaps(s1, s2)
Test assertions of slice_overlaps.
test__parser__slice_overlaps_error
python
sqlfluff/sqlfluff
test/core/helpers/slice_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/slice_test.py
MIT
def test_helpers_dict_doctests(): """Run dict helper doctests. Doctests are important for coverage in this module, and coverage isn't currently picked up when we run the doctests via --doctests. That means in this case we run them directly here. https://stackoverflow.com/questions/45261772/how-to-make-pythons-coverage-library-include-doctests """ doctest.testmod(dict_module)
Run dict helper doctests. Doctests are important for coverage in this module, and coverage isn't currently picked up when we run the doctests via --doctests. That means in this case we run them directly here. https://stackoverflow.com/questions/45261772/how-to-make-pythons-coverage-library-include-doctests
test_helpers_dict_doctests
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__nested_combine(): """Test combination of two config dicts.""" a = {"a": {"b": {"c": 123, "d": 456}}} b = {"b": {"b": {"c": 123, "d": 456}}} c = {"a": {"b": {"c": 234, "e": 456}}} r = nested_combine(a, b, c) assert r == { "a": {"b": {"c": 234, "e": 456, "d": 456}}, "b": {"b": {"c": 123, "d": 456}}, }
Test combination of two config dicts.
test__helpers_dict__nested_combine
python
sqlfluff/sqlfluff
test/core/helpers/dict_test.py
https://github.com/sqlfluff/sqlfluff/blob/master/test/core/helpers/dict_test.py
MIT