-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathtest_model.py
More file actions
1116 lines (960 loc) · 39.5 KB
/
test_model.py
File metadata and controls
1116 lines (960 loc) · 39.5 KB
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
import datetime
import logging
import pytest
from pathlib import Path
from sqlglot import exp
from sqlglot.errors import SchemaError
from sqlmesh import Context
from sqlmesh.core.console import NoopConsole, get_console
from sqlmesh.core.model import TimeColumn, IncrementalByTimeRangeKind
from sqlmesh.core.model.kind import OnDestructiveChange, OnAdditiveChange, SCDType2ByColumnKind
from sqlmesh.core.state_sync.db.snapshot import _snapshot_to_json
from sqlmesh.core.config.common import VirtualEnvironmentMode
from sqlmesh.core.model.meta import GrantsTargetLayer
from sqlmesh.dbt.common import Dependencies
from sqlmesh.dbt.context import DbtContext
from sqlmesh.dbt.model import ModelConfig
from sqlmesh.dbt.target import BigQueryConfig, DuckDbConfig, PostgresConfig
from sqlmesh.dbt.test import TestConfig
from sqlmesh.utils.yaml import YAML
from sqlmesh.utils.date import to_ds
import typing as t
pytestmark = pytest.mark.dbt
def test_test_config_is_standalone_behavior() -> None:
"""Test that TestConfig.is_standalone correctly identifies tests with cross-model references"""
# Test with no model_name (should be standalone)
standalone_test = TestConfig(
name="standalone_test",
sql="SELECT 1",
model_name=None,
dependencies=Dependencies(refs={"some_model"}),
)
assert standalone_test.is_standalone is True
# Test with only self-reference (should not be standalone)
self_ref_test = TestConfig(
name="self_ref_test",
sql="SELECT * FROM {{ this }}",
model_name="my_model",
dependencies=Dependencies(refs={"my_model"}),
)
assert self_ref_test.is_standalone is False
# Test with no references (should not be standalone)
no_ref_test = TestConfig(
name="no_ref_test",
sql="SELECT 1",
model_name="my_model",
dependencies=Dependencies(),
)
assert no_ref_test.is_standalone is False
# Test with references to other models (should be standalone)
cross_ref_test = TestConfig(
name="cross_ref_test",
sql="SELECT * FROM {{ ref('other_model') }}",
model_name="my_model",
dependencies=Dependencies(refs={"my_model", "other_model"}),
)
assert cross_ref_test.is_standalone is True
# Test with only references to other models, no self-reference (should be standalone)
other_only_test = TestConfig(
name="other_only_test",
sql="SELECT * FROM {{ ref('other_model') }}",
model_name="my_model",
dependencies=Dependencies(refs={"other_model"}),
)
assert other_only_test.is_standalone is True
def test_test_to_sqlmesh_creates_correct_audit_type(
dbt_dummy_postgres_config: PostgresConfig,
) -> None:
"""Test that TestConfig.to_sqlmesh creates the correct audit type based on is_standalone"""
from sqlmesh.core.audit.definition import StandaloneAudit, ModelAudit
# Set up models in context
my_model = ModelConfig(
name="my_model", sql="SELECT 1", schema="test_schema", database="test_db", alias="my_model"
)
other_model = ModelConfig(
name="other_model",
sql="SELECT 2",
schema="test_schema",
database="test_db",
alias="other_model",
)
context = DbtContext(
_refs={"my_model": my_model, "other_model": other_model},
_target=dbt_dummy_postgres_config,
)
# Test with only self-reference (should create ModelAudit)
self_ref_test = TestConfig(
name="self_ref_test",
sql="SELECT * FROM {{ this }}",
model_name="my_model",
dependencies=Dependencies(refs={"my_model"}),
)
audit = self_ref_test.to_sqlmesh(context)
assert isinstance(audit, ModelAudit)
assert audit.name == "self_ref_test"
# Test with references to other models (should create StandaloneAudit)
cross_ref_test = TestConfig(
name="cross_ref_test",
sql="SELECT * FROM {{ ref('other_model') }}",
model_name="my_model",
dependencies=Dependencies(refs={"my_model", "other_model"}),
)
audit = cross_ref_test.to_sqlmesh(context)
assert isinstance(audit, StandaloneAudit)
assert audit.name == "cross_ref_test"
# Test with no model_name (should create StandaloneAudit)
standalone_test = TestConfig(
name="standalone_test",
sql="SELECT 1",
model_name=None,
dependencies=Dependencies(),
)
audit = standalone_test.to_sqlmesh(context)
assert isinstance(audit, StandaloneAudit)
assert audit.name == "standalone_test"
@pytest.mark.slow
def test_manifest_filters_standalone_tests_from_models(
tmp_path: Path, create_empty_project
) -> None:
"""Integration test that verifies models only contain non-standalone tests after manifest loading."""
yaml = YAML()
project_dir, model_dir = create_empty_project(project_name="local")
# Create two models
model1_contents = "SELECT 1 as id"
model1_file = model_dir / "model1.sql"
with open(model1_file, "w", encoding="utf-8") as f:
f.write(model1_contents)
model2_contents = "SELECT 2 as id"
model2_file = model_dir / "model2.sql"
with open(model2_file, "w", encoding="utf-8") as f:
f.write(model2_contents)
# Create schema with both standalone and non-standalone tests
schema_yaml = {
"version": 2,
"models": [
{
"name": "model1",
"columns": [
{
"name": "id",
"tests": [
"not_null", # Non-standalone test - only references model1
{
"relationships": { # Standalone test - references model2
"to": "ref('model2')",
"field": "id",
}
},
],
}
],
},
{
"name": "model2",
"columns": [
{"name": "id", "tests": ["not_null"]} # Non-standalone test
],
},
],
}
schema_file = model_dir / "schema.yml"
with open(schema_file, "w", encoding="utf-8") as f:
yaml.dump(schema_yaml, f)
# Load the project through SQLMesh Context
from sqlmesh.core.context import Context
context = Context(paths=project_dir)
model1_snapshot = context.snapshots['"local"."main"."model1"']
model2_snapshot = context.snapshots['"local"."main"."model2"']
# Verify model1 only has non-standalone test in its audits
# Should only have "not_null" test, not the "relationships" test
model1_audit_names = [audit[0] for audit in model1_snapshot.model.audits]
assert len(model1_audit_names) == 1
assert model1_audit_names[0] == "local.not_null_model1_id"
# Verify model2 has its non-standalone test
model2_audit_names = [audit[0] for audit in model2_snapshot.model.audits]
assert len(model2_audit_names) == 1
assert model2_audit_names[0] == "local.not_null_model2_id"
# Verify the standalone test (relationships) exists as a StandaloneAudit
all_non_standalone_audits = [name for name in context._audits]
assert sorted(all_non_standalone_audits) == [
"local.not_null_model1_id",
"local.not_null_model2_id",
]
standalone_audits = [name for name in context._standalone_audits]
assert len(standalone_audits) == 1
assert standalone_audits[0] == "local.relationships_model1_id__id__ref_model2_"
plan_builder = context.plan_builder()
dag = plan_builder._build_dag()
assert [x.name for x in dag.sorted] == [
'"local"."main"."model1"',
'"local"."main"."model2"',
"relationships_model1_id__id__ref_model2_",
]
@pytest.mark.slow
def test_load_invalid_ref_audit_constraints(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
yaml = YAML()
project_dir, model_dir = create_empty_project(project_name="local")
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
full_model_contents = """{{ config(tags=["blah"], tests=[{"blah": {"to": "ref('completely_ignored')", "field": "blah2"} }]) }} SELECT 1 as cola"""
full_model_file = model_dir / "full_model.sql"
with open(full_model_file, "w", encoding="utf-8") as f:
f.write(full_model_contents)
model_schema = {
"version": 2,
"models": [
{
"name": "full_model",
"description": "A full model bad ref for audit and constraints",
"columns": [
{
"name": "cola",
"description": "A column that is used in a ref audit and constraints",
"constraints": [
{
"type": "primary_key",
"columns": ["cola"],
"expression": "ref('not_real_model') (cola)",
}
],
"tests": [
{
# References a model that doesn't exist
"relationships": {
"to": "ref('not_real_model')",
"field": "cola",
},
},
{
# Reference a source that doesn't exist
"relationships": {
"to": "source('not_real_source', 'not_real_table')",
"field": "cola",
},
},
],
}
],
}
],
}
model_schema_file = model_dir / "schema.yml"
with open(model_schema_file, "w", encoding="utf-8") as f:
yaml.dump(model_schema, f)
assert isinstance(get_console(), NoopConsole)
with caplog.at_level(logging.DEBUG):
context = Context(paths=project_dir)
assert (
"Skipping audit 'relationships_full_model_cola__cola__ref_not_real_model_' because model 'not_real_model' is not a valid ref"
in caplog.text
)
assert (
"Skipping audit 'relationships_full_model_cola__cola__source_not_real_source_not_real_table_' because source 'not_real_source.not_real_table' is not a valid ref"
in caplog.text
)
fqn = '"local"."main"."full_model"'
assert fqn in context.snapshots
# The audit isn't loaded due to the invalid ref
assert context.snapshots[fqn].model.audits == []
@pytest.mark.slow
def test_load_microbatch_all_defined(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
project_dir, model_dir = create_empty_project(project_name="local")
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
microbatch_contents = """
{{
config(
materialized='incremental',
incremental_strategy='microbatch',
event_time='ds',
begin='2020-01-01',
batch_size='day',
lookback=2,
concurrent_batches=true
)
}}
SELECT 1 as cola, '2025-01-01' as ds
"""
microbatch_model_file = model_dir / "microbatch.sql"
with open(microbatch_model_file, "w", encoding="utf-8") as f:
f.write(microbatch_contents)
snapshot_fqn = '"local"."main"."microbatch"'
context = Context(paths=project_dir)
model = context.snapshots[snapshot_fqn].model
# Validate model-level attributes
assert model.start == datetime.datetime(2020, 1, 1, 0, 0)
assert model.interval_unit.is_day
# Validate model kind attributes
assert isinstance(model.kind, IncrementalByTimeRangeKind)
assert model.kind.lookback == 2
assert model.kind.time_column == TimeColumn(
column=exp.to_column("ds", quoted=True), format="%Y-%m-%d"
)
assert model.kind.batch_size == 1
assert model.depends_on_self is False
@pytest.mark.slow
def test_load_microbatch_all_defined_diff_values(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
project_dir, model_dir = create_empty_project(project_name="local")
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
microbatch_contents = """
{{
config(
materialized='incremental',
incremental_strategy='microbatch',
cron='@yearly',
event_time='blah',
begin='2022-01-01',
batch_size='year',
lookback=20,
concurrent_batches=false
)
}}
SELECT 1 as cola, '2022-01-01' as blah
"""
microbatch_model_file = model_dir / "microbatch.sql"
with open(microbatch_model_file, "w", encoding="utf-8") as f:
f.write(microbatch_contents)
snapshot_fqn = '"local"."main"."microbatch"'
context = Context(paths=project_dir)
model = context.snapshots[snapshot_fqn].model
# Validate model-level attributes
assert model.start == datetime.datetime(2022, 1, 1, 0, 0)
assert model.interval_unit.is_year
# Validate model kind attributes
assert isinstance(model.kind, IncrementalByTimeRangeKind)
assert model.kind.lookback == 20
assert model.kind.time_column == TimeColumn(
column=exp.to_column("blah", quoted=True), format="%Y-%m-%d"
)
assert model.kind.batch_size == 1
assert model.depends_on_self is True
@pytest.mark.slow
def test_load_microbatch_required_only(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
project_dir, model_dir = create_empty_project(project_name="local")
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
microbatch_contents = """
{{
config(
materialized='incremental',
incremental_strategy='microbatch',
begin='2021-01-01',
event_time='ds',
batch_size='hour',
)
}}
SELECT 1 as cola, '2021-01-01' as ds
"""
microbatch_model_file = model_dir / "microbatch.sql"
with open(microbatch_model_file, "w", encoding="utf-8") as f:
f.write(microbatch_contents)
snapshot_fqn = '"local"."main"."microbatch"'
context = Context(paths=project_dir)
model = context.snapshots[snapshot_fqn].model
# Validate model-level attributes
assert model.start == datetime.datetime(2021, 1, 1, 0, 0)
assert model.interval_unit.is_hour
# Validate model kind attributes
assert isinstance(model.kind, IncrementalByTimeRangeKind)
assert model.kind.lookback == 1
assert model.kind.time_column == TimeColumn(
column=exp.to_column("ds", quoted=True), format="%Y-%m-%d"
)
assert model.kind.batch_size == 1
assert model.depends_on_self is False
@pytest.mark.slow
def test_load_incremental_time_range_strategy_required_only(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
project_dir, model_dir = create_empty_project(project_name="local", start="2025-01-01")
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
incremental_time_range_contents = """
{{
config(
materialized='incremental',
incremental_strategy='incremental_by_time_range',
time_column='ds',
)
}}
SELECT 1 as cola, '2021-01-01' as ds
"""
incremental_time_range_model_file = model_dir / "incremental_time_range.sql"
with open(incremental_time_range_model_file, "w", encoding="utf-8") as f:
f.write(incremental_time_range_contents)
snapshot_fqn = '"local"."main"."incremental_time_range"'
context = Context(paths=project_dir)
snapshot = context.snapshots[snapshot_fqn]
model = snapshot.model
# Validate model-level attributes
assert to_ds(model.start or "") == "2025-01-01"
assert model.interval_unit.is_day
# Validate model kind attributes
assert isinstance(model.kind, IncrementalByTimeRangeKind)
assert model.kind.lookback == 1
assert model.kind.time_column == TimeColumn(
column=exp.to_column("ds", quoted=True), format="%Y-%m-%d"
)
assert model.kind.batch_size is None
assert model.depends_on_self is False
assert model.kind.auto_restatement_intervals is None
assert model.kind.partition_by_time_column is True
# make sure the snapshot can be serialized to json
assert isinstance(_snapshot_to_json(snapshot), str)
@pytest.mark.slow
def test_load_incremental_time_range_strategy_all_defined(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
project_dir, model_dir = create_empty_project(project_name="local", start="2025-01-01")
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
incremental_time_range_contents = """
{{
config(
materialized='incremental',
incremental_strategy='incremental_by_time_range',
time_column={
'column': 'ds',
'format': '%Y%m%d'
},
auto_restatement_intervals=3,
partition_by_time_column=false,
lookback=5,
batch_size=3,
batch_concurrency=2,
forward_only=true,
disable_restatement=true,
on_destructive_change='allow',
on_additive_change='error',
auto_restatement_cron='@hourly',
on_schema_change='ignore'
)
}}
SELECT 1 as cola, '2021-01-01' as ds
"""
incremental_time_range_model_file = model_dir / "incremental_time_range.sql"
with open(incremental_time_range_model_file, "w", encoding="utf-8") as f:
f.write(incremental_time_range_contents)
snapshot_fqn = '"local"."main"."incremental_time_range"'
context = Context(paths=project_dir)
snapshot = context.snapshots[snapshot_fqn]
model = snapshot.model
# Validate model-level attributes
assert to_ds(model.start or "") == "2025-01-01"
assert model.interval_unit.is_day
# Validate model kind attributes
assert isinstance(model.kind, IncrementalByTimeRangeKind)
# `on_schema_change` is ignored since the user explicitly overrode the values
assert model.kind.on_destructive_change == OnDestructiveChange.ALLOW
assert model.kind.on_additive_change == OnAdditiveChange.ERROR
assert model.kind.forward_only is True
assert model.kind.disable_restatement is True
assert model.kind.auto_restatement_cron == "@hourly"
assert model.kind.auto_restatement_intervals == 3
assert model.kind.partition_by_time_column is False
assert model.kind.lookback == 5
assert model.kind.time_column == TimeColumn(
column=exp.to_column("ds", quoted=True), format="%Y%m%d"
)
assert model.kind.batch_size == 3
assert model.kind.batch_concurrency == 2
assert model.depends_on_self is False
# make sure the snapshot can be serialized to json
assert isinstance(_snapshot_to_json(snapshot), str)
@pytest.mark.slow
def test_load_deprecated_incremental_time_column(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
project_dir, model_dir = create_empty_project(project_name="local", start="2025-01-01")
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
incremental_time_range_contents = """
{{
config(
materialized='incremental',
incremental_strategy='delete+insert',
time_column='ds'
)
}}
SELECT 1 as cola, '2021-01-01' as ds
"""
incremental_time_range_model_file = model_dir / "incremental_time_range.sql"
with open(incremental_time_range_model_file, "w", encoding="utf-8") as f:
f.write(incremental_time_range_contents)
snapshot_fqn = '"local"."main"."incremental_time_range"'
assert isinstance(get_console(), NoopConsole)
with caplog.at_level(logging.DEBUG):
context = Context(paths=project_dir)
model = context.snapshots[snapshot_fqn].model
# Validate model-level attributes
assert to_ds(model.start or "") == "2025-01-01"
assert model.interval_unit.is_day
# Validate model-level attributes
assert to_ds(model.start or "") == "2025-01-01"
assert model.interval_unit.is_day
# Validate model kind attributes
assert isinstance(model.kind, IncrementalByTimeRangeKind)
assert model.kind.lookback == 1
assert model.kind.time_column == TimeColumn(
column=exp.to_column("ds", quoted=True), format="%Y-%m-%d"
)
assert model.kind.batch_size is None
assert model.depends_on_self is False
assert model.kind.auto_restatement_intervals is None
assert model.kind.partition_by_time_column is True
assert (
"Using `time_column` on a model with incremental_strategy 'delete+insert' has been deprecated. Please use `incremental_by_time_range` instead in model 'main.incremental_time_range'."
in caplog.text
)
@pytest.mark.slow
def test_load_microbatch_with_ref(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
yaml = YAML()
project_dir, model_dir = create_empty_project(project_name="local")
source_schema = {
"version": 2,
"sources": [
{
"name": "my_source",
"tables": [{"name": "my_table", "config": {"event_time": "ds_source"}}],
}
],
}
source_schema_file = model_dir / "source_schema.yml"
with open(source_schema_file, "w", encoding="utf-8") as f:
yaml.dump(source_schema, f)
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
microbatch_contents = """
{{
config(
materialized='incremental',
incremental_strategy='microbatch',
event_time='ds',
begin='2020-01-01',
batch_size='day'
)
}}
SELECT cola, ds_source as ds FROM {{ source('my_source', 'my_table') }}
"""
microbatch_model_file = model_dir / "microbatch.sql"
with open(microbatch_model_file, "w", encoding="utf-8") as f:
f.write(microbatch_contents)
microbatch_two_contents = """
{{
config(
materialized='incremental',
incremental_strategy='microbatch',
event_time='ds',
begin='2020-01-05',
batch_size='day'
)
}}
SELECT cola, ds FROM {{ ref('microbatch') }}
"""
microbatch_two_model_file = model_dir / "microbatch_two.sql"
with open(microbatch_two_model_file, "w", encoding="utf-8") as f:
f.write(microbatch_two_contents)
microbatch_snapshot_fqn = '"local"."main"."microbatch"'
microbatch_two_snapshot_fqn = '"local"."main"."microbatch_two"'
context = Context(paths=project_dir)
assert (
context.render(microbatch_snapshot_fqn, start="2025-01-01", end="2025-01-10").sql()
== 'SELECT "cola" AS "cola", "ds_source" AS "ds" FROM (SELECT * FROM "local"."my_source"."my_table" AS "my_table" WHERE "ds_source" >= \'2025-01-01 00:00:00+00:00\' AND "ds_source" < \'2025-01-11 00:00:00+00:00\') AS "_q_0"'
)
assert (
context.render(microbatch_two_snapshot_fqn, start="2025-01-01", end="2025-01-10").sql()
== 'SELECT "_q_0"."cola" AS "cola", "_q_0"."ds" AS "ds" FROM (SELECT "microbatch"."cola" AS "cola", "microbatch"."ds" AS "ds" FROM "local"."main"."microbatch" AS "microbatch" WHERE "microbatch"."ds" < \'2025-01-11 00:00:00+00:00\' AND "microbatch"."ds" >= \'2025-01-01 00:00:00+00:00\') AS "_q_0"'
)
@pytest.mark.slow
def test_load_microbatch_with_ref_no_filter(
tmp_path: Path, caplog, dbt_dummy_postgres_config: PostgresConfig, create_empty_project
) -> None:
yaml = YAML()
project_dir, model_dir = create_empty_project(project_name="local")
source_schema = {
"version": 2,
"sources": [
{
"name": "my_source",
"tables": [{"name": "my_table", "config": {"event_time": "ds"}}],
}
],
}
source_schema_file = model_dir / "source_schema.yml"
with open(source_schema_file, "w", encoding="utf-8") as f:
yaml.dump(source_schema, f)
# add `tests` to model config since this is loaded by dbt and ignored and we shouldn't error when loading it
microbatch_contents = """
{{
config(
materialized='incremental',
incremental_strategy='microbatch',
event_time='ds',
begin='2020-01-01',
batch_size='day'
)
}}
SELECT cola, ds FROM {{ source('my_source', 'my_table').render() }}
"""
microbatch_model_file = model_dir / "microbatch.sql"
with open(microbatch_model_file, "w", encoding="utf-8") as f:
f.write(microbatch_contents)
microbatch_two_contents = """
{{
config(
materialized='incremental',
incremental_strategy='microbatch',
event_time='ds',
begin='2020-01-01',
batch_size='day'
)
}}
SELECT cola, ds FROM {{ ref('microbatch').render() }}
"""
microbatch_two_model_file = model_dir / "microbatch_two.sql"
with open(microbatch_two_model_file, "w", encoding="utf-8") as f:
f.write(microbatch_two_contents)
microbatch_snapshot_fqn = '"local"."main"."microbatch"'
microbatch_two_snapshot_fqn = '"local"."main"."microbatch_two"'
context = Context(paths=project_dir)
assert (
context.render(microbatch_snapshot_fqn, start="2025-01-01", end="2025-01-10").sql()
== 'SELECT "cola" AS "cola", "ds" AS "ds" FROM "local"."my_source"."my_table" AS "my_table"'
)
assert (
context.render(microbatch_two_snapshot_fqn, start="2025-01-01", end="2025-01-10").sql()
== 'SELECT "microbatch"."cola" AS "cola", "microbatch"."ds" AS "ds" FROM "local"."main"."microbatch" AS "microbatch"'
)
@pytest.mark.slow
def test_load_multiple_snapshots_defined_in_same_file(sushi_test_dbt_context: Context) -> None:
context = sushi_test_dbt_context
assert context.get_model("snapshots.items_snapshot")
assert context.get_model("snapshots.items_check_snapshot")
# Make sure cache works too
context.load()
assert context.get_model("snapshots.items_snapshot")
assert context.get_model("snapshots.items_check_snapshot")
@pytest.mark.slow
def test_dbt_snapshot_with_check_cols_expressions(sushi_test_dbt_context: Context) -> None:
context = sushi_test_dbt_context
model = context.get_model("snapshots.items_check_with_cast_snapshot")
assert model is not None
assert isinstance(model.kind, SCDType2ByColumnKind)
columns = model.kind.columns
assert isinstance(columns, list)
assert len(columns) == 1
# expression in check_cols is: ds::DATE
assert isinstance(columns[0], exp.Cast)
assert columns[0].sql() == 'CAST("ds" AS DATE)'
context.load()
cached_model = context.get_model("snapshots.items_check_with_cast_snapshot")
assert cached_model is not None
assert isinstance(cached_model.kind, SCDType2ByColumnKind)
assert isinstance(cached_model.kind.columns, list)
assert len(cached_model.kind.columns) == 1
@pytest.mark.slow
def test_dbt_jinja_macro_undefined_variable_error(create_empty_project):
project_dir, model_dir = create_empty_project()
macros_dir = project_dir / "macros"
macros_dir.mkdir()
# the execute guard in the macro is so that dbt won't fail on the manifest loading earlier
macro_file = macros_dir / "my_macro.sql"
macro_file.write_text("""
{%- macro select_columns(table_name) -%}
{% if execute %}
{%- if target.name == 'production' -%}
{%- set columns = run_query('SELECT column_name FROM information_schema.columns WHERE table_name = \'' ~ table_name ~ '\'') -%}
{%- endif -%}
SELECT {{ columns.rows[0][0] }} FROM {{ table_name }}
{%- endif -%}
{%- endmacro -%}
""")
model_file = model_dir / "my_model.sql"
model_file.write_text("""
{{ config(
materialized='table'
) }}
{{ select_columns('users') }}
""")
with pytest.raises(SchemaError) as exc_info:
Context(paths=project_dir)
error_message = str(exc_info.value)
assert "Failed to update model schemas" in error_message
assert "Could not render jinja for" in error_message
assert "Undefined macro/variable: 'columns' in macro: 'select_columns'" in error_message
@pytest.mark.slow
def test_node_name_populated_for_dbt_models(dbt_dummy_postgres_config: PostgresConfig) -> None:
model_config = ModelConfig(
unique_id="model.test_package.test_model",
fqn=["test_package", "test_model"],
name="test_model",
package_name="test_package",
sql="SELECT 1 as id",
database="test_db",
schema_="test_schema",
alias="test_model",
)
context = DbtContext()
context.project_name = "test_project"
context.target = dbt_dummy_postgres_config
# check after convert to SQLMesh model that node_name is populated correctly
sqlmesh_model = model_config.to_sqlmesh(context)
assert sqlmesh_model.dbt_unique_id == "model.test_package.test_model"
assert sqlmesh_model.dbt_fqn == "test_package.test_model"
@pytest.mark.slow
def test_load_model_dbt_node_name(tmp_path: Path) -> None:
yaml = YAML()
dbt_project_dir = tmp_path / "dbt"
dbt_project_dir.mkdir()
dbt_model_dir = dbt_project_dir / "models"
dbt_model_dir.mkdir()
model_contents = "SELECT 1 as id, 'test' as name"
model_file = dbt_model_dir / "simple_model.sql"
with open(model_file, "w", encoding="utf-8") as f:
f.write(model_contents)
dbt_project_config = {
"name": "test_project",
"version": "1.0.0",
"config-version": 2,
"profile": "test",
"model-paths": ["models"],
}
dbt_project_file = dbt_project_dir / "dbt_project.yml"
with open(dbt_project_file, "w", encoding="utf-8") as f:
yaml.dump(dbt_project_config, f)
sqlmesh_config = {
"model_defaults": {
"start": "2025-01-01",
}
}
sqlmesh_config_file = dbt_project_dir / "sqlmesh.yaml"
with open(sqlmesh_config_file, "w", encoding="utf-8") as f:
yaml.dump(sqlmesh_config, f)
dbt_data_dir = tmp_path / "dbt_data"
dbt_data_dir.mkdir()
dbt_data_file = dbt_data_dir / "local.db"
dbt_profile_config = {
"test": {
"outputs": {"duckdb": {"type": "duckdb", "path": str(dbt_data_file)}},
"target": "duckdb",
}
}
db_profile_file = dbt_project_dir / "profiles.yml"
with open(db_profile_file, "w", encoding="utf-8") as f:
yaml.dump(dbt_profile_config, f)
context = Context(paths=dbt_project_dir)
# find the model by its sqlmesh fully qualified name
model_fqn = '"local"."main"."simple_model"'
assert model_fqn in context.snapshots
# Verify that node_name is the equivalent dbt one
model = context.snapshots[model_fqn].model
assert model.dbt_unique_id == "model.test_project.simple_model"
assert model.dbt_fqn == "test_project.simple_model"
assert model.dbt_node_info
assert model.dbt_node_info.name == "simple_model"
@pytest.mark.slow
def test_jinja_config_no_query(create_empty_project):
project_dir, model_dir = create_empty_project(project_name="local")
# model definition contains only a comment and non-SQL jinja
model_contents = "/* comment */ {{ config(materialized='table') }}"
model_file = model_dir / "comment_config_model.sql"
with open(model_file, "w", encoding="utf-8") as f:
f.write(model_contents)
schema_yaml = {"version": 2, "models": [{"name": "comment_config_model"}]}
schema_file = model_dir / "schema.yml"
with open(schema_file, "w", encoding="utf-8") as f:
YAML().dump(schema_yaml, f)
context = Context(paths=project_dir)
# loads without error and contains empty query (which will error at runtime)
assert not context.snapshots['"local"."main"."comment_config_model"'].model.render_query()
@pytest.mark.slow
def test_load_custom_materialisations(sushi_test_dbt_context: Context) -> None:
context = sushi_test_dbt_context
assert context.get_model("sushi.custom_incremental_model")
assert context.get_model("sushi.custom_incremental_with_filter")
context.load()
assert context.get_model("sushi.custom_incremental_model")
assert context.get_model("sushi.custom_incremental_with_filter")
def test_model_grants_to_sqlmesh_grants_config() -> None:
grants_config = {
"select": ["user1", "user2"],
"insert": ["admin_user"],
"update": ["power_user"],
}
model_config = ModelConfig(
name="test_model",
sql="SELECT 1 as id",
grants=grants_config,
path=Path("test_model.sql"),
)
context = DbtContext()
context.project_name = "test_project"
context.target = DuckDbConfig(name="target", schema="test_schema")
sqlmesh_model = model_config.to_sqlmesh(
context, virtual_environment_mode=VirtualEnvironmentMode.FULL
)
model_grants = sqlmesh_model.grants
assert model_grants == grants_config
assert sqlmesh_model.grants_target_layer == GrantsTargetLayer.default
def test_model_grants_empty_permissions() -> None:
model_config = ModelConfig(
name="test_model_empty",
sql="SELECT 1 as id",
grants={"select": [], "insert": ["admin_user"]},
path=Path("test_model_empty.sql"),
)
context = DbtContext()
context.project_name = "test_project"
context.target = DuckDbConfig(name="target", schema="test_schema")
sqlmesh_model = model_config.to_sqlmesh(
context, virtual_environment_mode=VirtualEnvironmentMode.FULL
)
model_grants = sqlmesh_model.grants
expected_grants = {"select": [], "insert": ["admin_user"]}
assert model_grants == expected_grants
def test_model_no_grants() -> None:
model_config = ModelConfig(
name="test_model_no_grants",
sql="SELECT 1 as id",
path=Path("test_model_no_grants.sql"),
)
context = DbtContext()
context.project_name = "test_project"
context.target = DuckDbConfig(name="target", schema="test_schema")
sqlmesh_model = model_config.to_sqlmesh(
context, virtual_environment_mode=VirtualEnvironmentMode.FULL
)
grants_config = sqlmesh_model.grants
assert grants_config is None
def test_model_empty_grants() -> None:
model_config = ModelConfig(
name="test_model_empty_grants",
sql="SELECT 1 as id",
grants={},
path=Path("test_model_empty_grants.sql"),
)
context = DbtContext()
context.project_name = "test_project"
context.target = DuckDbConfig(name="target", schema="test_schema")
sqlmesh_model = model_config.to_sqlmesh(
context, virtual_environment_mode=VirtualEnvironmentMode.FULL
)
grants_config = sqlmesh_model.grants
assert grants_config is None
def test_model_grants_valid_special_characters() -> None:
valid_grantees = [
"user@domain.com",
"service-account@project.iam.gserviceaccount.com",
"group:analysts",
'"quoted user"',
"`backtick user`",
"user_with_underscores",
"user.with.dots",
]
model_config = ModelConfig(
name="test_model_special_chars",
sql="SELECT 1 as id",
grants={"select": valid_grantees},
path=Path("test_model.sql"),
)
context = DbtContext()
context.project_name = "test_project"
context.target = DuckDbConfig(name="target", schema="test_schema")
sqlmesh_model = model_config.to_sqlmesh(