-
-
Notifications
You must be signed in to change notification settings - Fork 661
/
jinja_test.py
1866 lines (1763 loc) · 68.3 KB
/
jinja_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for the jinja templater.
These tests also test much of the core lexer, especially
the treatment of templated sections which only really make
sense to test in the context of a templater which supports
loops and placeholders.
"""
import logging
from collections import defaultdict
from pathlib import Path
from typing import List, NamedTuple, Union
import pytest
from jinja2 import Environment, nodes
from jinja2.exceptions import UndefinedError
from jinja2.ext import Extension
from jinja2.nodes import Node
from jinja2.parser import Parser
from sqlfluff.core import FluffConfig, Linter
from sqlfluff.core.errors import SQLFluffSkipFile, SQLFluffUserError, SQLTemplaterError
from sqlfluff.core.parser import BaseSegment
from sqlfluff.core.templaters import JinjaTemplater
from sqlfluff.core.templaters.base import RawFileSlice, TemplatedFile
from sqlfluff.core.templaters.jinja import DummyUndefined
from sqlfluff.core.templaters.slicers.tracer import JinjaAnalyzer, JinjaTagConfiguration
JINJA_STRING = (
"SELECT * FROM {% for c in blah %}{{c}}{% if not loop.last %}, "
"{% endif %}{% endfor %} WHERE {{condition}}\n\n"
)
JINJA_MACRO_CALL_SQL = (
"{% macro render_name(title) %}\n"
" '{{ title }}. foo' as {{ caller() }}\n"
"{% endmacro %}\n"
"SELECT\n"
" {% call render_name('Sir') %}\n"
" bar\n"
" {% endcall %}\n"
"FROM baz\n"
)
def get_parsed(path: str) -> BaseSegment:
"""Testing helper to parse paths."""
linter = Linter()
# Get the first file matching the path string
first_path = next(linter.parse_path(path))
# Delegate parse assertions to the `.tree` property
return first_path.tree
@pytest.mark.parametrize(
"instr, expected_outstr",
[
(
JINJA_STRING,
"SELECT * FROM f, o, o WHERE a < 10\n\n",
),
# Test for issue #968. This was previously raising an UnboundLocalError.
(
"""
{% set event_columns = ['campaign', 'click_item'] %}
SELECT
event_id
{% for event_column in event_columns %}
, {{ event_column }}
{% endfor %}
FROM events
""",
(
"\n\n\nSELECT\n event_id\n \n , campaign\n \n , "
"click_item\n \nFROM events\n "
),
),
],
ids=["simple", "unboundlocal_bugfix"],
)
def test__templater_jinja(instr, expected_outstr):
"""Test jinja templating and the treatment of whitespace."""
t = JinjaTemplater(override_context=dict(blah="foo", condition="a < 10"))
outstr, _ = t.process(
in_str=instr, fname="test", config=FluffConfig(overrides={"dialect": "ansi"})
)
assert str(outstr) == expected_outstr
class RawTemplatedTestCase(NamedTuple):
"""Instances of this object are test cases for test__templater_jinja_slices."""
name: str
instr: str
templated_str: str
# These fields are used to check TemplatedFile.sliced_file.
expected_templated_sliced__source_list: List[str]
expected_templated_sliced__templated_list: List[str]
# This field is used to check TemplatedFile.raw_sliced.
expected_raw_sliced__source_list: List[str]
@pytest.mark.parametrize(
"case",
[
RawTemplatedTestCase(
name="basic_block",
instr="\n\n{% set x = 42 %}\nSELECT 1, 2\n",
templated_str="\n\n\nSELECT 1, 2\n",
expected_templated_sliced__source_list=[
"\n\n",
"{% set x = 42 %}",
"\nSELECT 1, 2\n",
],
expected_templated_sliced__templated_list=[
"\n\n",
"",
"\nSELECT 1, 2\n",
],
expected_raw_sliced__source_list=[
"\n\n",
"{% set x = 42 %}",
"\nSELECT 1, 2\n",
],
),
RawTemplatedTestCase(
name="strip_left_block",
instr="\n\n{%- set x = 42 %}\nSELECT 1, 2\n",
templated_str="\nSELECT 1, 2\n",
expected_templated_sliced__source_list=[
"\n\n",
"{%- set x = 42 %}",
"\nSELECT 1, 2\n",
],
expected_templated_sliced__templated_list=[
"",
"",
"\nSELECT 1, 2\n",
],
expected_raw_sliced__source_list=[
"\n\n",
"{%- set x = 42 %}",
"\nSELECT 1, 2\n",
],
),
RawTemplatedTestCase(
name="strip_both_block",
instr="\n\n{%- set x = 42 -%}\nSELECT 1, 2\n",
templated_str="SELECT 1, 2\n",
expected_templated_sliced__source_list=[
"\n\n",
"{%- set x = 42 -%}",
"\n",
"SELECT 1, 2\n",
],
expected_templated_sliced__templated_list=[
"",
"",
"",
"SELECT 1, 2\n",
],
expected_raw_sliced__source_list=[
"\n\n",
"{%- set x = 42 -%}",
"\n",
"SELECT 1, 2\n",
],
),
RawTemplatedTestCase(
name="strip_and_templated_whitespace",
instr="SELECT {{- ' ' -}} 1{{ ' , 2' -}}\n",
templated_str="SELECT 1 , 2",
expected_templated_sliced__source_list=[
"SELECT",
" ",
"{{- ' ' -}}",
" ",
"1",
"{{ ' , 2' -}}",
"\n",
],
expected_templated_sliced__templated_list=[
"SELECT",
"", # Placeholder for consumed whitespace
" ", # Placeholder for templated whitespace
"", # Placeholder for consumed whitespace
"1",
" , 2",
"", # Placeholder for consumed newline
],
expected_raw_sliced__source_list=[
"SELECT",
" ",
"{{- ' ' -}}",
" ",
"1",
"{{ ' , 2' -}}",
"\n",
],
),
RawTemplatedTestCase(
name="strip_both_block_hard",
instr="SELECT {%- set x = 42 %} 1 {%- if true -%} , 2{% endif -%}\n",
templated_str="SELECT 1, 2",
expected_templated_sliced__source_list=[
"SELECT",
# NB: Even though the jinja tag consumes whitespace, we still
# get it here as a placeholder.
" ",
"{%- set x = 42 %}",
" 1",
# This whitespace is a separate from the 1 because it's consumed.
" ",
"{%- if true -%}",
" ",
", 2",
"{% endif -%}",
"\n",
],
expected_templated_sliced__templated_list=[
"SELECT",
"", # Consumed whitespace placeholder
"", # Jinja block placeholder
" 1",
"", # Consumed whitespace
"", # Jinja block placeholder
"", # More consumed whitespace
", 2",
"", # Jinja block
"", # Consumed final newline.
],
expected_raw_sliced__source_list=[
"SELECT",
" ",
"{%- set x = 42 %}",
" 1",
" ",
"{%- if true -%}",
" ",
", 2",
"{% endif -%}",
"\n",
],
),
RawTemplatedTestCase(
name="basic_data",
instr="""select
c1,
{{ 'c' }}2 as user_id
""",
templated_str="""select
c1,
c2 as user_id
""",
expected_templated_sliced__source_list=[
"select\n c1,\n ",
"{{ 'c' }}",
"2 as user_id\n",
],
expected_templated_sliced__templated_list=[
"select\n c1,\n ",
"c",
"2 as user_id\n",
],
expected_raw_sliced__source_list=[
"select\n c1,\n ",
"{{ 'c' }}",
"2 as user_id\n",
],
),
# Note this is basically identical to the "basic_data" case above.
# "Right strip" is not actually a thing in Jinja.
RawTemplatedTestCase(
name="strip_right_data",
instr="""SELECT
{{ 'col1,' -}}
col2
""",
templated_str="""SELECT
col1,col2
""",
expected_templated_sliced__source_list=[
"SELECT\n ",
"{{ 'col1,' -}}",
"\n ",
"col2\n",
],
expected_templated_sliced__templated_list=[
"SELECT\n ",
"col1,",
"",
"col2\n",
],
expected_raw_sliced__source_list=[
"SELECT\n ",
"{{ 'col1,' -}}",
"\n ",
"col2\n",
],
),
RawTemplatedTestCase(
name="strip_both_data",
instr="""select
c1,
{{- 'c' -}}
2 as user_id
""",
templated_str="""select
c1,c2 as user_id
""",
expected_templated_sliced__source_list=[
"select\n c1,",
"\n ",
"{{- 'c' -}}",
"\n",
"2 as user_id\n",
],
expected_templated_sliced__templated_list=[
"select\n c1,",
"",
"c",
"",
"2 as user_id\n",
],
expected_raw_sliced__source_list=[
"select\n c1,",
"\n ",
"{{- 'c' -}}",
"\n",
"2 as user_id\n",
],
),
RawTemplatedTestCase(
name="strip_both_comment",
instr="""select
c1,
{#- Column 2 -#} c2 as user_id
""",
templated_str="""select
c1,c2 as user_id
""",
expected_templated_sliced__source_list=[
"select\n c1,",
"\n ",
"{#- Column 2 -#}",
" ",
"c2 as user_id\n",
],
expected_templated_sliced__templated_list=[
"select\n c1,",
"",
"",
"",
"c2 as user_id\n",
],
expected_raw_sliced__source_list=[
"select\n c1,",
"\n ",
"{#- Column 2 -#}",
" ",
"c2 as user_id\n",
],
),
RawTemplatedTestCase(
name="union_all_loop1",
instr="""{% set products = [
'table1',
'table2',
] %}
{% for product in products %}
SELECT
brand
FROM
{{ product }}
{% if not loop.last -%} UNION ALL {%- endif %}
{% endfor %}
""",
templated_str=(
"\n\n\nSELECT\n brand\nFROM\n table1\nUNION ALL\n\nSELECT\n "
"brand\nFROM\n table2\n\n\n"
),
expected_templated_sliced__source_list=[
"{% set products = [\n 'table1',\n 'table2',\n ] %}",
"\n\n",
"{% for product in products %}",
"\nSELECT\n brand\nFROM\n ",
"{{ product }}",
"\n",
"{% if not loop.last -%}",
" ",
"UNION ALL",
" ",
"{%- endif %}",
"\n",
"{% endfor %}",
"\nSELECT\n brand\nFROM\n ",
"{{ product }}",
"\n",
"{% if not loop.last -%}",
"{%- endif %}",
"\n",
"{% endfor %}",
"\n",
],
expected_templated_sliced__templated_list=[
"",
"\n\n",
"",
"\nSELECT\n brand\nFROM\n ",
"table1",
"\n",
"",
"",
"UNION ALL",
"",
"",
"\n",
"",
"\nSELECT\n brand\nFROM\n ",
"table2",
"\n",
"",
"",
"\n",
"",
"\n",
],
expected_raw_sliced__source_list=[
"{% set products = [\n 'table1',\n 'table2',\n ] %}",
"\n\n",
"{% for product in products %}",
"\nSELECT\n brand\nFROM\n ",
"{{ product }}",
"\n",
"{% if not loop.last -%}",
" ",
"UNION ALL",
" ",
"{%- endif %}",
"\n",
"{% endfor %}",
"\n",
],
),
RawTemplatedTestCase(
"set_multiple_variables_and_define_macro",
"""{% macro echo(text) %}
{{text}}
{% endmacro %}
{% set a, b = 1, 2 %}
SELECT
{{ echo(a) }},
{{ echo(b) }}""",
"\n\n\n\nSELECT\n \n1\n,\n \n2\n",
[
"{% macro echo(text) %}",
"\n",
"{{text}}",
"\n",
"{% endmacro %}",
"\n\n",
"{% set a, b = 1, 2 %}",
"\n\nSELECT\n ",
"{{ echo(a) }}",
",\n ",
"{{ echo(b) }}",
],
[
"",
"",
"",
"",
"",
"\n\n",
"",
"\n\nSELECT\n ",
"\n1\n",
",\n ",
"\n2\n",
],
[
"{% macro echo(text) %}",
"\n",
"{{text}}",
"\n",
"{% endmacro %}",
"\n\n",
"{% set a, b = 1, 2 %}",
"\n\nSELECT\n ",
"{{ echo(a) }}",
",\n ",
"{{ echo(b) }}",
],
),
],
ids=lambda case: case.name,
)
def test__templater_jinja_slices(case: RawTemplatedTestCase):
"""Test that Jinja templater slices raw and templated file correctly."""
t = JinjaTemplater()
templated_file, _ = t.process(
in_str=case.instr,
fname="test",
config=FluffConfig(overrides={"dialect": "ansi"}),
)
assert templated_file is not None
assert templated_file.source_str == case.instr
assert templated_file.templated_str == case.templated_str
# Build and check the list of source strings referenced by "sliced_file".
actual_ts_source_list = [
case.instr[ts.source_slice] for ts in templated_file.sliced_file
]
assert actual_ts_source_list == case.expected_templated_sliced__source_list
# Build and check the list of templated strings referenced by "sliced_file".
actual_ts_templated_list = [
templated_file.templated_str[ts.templated_slice]
for ts in templated_file.sliced_file
]
assert actual_ts_templated_list == case.expected_templated_sliced__templated_list
# Build and check the list of source strings referenced by "raw_sliced".
previous_rs = None
actual_rs_source_list: List[RawFileSlice] = []
for rs in templated_file.raw_sliced + [None]: # type: ignore
if previous_rs:
if rs:
actual_source = case.instr[previous_rs.source_idx : rs.source_idx]
else:
actual_source = case.instr[previous_rs.source_idx :]
actual_rs_source_list.append(actual_source)
previous_rs = rs
assert actual_rs_source_list == case.expected_raw_sliced__source_list
def test_templater_set_block_handling():
"""Test handling of literals in {% set %} blocks.
Specifically, verify they are not modified in the alternate template.
"""
def run_query(sql):
# Prior to the bug fix, this assertion failed. This was bad because,
# inside JinjaTracer, dbt templates similar to the one in this test
# would call the database with funky SQL (including weird strings it
# uses internally like: 00000000000000000000000000000002.
assert sql == "\n\nselect 1 from foobarfoobarfoobarfoobar_dev\n\n"
return sql
t = JinjaTemplater(override_context=dict(run_query=run_query))
instr = """{% set my_query1 %}
select 1 from foobarfoobarfoobarfoobar_{{ "dev" }}
{% endset %}
{% set my_query2 %}
{{ my_query1 }}
{% endset %}
{{ run_query(my_query2) }}
"""
outstr, vs = t.process(
in_str=instr, fname="test", config=FluffConfig(overrides={"dialect": "ansi"})
)
assert str(outstr) == "\n\n\n\n\nselect 1 from foobarfoobarfoobarfoobar_dev\n\n\n"
assert len(vs) == 0
def test__templater_jinja_error_variable():
"""Test missing variable error handling in the jinja templater."""
t = JinjaTemplater(override_context=dict(blah="foo"))
instr = JINJA_STRING
outstr, vs = t.process(
in_str=instr, fname="test", config=FluffConfig(overrides={"dialect": "ansi"})
)
assert str(outstr) == "SELECT * FROM f, o, o WHERE \n\n"
# Check we have violations.
assert len(vs) > 0
# Check one of them is a templating error on line 1
assert any(v.rule_code() == "TMP" and v.line_no == 1 for v in vs)
def test__templater_jinja_dynamic_variable_no_violations():
"""Test no templater violation for variable defined within template."""
t = JinjaTemplater(override_context=dict(blah="foo"))
instr = """{% if True %}
{% set some_var %}1{% endset %}
SELECT {{some_var}}
{% endif %}
"""
outstr, vs = t.process(
in_str=instr, fname="test", config=FluffConfig(overrides={"dialect": "ansi"})
)
assert str(outstr) == "\n \n SELECT 1\n\n"
# Check we have no violations.
assert len(vs) == 0
def test__templater_jinja_error_syntax():
"""Test syntax problems in the jinja templater."""
t = JinjaTemplater()
instr = "SELECT {{foo} FROM jinja_error\n"
with pytest.raises(SQLTemplaterError) as excinfo:
t.process(
in_str=instr,
fname="test",
config=FluffConfig(overrides={"dialect": "ansi"}),
)
templater_exception = excinfo.value
assert templater_exception.rule_code() == "TMP"
assert templater_exception.line_no == 1
assert "Failed to parse Jinja syntax" in str(templater_exception)
def test__templater_jinja_error_catastrophic():
"""Test error handling in the jinja templater."""
t = JinjaTemplater(override_context=dict(blah=7))
instr = JINJA_STRING
with pytest.raises(SQLTemplaterError) as excinfo:
t.process(
in_str=instr,
fname="test",
config=FluffConfig(overrides={"dialect": "ansi"}),
)
templater_exception = excinfo.value
assert templater_exception.rule_code() == "TMP"
assert templater_exception.line_no == 1
assert "Unrecoverable failure in Jinja templating" in str(templater_exception)
def test__templater_jinja_error_macro_path_does_not_exist():
"""Tests that an error is raised if macro path doesn't exist."""
with pytest.raises(ValueError) as e:
JinjaTemplater().construct_render_func(
config=FluffConfig.from_path(
"test/fixtures/templater/jinja_macro_path_does_not_exist"
)
)
assert str(e.value).startswith("Path does not exist")
def test__templater_jinja_error_macro_invalid():
"""Tests that an error is raised if a macro is invalid."""
invalid_macro_config_string = (
"[sqlfluff]\n"
"templater = jinja\n"
"dialect = ansi\n"
"[sqlfluff:templater:jinja:macros]\n"
"a_macro_def = {% macro pkg.my_macro() %}pass{% endmacro %}\n"
)
config = FluffConfig.from_string(invalid_macro_config_string)
with pytest.raises(SQLFluffUserError) as e:
JinjaTemplater().construct_render_func(config=config)
error_string = str(e.value)
assert error_string.startswith("Error loading user provided macro")
assert "{% macro pkg.my_macro() %}pass{% endmacro %}" in error_string
def test__templater_jinja_lint_empty():
"""Check that parsing a file which renders to an empty string.
No exception should be raised, and we should get a single templated element.
"""
lntr = Linter(dialect="ansi")
parsed = lntr.parse_string(in_str='{{ "" }}')
parsed_variant = parsed.parsed_variants[0]
assert parsed_variant.templated_file.source_str == '{{ "" }}'
assert parsed_variant.templated_file.templated_str == ""
# Get the types of the segments
print(f"Segments: {parsed_variant.tree.raw_segments}")
seg_types = [seg.get_type() for seg in parsed_variant.tree.raw_segments]
assert seg_types == ["placeholder", "end_of_file"]
def assert_structure(yaml_loader, path, code_only=True, include_meta=False):
"""Check that a parsed sql file matches the yaml file with the same name."""
parsed = get_parsed(path + ".sql")
# Whitespace is important here to test how that's treated
tpl = parsed.to_tuple(code_only=code_only, show_raw=True, include_meta=include_meta)
# Check nothing unparsable
if "unparsable" in parsed.type_set():
print(parsed.stringify())
raise ValueError("Input file is unparsable.")
_, expected = yaml_loader(path + ".yml")
assert tpl == expected
@pytest.mark.parametrize(
"subpath,code_only,include_meta",
[
# Config Scalar
("jinja_a/jinja", True, False),
# Macros
("jinja_b/jinja", False, False),
# dbt builtins
("jinja_c_dbt/dbt_builtins_cross_ref", True, False),
("jinja_c_dbt/dbt_builtins_config", True, False),
("jinja_c_dbt/dbt_builtins_is_incremental", True, False),
("jinja_c_dbt/dbt_builtins_ref", True, False),
("jinja_c_dbt/dbt_builtins_source", True, False),
("jinja_c_dbt/dbt_builtins_this", True, False),
("jinja_c_dbt/dbt_builtins_var_default", True, False),
("jinja_c_dbt/dbt_builtins_test", True, False),
# do directive
("jinja_e/jinja", True, False),
# case sensitivity and python literals
("jinja_f/jinja", True, False),
# Macro loading from a folder
("jinja_g_macros/jinja", True, False),
# jinja raw tag
("jinja_h_macros/jinja", True, False),
("jinja_i_raw/raw_tag", True, False),
("jinja_i_raw/raw_tag_2", True, False),
# Library Loading from a folder
("jinja_j_libraries/jinja", True, False),
# Priority of macros
("jinja_k_config_override_path_macros/jinja", True, False),
# Placeholders and metas
("jinja_l_metas/001", False, True),
("jinja_l_metas/002", False, True),
("jinja_l_metas/003", False, True),
("jinja_l_metas/004", False, True),
("jinja_l_metas/005", False, True),
("jinja_l_metas/006", False, True),
("jinja_l_metas/007", False, True),
("jinja_l_metas/008", False, True),
("jinja_l_metas/009", False, True),
("jinja_l_metas/010", False, True),
("jinja_l_metas/011", False, True),
# Library Loading from a folder when library is module
("jinja_m_libraries_module/jinja", True, False),
("jinja_n_nested_macros/jinja", True, False),
# Test more dbt configurations
("jinja_o_config_override_dbt_builtins/override_dbt_builtins", True, False),
("jinja_p_disable_dbt_builtins/disable_dbt_builtins", True, False),
# Load all the macros
("jinja_q_multiple_path_macros/jinja", True, False),
("jinja_s_filters_in_library/jinja", True, False),
# Jinja loader search path, without also loading macros into global namespace
("jinja_t_loader_search_path/jinja", True, False),
],
)
def test__templater_full(subpath, code_only, include_meta, yaml_loader, caplog):
"""Check structure can be parsed from jinja templated files."""
# Log the templater and lexer throughout this test
caplog.set_level(logging.DEBUG, logger="sqlfluff.templater")
caplog.set_level(logging.DEBUG, logger="sqlfluff.lexer")
assert_structure(
yaml_loader,
"test/fixtures/templater/" + subpath,
code_only=code_only,
include_meta=include_meta,
)
def test__templater_jinja_block_matching(caplog):
"""Test the block UUID matching works with a complicated case."""
caplog.set_level(logging.DEBUG, logger="sqlfluff.lexer")
path = "test/fixtures/templater/jinja_l_metas/002.sql"
# Parse the file.
parsed = get_parsed(path)
# We only care about the template elements
template_segments = [
seg
for seg in parsed.raw_segments
if seg.is_type("template_loop")
or (
seg.is_type("placeholder")
and seg.block_type in ("block_start", "block_end", "block_mid")
)
]
# Group them together by block UUID
assert all(
seg.block_uuid for seg in template_segments
), "All templated segments should have a block uuid!"
grouped = defaultdict(list)
for seg in template_segments:
grouped[seg.block_uuid].append(seg.pos_marker.working_loc)
print(grouped)
# Now the matching block IDs should be found at the following positions.
# NOTE: These are working locations in the rendered file.
groups = {
"for actions clause 1": [(6, 5), (9, 5), (12, 5), (15, 5)],
"for actions clause 2": [(17, 5), (21, 5), (29, 5), (37, 5)],
# NOTE: all the if loop clauses are grouped together.
"if loop.first": [
(18, 9),
(20, 9),
(20, 9),
(22, 9),
(22, 9),
(28, 9),
(30, 9),
(30, 9),
(36, 9),
],
}
# Check all are accounted for:
for clause in groups.keys():
for block_uuid, locations in grouped.items():
if groups[clause] == locations:
print(f"Found {clause}, locations with UUID: {block_uuid}")
break
else:
raise ValueError(f"Couldn't find appropriate grouping of blocks: {clause}")
class DerivedJinjaAnalyzer(JinjaAnalyzer):
"""An analyzer that includes some custom Jinja tags.
This is used for tests that show the analyzer can be extended for custom plugin
templaters that support custom tags.
"""
@classmethod
def _get_tag_configuration(cls, tag: str) -> JinjaTagConfiguration:
tag_map = {
"up": JinjaTagConfiguration(
block_type="block_start",
block_tracking=True,
),
"down": JinjaTagConfiguration(
block_type="block_mid",
block_tracking=True,
),
"end": JinjaTagConfiguration(
block_type="block_end",
block_tracking=True,
),
}
return tag_map.get(tag, super()._get_tag_configuration(tag))
@pytest.mark.parametrize(
"test,result,analyzer_class",
[
("", [], JinjaAnalyzer),
("foo", [("foo", "literal", 0)], JinjaAnalyzer),
(
"foo {{bar}} z ",
[
("foo ", "literal", 0),
("{{bar}}", "templated", 4),
(" z ", "literal", 11),
],
JinjaAnalyzer,
),
(
(
"SELECT {# A comment #} {{field}} {% for i in [1, 3]%}, "
"fld_{{i}}{% endfor %} FROM my_schema.{{my_table}} "
),
[
("SELECT ", "literal", 0),
("{# A comment #}", "comment", 7),
(" ", "literal", 22),
("{{field}}", "templated", 23),
(" ", "literal", 32),
("{% for i in [1, 3]%}", "block_start", 33, 1, "for"),
(", fld_", "literal", 53, 1),
("{{i}}", "templated", 59, 1),
("{% endfor %}", "block_end", 64, 1, "endfor"),
(" FROM my_schema.", "literal", 76, 2),
("{{my_table}}", "templated", 92, 2),
(" ", "literal", 104, 2),
],
JinjaAnalyzer,
),
(
"{% set thing %}FOO{% endset %} BAR",
[
("{% set thing %}", "block_start", 0, 1, "set"),
("FOO", "literal", 15, 1),
("{% endset %}", "block_end", 18, 1, "endset"),
(" BAR", "literal", 30, 2),
],
JinjaAnalyzer,
),
(
# Tests Jinja "block assignment" syntax. Also tests the use of
# template substitution within the block: {{ "dev" }}.
"""{% set my_query %}
select 1 from foobarfoobarfoobarfoobar_{{ "dev" }}
{% endset %}
{{ my_query }}
""",
[
("{% set my_query %}", "block_start", 0, 1, "set"),
("\nselect 1 from foobarfoobarfoobarfoobar_", "literal", 18, 1),
('{{ "dev" }}', "templated", 58, 1),
("\n", "literal", 69, 1),
("{% endset %}", "block_end", 70, 1, "endset"),
("\n", "literal", 82, 2),
("{{ my_query }}", "templated", 83, 2),
("\n", "literal", 97, 2),
],
JinjaAnalyzer,
),
# Tests for jinja blocks that consume whitespace.
(
"""SELECT 1 FROM {%+if true-%} {{ref('foo')}} {%-endif%}""",
[
("SELECT 1 FROM ", "literal", 0),
("{%+if true-%}", "block_start", 14, 1, "if"),
(" ", "literal", 27, 1),
("{{ref('foo')}}", "templated", 28, 1),
(" ", "literal", 42, 1),
("{%-endif%}", "block_end", 43, 1, "endif"),
],
JinjaAnalyzer,
),
(
"""{% for item in some_list -%}
SELECT *
FROM some_table
{{ "UNION ALL\n" if not loop.last }}
{%- endfor %}""",
[
("{% for item in some_list -%}", "block_start", 0, 1, "for"),
# This gets consumed in the templated file, but it's still here.
("\n ", "literal", 28, 1),
("SELECT *\n FROM some_table\n", "literal", 33, 1),
('{{ "UNION ALL\n" if not loop.last }}', "templated", 62, 1),
("\n", "literal", 97, 1),
("{%- endfor %}", "block_end", 98, 1, "endfor"),
],
JinjaAnalyzer,
),
(
JINJA_MACRO_CALL_SQL,
[
("{% macro render_name(title) %}", "block_start", 0, 1, "macro"),
("\n" " '", "literal", 30, 1),
("{{ title }}", "templated", 34, 1),
(". foo' as ", "literal", 45, 1),
("{{ caller() }}", "templated", 55, 1),
("\n", "literal", 69, 1),
("{% endmacro %}", "block_end", 70, 1, "endmacro"),
("\n" "SELECT\n" " ", "literal", 84, 2),
("{% call render_name('Sir') %}", "block_start", 96, 3, "call"),
("\n" " bar\n" " ", "literal", 125, 3),
("{% endcall %}", "block_end", 142, 3, "endcall"),
("\n" "FROM baz\n", "literal", 155, 4),
],
JinjaAnalyzer,
),
(
# Test of tag heuristics in the default _get_tag_configuration
"""{% randomtagstart %}
SELECT 1;
{% elphony %}
SELECT 2;
{% endsomethingweird %}""",
[
("{% randomtagstart %}", "block_start", 0, 1, "randomtagstart"),
("\n SELECT 1;\n", "literal", 20, 1),
("{% elphony %}", "block_mid", 35, 1, "elphony"),
("\n SELECT 2;\n", "literal", 48, 1),
("{% endsomethingweird %}", "block_end", 63, 1, "endsomethingweird"),
],
JinjaAnalyzer,
),
(
# Basic test with a derived JinjaAnalyzer that supports some custom tags
"""{% up 'create table xyz' %}
CREATE TABLE xyz (id int);
{% down %}
DROP TABLE xyz;
{% end %}""",
[
("{% up 'create table xyz' %}", "block_start", 0, 1, "up"),
("\n CREATE TABLE xyz (id int);\n", "literal", 27, 1),
("{% down %}", "block_mid", 59, 1, "down"),
("\n DROP TABLE xyz;\n", "literal", 69, 1),
("{% end %}", "block_end", 90, 1, "end"),
],
DerivedJinjaAnalyzer,
),
],
)
def test__templater_jinja_slice_template(test, result, analyzer_class):
"""Test _slice_template."""
templater = JinjaTemplater()
env, _, render_func = templater.construct_render_func()
analyzer = analyzer_class(test, env)
analyzer.analyze(render_func=render_func)
resp = analyzer.raw_sliced
# check contiguous (unless there's a comment in it)
if "{#" not in test:
assert "".join(elem.raw for elem in resp) == test