|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +from pathlib import Path |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import pandas as pd |
| 8 | +import pytest |
| 9 | +import yaml |
| 10 | +from click.testing import CliRunner |
| 11 | + |
| 12 | +pytest.importorskip("dbt_artifacts_parser", reason="dbt-artifacts-parser not installed") |
| 13 | + |
| 14 | +from feast import FeatureStore # noqa: E402 |
| 15 | +from feast.cli.cli import cli # noqa: E402 |
| 16 | +from feast.dbt.codegen import DbtCodeGenerator, generate_feast_code # noqa: E402 |
| 17 | +from feast.dbt.mapper import DbtToFeastMapper # noqa: E402 |
| 18 | +from feast.dbt.parser import DbtColumn, DbtModel # noqa: E402 |
| 19 | + |
| 20 | + |
| 21 | +def _execute_generated(code: str) -> dict[str, Any]: |
| 22 | + namespace: dict[str, Any] = {} |
| 23 | + with pytest.warns(DeprecationWarning, match="Entity value_type will be mandatory"): |
| 24 | + exec(compile(code, "<dbt-generated>", "exec"), namespace) |
| 25 | + return namespace |
| 26 | + |
| 27 | + |
| 28 | +@pytest.fixture |
| 29 | +def model() -> DbtModel: |
| 30 | + return DbtModel( |
| 31 | + name="Driver-stats", |
| 32 | + unique_id="model.demo.Driver-stats", |
| 33 | + database="warehouse", |
| 34 | + schema="analytics", |
| 35 | + alias="physical_stats", |
| 36 | + columns=[ |
| 37 | + DbtColumn(name="driver_id", data_type="INT64"), |
| 38 | + DbtColumn(name="event_timestamp", data_type="TIMESTAMP"), |
| 39 | + DbtColumn(name="value", data_type="INT64"), |
| 40 | + ], |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +@pytest.fixture |
| 45 | +def import_project(tmp_path: Path) -> tuple[Path, Path, Path]: |
| 46 | + repo = tmp_path / "repo" |
| 47 | + repo.mkdir() |
| 48 | + data = tmp_path / "warehouse data" |
| 49 | + data.mkdir() |
| 50 | + nodes = {} |
| 51 | + for name, value in (("driver_stats", 42), ("merchant_stats", 84)): |
| 52 | + pd.DataFrame( |
| 53 | + { |
| 54 | + "driver_id": [1], |
| 55 | + "event_timestamp": pd.to_datetime(["2026-10-14T00:00:00Z"]), |
| 56 | + "value": [value], |
| 57 | + } |
| 58 | + ).to_parquet(data / f"{name}.parquet") |
| 59 | + unique_id = f"model.demo.{name}" |
| 60 | + nodes[unique_id] = { |
| 61 | + "name": name, |
| 62 | + "unique_id": unique_id, |
| 63 | + "resource_type": "model", |
| 64 | + "package_name": "demo", |
| 65 | + "path": f"models/{name}.sql", |
| 66 | + "original_file_path": f"models/{name}.sql", |
| 67 | + "fqn": ["demo", name], |
| 68 | + "alias": f"physical_{name}", |
| 69 | + "checksum": {"name": "sha256", "checksum": "abc123"}, |
| 70 | + "database": "demo", |
| 71 | + "schema": "analytics", |
| 72 | + "description": "", |
| 73 | + "columns": { |
| 74 | + column: {"name": column, "data_type": dtype, "description": ""} |
| 75 | + for column, dtype in ( |
| 76 | + ("driver_id", "INT64"), |
| 77 | + ("event_timestamp", "TIMESTAMP"), |
| 78 | + ("value", "INT64"), |
| 79 | + ) |
| 80 | + }, |
| 81 | + "tags": [], |
| 82 | + "meta": {}, |
| 83 | + "config": {"enabled": True, "materialized": "table"}, |
| 84 | + "depends_on": {"nodes": [], "macros": []}, |
| 85 | + "refs": [], |
| 86 | + "sources": [], |
| 87 | + "metrics": [], |
| 88 | + } |
| 89 | + manifest = tmp_path / "manifest.json" |
| 90 | + manifest.write_text( |
| 91 | + json.dumps( |
| 92 | + { |
| 93 | + "metadata": { |
| 94 | + "dbt_schema_version": "https://schemas.getdbt.com/dbt/manifest/v9.json", |
| 95 | + "dbt_version": "1.5.0", |
| 96 | + "generated_at": "2026-10-14T00:00:00Z", |
| 97 | + "invocation_id": "test-invocation-id", |
| 98 | + "env": {}, |
| 99 | + "adapter_type": "duckdb", |
| 100 | + }, |
| 101 | + "nodes": nodes, |
| 102 | + **{ |
| 103 | + name: {} |
| 104 | + for name in ( |
| 105 | + "sources", |
| 106 | + "macros", |
| 107 | + "docs", |
| 108 | + "exposures", |
| 109 | + "metrics", |
| 110 | + "groups", |
| 111 | + "selectors", |
| 112 | + "disabled", |
| 113 | + "parent_map", |
| 114 | + "child_map", |
| 115 | + ) |
| 116 | + }, |
| 117 | + } |
| 118 | + ) |
| 119 | + ) |
| 120 | + (repo / "feature_store.yaml").write_text( |
| 121 | + yaml.safe_dump( |
| 122 | + { |
| 123 | + "project": "dbt_paths", |
| 124 | + "provider": "local", |
| 125 | + "registry": str(repo / "registry.db"), |
| 126 | + "online_store": {"type": "sqlite", "path": str(repo / "online.db")}, |
| 127 | + "offline_store": {"type": "file"}, |
| 128 | + "entity_key_serialization_version": 3, |
| 129 | + } |
| 130 | + ) |
| 131 | + ) |
| 132 | + return repo, manifest, data |
| 133 | + |
| 134 | + |
| 135 | +def _args(repo: Path, manifest: Path) -> list[str]: |
| 136 | + return [ |
| 137 | + "-c", |
| 138 | + str(repo), |
| 139 | + "dbt", |
| 140 | + "import", |
| 141 | + "-m", |
| 142 | + str(manifest), |
| 143 | + "-e", |
| 144 | + "driver_id", |
| 145 | + "-d", |
| 146 | + "file", |
| 147 | + ] |
| 148 | + |
| 149 | + |
| 150 | +@pytest.mark.parametrize("generated", [False, True], ids=["direct", "generated"]) |
| 151 | +@pytest.mark.parametrize("relative", [False, True], ids=["absolute", "relative"]) |
| 152 | +def test_file_template_retrieves_each_models_data( |
| 153 | + import_project: tuple[Path, Path, Path], |
| 154 | + generated: bool, |
| 155 | + relative: bool, |
| 156 | + monkeypatch: pytest.MonkeyPatch, |
| 157 | +) -> None: |
| 158 | + repo, manifest, data = import_project |
| 159 | + monkeypatch.chdir(repo.parent) |
| 160 | + output = repo / "definitions" / "features.py" |
| 161 | + output.parent.mkdir() |
| 162 | + path_root = Path("../warehouse data") if relative else data |
| 163 | + args = [ |
| 164 | + *_args(repo, manifest), |
| 165 | + "--file-path-template", |
| 166 | + str(path_root / "{model}.parquet"), |
| 167 | + ] |
| 168 | + if generated: |
| 169 | + args.extend(["--output", str(output)]) |
| 170 | + result = CliRunner().invoke(cli, args) |
| 171 | + assert result.exit_code == 0, (result.output, repr(result.exception)) |
| 172 | + |
| 173 | + store = FeatureStore(repo_path=str(repo)) |
| 174 | + if generated: |
| 175 | + definitions = _execute_generated(output.read_text()) |
| 176 | + store.apply( |
| 177 | + [ |
| 178 | + definitions["driver_id"], |
| 179 | + definitions["driver_stats_source"], |
| 180 | + definitions["driver_stats_fv"], |
| 181 | + definitions["merchant_stats_source"], |
| 182 | + definitions["merchant_stats_fv"], |
| 183 | + ] |
| 184 | + ) |
| 185 | + store = FeatureStore(repo_path=str(repo)) |
| 186 | + for name, expected in (("driver_stats", 42), ("merchant_stats", 84)): |
| 187 | + assert store.get_feature_view(name).batch_source.path == str( |
| 188 | + path_root / f"{name}.parquet" |
| 189 | + ) |
| 190 | + frame = store.get_historical_features( |
| 191 | + entity_df=pd.DataFrame( |
| 192 | + { |
| 193 | + "driver_id": [1], |
| 194 | + "event_timestamp": pd.to_datetime(["2026-10-14T01:00:00Z"]), |
| 195 | + } |
| 196 | + ), |
| 197 | + features=[f"{name}:value"], |
| 198 | + ).to_df() |
| 199 | + values = frame["value"].tolist() |
| 200 | + assert values == [expected] |
| 201 | + |
| 202 | + |
| 203 | +@pytest.mark.parametrize("generated", [False, True], ids=["direct", "generated"]) |
| 204 | +def test_omitting_file_template_preserves_default( |
| 205 | + import_project: tuple[Path, Path, Path], generated: bool |
| 206 | +) -> None: |
| 207 | + repo, manifest, _ = import_project |
| 208 | + output = repo / "features.py" |
| 209 | + args = _args(repo, manifest) |
| 210 | + if generated: |
| 211 | + args.extend(["--output", str(output)]) |
| 212 | + result = CliRunner().invoke(cli, args) |
| 213 | + assert result.exit_code == 0, (result.output, repr(result.exception)) |
| 214 | + if generated: |
| 215 | + definitions = _execute_generated(output.read_text()) |
| 216 | + paths = [ |
| 217 | + definitions[f"{name}_source"].path |
| 218 | + for name in ("driver_stats", "merchant_stats") |
| 219 | + ] |
| 220 | + else: |
| 221 | + store = FeatureStore(repo_path=str(repo)) |
| 222 | + paths = [ |
| 223 | + store.get_feature_view(name).batch_source.path |
| 224 | + for name in ("driver_stats", "merchant_stats") |
| 225 | + ] |
| 226 | + assert paths == ["/data/driver_stats.parquet", "/data/merchant_stats.parquet"] |
| 227 | + |
| 228 | + |
| 229 | +@pytest.mark.parametrize( |
| 230 | + ("template", "expected"), |
| 231 | + [ |
| 232 | + (None, "/data/Driver-stats.parquet"), |
| 233 | + ("/warehouse/{model}.parquet", "/warehouse/Driver-stats.parquet"), |
| 234 | + ("data/{model}.parquet", "data/Driver-stats.parquet"), |
| 235 | + ( |
| 236 | + "s3://bucket/{model}/{model}.parquet", |
| 237 | + "s3://bucket/Driver-stats/Driver-stats.parquet", |
| 238 | + ), |
| 239 | + ("shared.parquet", "shared.parquet"), |
| 240 | + ( |
| 241 | + "{{model}}/{model}/{{partition}}.parquet", |
| 242 | + "{model}/Driver-stats/{partition}.parquet", |
| 243 | + ), |
| 244 | + ("{{model:}}/{model}.parquet", "{model:}/Driver-stats.parquet"), |
| 245 | + (r'C:\data\"quoted"\{model}.parquet', r'C:\data\"quoted"\Driver-stats.parquet'), |
| 246 | + ( |
| 247 | + "a'b\"c\\n\\t/\n\t雪😀/{model}.parquet", |
| 248 | + "a'b\"c\\n\\t/\n\t雪😀/Driver-stats.parquet", |
| 249 | + ), |
| 250 | + ], |
| 251 | +) |
| 252 | +def test_mapper_and_generated_paths_round_trip( |
| 253 | + model: DbtModel, template: str | None, expected: str |
| 254 | +) -> None: |
| 255 | + objects = DbtToFeastMapper( |
| 256 | + data_source_type="file", file_path_template=template |
| 257 | + ).create_all_from_model(model, "driver_id") |
| 258 | + assert objects["data_source"].path == expected |
| 259 | + assert objects["feature_view"].batch_source.path == expected |
| 260 | + code = DbtCodeGenerator( |
| 261 | + data_source_type="file", file_path_template=template |
| 262 | + ).generate([model], "driver_id") |
| 263 | + definitions = _execute_generated(code) |
| 264 | + assert definitions["Driver_stats_source"].path == expected |
| 265 | + assert definitions["Driver_stats_fv"].batch_source.path == expected |
| 266 | + |
| 267 | + |
| 268 | +@pytest.mark.parametrize("api", ["mapper", "generator", "wrapper"]) |
| 269 | +@pytest.mark.parametrize( |
| 270 | + "template", |
| 271 | + [ |
| 272 | + "", |
| 273 | + "{schema}", |
| 274 | + "{}", |
| 275 | + "{0}", |
| 276 | + "{model.name}", |
| 277 | + "{model[0]}", |
| 278 | + "{model!r}", |
| 279 | + "{model:>10}", |
| 280 | + "{model:}", |
| 281 | + "{model:{schema}}", |
| 282 | + "{model", |
| 283 | + "model}", |
| 284 | + "{{{model}}", |
| 285 | + ], |
| 286 | +) |
| 287 | +def test_python_apis_reject_invalid_templates(api: str, template: str) -> None: |
| 288 | + with pytest.raises(ValueError, match="file_path_template") as error: |
| 289 | + if api == "mapper": |
| 290 | + DbtToFeastMapper(data_source_type="file", file_path_template=template) |
| 291 | + elif api == "generator": |
| 292 | + DbtCodeGenerator(data_source_type="file", file_path_template=template) |
| 293 | + else: |
| 294 | + generate_feast_code([], "driver_id", "file", file_path_template=template) |
| 295 | + if template: |
| 296 | + assert repr(template) in str(error.value) |
| 297 | + else: |
| 298 | + assert "must not be empty" in str(error.value) |
| 299 | + |
| 300 | + |
| 301 | +@pytest.mark.parametrize("backend", ["bigquery", "snowflake"]) |
| 302 | +@pytest.mark.parametrize("template", ["", "/data/{model}.parquet"]) |
| 303 | +@pytest.mark.parametrize("api", ["mapper", "generator", "wrapper"]) |
| 304 | +def test_non_file_python_apis_reject_explicit_template( |
| 305 | + api: str, backend: str, template: str |
| 306 | +) -> None: |
| 307 | + with pytest.raises(ValueError, match="only supported for file data sources"): |
| 308 | + if api == "mapper": |
| 309 | + DbtToFeastMapper(data_source_type=backend, file_path_template=template) |
| 310 | + elif api == "generator": |
| 311 | + DbtCodeGenerator(data_source_type=backend, file_path_template=template) |
| 312 | + else: |
| 313 | + generate_feast_code([], "driver_id", backend, file_path_template=template) |
| 314 | + |
| 315 | + |
| 316 | +@pytest.mark.parametrize("generated", [False, True], ids=["direct", "generated"]) |
| 317 | +@pytest.mark.parametrize( |
| 318 | + ("backend", "template", "message"), |
| 319 | + [ |
| 320 | + ("file", "", "must not be empty"), |
| 321 | + ("file", "{unknown}", "{unknown}"), |
| 322 | + ("file", "data/{model", "data/{model"), |
| 323 | + ("bigquery", "/data/{model}.parquet", "only supported for file data sources"), |
| 324 | + ("snowflake", "/data/{model}.parquet", "only supported for file data sources"), |
| 325 | + (None, "/data/{model}.parquet", "only supported for file data sources"), |
| 326 | + ], |
| 327 | +) |
| 328 | +def test_cli_rejects_invalid_template_before_filtering_or_writing( |
| 329 | + import_project: tuple[Path, Path, Path], |
| 330 | + generated: bool, |
| 331 | + backend: str | None, |
| 332 | + template: str, |
| 333 | + message: str, |
| 334 | +) -> None: |
| 335 | + repo, manifest, _ = import_project |
| 336 | + output = repo / "features.py" |
| 337 | + args = _args(repo, manifest)[:-2] |
| 338 | + if backend is not None: |
| 339 | + args.extend(["-d", backend]) |
| 340 | + args.extend(["--file-path-template", template, "--model", "does_not_exist"]) |
| 341 | + if generated: |
| 342 | + output.write_text("original contents") |
| 343 | + args.extend(["--output", str(output)]) |
| 344 | + result = CliRunner().invoke(cli, args) |
| 345 | + assert result.exit_code == 2, result.output |
| 346 | + assert "--file-path-template" in result.output |
| 347 | + assert message in result.output |
| 348 | + assert "No such option" not in result.output |
| 349 | + assert not (repo / "registry.db").exists() |
| 350 | + assert not (repo / "online.db").exists() |
| 351 | + if generated: |
| 352 | + assert output.read_text() == "original contents" |
| 353 | + else: |
| 354 | + assert not output.exists() |
| 355 | + |
| 356 | + |
| 357 | +@pytest.mark.parametrize("backend", ["bigquery", "snowflake"]) |
| 358 | +def test_omitted_template_preserves_other_backends( |
| 359 | + model: DbtModel, backend: str |
| 360 | +) -> None: |
| 361 | + source = DbtToFeastMapper(backend, "event_timestamp", 7).create_data_source(model) |
| 362 | + # Exercise the existing positional signature of the public convenience function. |
| 363 | + code = generate_feast_code( |
| 364 | + [model], "driver_id", backend, "event_timestamp", 7, "", "", None, False |
| 365 | + ) |
| 366 | + definitions = _execute_generated(code) |
| 367 | + generated_source = definitions["Driver_stats_source"] |
| 368 | + if backend == "bigquery": |
| 369 | + assert ( |
| 370 | + source.table |
| 371 | + == generated_source.table |
| 372 | + == "warehouse.analytics.physical_stats" |
| 373 | + ) |
| 374 | + else: |
| 375 | + assert source.database == generated_source.database == "warehouse" |
| 376 | + assert source.schema == generated_source.schema == "analytics" |
| 377 | + assert source.table == generated_source.table == "physical_stats" |
| 378 | + assert definitions["Driver_stats_fv"].ttl.days == 7 |
| 379 | + assert definitions["Driver_stats_fv"].online is False |
0 commit comments