-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathtest_integration.py
More file actions
654 lines (586 loc) · 26.7 KB
/
test_integration.py
File metadata and controls
654 lines (586 loc) · 26.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
import datetime
import shutil
import typing as t
from enum import Enum
from functools import partial
from pathlib import Path
import pandas as pd # noqa: TID253
import pytest
from sqlmesh.dbt.util import DBT_VERSION
if DBT_VERSION >= (1, 5, 0):
from dbt.cli.main import dbtRunner # type: ignore
import time_machine
from sqlmesh import Context
from sqlmesh.core.config.connection import DuckDBConnectionConfig
from sqlmesh.core.engine_adapter import DuckDBEngineAdapter
from sqlmesh.utils.pandas import columns_to_types_from_df
from sqlmesh.utils.yaml import YAML, load as yaml_load, dump as yaml_dump
from sqlmesh_dbt.operations import init_project_if_required
from tests.utils.pandas import compare_dataframes, create_df
# Some developers had issues with this test freezing locally so we mark it as cicdonly
pytestmark = [pytest.mark.dbt, pytest.mark.slow, pytest.mark.cicdonly]
class TestType(str, Enum):
__test__ = False # prevent pytest trying to collect this as a test class
DBT_RUNTIME = "dbt_runtime"
DBT_ADAPTER = "dbt_adapter"
SQLMESH = "sqlmesh"
@property
def is_sqlmesh(self) -> bool:
return self == TestType.SQLMESH
@property
def is_dbt_runtime(self) -> bool:
return self == TestType.DBT_RUNTIME
@property
def is_dbt_adapter(self) -> bool:
return self == TestType.DBT_ADAPTER
@property
def is_dbt_project(self):
return self.is_dbt_adapter or self.is_dbt_runtime
@property
def is_sqlmesh_runtime(self) -> bool:
return self.is_sqlmesh or self.is_dbt_adapter
class TestStrategy(str, Enum):
__test__ = False # prevent pytest trying to collect this as a test class
CHECK = "check"
TIMESTAMP = "timestamp"
@property
def is_timestamp(self) -> bool:
return self == TestStrategy.TIMESTAMP
@property
def is_check(self) -> bool:
return self == TestStrategy.CHECK
class TestSCDType2:
source_schema = {"customer_id": "int32", "status": "object", "updated_at": "datetime64[us]"}
target_schema = {
"customer_id": "int32",
"status": "object",
"updated_at": "datetime64[us]",
"valid_from": "datetime64[us]",
"valid_to": "datetime64[us]",
}
@pytest.fixture(params=list(TestType))
def test_type(self, request):
return request.param
@pytest.fixture(params=[True, False])
def invalidate_hard_deletes(self, request):
return request.param
@pytest.fixture(scope="function")
def create_scd_type_2_dbt_project(self, tmp_path):
def _make_function(
test_strategy: TestStrategy,
include_dbt_adapter_support: bool = False,
invalidate_hard_deletes: bool = False,
) -> t.Tuple[Path, Path]:
yaml = YAML()
dbt_project_dir = tmp_path / "dbt"
dbt_project_dir.mkdir()
dbt_snapshot_dir = dbt_project_dir / "snapshots"
dbt_snapshot_dir.mkdir()
snapshot_file_contents = f"""{{% snapshot marketing %}}
{{{{
config(
target_schema='sushi',
unique_key='customer_id',
strategy='{test_strategy.value}',
{"updated_at='updated_at'" if test_strategy.is_timestamp else "check_cols='all'"},
invalidate_hard_deletes={invalidate_hard_deletes},
)
}}}}
select * from local.sushi.raw_marketing
{{% endsnapshot %}}"""
snapshot_file = dbt_snapshot_dir / "marketing.sql"
with open(snapshot_file, "w", encoding="utf-8") as f:
f.write(snapshot_file_contents)
dbt_project_config = {
"name": "scd_type_2",
"version": "1.0.0",
"config-version": 2,
"profile": "test",
"snapshot-paths": ["snapshots"],
"models": {"start": "Jan 1 2020"},
}
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)
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",
}
}
dbt_profile_file = dbt_project_dir / "profiles.yml"
with open(dbt_profile_file, "w", encoding="utf-8") as f:
yaml.dump(dbt_profile_config, f)
if include_dbt_adapter_support:
sqlmesh_config_file = dbt_project_dir / "config.py"
with open(sqlmesh_config_file, "w", encoding="utf-8") as f:
f.write(
"""from pathlib import Path
from sqlmesh.dbt.loader import sqlmesh_config
config = sqlmesh_config(Path(__file__).parent)
test_config = config"""
)
return dbt_project_dir, dbt_data_file
return _make_function
@pytest.fixture
def create_scd_type_2_sqlmesh_project(self, tmp_path):
def _make_function(
test_strategy: TestStrategy, invalidate_hard_deletes: bool
) -> t.Tuple[Path, Path]:
sushi_root = Path("examples/sushi")
project_root = tmp_path / "sqlmesh"
project_root.mkdir()
shutil.copy(str(sushi_root / "config.py"), str(project_root / "config.py"))
(project_root / "models").mkdir()
if test_strategy.is_timestamp:
kind_def = f"SCD_TYPE_2(unique_key customer_id, updated_at_as_valid_from true, invalidate_hard_deletes {invalidate_hard_deletes})"
else:
kind_def = f"SCD_TYPE_2_BY_COLUMN(unique_key customer_id, execution_time_as_valid_from true, columns *, invalidate_hard_deletes {invalidate_hard_deletes})"
snapshot_def = f"""MODEL (
name sushi.marketing,
kind {kind_def},
owner jen,
cron '@daily',
grain customer_id,
);
SELECT
customer_id::INT AS customer_id,
status::TEXT AS status,
updated_at::TIMESTAMP AS updated_at
FROM
sushi.raw_marketing"""
with open(project_root / "models" / "marketing.sql", "w", encoding="utf-8") as f:
f.write(snapshot_def)
data_dir = tmp_path / "sqlm_data"
data_dir.mkdir()
data_file = data_dir / "local.db"
return project_root, data_file
return _make_function
def _replace_source_table(
self,
adapter: DuckDBEngineAdapter,
values: t.List[t.Tuple[int, str, str]],
):
df = create_df(values, self.source_schema)
columns_to_types = columns_to_types_from_df(df)
if values:
adapter.replace_query(
"sushi.raw_marketing", df, target_columns_to_types=columns_to_types
)
else:
adapter.create_table("sushi.raw_marketing", target_columns_to_types=columns_to_types)
def _normalize_dbt_dataframe(
self,
df: pd.DataFrame,
test_type: TestType,
time_start_end_mapping: t.Optional[
t.Dict[str, t.Tuple[datetime.datetime, datetime.datetime]]
],
) -> pd.DataFrame:
def update_now_column(col_timestamp: pd.Timestamp) -> datetime.datetime:
assert time_start_end_mapping is not None
col_datetime = col_timestamp.to_pydatetime()
for now_time, (start_time, end_time) in time_start_end_mapping.items():
start_time = start_time.replace(tzinfo=None)
end_time = end_time.replace(tzinfo=None)
if start_time <= col_datetime <= end_time:
col_datetime = pd.to_datetime(now_time).tz_localize(None)
return col_datetime
df = df.rename(columns={"dbt_valid_from": "valid_from", "dbt_valid_to": "valid_to"})
if test_type.is_dbt_runtime:
df = df.drop(columns=["dbt_updated_at", "dbt_scd_id"])
for col in ["valid_from", "valid_to"]:
df[col] = df[col].apply(update_now_column)
df[col] = df[col].astype("datetime64[us]")
return df
def _get_current_df(
self,
adapter: DuckDBEngineAdapter,
*,
test_type: TestType,
time_start_end_mapping: t.Optional[
t.Dict[str, t.Tuple[datetime.datetime, datetime.datetime]]
] = None,
) -> pd.DataFrame:
df = adapter.fetchdf("SELECT * FROM sushi.marketing")
if test_type.is_dbt_project:
df = self._normalize_dbt_dataframe(
df, test_type, time_start_end_mapping=time_start_end_mapping
)
return df
def _get_duckdb_now(self, adapter: DuckDBEngineAdapter) -> datetime.datetime:
return adapter.fetchone("SELECT now()")[0] # type: ignore
def _init_test(
self,
create_scd_type_2_dbt_project,
create_scd_type_2_sqlmesh_project,
test_type: TestType,
test_strategy: TestStrategy,
invalidate_hard_deletes: bool,
):
project_dir, data_file = (
create_scd_type_2_sqlmesh_project(
test_strategy=test_strategy, invalidate_hard_deletes=invalidate_hard_deletes
)
if test_type.is_sqlmesh
else create_scd_type_2_dbt_project(
test_strategy=test_strategy,
include_dbt_adapter_support=test_type.is_dbt_adapter,
invalidate_hard_deletes=invalidate_hard_deletes,
)
)
context: t.Union[Context, dbtRunner]
if test_type.is_dbt_runtime:
dbt_run_args = [
"snapshot",
"--profiles-dir",
f"{project_dir}",
"--project-dir",
f"{project_dir}",
"--target",
"duckdb",
]
adapter = t.cast(
DuckDBEngineAdapter,
DuckDBConnectionConfig(database=str(data_file)).create_engine_adapter(),
)
context = dbtRunner()
run = partial(context.invoke, dbt_run_args)
else:
context = Context(paths=project_dir, config="test_config")
adapter = t.cast(DuckDBEngineAdapter, context.engine_adapter)
run = partial(context.run, skip_janitor=True) # type: ignore
adapter.create_schema("raw")
adapter.create_schema("sushi")
if test_type.is_sqlmesh_runtime:
self._replace_source_table(adapter, [])
with time_machine.travel("2019-12-31 00:00:00 UTC"):
context.plan("prod", auto_apply=True, no_prompts=True) # type: ignore
return run, adapter, context
def test_scd_type_2_by_time(
self,
tmp_path,
copy_to_temp_path,
create_scd_type_2_dbt_project,
create_scd_type_2_sqlmesh_project,
test_type: TestType,
invalidate_hard_deletes: bool,
):
if test_type.is_dbt_runtime and DBT_VERSION < (1, 5, 0):
pytest.skip("The dbt version being tested doesn't support the dbtRunner so skipping.")
run, adapter, context = self._init_test(
create_scd_type_2_dbt_project,
create_scd_type_2_sqlmesh_project,
test_type,
TestStrategy.TIMESTAMP,
invalidate_hard_deletes,
)
time_expected_mapping: t.Dict[
str,
t.Tuple[
t.List[t.Tuple[int, str, str]], t.List[t.Tuple[int, str, str, str, t.Optional[str]]]
],
] = {
"2020-01-01 00:00:00 UTC": (
[
(1, "a", "2020-01-01 00:00:00"),
(2, "b", "2020-01-01 00:00:00"),
(3, "c", "2020-01-01 00:00:00"),
],
[
(1, "a", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
(2, "b", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
(3, "c", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
],
),
"2020-01-02 00:00:00 UTC": (
[
# Update to "x"
(1, "x", "2020-01-02 00:00:00"),
# No Change
(2, "b", "2020-01-01 00:00:00"),
# Deleted 3
# (3, "c", "2020-01-01 00:00:00"),
# Added 4
(4, "d", "2020-01-02 00:00:00"),
],
[
(1, "a", "2020-01-01 00:00:00", "2020-01-01 00:00:00", "2020-01-02 00:00:00"),
(1, "x", "2020-01-02 00:00:00", "2020-01-02 00:00:00", None),
(2, "b", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
(
3,
"c",
"2020-01-01 00:00:00",
"2020-01-01 00:00:00",
"2020-01-02 00:00:00" if invalidate_hard_deletes else None,
),
(4, "d", "2020-01-02 00:00:00", "2020-01-02 00:00:00", None),
],
),
"2020-01-04 00:00:00 UTC": (
[
# Update to "y"
(1, "y", "2020-01-03 00:00:00"),
# Delete 2
# (2, "b", "2020-01-01 00:00:00"),
# Add back 3
(3, "c", "2020-02-01 00:00:00"),
# No Change
(4, "d", "2020-01-02 00:00:00"),
# Added 5
(5, "e", "2020-01-03 00:00:00"),
],
[
(1, "a", "2020-01-01 00:00:00", "2020-01-01 00:00:00", "2020-01-02 00:00:00"),
(1, "x", "2020-01-02 00:00:00", "2020-01-02 00:00:00", "2020-01-03 00:00:00"),
(1, "y", "2020-01-03 00:00:00", "2020-01-03 00:00:00", None),
(
2,
"b",
"2020-01-01 00:00:00",
"2020-01-01 00:00:00",
"2020-01-04 00:00:00" if invalidate_hard_deletes else None,
),
(
3,
"c",
"2020-01-01 00:00:00",
"2020-01-01 00:00:00",
"2020-01-02 00:00:00" if invalidate_hard_deletes else "2020-02-01 00:00:00",
),
# Since 3 was deleted and came back and the updated at time when it came back
# is greater than the execution time when it was deleted, we have the valid_from
# match the updated_at time. If it was less then the valid_from would match the
# execution time when it was deleted.
(3, "c", "2020-02-01 00:00:00", "2020-02-01 00:00:00", None),
# What the result would be if the updated_at time was `2020-01-03`
# (3, "c", "2020-01-03 00:00:00", "2020-01-04 00:00:00", None),
(4, "d", "2020-01-02 00:00:00", "2020-01-02 00:00:00", None),
(5, "e", "2020-01-03 00:00:00", "2020-01-03 00:00:00", None),
],
),
}
time_start_end_mapping = {}
for time, (starting_source_data, expected_table_data) in time_expected_mapping.items():
self._replace_source_table(adapter, starting_source_data)
# Tick when running dbt runtime because it hangs during execution for unknown reasons.
with time_machine.travel(time, tick=test_type.is_dbt_runtime):
start_time = self._get_duckdb_now(adapter)
run()
end_time = self._get_duckdb_now(adapter)
time_start_end_mapping[time] = (start_time, end_time)
df_actual = self._get_current_df(
adapter, test_type=test_type, time_start_end_mapping=time_start_end_mapping
)
df_expected = create_df(expected_table_data, self.target_schema)
compare_dataframes(df_actual, df_expected, msg=f"Failed on time {time}")
def test_scd_type_2_by_column(
self,
tmp_path,
copy_to_temp_path,
create_scd_type_2_dbt_project,
create_scd_type_2_sqlmesh_project,
test_type: TestType,
invalidate_hard_deletes: bool,
):
if test_type.is_dbt_runtime:
pytest.skip(
"the dbt runner, despite running in an entirely different project with different connection config, reuses the adapter from other tests. As a result we skip this test when running automatically to avoid an error but comment this out if testing column scd type 2 in isolation."
)
run, adapter, context = self._init_test(
create_scd_type_2_dbt_project,
create_scd_type_2_sqlmesh_project,
test_type,
TestStrategy.CHECK,
invalidate_hard_deletes,
)
time_expected_mapping: t.Dict[
str,
t.Tuple[
t.List[t.Tuple[int, str, str]], t.List[t.Tuple[int, str, str, str, t.Optional[str]]]
],
] = {
"2020-01-01 00:00:00 UTC": (
[
(1, "a", "2020-01-01 00:00:00"),
(2, "b", "2020-01-01 00:00:00"),
(3, "c", "2020-01-01 00:00:00"),
],
[
(1, "a", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
(2, "b", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
(3, "c", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
],
),
"2020-01-02 00:00:00 UTC": (
[
# Update to "x"
(1, "x", "2020-01-02 00:00:00"),
# No Change
(2, "b", "2020-01-01 00:00:00"),
# Deleted 3
# (3, "c", "2020-01-01 00:00:00"),
# Added 4
(4, "d", "2020-01-02 00:00:00"),
],
[
(1, "a", "2020-01-01 00:00:00", "2020-01-01 00:00:00", "2020-01-02 00:00:00"),
(1, "x", "2020-01-02 00:00:00", "2020-01-02 00:00:00", None),
(2, "b", "2020-01-01 00:00:00", "2020-01-01 00:00:00", None),
(
3,
"c",
"2020-01-01 00:00:00",
"2020-01-01 00:00:00",
"2020-01-02 00:00:00" if invalidate_hard_deletes else None,
),
(4, "d", "2020-01-02 00:00:00", "2020-01-02 00:00:00", None),
],
),
"2020-01-04 00:00:00 UTC": (
[
# Update to "y"
(1, "y", "2020-01-03 00:00:00"),
# Delete 2
# (2, "b", "2020-01-01 00:00:00"),
# Add back 3
(3, "c", "2020-02-01 00:00:00"),
# No Change
(4, "d", "2020-01-02 00:00:00"),
# Added 5
(5, "e", "2020-01-03 00:00:00"),
],
[
(1, "a", "2020-01-01 00:00:00", "2020-01-01 00:00:00", "2020-01-02 00:00:00"),
(1, "x", "2020-01-02 00:00:00", "2020-01-02 00:00:00", "2020-01-04 00:00:00"),
(1, "y", "2020-01-03 00:00:00", "2020-01-04 00:00:00", None),
(
2,
"b",
"2020-01-01 00:00:00",
"2020-01-01 00:00:00",
"2020-01-04 00:00:00" if invalidate_hard_deletes else None,
),
(
3,
"c",
"2020-01-01 00:00:00",
"2020-01-01 00:00:00",
"2020-01-02 00:00:00" if invalidate_hard_deletes else "2020-01-04 00:00:00",
),
# Since 3 was deleted and came back then the valid_from is set to the execution_time when it
# came back.
(3, "c", "2020-02-01 00:00:00", "2020-01-04 00:00:00", None),
(4, "d", "2020-01-02 00:00:00", "2020-01-02 00:00:00", None),
(5, "e", "2020-01-03 00:00:00", "2020-01-04 00:00:00", None),
],
),
}
time_start_end_mapping = {}
for time, (starting_source_data, expected_table_data) in time_expected_mapping.items():
self._replace_source_table(adapter, starting_source_data)
with time_machine.travel(time, tick=False):
start_time = self._get_duckdb_now(adapter)
run()
end_time = self._get_duckdb_now(adapter)
time_start_end_mapping[time] = (start_time, end_time)
df_actual = self._get_current_df(
adapter, test_type=test_type, time_start_end_mapping=time_start_end_mapping
)
df_expected = create_df(expected_table_data, self.target_schema)
compare_dataframes(df_actual, df_expected, msg=f"Failed on time {time}")
def test_dbt_node_info(jaffle_shop_duckdb_context: Context):
ctx = jaffle_shop_duckdb_context
customers = ctx.models['"jaffle_shop"."main"."customers"']
assert customers.dbt_unique_id == "model.jaffle_shop.customers"
assert customers.dbt_fqn == "jaffle_shop.customers"
assert customers.dbt_node_info
assert customers.dbt_node_info.name == "customers"
orders = ctx.models['"jaffle_shop"."main"."orders"']
assert orders.dbt_unique_id == "model.jaffle_shop.orders"
assert orders.dbt_fqn == "jaffle_shop.orders"
assert orders.dbt_node_info
assert orders.dbt_node_info.name == "orders"
stg_customers = ctx.models['"jaffle_shop"."main"."stg_customers"']
assert stg_customers.dbt_unique_id == "model.jaffle_shop.stg_customers"
assert stg_customers.dbt_fqn == "jaffle_shop.staging.stg_customers"
assert stg_customers.dbt_node_info
assert stg_customers.dbt_node_info.name == "stg_customers"
stg_orders = ctx.models['"jaffle_shop"."main"."stg_orders"']
assert stg_orders.dbt_unique_id == "model.jaffle_shop.stg_orders"
assert stg_orders.dbt_fqn == "jaffle_shop.staging.stg_orders"
assert stg_orders.dbt_node_info
assert stg_orders.dbt_node_info.name == "stg_orders"
raw_customers = ctx.models['"jaffle_shop"."main"."raw_customers"']
assert raw_customers.dbt_unique_id == "seed.jaffle_shop.raw_customers"
assert raw_customers.dbt_fqn == "jaffle_shop.raw_customers"
assert raw_customers.dbt_node_info
assert raw_customers.dbt_node_info.name == "raw_customers"
raw_orders = ctx.models['"jaffle_shop"."main"."raw_orders"']
assert raw_orders.dbt_unique_id == "seed.jaffle_shop.raw_orders"
assert raw_orders.dbt_fqn == "jaffle_shop.raw_orders"
assert raw_orders.dbt_node_info
assert raw_orders.dbt_node_info.name == "raw_orders"
raw_payments = ctx.models['"jaffle_shop"."main"."raw_payments"']
assert raw_payments.dbt_unique_id == "seed.jaffle_shop.raw_payments"
assert raw_payments.dbt_fqn == "jaffle_shop.raw_payments"
assert raw_payments.dbt_node_info
assert raw_payments.dbt_node_info.name == "raw_payments"
relationship_audit = ctx.snapshots[
"relationships_orders_customer_id__customer_id__ref_customers_"
]
assert relationship_audit.node.is_audit
assert (
relationship_audit.node.dbt_unique_id
== "test.jaffle_shop.relationships_orders_customer_id__customer_id__ref_customers_.c6ec7f58f2"
)
assert (
relationship_audit.node.dbt_fqn
== "jaffle_shop.relationships_orders_customer_id__customer_id__ref_customers_"
)
assert relationship_audit.node.dbt_node_info
assert (
relationship_audit.node.dbt_node_info.name
== "relationships_orders_customer_id__customer_id__ref_customers_"
)
def test_state_schema_isolation_per_target(jaffle_shop_duckdb: Path):
profiles_file = jaffle_shop_duckdb / "profiles.yml"
profiles_yml = yaml_load(profiles_file)
# make prod / dev config identical with the exception of a different default schema to simulate using the same warehouse
profiles_yml["jaffle_shop"]["outputs"]["prod"] = {
**profiles_yml["jaffle_shop"]["outputs"]["dev"]
}
profiles_yml["jaffle_shop"]["outputs"]["prod"]["schema"] = "prod_schema"
profiles_yml["jaffle_shop"]["outputs"]["dev"]["schema"] = "dev_schema"
profiles_file.write_text(yaml_dump(profiles_yml))
init_project_if_required(jaffle_shop_duckdb)
# start off with the prod target
prod_ctx = Context(paths=[jaffle_shop_duckdb], config_loader_kwargs={"target": "prod"})
assert prod_ctx.config.get_state_schema() == "sqlmesh_state_jaffle_shop_prod_schema"
assert all("prod_schema" in fqn for fqn in prod_ctx.models)
assert prod_ctx.plan(auto_apply=True).has_changes
assert not prod_ctx.plan(auto_apply=True).has_changes
# dev target should have changes - new state separate from prod
dev_ctx = Context(paths=[jaffle_shop_duckdb], config_loader_kwargs={"target": "dev"})
assert dev_ctx.config.get_state_schema() == "sqlmesh_state_jaffle_shop_dev_schema"
assert all("dev_schema" in fqn for fqn in dev_ctx.models)
assert dev_ctx.plan(auto_apply=True).has_changes
assert not dev_ctx.plan(auto_apply=True).has_changes
# no explicitly specified target should use dev because that's what's set for the default in the profiles.yml
assert profiles_yml["jaffle_shop"]["target"] == "dev"
default_ctx = Context(paths=[jaffle_shop_duckdb])
assert default_ctx.config.get_state_schema() == "sqlmesh_state_jaffle_shop_dev_schema"
assert all("dev_schema" in fqn for fqn in default_ctx.models)
assert not default_ctx.plan(auto_apply=True).has_changes
# an explicit state schema override set in `sqlmesh.yaml` should use that
sqlmesh_yaml_file = jaffle_shop_duckdb / "sqlmesh.yaml"
sqlmesh_yaml = yaml_load(sqlmesh_yaml_file)
sqlmesh_yaml["gateways"] = {"dev": {"state_schema": "sqlmesh_dev_state_override"}}
sqlmesh_yaml_file.write_text(yaml_dump(sqlmesh_yaml))
default_ctx = Context(paths=[jaffle_shop_duckdb])
assert default_ctx.config.get_state_schema() == "sqlmesh_dev_state_override"
assert all("dev_schema" in fqn for fqn in default_ctx.models)