Skip to content

Commit beda572

Browse files
feat(dbt): nest generic test arguments under arguments property (closes #1680) (#1682)
* feat(dbt): nest generic test arguments under arguments property DBT 1.10+ deprecated declaring generic test parameters directly under the test key without an arguments mapping (MissingArgumentsPropertyInGenericTestDeprecation). This updates export dbt-sources, export dbt-models, and dbt sync to emit generic test parameters under the arguments property while preserving backwards-compatibility in sync helpers when reading pre-existing tests. Closes #1680 * style: apply ruff format to the dbt test changes * fix(dbt): keep a versioned column's tests shared when its existing file still uses the pre-arguments syntax A versioned `dbt sync` compared the tests in the existing model YAML with the freshly generated ones including the `arguments:` wrapper, so any file written by an earlier CLI release never matched. An unchanged column was then forked into per-version overrides on the first sync after upgrading, and the sibling version kept its old-syntax test (and dbt's deprecation warning). Both shapes now compare by their arguments, so the column stays shared and is rewritten to the new syntax. * refactor(dbt): drop the unreachable pre-arguments branch from the relationships ref rewrite * test(dbt): keep one pre-arguments case in the test-description templates * feat(dbt): explain that dbt 1.10 or later is required when dbt test fails on an older dbt `datacontract dbt test` and `dbt sync --run-tests` now stop with "dbt 1.9.11 is not supported: the generated tests need dbt 1.10 or later" instead of dbt's raw macro error when an older dbt fails to parse the generated tests. The dbt guide and the dbt-models / dbt-sources export pages state the dbt 1.10 minimum. * Add CHANGELOG entry --------- Co-authored-by: Jakob Schödl <jakob.schoedl@entropy-data.com>
1 parent 795e807 commit beda572

11 files changed

Lines changed: 215 additions & 93 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1111
- `datacontract export pydantic-model`: export `logicalTypeOptions` as `pydantic.Field` constraints (#1679)
1212

1313
### Changed
14+
- `datacontract export dbt-models`, `datacontract export dbt-sources` and `datacontract dbt sync` nest generic-test parameters under `arguments:` **(we now require dbt 1.10+)** (#1680)
1415
- `datacontract export pydantic-model`: optional fields default to `None` (#1679)
1516

1617
### Fixed

‎datacontract/export/dbt_exporter.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def _to_dbt_model(
164164
if len(primary_key_columns) > 1:
165165
# Multiple columns: use dbt_utils.unique_combination_of_columns
166166
dbt_model["data_tests"] = [
167-
{"dbt_utils.unique_combination_of_columns": {"combination_of_columns": primary_key_columns}}
167+
{"dbt_utils.unique_combination_of_columns": {"arguments": {"combination_of_columns": primary_key_columns}}}
168168
]
169169

170170
columns = _to_columns(
@@ -229,7 +229,11 @@ def _to_column(
229229
column["data_type"] = dbt_type
230230
else:
231231
column["data_tests"].append(
232-
{"dbt_expectations.dbt_expectations.expect_column_values_to_be_of_type": {"column_type": dbt_type}}
232+
{
233+
"dbt_expectations.dbt_expectations.expect_column_values_to_be_of_type": {
234+
"arguments": {"column_type": dbt_type}
235+
}
236+
}
233237
)
234238
if prop.description is not None:
235239
column["description"] = prop.description.strip().replace("\n", " ")

‎datacontract/integration/dbt_sync.py‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,7 @@ def _describe_dbt_test(test: Any, field_name: Optional[str], model_name: str) ->
472472
return _describe_dbt_test(name, field_name, model_name)
473473
if not isinstance(args, dict):
474474
return None
475+
args = _test_args(args)
475476
if name == "accepted_values":
476477
values = args.get("values")
477478
if isinstance(values, list) and len(values) == 1:
@@ -531,10 +532,12 @@ def _rewrite_relationships_to_ref(tests: list) -> list:
531532
for t in tests:
532533
if isinstance(t, dict) and "relationships" in t and isinstance(t["relationships"], dict):
533534
rel = dict(t["relationships"])
534-
to_value = rel.get("to") or ""
535+
args = dict(rel["arguments"])
536+
to_value = args.get("to") or ""
535537
m = _REL_SOURCE_RE.match(to_value)
536538
if m:
537-
rel["to"] = f"ref('{m.group(1)}')"
539+
args["to"] = f"ref('{m.group(1)}')"
540+
rel["arguments"] = args
538541
out.append({"relationships": rel})
539542
else:
540543
out.append(t)
@@ -1060,7 +1063,7 @@ def _column_dict(
10601063
if data_quality.query:
10611064
continue
10621065
if data_quality.mustBe is not None:
1063-
entry = {"accepted_values": {"values": [data_quality.mustBe]}}
1066+
entry = {"accepted_values": {"arguments": {"values": [data_quality.mustBe]}}}
10641067
tests.append(
10651068
_attach_test_config(
10661069
entry,
@@ -1182,6 +1185,13 @@ def _test_body(entry: str | dict) -> dict:
11821185
return {}
11831186

11841187

1188+
def _test_args(body: dict) -> dict:
1189+
"""A test's arguments, whether nested under `arguments:` (dbt 1.10+) or inline (older CLI output)."""
1190+
if isinstance(body.get("arguments"), dict):
1191+
return body["arguments"]
1192+
return {k: v for k, v in body.items() if k not in ("config", "description")}
1193+
1194+
11851195
def _meta_block_for_test(entry: str | dict) -> dict:
11861196
"""The CLI's `config.meta.datacontract_cli` block on a test entry, or `{}`."""
11871197
meta = (_test_body(entry).get("config") or {}).get("meta") or {}
@@ -1879,7 +1889,7 @@ def _managed_test_args(container: dict) -> dict[str, dict]:
18791889
continue
18801890
name = _test_name(test)
18811891
if name is not None:
1882-
out[name] = {k: v for k, v in _test_body(test).items() if k not in ("config", "description")}
1892+
out[name] = _test_args(_test_body(test))
18831893
return out
18841894

18851895

@@ -1888,7 +1898,7 @@ def _desired_test_args(desired_tests: list) -> dict[str, dict]:
18881898
for test in desired_tests or []:
18891899
name = _test_name(test)
18901900
if name is not None:
1891-
out[name] = {k: v for k, v in _test_body(test).items() if k not in ("config", "description")}
1901+
out[name] = _test_args(_test_body(test))
18921902
return out
18931903

18941904

@@ -2502,6 +2512,15 @@ def run_dbt_test(
25022512
ansi_control_chars = re.compile(r"\x1b\[[0-9;]*[mGKHF]")
25032513
output = ansi_control_chars.sub("", (result.stderr or "") + (result.stdout or ""))
25042514
if result.returncode != 0 and not run_results_path.is_file():
2515+
dbt_version = re.search(r"Running with dbt=((\d+)\.(\d+)\S*)", output)
2516+
if dbt_version and (int(dbt_version.group(2)), int(dbt_version.group(3))) < (1, 10):
2517+
raise DataContractException(
2518+
type="dbt_sync",
2519+
name="dbt test",
2520+
reason=f"dbt {dbt_version.group(1)} is not supported: the generated tests need dbt 1.10 or later. "
2521+
"Upgrade dbt and run again.",
2522+
engine="datacontract-cli",
2523+
)
25052524
raise DataContractException(
25062525
type="dbt_sync",
25072526
name="dbt test",

‎datacontract/integration/dbt_test_mapping.py‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def field_to_data_tests(
5858

5959
enum_values = get_enum_values(prop)
6060
if enum_values and len(enum_values) > 0:
61-
tests.append({"accepted_values": {"values": enum_values}})
61+
tests.append({"accepted_values": {"arguments": {"values": enum_values}}})
6262

6363
if include_dbt_expectations_bounds:
6464
min_length = get_logical_type_option(prop, "minLength")
@@ -69,11 +69,11 @@ def field_to_data_tests(
6969
length_test["min_value"] = min_length
7070
if max_length is not None:
7171
length_test["max_value"] = max_length
72-
tests.append({"dbt_expectations.expect_column_value_lengths_to_be_between": length_test})
72+
tests.append({"dbt_expectations.expect_column_value_lengths_to_be_between": {"arguments": length_test}})
7373

7474
pattern = get_logical_type_option(prop, "pattern")
7575
if pattern is not None:
76-
tests.append({"dbt_expectations.expect_column_values_to_match_regex": {"regex": pattern}})
76+
tests.append({"dbt_expectations.expect_column_values_to_match_regex": {"arguments": {"regex": pattern}}})
7777

7878
minimum = get_logical_type_option(prop, "minimum")
7979
maximum = get_logical_type_option(prop, "maximum")
@@ -86,35 +86,43 @@ def field_to_data_tests(
8686
range_test["min_value"] = minimum
8787
if maximum is not None:
8888
range_test["max_value"] = maximum
89-
tests.append({"dbt_expectations.expect_column_values_to_be_between": range_test})
89+
tests.append({"dbt_expectations.expect_column_values_to_be_between": {"arguments": range_test}})
9090
elif (exclusive_minimum is not None or exclusive_maximum is not None) and minimum is None and maximum is None:
9191
range_test = {}
9292
if exclusive_minimum is not None:
9393
range_test["min_value"] = exclusive_minimum
9494
if exclusive_maximum is not None:
9595
range_test["max_value"] = exclusive_maximum
9696
range_test["strictly"] = True
97-
tests.append({"dbt_expectations.expect_column_values_to_be_between": range_test})
97+
tests.append({"dbt_expectations.expect_column_values_to_be_between": {"arguments": range_test}})
9898
else:
9999
if minimum is not None:
100-
tests.append({"dbt_expectations.expect_column_values_to_be_between": {"min_value": minimum}})
100+
tests.append(
101+
{"dbt_expectations.expect_column_values_to_be_between": {"arguments": {"min_value": minimum}}}
102+
)
101103
if maximum is not None:
102-
tests.append({"dbt_expectations.expect_column_values_to_be_between": {"max_value": maximum}})
104+
tests.append(
105+
{"dbt_expectations.expect_column_values_to_be_between": {"arguments": {"max_value": maximum}}}
106+
)
103107
if exclusive_minimum is not None:
104108
tests.append(
105109
{
106110
"dbt_expectations.expect_column_values_to_be_between": {
107-
"min_value": exclusive_minimum,
108-
"strictly": True,
111+
"arguments": {
112+
"min_value": exclusive_minimum,
113+
"strictly": True,
114+
}
109115
}
110116
}
111117
)
112118
if exclusive_maximum is not None:
113119
tests.append(
114120
{
115121
"dbt_expectations.expect_column_values_to_be_between": {
116-
"max_value": exclusive_maximum,
117-
"strictly": True,
122+
"arguments": {
123+
"max_value": exclusive_maximum,
124+
"strictly": True,
125+
}
118126
}
119127
}
120128
)
@@ -131,8 +139,10 @@ def field_to_data_tests(
131139
tests.append(
132140
{
133141
"relationships": {
134-
"to": f"""source("{source_name}", "{table_name}")""",
135-
"field": f"{column_name}",
142+
"arguments": {
143+
"to": f"""source("{source_name}", "{table_name}")""",
144+
"field": f"{column_name}",
145+
}
136146
}
137147
}
138148
)

‎docs/docs/dbt.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ The Data Contract CLI integrates with [dbt](https://www.getdbt.com/) in multiple
1515
- **Export**: Do a one-time export from a data contract into a dbt model schema, a sources YAML, or a staging SQL file (`datacontract export`)
1616
- **Import**: Create a data contract from a dbt manifest file (`datacontract import dbt`)
1717

18+
The tests that `dbt sync`, `dbt-models` and `dbt-sources` generate need dbt 1.10 or later. `datacontract dbt test`
19+
and `dbt sync --run-tests` stop with an error on an older dbt.
20+
1821

1922
## `datacontract dbt sync`
2023

‎docs/docs/exports/dbt-models.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ models:
6464

6565
If a server is selected via `--server` (based on its `type`), the dbt column `data_types` match the expected data types of that server. If no server is selected, it defaults to `snowflake`.
6666

67+
The generated tests need dbt 1.10 or later.
68+
6769
See the [dbt Integration](../dbt.md) guide for the full picture, including `datacontract dbt sync`.
6870

6971
All options: **[`datacontract export dbt-models`](../commands/export/dbt-models.md)**.

‎docs/docs/exports/dbt-sources.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,6 @@ sources:
6464

6565
As with [`dbt-models`](./dbt-models.md), selecting a server maps logical types to that server's data types; otherwise `snowflake` is used.
6666

67+
The generated tests need dbt 1.10 or later.
68+
6769
All options: **[`datacontract export dbt-sources`](../commands/export/dbt-sources.md)**.

‎tests/test_dbt_sync.py‎

Lines changed: 63 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -727,11 +727,15 @@ def test_normalize_severity():
727727

728728
def test_attach_config_dict_test():
729729
result = _attach_test_config(
730-
{"accepted_values": {"values": [1, 2]}}, "error", check_type="field_enum", model="orders", field="status"
730+
{"accepted_values": {"arguments": {"values": [1, 2]}}},
731+
"error",
732+
check_type="field_enum",
733+
model="orders",
734+
field="status",
731735
)
732736
assert result == {
733737
"accepted_values": {
734-
"values": [1, 2],
738+
"arguments": {"values": [1, 2]},
735739
"config": {
736740
"severity": "error",
737741
"meta": {"datacontract_cli": {"check": "orders__status__field_enum"}},
@@ -745,17 +749,25 @@ def test_attach_config_dict_test():
745749
[
746750
("not_null", "Check that field order_id has no missing values"),
747751
("unique", "Check that field order_id has no duplicate values"),
752+
(
753+
{"accepted_values": {"arguments": {"values": ["pending", "shipped"]}}},
754+
"Check that field order_id only contains enum values ['pending', 'shipped']",
755+
),
748756
(
749757
{"accepted_values": {"values": ["pending", "shipped"]}},
750758
"Check that field order_id only contains enum values ['pending', 'shipped']",
751759
),
752-
({"accepted_values": {"values": ["X"]}}, "Check that field order_id is equal to X"),
760+
({"accepted_values": {"arguments": {"values": ["X"]}}}, "Check that field order_id is equal to X"),
753761
(
754-
{"relationships": {"to": "ref('customers')", "field": "id"}},
762+
{"relationships": {"arguments": {"to": "ref('customers')", "field": "id"}}},
755763
"Check that field order_id references ref('customers').id",
756764
),
757765
(
758-
{"dbt_utils.unique_combination_of_columns": {"combination_of_columns": ["order_id", "order_status"]}},
766+
{
767+
"dbt_utils.unique_combination_of_columns": {
768+
"arguments": {"combination_of_columns": ["order_id", "order_status"]}
769+
}
770+
},
759771
"Check that model orders has a unique combination of columns order_id, order_status",
760772
),
761773
],
@@ -786,11 +798,11 @@ def test_generate_outputs_emits_descriptions_for_typed_field_tests():
786798

787799
def test_rewrite_relationships_to_ref():
788800
tests = [
789-
{"relationships": {"to": 'source("contract-id", "customers")', "field": "id"}},
801+
{"relationships": {"arguments": {"to": 'source("contract-id", "customers")', "field": "id"}}},
790802
"not_null",
791803
]
792804
rewritten = _rewrite_relationships_to_ref(tests)
793-
assert rewritten[0] == {"relationships": {"to": "ref('customers')", "field": "id"}}
805+
assert rewritten[0] == {"relationships": {"arguments": {"to": "ref('customers')", "field": "id"}}}
794806
assert rewritten[1] == "not_null"
795807

796808

@@ -1497,6 +1509,24 @@ def fake_run(args, **kwargs):
14971509
assert "some unrelated parse failure" in exc.value.reason
14981510

14991511

1512+
def test_run_dbt_test_rejects_dbt_before_1_10(tmp_path: Path):
1513+
project = _copy_dbt_project(tmp_path)
1514+
stdout = (
1515+
"14:13:33 Running with dbt=1.9.11\n"
1516+
"Compilation Error in test accepted_values_orders__pending_shipped___status (models/orders.yml)\n"
1517+
" macro 'dbt_macro__test_accepted_values' takes no keyword argument 'arguments'\n"
1518+
)
1519+
1520+
def fake_run(args, **kwargs):
1521+
return subprocess.CompletedProcess(args=args, returncode=2, stdout=stdout, stderr="")
1522+
1523+
with mock.patch.object(subprocess, "run", side_effect=fake_run):
1524+
with pytest.raises(DataContractException) as exc:
1525+
run_dbt_test(project, target=None, profiles_dir=None)
1526+
1527+
assert exc.value.reason.startswith("dbt 1.9.11 is not supported: the generated tests need dbt 1.10 or later")
1528+
1529+
15001530
def test_run_dbt_test_does_not_raise_when_run_results_present(tmp_path: Path):
15011531
"""Test failures (non-zero exit but run_results.json exists) are normal, not errors."""
15021532
project = _copy_dbt_project(tmp_path)
@@ -2762,10 +2792,10 @@ def test_versioned_sync_divergent_column_goes_to_override(tmp_path: Path):
27622792
# so a divergent column must have NO top-level tests — each version carries its full set in its bullet.
27632793
assert "data_tests" not in _col(entry, "status")
27642794
v1_status = _override(entry, 1, "status")["data_tests"][0]
2765-
assert v1_status["accepted_values"]["values"] == ["a", "b"]
2795+
assert v1_status["accepted_values"]["arguments"]["values"] == ["a", "b"]
27662796
assert _cv(v1_status) == ["1.0.0"]
27672797
v2_status = _override(entry, 2, "status")["data_tests"][0]
2768-
assert v2_status["accepted_values"]["values"] == ["a", "b", "c"]
2798+
assert v2_status["accepted_values"]["arguments"]["values"] == ["a", "b", "c"]
27692799
assert _cv(v2_status) == ["2.0.0"]
27702800

27712801
# Each override must ride alongside an `include: '*'` element, else dbt reads the version as having only `status`.
@@ -2825,7 +2855,28 @@ def test_versioned_sync_keeps_sibling_version_behavior(tmp_path: Path):
28252855
# v1's effective slice is unchanged by the v2 sync: it still excludes region and still tests
28262856
# `status` against [a,b] (relocated from top level to v1's bullet when v2 made the column diverge).
28272857
assert [e for e in _bullet(entry, 1)["columns"] if "include" in e][0]["exclude"] == ["region"]
2828-
assert _override(entry, 1, "status")["data_tests"][0]["accepted_values"]["values"] == ["a", "b"]
2858+
assert _override(entry, 1, "status")["data_tests"][0]["accepted_values"]["arguments"]["values"] == ["a", "b"]
2859+
2860+
2861+
def test_versioned_sync_keeps_old_syntax_shared_test_shared(tmp_path: Path):
2862+
"""A shared test written by an earlier CLI (args inline, no `arguments:`) still agrees with an identical v2."""
2863+
project = _versioned_project(tmp_path)
2864+
(project / "customers-v2.odcs.yaml").write_text(_V2_CONTRACT.replace("value: [a, b, c]", "value: [a, b]"))
2865+
_sync_versioned(project, "customers-v1.odcs.yaml", "1")
2866+
models_yml = project / "models" / "customers.yml"
2867+
y = yaml.safe_load(models_yml.read_text())
2868+
status_test = _col(y["models"][0], "status")["data_tests"][0]["accepted_values"]
2869+
status_test.update(status_test.pop("arguments"))
2870+
models_yml.write_text(yaml.safe_dump(y, sort_keys=False))
2871+
2872+
_sync_versioned(project, "customers-v2.odcs.yaml", "2")
2873+
2874+
entry = _versioned_entry(project)
2875+
status_test = _col(entry, "status")["data_tests"][0]
2876+
assert status_test["accepted_values"]["arguments"]["values"] == ["a", "b"]
2877+
assert _cv(status_test) == ["1.0.0", "2.0.0"]
2878+
for v in (1, 2):
2879+
assert "status" not in {e["name"] for e in _bullet(entry, v).get("columns", []) if "name" in e}
28292880

28302881

28312882
_V2_NO_REGION = _V2_CONTRACT.replace(" - name: region\n logicalType: string\n required: true\n", "")
@@ -2849,7 +2900,7 @@ def test_versioned_prune_drops_version_only_column(tmp_path: Path):
28492900
assert "region" not in {c["name"] for c in entry.get("columns", [])}
28502901
assert "region" not in [e for e in _bullet(entry, 1)["columns"] if "include" in e][0].get("exclude", [])
28512902
# v1's slice is untouched: still tests `status` against [a, b].
2852-
assert _override(entry, 1, "status")["data_tests"][0]["accepted_values"]["values"] == ["a", "b"]
2903+
assert _override(entry, 1, "status")["data_tests"][0]["accepted_values"]["arguments"]["values"] == ["a", "b"]
28532904

28542905

28552906
def test_versioned_prune_leaves_sibling_shared_column(tmp_path: Path):
@@ -2871,7 +2922,7 @@ def test_versioned_prune_leaves_sibling_shared_column(tmp_path: Path):
28712922

28722923
entry = _versioned_entry(project)
28732924
# status is still referenced by v1 → kept; v2 now excludes it.
2874-
assert _override(entry, 1, "status")["data_tests"][0]["accepted_values"]["values"] == ["a", "b"]
2925+
assert _override(entry, 1, "status")["data_tests"][0]["accepted_values"]["arguments"]["values"] == ["a", "b"]
28752926
assert "status" in [e for e in _bullet(entry, 2)["columns"] if "include" in e][0].get("exclude", [])
28762927

28772928

0 commit comments

Comments
 (0)