Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions tests/cli/test_prune_existing.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

from __future__ import annotations

import os
import re
import shutil
from pathlib import Path
Expand Down Expand Up @@ -518,3 +519,125 @@ def test_bad_project_dir_exit_1(tmp_path: Path, capsys: pytest.CaptureFixture[st
err = capsys.readouterr().err
assert code == 1
assert "Traceback" not in err


# ---------------------------------------------------------------------------
# Default project-dir resolution: walk up from cwd (DEC-001)
# ---------------------------------------------------------------------------


def test_walk_up_resolves_project_dir_without_flag(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
"""With no ``--project-dir``, the handler walks up from cwd to the dbt
project root (DEC-001)."""
project_dir, schema_path = _setup_project(tmp_path)
# Run from a nested subdir so the walk-up traverses >=1 parent.
nested = project_dir / "models" / "staging"
monkeypatch.chdir(nested)
argv = [
"prune-existing",
_MODEL_UNIQUE_ID,
"--schema",
str(schema_path),
"--scope",
"full",
"--sample-strategy",
"oneshot",
]
factory = _make_fake_adapter_factory()
with patch("signalforge.cli.prune_existing._make_warehouse_adapter", factory):
code = main(argv)
assert code == 0
# Default-on sidecar lands under the walked-up project root (#105).
assert (project_dir / ".signalforge" / "diff.json").is_file()
assert "Traceback" not in capsys.readouterr().err

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

def test_walk_up_fails_outside_project_exit_1(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
"""No ``--project-dir`` and no dbt_project.yml up the tree -> CliPathError
-> exit 1, no traceback."""
monkeypatch.chdir(tmp_path)
argv = [
"prune-existing",
_MODEL_UNIQUE_ID,
"--schema",
"schema.yml",
]
code = _run(argv)
err = capsys.readouterr().err
assert code == 1
assert "could not find dbt_project.yml" in err
assert "Traceback" not in err


# ---------------------------------------------------------------------------
# --no-color env mutation (DEC-023) + empty skipped-report guard
# ---------------------------------------------------------------------------


def test_no_color_sets_env_and_runs(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""``--no-color`` mutates ``NO_COLOR`` and the run still succeeds (DEC-023)."""
prior = os.environ.get("NO_COLOR")
project_dir, schema_path = _setup_project(tmp_path)
argv = [*_base_argv(project_dir, schema_path), "--no-color"]
try:
code = _run(argv)
assert code == 0
assert (project_dir / ".signalforge" / "diff.json").is_file()
assert os.environ.get("NO_COLOR") == "1"
assert "Traceback" not in capsys.readouterr().err
finally:
# The handler does NOT restore env (DEC-023); restore here so the
# mutation does not leak into sibling tests.
if prior is None:
os.environ.pop("NO_COLOR", None)
else:
os.environ["NO_COLOR"] = prior


def test_no_skipped_tests_emits_no_summary(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
"""A schema with only supported tests produces zero skips -> the
skipped-report guard returns early, no summary line."""
project_dir, _ = _setup_project(tmp_path)
# A minimal schema referencing only real columns with supported tests, so
# ingest records ZERO skipped tests.
only_supported = project_dir / "models" / "staging" / "supported_only.yml"
only_supported.write_text(
"version: 2\n"
"models:\n"
" - name: stg_bikeshare_trips\n"
" columns:\n"
" - name: trip_id\n"
" tests:\n"
" - not_null\n"
)
argv = [
"prune-existing",
_MODEL_UNIQUE_ID,
"--schema",
str(only_supported),
"--project-dir",
str(project_dir),
"--scope",
"full",
"--sample-strategy",
"oneshot",
]
# One supported test -> exactly one COUNT(*) query.
factory = _make_fake_adapter_factory(failure_counts=(0,))
with patch("signalforge.cli.prune_existing._make_warehouse_adapter", factory):
code = main(argv)
err = capsys.readouterr().err
assert code == 0
assert (project_dir / ".signalforge" / "diff.json").is_file()
assert "unsupported" not in err
assert "Traceback" not in err
72 changes: 72 additions & 0 deletions tests/ingest/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,3 +231,75 @@ def test_inline_args_with_non_mapping_arguments_key_is_stripped() -> None:
)
assert isinstance(result, CandidateTestAcceptedValues)
assert result.values == ("a", "b")


# --- ref() / source() non-quoted + arity edge cases (DEC-009) -------------


def test_ref_with_unquoted_arg_is_carried_verbatim() -> None:
# `ref(my_var)` matches the ref() shape but carries no QUOTED positional,
# so the unwrap finds nothing and returns the string verbatim.
result = parse_test_entry({"relationships": {"to": "ref(my_var)", "field": "id"}}, column="fk")
assert isinstance(result, CandidateTestRelationships)
assert result.to == "ref(my_var)"


def test_source_single_arg_unwraps_to_that_arg() -> None:
# A one-positional `source('only')` returns that single arg (not dotted).
result = parse_test_entry(
{"relationships": {"to": "source('only')", "field": "id"}}, column="fk"
)
assert isinstance(result, CandidateTestRelationships)
assert result.to == "only"


def test_source_with_unquoted_args_is_carried_verbatim() -> None:
# `source(a, b)` matches the source() shape but carries no QUOTED args,
# so neither the 2-arg nor 1-arg branch fires; returned verbatim.
result = parse_test_entry({"relationships": {"to": "source(a, b)", "field": "id"}}, column="fk")
assert isinstance(result, CandidateTestRelationships)
assert result.to == "source(a, b)"


# --- non-dict bodies + non-conforming entry shapes ------------------------


def test_accepted_values_non_dict_body_is_malformed() -> None:
# A non-dict body yields no extracted args, so the required `values` is
# absent -> malformed-supported-test.
result = parse_test_entry({"accepted_values": "not-a-mapping"}, column="status")
assert isinstance(result, SkippedTest)
assert result.reason == "malformed-supported-test"
assert result.test_name == "accepted_values"


def test_multi_key_dict_entry_is_custom_skip() -> None:
# A test entry is a single-key dict by dbt's grammar; a multi-key dict is
# not a shape we model -> custom-or-generic-test, naming the first key.
result = parse_test_entry({"foo": 1, "bar": 2}, column="id")
assert isinstance(result, SkippedTest)
assert result.reason == "custom-or-generic-test"
assert result.test_name == "foo"
assert result.column == "id"
assert "single-key" in result.detail


def test_non_string_non_dict_entry_is_custom_skip() -> None:
# An entry that is neither a string nor a mapping (e.g. an int) is skipped
# and recorded, never silently dropped.
result = parse_test_entry(123, column="id") # type: ignore[arg-type]
assert isinstance(result, SkippedTest)
assert result.reason == "custom-or-generic-test"
assert result.test_name == "123"
assert result.column == "id"


def test_model_level_relationships_skips_malformed() -> None:
# relationships at model level (column=None) is not representable -> skip.
result = parse_test_entry(
{"relationships": {"to": "ref('orders')", "field": "id"}}, column=None
)
assert isinstance(result, SkippedTest)
assert result.reason == "malformed-supported-test"
assert result.column is None
assert result.test_name == "relationships"
64 changes: 64 additions & 0 deletions tests/ingest/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from __future__ import annotations

import os
from pathlib import Path

import pytest
Expand Down Expand Up @@ -212,6 +213,69 @@ def test_read_schema_nonexistent_path() -> None:
read_schema(missing, _make_orders_model())


def test_read_schema_path_outside_project_dir_raises_parse_error(tmp_path: Path) -> None:
# A Path that escapes the symlink-hardened containment of project_dir
# re-raises PathContainmentError as IngestSchemaParseError (DEC).
project_dir = tmp_path / "proj"
project_dir.mkdir()
outside = tmp_path / "outside.yml"
outside.write_text("models: []\n")
with pytest.raises(IngestSchemaParseError) as excinfo:
read_schema(outside, _make_orders_model(), project_dir=project_dir)
assert "canonicalisation" in str(excinfo.value)


@pytest.mark.skipif(
os.name != "posix" or (hasattr(os, "geteuid") and os.geteuid() == 0),
reason="root / non-POSIX bypasses file-mode perms; unreadable-file path unreachable",
)
def test_read_schema_unreadable_file_raises_parse_error(tmp_path: Path) -> None:
# A file that exists (is_file True) but cannot be read raises
# IngestSchemaParseError via the OSError branch.
schema = tmp_path / "schema.yml"
schema.write_text("models: []\n")
schema.chmod(0o000)
try:
with pytest.raises(IngestSchemaParseError) as excinfo:
read_schema(schema, _make_orders_model(), project_dir=tmp_path)
assert "could not be read" in str(excinfo.value)
finally:
# Restore so pytest's tmp_path teardown can remove the file.
schema.chmod(0o644)


def test_read_schema_non_dict_column_entry_is_ignored() -> None:
# A non-dict entry in `columns:` (e.g. a bare string) is skipped, not a
# crash; the well-formed sibling column still parses.
raw = (
"models:\n"
" - name: orders\n"
" columns:\n"
" - just_a_string\n"
" - name: order_id\n"
" tests:\n"
" - not_null\n"
)
result = read_schema(raw, _make_orders_model())
assert {c.name for c in result.candidate.columns} == {"order_id"}


def test_read_schema_column_without_name_is_ignored() -> None:
# A column dict missing a usable `name` is skipped; the named sibling
# still parses.
raw = (
"models:\n"
" - name: orders\n"
" columns:\n"
" - description: nameless column\n"
" - name: order_id\n"
" tests:\n"
" - not_null\n"
)
result = read_schema(raw, _make_orders_model())
assert {c.name for c in result.candidate.columns} == {"order_id"}


# ---------------------------------------------------------------------------
# Bonus: prune accepts the produced candidate end-to-end without a warehouse
# (disabled-prune path short-circuits before any warehouse call — see
Expand Down
Loading