-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathtest_magics.py
More file actions
913 lines (801 loc) · 31.9 KB
/
test_magics.py
File metadata and controls
913 lines (801 loc) · 31.9 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
import logging
import pathlib
import typing as t
from unittest.mock import MagicMock
import pytest
from bs4 import BeautifulSoup
import time_machine
from hyperscript import h
from IPython.core.error import UsageError
from IPython.testing.globalipapp import start_ipython
from IPython.utils.capture import CapturedIO, capture_output
from pytest_mock.plugin import MockerFixture
from rich.console import Console as RichConsole
from sqlmesh import Context, RuntimeEnv
from sqlmesh.magics import register_magics
from pathlib import Path
logger = logging.getLogger(__name__)
SUSHI_EXAMPLE_PATH = pathlib.Path("./examples/sushi")
SUCCESS_STYLE = "color: #008000; text-decoration-color: #008000"
NEUTRAL_STYLE = "color: #008080; text-decoration-color: #008080"
BOLD_ONLY = "font-weight: bold"
BOLD_NEUTRAL_STYLE = f"{NEUTRAL_STYLE}; {BOLD_ONLY}"
BOLD_SUCCESS_STYLE = f"{SUCCESS_STYLE}; {BOLD_ONLY}"
RICH_PRE_STYLE = "white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"
FREEZE_TIME = "2023-01-01 00:00:00 UTC"
pytestmark = pytest.mark.jupyter
@pytest.fixture(scope="session")
def ip():
logger.root.handlers.clear()
return start_ipython()
@pytest.fixture
def notebook(mocker: MockerFixture, ip):
mocker.patch("sqlmesh.RuntimeEnv.get", MagicMock(side_effect=lambda: RuntimeEnv.JUPYTER))
mocker.patch(
"sqlmesh.core.console.RichConsole",
MagicMock(return_value=RichConsole(force_jupyter=True, color_system="truecolor")),
)
register_magics()
return ip
@pytest.fixture
def sushi_context(copy_to_temp_path, notebook, tmp_path) -> Context:
sushi_dir = copy_to_temp_path(SUSHI_EXAMPLE_PATH)[0]
notebook.run_line_magic(
magic_name="context", line=f"{str(sushi_dir)} --log-file-dir {tmp_path}"
)
return notebook.user_ns["context"]
@pytest.fixture
@time_machine.travel(FREEZE_TIME)
def loaded_sushi_context(sushi_context) -> Context:
with capture_output():
sushi_context.plan(no_prompts=True, auto_apply=True)
return sushi_context
@pytest.fixture
def convert_all_html_output_to_text():
def _convert(output: CapturedIO) -> t.List[str]:
return [
BeautifulSoup(output.data["text/html"]).get_text().strip() for output in output.outputs
]
return _convert
@pytest.fixture
def convert_all_html_output_to_tags():
def _convert_html_to_tags(html: str) -> t.List[str]:
# BS4 automatically adds html and body tags so we remove those since they are not actually part of the output
return [
tag.name # type: ignore
for tag in BeautifulSoup(html, "html").find_all()
if tag.name not in {"html", "body"} # type: ignore
]
def _convert(output: CapturedIO) -> t.List[t.List[str]]:
return [_convert_html_to_tags(output.data["text/html"]) for output in output.outputs]
return _convert
@pytest.fixture
def get_all_html_output():
def _convert(output: CapturedIO) -> t.List[str]:
# We remove newlines to make it easier to compare the output to expected output
return [output.data["text/html"].replace("\n", "") for output in output.outputs]
return _convert
def test_context(notebook, convert_all_html_output_to_text, get_all_html_output, tmp_path):
with capture_output() as output:
notebook.run_line_magic(
magic_name="context", line=f"{str(SUSHI_EXAMPLE_PATH)} --log-file-dir {tmp_path}"
)
assert output.stdout == ""
assert output.stderr == ""
assert len(output.outputs) == 1
sushi_path = str(Path("examples/sushi"))
assert convert_all_html_output_to_text(output) == [
f"SQLMesh project context set to: {sushi_path}"
]
assert get_all_html_output(output) == [
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
h(
"span",
{"style": SUCCESS_STYLE},
f"SQLMesh project context set to: {sushi_path}",
autoescape=False,
),
autoescape=False,
)
)
]
def test_init(tmp_path, notebook, convert_all_html_output_to_text, get_all_html_output):
with pytest.raises(UsageError, match="the following arguments are required: path"):
notebook.run_line_magic(magic_name="init", line="")
with pytest.raises(UsageError, match="the following arguments are required: engine"):
notebook.run_line_magic(magic_name="init", line="foo")
with capture_output() as output:
notebook.run_line_magic(magic_name="init", line=f"{tmp_path} duckdb")
assert output.stdout == ""
assert output.stderr == ""
assert len(output.outputs) == 1
assert convert_all_html_output_to_text(output) == ["SQLMesh project scaffold created"]
assert get_all_html_output(output) == [
str(
h(
"div",
h(
"span",
{"style": "color: green; font-weight: bold"},
"SQLMesh project scaffold created",
autoescape=False,
),
autoescape=False,
)
)
]
@pytest.mark.slow
def test_render(
notebook, sushi_context, convert_all_html_output_to_text, convert_all_html_output_to_tags
):
with capture_output() as output:
notebook.run_line_magic(magic_name="render", line="sushi.top_waiters")
assert output.stdout == ""
assert output.stderr == ""
assert len(output.outputs) == 2
assert len(convert_all_html_output_to_text(output)[1]) > 2200
assert len(convert_all_html_output_to_tags(output)[1]) > 150
@pytest.mark.slow
def test_render_no_format(
notebook, sushi_context, convert_all_html_output_to_text, convert_all_html_output_to_tags
):
with capture_output() as output:
notebook.run_line_magic(magic_name="render", line="sushi.top_waiters --no-format")
assert output.stdout == ""
assert output.stderr == ""
assert len(output.outputs) == 2
assert len(convert_all_html_output_to_text(output)[1]) >= 700
assert len(convert_all_html_output_to_tags(output)[1]) >= 50
@pytest.mark.slow
@time_machine.travel(FREEZE_TIME)
def test_evaluate(notebook, loaded_sushi_context):
with capture_output() as output:
notebook.run_line_magic(magic_name="evaluate", line="sushi.top_waiters")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 1
# TODO: Add console method to display pandas dataframe and then use that instead of calling display directly
assert not output.outputs[0].data.get("text/html")
# Since there is no ordering in the query, we can't assert the exact output, but we can assert the columns
# and it starts with the index
assert output.outputs[0].data["text/plain"].startswith(" waiter_id revenue\n0")
def test_format(notebook, sushi_context):
with capture_output():
test_model_path = sushi_context.path / "models" / "test_model.sql"
test_model_path.write_text("MODEL(name db.test); SELECT 1 AS foo FROM t")
sushi_context.load()
assert test_model_path.read_text() == "MODEL(name db.test); SELECT 1 AS foo FROM t"
with capture_output() as output:
notebook.run_line_magic(magic_name="format", line="")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 0
assert (
test_model_path.read_text()
== """MODEL (
name db.test
);
SELECT
1 AS foo
FROM t"""
)
@pytest.mark.slow
def test_diff(sushi_context, notebook, convert_all_html_output_to_text, get_all_html_output):
with capture_output():
test_model_path = sushi_context.path / "models" / "test_model.sql"
test_model_path.write_text("MODEL(name sqlmesh_example.test); SELECT 1 AS foo")
sushi_context.load()
notebook.run_line_magic(magic_name="plan", line="--no-prompts --auto-apply")
test_model_path.write_text("MODEL(name sqlmesh_example.test); SELECT 1 AS foo, 2 AS bar")
with capture_output() as output:
notebook.run_line_magic(magic_name="diff", line="prod")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 2
assert convert_all_html_output_to_text(output) == [
"Differences from the `prod` environment:",
"Models:\n└── Directly Modified:\n └── sqlmesh_example.test",
]
assert get_all_html_output(output) == [
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
h(
"span",
{"style": "font-weight: bold"},
"Differences from the `prod` environment:",
autoescape=False,
),
autoescape=False,
)
),
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
str(
h(
"span",
{"style": "font-weight: bold"},
"Models:",
autoescape=False,
)
)
+ "└── "
+ str(
h(
"span",
{"style": "font-weight: bold"},
"Directly Modified:",
autoescape=False,
)
)
+ " └── sqlmesh_example.test",
autoescape=False,
)
),
]
@pytest.mark.slow
def test_plan(
notebook, sushi_context, convert_all_html_output_to_text, convert_all_html_output_to_tags
):
with capture_output() as output:
notebook.run_line_magic(magic_name="plan", line="--no-prompts --auto-apply")
assert not output.stderr
assert len(output.outputs) == 4
text_output = convert_all_html_output_to_text(output)
# TODO: Is this what we expect?
# This has minor differences between CI/CD and local.
assert "[2K" in text_output[0]
assert text_output[1].startswith(
"Updating virtual layer ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0%"
)
# TODO: Is this what we expect?
assert text_output[2] == ""
assert text_output[3] == "✔ Virtual layer updated"
assert convert_all_html_output_to_tags(output) == [
["pre", "span"],
["pre"] + ["span"] * 5,
["pre"],
["pre", "span"],
]
@pytest.mark.slow
@time_machine.travel("2023-01-03 00:00:00 UTC")
def test_run_dag(
notebook, loaded_sushi_context, convert_all_html_output_to_text, get_all_html_output
):
with capture_output() as output:
notebook.run_line_magic(magic_name="run_dag", line="")
assert not output.stdout.startswith(
"'Executing model batches ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100.0% • 18/18"
)
assert not output.stderr
# At least 4 outputs expected as the number of models in the particular batch might vary
assert len(output.outputs) >= 4
html_text_actual = convert_all_html_output_to_text(output)
# Check for key elements in the output
assert any("[2K" in text for text in html_text_actual)
assert any("Executing model batches" in text for text in html_text_actual)
assert any("✔ Model batches executed" in text for text in html_text_actual)
assert any("Run finished for environment 'prod'" in text for text in html_text_actual)
# Check the final messages
final_outputs = [text for text in html_text_actual if text.strip()]
assert final_outputs[-2] == "✔ Model batches executed"
assert final_outputs[-1] == "Run finished for environment 'prod'"
actual_html_output = get_all_html_output(output)
# Replace dynamic elapsed time with 00
for i, chunk in enumerate(actual_html_output):
pattern = r'font-weight: bold">0.</span>\d{2}s </pre>'
import re
actual_html_output[i] = re.sub(pattern, 'font-weight: bold">0.</span>00s </pre>', chunk)
expected_html_output = [
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
"\x1b",
h(
"span",
{"style": BOLD_ONLY},
"[",
autoescape=False,
),
"2K",
autoescape=False,
)
),
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
h(
"span",
{"style": "color: #000080; text-decoration-color: #000080; font-weight: bold"},
"Executing model batches",
autoescape=False,
),
" ",
h(
"span",
{"style": "color: #f92672; text-decoration-color: #f92672"},
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸",
autoescape=False,
),
h(
"span",
{"style": "color: #3a3a3a; text-decoration-color: #3a3a3a"},
"━━",
autoescape=False,
),
" ",
h(
"span",
{"style": "color: #800080; text-decoration-color: #800080"},
"93.8%",
autoescape=False,
),
" • ",
h(
"span",
{"style": SUCCESS_STYLE},
"15/16",
autoescape=False,
),
" • ",
h(
"span",
{"style": "color: #808000; text-decoration-color: #808000"},
"0:00:00",
autoescape=False,
),
"sushi.waiter_as_customer_by_day ",
h(
"span",
{"style": SUCCESS_STYLE},
".. ",
autoescape=False,
),
" ",
autoescape=False,
)
),
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
h(
"span",
{"style": BOLD_ONLY},
"[",
autoescape=False,
),
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"1",
autoescape=False,
),
"/",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"1",
autoescape=False,
),
h(
"span",
{"style": BOLD_ONLY},
"]",
autoescape=False,
),
" sushi.waiter_as_customer_by_day ",
h(
"span",
{"style": BOLD_ONLY},
"[",
autoescape=False,
),
"insert ",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"2023",
autoescape=False,
),
"-",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"01",
autoescape=False,
),
"-",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"01",
autoescape=False,
),
" - ",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"2023",
autoescape=False,
),
"-",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"01",
autoescape=False,
),
"-",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"02",
autoescape=False,
),
", audits ",
h(
"span",
{"style": SUCCESS_STYLE},
"✔",
autoescape=False,
),
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"2",
autoescape=False,
),
h(
"span",
{"style": BOLD_ONLY},
"]",
autoescape=False,
),
" ",
h(
"span",
{"style": BOLD_NEUTRAL_STYLE},
"0.",
autoescape=False,
),
"00s ",
autoescape=False,
)
),
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
"",
autoescape=False,
)
),
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
h(
"span",
{"style": SUCCESS_STYLE},
"✔ Model batches executed",
autoescape=False,
),
autoescape=False,
)
),
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
h(
"span",
{"style": SUCCESS_STYLE},
"Run finished for environment ",
autoescape=False,
),
h(
"span",
{"style": SUCCESS_STYLE},
"'prod'",
autoescape=False,
),
autoescape=False,
)
),
]
@pytest.mark.slow
@time_machine.travel(FREEZE_TIME)
def test_invalidate(
notebook, loaded_sushi_context, convert_all_html_output_to_text, get_all_html_output
):
with capture_output():
notebook.run_line_magic(
magic_name="plan", line="dev --include-unmodified --no-prompts --auto-apply"
)
with capture_output() as output:
notebook.run_line_magic(magic_name="invalidate", line="dev")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 1
assert convert_all_html_output_to_text(output) == [
"Environment 'dev' invalidated.",
]
assert get_all_html_output(output) == [
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
str(
h(
"span",
{"style": SUCCESS_STYLE},
"Environment ",
autoescape=False,
)
)
+ str(
h(
"span",
{"style": SUCCESS_STYLE},
"'dev'",
autoescape=False,
)
)
+ str(
h(
"span",
{"style": SUCCESS_STYLE},
" invalidated.",
autoescape=False,
)
),
autoescape=False,
)
)
]
@pytest.mark.slow
def test_janitor(
notebook, loaded_sushi_context, convert_all_html_output_to_text, get_all_html_output
):
with capture_output():
notebook.run_line_magic(
magic_name="plan", line="dev --include-unmodified --no-prompts --auto-apply"
)
notebook.run_line_magic(magic_name="invalidate", line="dev")
with capture_output() as output:
notebook.run_line_magic(magic_name="janitor", line="")
assert not output.stdout
assert not output.stderr
assert convert_all_html_output_to_text(output) == [
"Deleted object memory.sushi__dev",
"Cleanup complete.",
]
def test_dag(tmp_path_factory, notebook, sushi_context):
temp_dir = tmp_path_factory.mktemp("dag")
dag_file = temp_dir / "dag.html"
with capture_output() as output:
notebook.run_line_magic(magic_name="dag", line=f"--file {str(dag_file)}")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 1
output_plain = output.outputs[0].data["text/plain"]
# When we capture output it just captures the repr of the class, but it gets displayed fine in a notebook
assert "GraphHTML" in output_plain
file_contents = dag_file.read_text()
assert '<div id="sqlglot-lineage">' in file_contents
assert "waiter_revenue_by_day" in file_contents
def test_create_test(notebook, sushi_context):
with capture_output():
notebook.run_line_magic(
magic_name="create_test",
line='''sushi.top_waiters --query sushi.waiter_revenue_by_day "SELECT 1 as waiter_id"''',
)
test_file = sushi_context.path / "tests" / "test_top_waiters.yaml"
assert test_file.exists()
assert (
test_file.read_text()
== """test_top_waiters:
model: '"memory"."sushi"."top_waiters"'
inputs:
'"memory"."sushi"."waiter_revenue_by_day"':
- waiter_id: 1
outputs:
query: []
"""
)
def test_test(notebook, sushi_context):
"""
Not sure how to test the cell contents. If we can figure that out, then it would be great to test
starting with a line magic, output the test to the cell, update cell contents, and then run the cell
and verify the new contents get written to the file. That is a common workflow a user would go through.
Also easier test is testing the ls command
"""
with capture_output() as output:
notebook.run_cell_magic(
magic_name="test",
line="sushi.customer_revenue_by_day test_customer_revenue_by_day",
cell="TESTING",
)
assert not output.stdout
assert not output.stderr
assert not output.outputs
test_file = sushi_context.path / "tests" / "test_customer_revenue_by_day.yaml"
assert test_file.exists()
assert test_file.read_text() == """test_customer_revenue_by_day: TESTING\n"""
@pytest.mark.slow
def test_audit(notebook, loaded_sushi_context, convert_all_html_output_to_text):
with capture_output() as output:
notebook.run_line_magic(magic_name="audit", line="sushi.top_waiters")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 4
assert convert_all_html_output_to_text(output) == [
"Found 1 audit(s).",
"unique_values on model sushi.top_waiters ✅ PASS.",
"Finished with 0 audit errors and 0 audits skipped.",
"Done.",
]
def test_fetchdf(notebook, sushi_context):
with capture_output() as output:
notebook.run_cell_magic(magic_name="fetchdf", line="my_result", cell="SELECT 1 AS foo")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 1
assert output.outputs[0].data["text/plain"] == """ foo\n0 1"""
assert notebook.user_ns["my_result"].to_dict() == {"foo": {0: 1}}
def test_info(notebook, sushi_context, convert_all_html_output_to_text, get_all_html_output):
with capture_output() as output:
notebook.run_line_magic(magic_name="info", line="--verbose")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 6
assert convert_all_html_output_to_text(output) == [
"Models: 20",
"Macros: 8",
"",
"Connection:\n type: duckdb\n concurrent_tasks: 1\n register_comments: true\n pre_ping: false\n pretty_sql: false\n extensions: []\n connector_config: {}\n secrets: None\n filesystems: []",
"Test Connection:\n type: duckdb\n concurrent_tasks: 1\n register_comments: true\n pre_ping: false\n pretty_sql: false\n extensions: []\n connector_config: {}\n secrets: None\n filesystems: []",
"Data warehouse connection succeeded",
]
assert get_all_html_output(output) == [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Models: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">20</span></pre>",
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Macros: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">8</span></pre>",
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>",
'<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace">Connection: type: duckdb concurrent_tasks: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span> register_comments: true pre_ping: false pretty_sql: false extensions: <span style="font-weight: bold">[]</span> connector_config: <span style="font-weight: bold">{}</span> secrets: <span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span> filesystems: <span style="font-weight: bold">[]</span></pre>',
'<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,\'DejaVu Sans Mono\',consolas,\'Courier New\',monospace">Test Connection: type: duckdb concurrent_tasks: <span style="color: #008080; text-decoration-color: #008080; font-weight: bold">1</span> register_comments: true pre_ping: false pretty_sql: false extensions: <span style="font-weight: bold">[]</span> connector_config: <span style="font-weight: bold">{}</span> secrets: <span style="color: #800080; text-decoration-color: #800080; font-style: italic">None</span> filesystems: <span style="font-weight: bold">[]</span></pre>',
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">Data warehouse connection <span style=\"color: #008000; text-decoration-color: #008000\">succeeded</span></pre>",
]
@pytest.mark.slow
def test_migrate(
notebook, loaded_sushi_context, convert_all_html_output_to_text, get_all_html_output
):
with capture_output() as output:
notebook.run_line_magic(magic_name="migrate", line="")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 1
assert convert_all_html_output_to_text(output) == [
"Migration complete",
]
assert get_all_html_output(output) == [
str(
h(
"pre",
{"style": RICH_PRE_STYLE},
h(
"span",
{"style": SUCCESS_STYLE},
"Migration complete",
autoescape=False,
),
autoescape=False,
)
)
]
# TODO: Add test for rollback
# def test_rollback(notebook, loaded_sushi_context):
# with capture_output() as output:
# notebook.run_line_magic(magic_name="rollback", line="")
#
@pytest.mark.slow
def test_create_external_models(notebook, loaded_sushi_context, convert_all_html_output_to_text):
external_model_file = loaded_sushi_context.path / "external_models.yaml"
external_model_file.unlink()
assert not external_model_file.exists()
loaded_sushi_context.load()
with capture_output() as output:
notebook.run_line_magic(magic_name="create_external_models", line="")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 2
converted = sorted(convert_all_html_output_to_text(output))
assert 'Unable to get schema for \'"memory"."raw"."model1"\'' in converted[0]
assert 'Unable to get schema for \'"memory"."raw"."model2"\'' in converted[1]
assert external_model_file.exists()
assert (
external_model_file.read_text()
== """- name: '"memory"."raw"."demographics"'
columns:
customer_id: INT
zip: TEXT
gateway: duckdb
"""
)
@pytest.mark.slow
@time_machine.travel(FREEZE_TIME)
def test_table_diff(notebook, loaded_sushi_context, convert_all_html_output_to_text):
with capture_output():
loaded_sushi_context.plan("dev", no_prompts=True, auto_apply=True, include_unmodified=True)
with capture_output() as output:
notebook.run_line_magic(magic_name="table_diff", line="dev:prod --model sushi.top_waiters")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 1
assert convert_all_html_output_to_text(output) == [
"No models contain differences with the selection criteria: 'sushi.top_waiters'"
]
@pytest.mark.slow
@time_machine.travel(FREEZE_TIME)
def test_table_name(notebook, loaded_sushi_context, convert_all_html_output_to_text):
with capture_output() as output:
notebook.run_line_magic(magic_name="table_name", line="sushi.orders")
assert not output.stdout
assert not output.stderr
assert len(output.outputs) == 1
assert convert_all_html_output_to_text(output)[0].startswith(
"memory.sqlmesh__sushi.sushi__orders__"
)
def test_lint(notebook, sushi_context):
from sqlmesh.core.config import LinterConfig
sushi_context.config.linter = LinterConfig(enabled=True, warn_rules="ALL")
sushi_context.load()
with capture_output() as output:
notebook.run_line_magic(magic_name="lint", line="")
assert len(output.outputs) > 1
assert "Linter warnings for" in output.outputs[0].data["text/plain"]
with capture_output() as output:
notebook.run_line_magic(magic_name="lint", line="--models sushi.items")
assert len(output.outputs) == 1
assert "Linter warnings for" in output.outputs[0].data["text/plain"]
with capture_output() as output:
notebook.run_line_magic(magic_name="lint", line="--models sushi.items sushi.raw_marketing")
assert len(output.outputs) == 2
assert "Linter warnings for" in output.outputs[0].data["text/plain"]
@pytest.mark.slow
def test_destroy(
notebook,
loaded_sushi_context,
convert_all_html_output_to_text,
get_all_html_output,
monkeypatch,
):
# Mock input to return 'y' for the confirmation prompt
monkeypatch.setattr("builtins.input", lambda: "y")
with capture_output() as output:
notebook.run_line_magic(magic_name="destroy", line="")
assert not output.stdout
assert not output.stderr
text_output = convert_all_html_output_to_text(output)
expected_messages = [
"[WARNING] This will permanently delete all engine-managed objects, state tables and SQLMesh cache.\nThe operation may disrupt any currently running or scheduled plans.",
"Schemas to be deleted:",
"• memory.sushi",
"Snapshot tables to be deleted:",
"This action will DELETE ALL the above resources managed by SQLMesh AND\npotentially external resources created by other tools in these schemas.",
"Are you ABSOLUTELY SURE you want to proceed with deletion? [y/n]:",
"Environment 'prod' invalidated.",
"Deleted object memory.sushi",
"State tables removed.",
"Destroy completed successfully.",
]
for message in expected_messages:
assert any(message in line for line in text_output)