-
Notifications
You must be signed in to change notification settings - Fork 353
Expand file tree
/
Copy pathtest_cli.py
More file actions
2241 lines (1875 loc) · 69.7 KB
/
test_cli.py
File metadata and controls
2241 lines (1875 loc) · 69.7 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 json
import os
import pytest
import string
import time_machine
from os import getcwd, path, remove
from pathlib import Path
from shutil import rmtree
from unittest.mock import MagicMock
from click import ClickException
from click.testing import CliRunner
from sqlmesh import RuntimeEnv
from sqlmesh.cli.project_init import ProjectTemplate, init_example_project
from sqlmesh.cli.main import cli
from sqlmesh.core.context import Context
from sqlmesh.integrations.dlt import generate_dlt_models
from sqlmesh.utils.date import now_ds, time_like_to_str, timedelta, to_datetime, yesterday_ds
from sqlmesh.core.config.connection import DIALECT_TO_TYPE
FREEZE_TIME = "2023-01-01 00:00:00 UTC"
pytestmark = pytest.mark.slow
@pytest.fixture(autouse=True)
def mock_runtime_env(monkeypatch):
monkeypatch.setattr("sqlmesh.RuntimeEnv.get", MagicMock(return_value=RuntimeEnv.TERMINAL))
@pytest.fixture(scope="session")
def runner() -> CliRunner:
return CliRunner(env={"COLUMNS": "80"})
def create_example_project(temp_dir, template=ProjectTemplate.DEFAULT) -> None:
"""
Sets up CLI tests requiring a real SQLMesh project by:
- Creating the SQLMesh example project in the temp_dir directory
- Overwriting the config.yaml file so the duckdb database file will be created in the temp_dir directory
"""
init_example_project(temp_dir, engine_type="duckdb", template=template)
with open(temp_dir / "config.yaml", "w", encoding="utf-8") as f:
f.write(
f"""gateways:
local:
connection:
type: duckdb
database: {temp_dir}/db.db
default_gateway: local
model_defaults:
dialect: duckdb
plan:
no_prompts: false
"""
)
def update_incremental_model(temp_dir) -> None:
with open(temp_dir / "models" / "incremental_model.sql", "w", encoding="utf-8") as f:
f.write(
"""
MODEL (
name sqlmesh_example.incremental_model,
kind INCREMENTAL_BY_TIME_RANGE (
time_column event_date
),
start '2020-01-01',
cron '@daily',
grain (id, event_date)
);
SELECT
id,
item_id,
'a' as new_col,
event_date,
FROM
sqlmesh_example.seed_model
WHERE
event_date between @start_date and @end_date
"""
)
def update_full_model(temp_dir) -> None:
with open(temp_dir / "models" / "full_model.sql", "w", encoding="utf-8") as f:
f.write(
"""
MODEL (
name sqlmesh_example.full_model,
kind FULL,
cron '@daily',
grain item_id,
audits (assert_positive_order_ids),
);
SELECT
item_id + 1 as item_id,
count(distinct id) AS num_orders,
FROM
sqlmesh_example.incremental_model
GROUP BY item_id
"""
)
def init_prod_and_backfill(runner, temp_dir) -> None:
result = runner.invoke(
cli, ["--log-file-dir", temp_dir, "--paths", temp_dir, "plan", "--auto-apply"]
)
assert_plan_success(result)
assert path.exists(temp_dir / "db.db")
def assert_duckdb_test(result) -> None:
assert "Successfully Ran 1 tests against duckdb" in result.output
def assert_new_env(result, new_env="prod", from_env="prod", initialize=True) -> None:
assert (
f"`{new_env}` environment will be initialized"
if initialize
else f"New environment `{new_env}` will be created from `{from_env}`"
) in result.output
def assert_model_batches_executed(result) -> None:
assert "Model batches executed" in result.output
def assert_virtual_layer_updated(result) -> None:
assert "Virtual layer updated" in result.output
def assert_backfill_success(result) -> None:
assert_model_batches_executed(result)
assert_virtual_layer_updated(result)
def assert_plan_success(result, new_env="prod", from_env="prod") -> None:
assert result.exit_code == 0
assert_duckdb_test(result)
assert_new_env(result, new_env, from_env)
assert_backfill_success(result)
def test_version(runner, tmp_path):
from sqlmesh import __version__ as SQLMESH_VERSION
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--version"])
assert result.exit_code == 0
assert SQLMESH_VERSION in result.output
def test_plan_no_config(runner, tmp_path):
# Error if no SQLMesh project config is found
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan"])
assert result.exit_code == 1
assert "Error: SQLMesh project config could not be found" in result.output
@time_machine.travel(FREEZE_TIME)
def test_plan(runner, tmp_path):
create_example_project(tmp_path)
# Example project models have start dates, so there are no date prompts
# for the `prod` environment.
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan"], input="y\n"
)
assert_plan_success(result)
# 'Models needing backfill' section and eval progress bar should display the same inclusive intervals
assert "sqlmesh_example.incremental_model: [2020-01-01 - 2022-12-31]" in result.output
assert "sqlmesh_example.incremental_model [insert 2020-01-01 - 2022-12-31]" in result.output
def test_plan_skip_tests(runner, tmp_path):
create_example_project(tmp_path)
# Successful test run message should not appear with `--skip-tests`
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--skip-tests"], input="y\n"
)
assert result.exit_code == 0
assert "Successfully Ran 1 tests against duckdb" not in result.output
assert_new_env(result)
assert_backfill_success(result)
def test_plan_skip_linter(runner, tmp_path):
create_example_project(tmp_path)
with open(tmp_path / "config.yaml", "a", encoding="utf-8") as f:
f.write(
"""linter:
enabled: True
rules: "ALL"
"""
)
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--skip-linter"], input="y\n"
)
assert result.exit_code == 0
assert "Linter warnings" not in result.output
assert_new_env(result)
assert_backfill_success(result)
def test_plan_restate_model(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
# plan with no changes and full_model restated
# Input: enter for backfill start date prompt, enter for end date prompt, `y` to apply and backfill
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"--restate-model",
"sqlmesh_example.full_model",
],
input="\n\ny\n",
)
assert result.exit_code == 0
assert_duckdb_test(result)
assert "Models selected for restatement" in result.output
assert "sqlmesh_example.full_model [full refresh" in result.output
assert_model_batches_executed(result)
assert "Virtual layer updated" not in result.output
@pytest.mark.parametrize("flag", ["--skip-backfill", "--dry-run"])
def test_plan_skip_backfill(runner, tmp_path, flag):
create_example_project(tmp_path)
# plan for `prod` errors if `--skip-backfill` is passed without --no-gaps
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", flag])
assert result.exit_code == 1
assert "Skipping the backfill stage for production can lead to unexpected" in result.output
# plan executes virtual update without executing model batches
# Input: `y` to perform virtual update
result = runner.invoke(
cli,
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", flag, "--no-gaps"],
input="y\n",
)
assert result.exit_code == 0
assert_virtual_layer_updated(result)
assert "Model batches executed" not in result.output
def test_plan_auto_apply(runner, tmp_path):
create_example_project(tmp_path)
# plan for `prod` runs end-to-end with no user input with `--auto-apply`
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--auto-apply"]
)
assert_plan_success(result)
# confirm verbose output not present
assert "sqlmesh_example.seed_model created" not in result.output
assert "sqlmesh_example.seed_model updated" not in result.output
def test_plan_verbose(runner, tmp_path):
create_example_project(tmp_path)
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--verbose"], input="y\n"
)
assert_plan_success(result)
assert "sqlmesh_example.seed_model created" in result.output
assert "sqlmesh_example.full_model created" in result.output
# confirm virtual layer action labels correct
update_incremental_model(tmp_path)
import os
os.remove(tmp_path / "models" / "full_model.sql")
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--verbose"], input="y\n"
)
assert result.exit_code == 0
assert_backfill_success(result)
assert "sqlmesh_example.incremental_model updated" in result.output
assert "sqlmesh_example.full_model dropped" in result.output
def test_plan_very_verbose(runner, tmp_path, copy_to_temp_path):
temp_path = copy_to_temp_path("examples/sushi")
# Input: `y` to apply and backfill
result = runner.invoke(
cli,
["--log-file-dir", temp_path[0], "--paths", temp_path[0], "plan", "-v"],
input="y\n",
)
assert result.exit_code == 0
# models needing backfill list is still abbreviated with regular VERBOSE, so this should not be present
assert "sushi.customers: [full refresh]" not in result.output
# Input: `y` to apply and backfill
result = runner.invoke(
cli,
["--log-file-dir", temp_path[0], "--paths", temp_path[0], "plan", "-vv"],
input="y\n",
)
assert result.exit_code == 0
# models needing backfill list is complete with VERY_VERBOSE, so this should be present
assert "sushi.customers: [full refresh]" in result.output
def test_plan_dev(runner, tmp_path):
create_example_project(tmp_path)
# Input: enter for backfill start date prompt, enter for end date prompt, `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev"], input="\n\ny\n"
)
assert_plan_success(result, "dev")
def test_plan_dev_start_date(runner, tmp_path):
create_example_project(tmp_path)
# Input: enter for backfill end date prompt, `y` to apply and backfill
result = runner.invoke(
cli,
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev", "--start", "2023-01-01"],
input="\ny\n",
)
assert_plan_success(result, "dev")
assert "sqlmesh_example__dev.full_model: [full refresh]" in result.output
assert "sqlmesh_example__dev.incremental_model: [2023-01-01" in result.output
def test_plan_dev_end_date(runner, tmp_path):
create_example_project(tmp_path)
# Input: enter for backfill start date prompt, `y` to apply and backfill
result = runner.invoke(
cli,
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev", "--end", "2023-01-01"],
input="\ny\n",
)
assert_plan_success(result, "dev")
assert "sqlmesh_example__dev.full_model: [full refresh]" in result.output
assert "sqlmesh_example__dev.incremental_model: [2020-01-01 - 2023-01-01]" in result.output
def test_plan_dev_create_from_virtual(runner, tmp_path):
create_example_project(tmp_path)
# create dev environment and backfill
runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev",
"--no-prompts",
"--auto-apply",
],
)
# create dev2 environment from dev environment
# Input: `y` to apply and virtual update
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev2",
"--create-from",
"dev",
"--include-unmodified",
],
input="y\n",
)
assert result.exit_code == 0
assert_new_env(result, "dev2", "dev", initialize=False)
assert "SKIP: No physical layer updates to perform" in result.output
assert "SKIP: No model batches to execute" in result.output
assert_virtual_layer_updated(result)
def test_plan_dev_create_from(runner, tmp_path):
create_example_project(tmp_path)
# create dev environment and backfill
runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev",
"--no-prompts",
"--auto-apply",
],
)
# make model change
update_incremental_model(tmp_path)
# create dev2 environment from dev
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev2",
"--create-from",
"dev",
"--no-prompts",
"--auto-apply",
],
)
assert result.exit_code == 0
assert_new_env(result, "dev2", "dev", initialize=False)
assert "Differences from the `dev` environment:" in result.output
def test_plan_dev_bad_create_from(runner, tmp_path):
create_example_project(tmp_path)
# create dev environment and backfill
runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev",
"--no-prompts",
"--auto-apply",
],
)
# make model change
update_incremental_model(tmp_path)
# create dev2 environment from non-existent dev3
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev2",
"--create-from",
"dev3",
"--no-prompts",
"--auto-apply",
],
)
assert result.exit_code == 0
assert_new_env(result, "dev2", "dev")
assert (
"[WARNING] The environment name 'dev3' was passed to the `plan` command's `--create-from` argument, but 'dev3' does not exist. Initializing new environment 'dev2' from scratch."
in result.output.replace("\n", "")
)
def test_plan_dev_no_prompts(runner, tmp_path):
create_example_project(tmp_path)
# plan for non-prod environment doesn't prompt for dates but prompts to apply
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev", "--no-prompts"]
)
assert "Apply - Backfill Tables [y/n]: " in result.output
assert "Physical layer updated" not in result.output
assert "Model batches executed" not in result.output
assert "The target environment has been updated" not in result.output
def test_plan_dev_auto_apply(runner, tmp_path):
create_example_project(tmp_path)
# Input: enter for backfill start date prompt, enter for end date prompt
result = runner.invoke(
cli,
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev", "--auto-apply"],
input="\n\n",
)
assert_plan_success(result, "dev")
def test_plan_dev_no_changes(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
# Error if no changes made and `--include-unmodified` is not passed
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev"])
assert result.exit_code == 1
assert (
"Error: Creating a new environment requires a change, but project files match the `prod` environment. Make a change or use the --include-unmodified flag to create a new environment without changes."
in result.output
)
# No error if no changes made and `--include-unmodified` is passed
# Input: `y` to apply and virtual update
result = runner.invoke(
cli,
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev", "--include-unmodified"],
input="y\n",
)
assert result.exit_code == 0
assert_new_env(result, "dev", initialize=False)
assert_virtual_layer_updated(result)
def test_plan_dev_longnames(runner, tmp_path):
create_example_project(tmp_path)
long_model_names = {
"full": f"full_{'a' * 80}",
"incremental": f"incremental_{'b' * 80}",
"seed": f"seed_{'c' * 80}",
}
for model_name in long_model_names:
with open(tmp_path / "models" / f"{model_name}_model.sql", "r") as f:
model_text = f.read()
for more_model_names in long_model_names:
model_text = model_text.replace(
f"sqlmesh_example.{more_model_names}_model",
f"sqlmesh_example.{long_model_names[more_model_names]}_model",
)
with open(tmp_path / "models" / f"{model_name}_model.sql", "w") as f:
f.write(model_text)
# Input: `y` to apply and backfill
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev_butamuchlongerenvironmentname",
"--skip-tests",
"--no-prompts",
"--auto-apply",
],
)
assert result.exit_code == 0
assert (
"sqlmesh_example__dev_butamuchlongerenvironmentname.seed_cccccccccccccccccccccccc\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccc_model [insert \nseed file]"
in result.output
)
assert (
"sqlmesh_example__dev_butamuchlongerenvironmentname.incremental_bbbbbbbbbbbbbbbbb\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb_model [insert "
in result.output
)
assert (
"sqlmesh_example__dev_butamuchlongerenvironmentname.full_aaaaaaaaaaaaaaaaaaaaaaaa\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_model [full \nrefresh"
in result.output
)
assert_backfill_success(result)
def test_plan_nonbreaking(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
update_incremental_model(tmp_path)
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan"], input="y\n"
)
assert result.exit_code == 0
assert "Differences from the `prod` environment" in result.output
assert "+ 'a' AS new_col" in result.output
assert "Directly Modified: sqlmesh_example.incremental_model (Non-breaking)" in result.output
assert "sqlmesh_example.full_model (Indirect Non-breaking)" in result.output
assert "sqlmesh_example.incremental_model [insert" in result.output
assert "sqlmesh_example.full_model [full refresh" not in result.output
assert_backfill_success(result)
def test_plan_nonbreaking_noautocategorization(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
update_incremental_model(tmp_path)
# Input: `2` to classify change as non-breaking, `y` to apply and backfill
result = runner.invoke(
cli,
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--no-auto-categorization"],
input="2\ny\n",
)
assert result.exit_code == 0
assert (
"[1] [Breaking] Backfill sqlmesh_example.incremental_model and indirectly \nmodified children"
in result.output
)
assert (
"[2] [Non-breaking] Backfill sqlmesh_example.incremental_model but not indirectly\nmodified children"
in result.output
)
assert_backfill_success(result)
def test_plan_nonbreaking_nodiff(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
update_incremental_model(tmp_path)
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--no-diff"], input="y\n"
)
assert result.exit_code == 0
assert "+ 'a' AS new_col" not in result.output
assert_backfill_success(result)
def test_plan_breaking(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
update_full_model(tmp_path)
# full_model change makes test fail, so we pass `--skip-tests`
# Input: `y` to apply and backfill
result = runner.invoke(
cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "--skip-tests"], input="y\n"
)
assert result.exit_code == 0
assert "+ item_id + 1 AS item_id," in result.output
assert "Directly Modified: sqlmesh_example.full_model (Breaking)" in result.output
assert "sqlmesh_example.full_model [full refresh" in result.output
assert "sqlmesh_example.incremental_model [insert" not in result.output
assert_backfill_success(result)
def test_plan_dev_select(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
update_incremental_model(tmp_path)
update_full_model(tmp_path)
# full_model change makes test fail, so we pass `--skip-tests`
# Input: enter for backfill start date prompt, enter for end date prompt, `y` to apply and backfill
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev",
"--skip-tests",
"--select-model",
"sqlmesh_example.incremental_model",
],
input="\n\ny\n",
)
assert result.exit_code == 0
# incremental_model diff present
assert "+ 'a' AS new_col" in result.output
assert (
"Directly Modified: sqlmesh_example__dev.incremental_model (Non-breaking)" in result.output
)
# full_model diff not present
assert "+ item_id + 1 AS item_id," not in result.output
assert "Directly Modified: sqlmesh_example__dev.full_model (Breaking)" not in result.output
# only incremental_model backfilled
assert "sqlmesh_example__dev.incremental_model [insert" in result.output
assert "sqlmesh_example__dev.full_model [full refresh" not in result.output
assert_backfill_success(result)
def test_plan_dev_backfill(runner, tmp_path):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
update_incremental_model(tmp_path)
update_full_model(tmp_path)
# full_model change makes test fail, so we pass `--skip-tests`
# Input: enter for backfill start date prompt, enter for end date prompt, `y` to apply and backfill
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"plan",
"dev",
"--skip-tests",
"--backfill-model",
"sqlmesh_example.incremental_model",
],
input="\n\ny\n",
)
assert result.exit_code == 0
assert_new_env(result, "dev", initialize=False)
# both model diffs present
assert "+ item_id + 1 AS item_id," in result.output
assert "Directly Modified: sqlmesh_example__dev.full_model (Breaking)" in result.output
assert "+ 'a' AS new_col" in result.output
assert (
"Directly Modified: sqlmesh_example__dev.incremental_model (Non-breaking)" in result.output
)
# only incremental_model backfilled
assert "sqlmesh_example__dev.incremental_model [insert" in result.output
assert "sqlmesh_example__dev.full_model [full refresh" not in result.output
assert_backfill_success(result)
def test_run_no_prod(runner, tmp_path):
create_example_project(tmp_path)
# Error if no env specified and `prod` doesn't exist
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "run"])
assert result.exit_code == 1
assert "Error: Environment 'prod' was not found." in result.output
@pytest.mark.parametrize("flag", ["--skip-backfill", "--dry-run"])
@time_machine.travel(FREEZE_TIME)
def test_run_dev(runner, tmp_path, flag):
create_example_project(tmp_path)
# Create dev environment but DO NOT backfill
# Input: `y` for virtual update
runner.invoke(
cli,
["--log-file-dir", tmp_path, "--paths", tmp_path, "plan", "dev", flag],
input="y\n",
)
# Confirm backfill occurs when we run non-backfilled dev env
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "run", "dev"])
assert result.exit_code == 0
assert_model_batches_executed(result)
@time_machine.travel(FREEZE_TIME)
def test_run_cron_not_elapsed(runner, tmp_path, caplog):
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
# No error if `prod` environment exists and cron has not elapsed
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "run"])
assert result.exit_code == 0
assert (
"No models are ready to run. Please wait until a model `cron` interval has \nelapsed.\n\nNext run will be ready at "
in result.output.strip()
)
def test_run_cron_elapsed(runner, tmp_path):
create_example_project(tmp_path)
# Create and backfill `prod` environment
with time_machine.travel("2023-01-01 23:59:00 UTC", tick=False) as traveler:
runner = CliRunner()
init_prod_and_backfill(runner, tmp_path)
# Run `prod` environment with daily cron elapsed
traveler.move_to("2023-01-02 00:01:00 UTC")
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "run"])
assert result.exit_code == 0
assert_model_batches_executed(result)
def test_clean(runner, tmp_path):
# Create and backfill `prod` environment
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
# Confirm cache exists
cache_path = Path(tmp_path) / ".cache"
assert cache_path.exists()
assert len(list(cache_path.iterdir())) > 0
# Invoke the clean command
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "clean"])
# Confirm cache was cleared
assert result.exit_code == 0
assert not cache_path.exists()
def test_table_name(runner, tmp_path):
# Create and backfill `prod` environment
create_example_project(tmp_path)
init_prod_and_backfill(runner, tmp_path)
result = runner.invoke(
cli,
[
"--log-file-dir",
tmp_path,
"--paths",
tmp_path,
"table_name",
"sqlmesh_example.full_model",
],
)
assert result.exit_code == 0
assert result.output.startswith("db.sqlmesh__sqlmesh_example.sqlmesh_example__full_model__")
def test_info_on_new_project_does_not_create_state_sync(runner, tmp_path):
create_example_project(tmp_path)
# Invoke the info command
result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "info"])
assert result.exit_code == 0
context = Context(paths=tmp_path)
# Confirm that the state sync tables haven't been created
assert not context.engine_adapter.table_exists("sqlmesh._snapshots")
assert not context.engine_adapter.table_exists("sqlmesh._environments")
assert not context.engine_adapter.table_exists("sqlmesh._intervals")
assert not context.engine_adapter.table_exists("sqlmesh._versions")
def test_dlt_pipeline_errors(runner, tmp_path):
# Error if no pipeline is provided
result = runner.invoke(cli, ["--paths", tmp_path, "init", "-t", "dlt", "duckdb"])
assert (
"Error: Please provide a DLT pipeline with the `--dlt-pipeline` flag to generate a SQLMesh project from DLT"
in result.output
)
# Error if the pipeline provided is not correct
result = runner.invoke(
cli,
["--paths", tmp_path, "init", "-t", "dlt", "--dlt-pipeline", "missing_pipeline", "duckdb"],
)
assert "Error: Could not attach to pipeline" in result.output
@time_machine.travel(FREEZE_TIME)
def test_dlt_filesystem_pipeline(tmp_path):
import dlt
root_dir = path.abspath(getcwd())
storage_path = root_dir + "/temp_storage"
if path.exists(storage_path):
rmtree(storage_path)
filesystem_pipeline = dlt.pipeline(
pipeline_name="filesystem_pipeline",
destination=dlt.destinations.filesystem("file://" + storage_path),
)
info = filesystem_pipeline.run([{"item_id": 1}], table_name="equipment")
assert not info.has_failed_jobs
init_example_project(
tmp_path, "athena", template=ProjectTemplate.DLT, pipeline="filesystem_pipeline"
)
# Validate generated sqlmesh config and models
config_path = tmp_path / "config.yaml"
equipment_model_path = tmp_path / "models/incremental_equipment.sql"
dlt_loads_model_path = tmp_path / "models/incremental__dlt_loads.sql"
assert config_path.exists()
assert equipment_model_path.exists()
assert dlt_loads_model_path.exists()
expected_incremental_model = """MODEL (
name filesystem_pipeline_dataset_sqlmesh.incremental_equipment,
kind INCREMENTAL_BY_TIME_RANGE (
time_column _dlt_load_time,
),
);
SELECT
CAST(c.item_id AS BIGINT) AS item_id,
CAST(c._dlt_load_id AS VARCHAR) AS _dlt_load_id,
CAST(c._dlt_id AS VARCHAR) AS _dlt_id,
TO_TIMESTAMP(CAST(c._dlt_load_id AS DOUBLE)) as _dlt_load_time
FROM
filesystem_pipeline_dataset.equipment as c
WHERE
TO_TIMESTAMP(CAST(c._dlt_load_id AS DOUBLE)) BETWEEN @start_ds AND @end_ds
"""
with open(equipment_model_path) as file:
incremental_model = file.read()
assert incremental_model == expected_incremental_model
expected_config = (
"# --- Gateway Connection ---\n"
"gateways:\n"
" athena:\n"
" connection:\n"
" # For more information on configuring the connection to your execution engine, visit:\n"
" # https://sqlmesh.readthedocs.io/en/stable/reference/configuration/#connection\n"
" # https://sqlmesh.readthedocs.io/en/stable/integrations/engines/athena/#connection-options\n"
" type: athena\n"
" # concurrent_tasks: 4\n"
" # register_comments: False\n"
" # pre_ping: False\n"
" # pretty_sql: False\n"
" # schema_differ_overrides: \n"
" # catalog_type_overrides: \n"
" # aws_access_key_id: \n"
" # aws_secret_access_key: \n"
" # role_arn: \n"
" # role_session_name: \n"
" # region_name: \n"
" # work_group: \n"
" # s3_staging_dir: \n"
" # schema_name: \n"
" # catalog_name: \n"
" # s3_warehouse_location: \n\n"
"default_gateway: athena\n\n"
"# --- Model Defaults ---\n"
"# https://sqlmesh.readthedocs.io/en/stable/reference/model_configuration/#model-defaults\n\n"
"model_defaults:\n"
" dialect: athena\n"
f" start: {yesterday_ds()} # Start date for backfill history\n"
" cron: '@daily' # Run models daily at 12am UTC (can override per model)\n\n"
"# --- Linting Rules ---\n"
"# Enforce standards for your team\n"
"# https://sqlmesh.readthedocs.io/en/stable/guides/linter/\n\n"
"linter:\n"
" enabled: true\n"
" rules:\n"
" - ambiguousorinvalidcolumn\n"
" - invalidselectstarexpansion\n"
" - noambiguousprojections\n"
)
with open(config_path) as file:
config = file.read()
assert config == expected_config
if path.exists(storage_path):
rmtree(storage_path)
@time_machine.travel(FREEZE_TIME)
def test_dlt_pipeline(runner, tmp_path):
from dlt.common.pipeline import get_dlt_pipelines_dir
root_dir = path.abspath(getcwd())
pipeline_path = root_dir + "/examples/sushi_dlt/sushi_pipeline.py"
dataset_path = root_dir + "/sushi.duckdb"
if path.exists(dataset_path):
remove(dataset_path)
with open(pipeline_path) as file:
exec(file.read())
# This should fail since it won't be able to locate the pipeline in this path
with pytest.raises(ClickException, match=r".*Could not attach to pipeline*"):