dbt-macro-test 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,3 @@
1
+ from dbt_macro_test.cli import main
2
+
3
+ main()
dbt_macro_test/cli.py ADDED
@@ -0,0 +1,291 @@
1
+ import os
2
+ import sys
3
+ import tempfile
4
+ from collections.abc import Iterator
5
+ from contextlib import contextmanager
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import click
10
+
11
+ from dbt_macro_test.engine import (
12
+ DbtError,
13
+ RawRun,
14
+ RunOutcome,
15
+ Verdict,
16
+ check_arguments,
17
+ invoke_unit_tests,
18
+ judge_error,
19
+ judge_warning,
20
+ read_project_config,
21
+ run_deps,
22
+ run_unit_tests,
23
+ )
24
+ from dbt_macro_test.project import (
25
+ FixtureError,
26
+ ProfilesChoice,
27
+ ProjectNotFoundError,
28
+ carried_over,
29
+ generate_project,
30
+ installed_packages_dir,
31
+ macro_directories,
32
+ resolve_profiles_dir,
33
+ resolve_project_root,
34
+ )
35
+ from dbt_macro_test.spec import (
36
+ Case,
37
+ ExpectedError,
38
+ SpecError,
39
+ SpecFile,
40
+ case_id,
41
+ case_ids,
42
+ load_specs,
43
+ select_cases,
44
+ split_isolated,
45
+ )
46
+
47
+
48
+ class CouldNotRun(click.ClickException):
49
+ """The tests could not be run at all, as opposed to a case failing (exit code 1)."""
50
+
51
+ exit_code = 2
52
+
53
+
54
+ @contextmanager
55
+ def _workspace(keep: bool) -> Iterator[Path]:
56
+ """A fresh directory for the generated project, removed afterwards unless kept."""
57
+ if keep:
58
+ yield Path(tempfile.mkdtemp(prefix="dbt-macro-test-"))
59
+ else:
60
+ with tempfile.TemporaryDirectory(
61
+ prefix="dbt-macro-test-", ignore_cleanup_errors=True
62
+ ) as directory:
63
+ yield Path(directory)
64
+
65
+
66
+ @click.group()
67
+ def main() -> None:
68
+ """Unit tests for dbt macros."""
69
+
70
+
71
+ @main.command()
72
+ @click.argument(
73
+ "path",
74
+ required=False,
75
+ type=click.Path(exists=True, path_type=Path, resolve_path=True),
76
+ )
77
+ @click.option(
78
+ "--project-dir",
79
+ type=click.Path(exists=True, file_okay=False, path_type=Path, resolve_path=True),
80
+ help="The dbt project. Defaults to the nearest one at or above PATH.",
81
+ )
82
+ @click.option(
83
+ "--profiles-dir",
84
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
85
+ help=(
86
+ "Directory with profiles.yml. Defaults to $DBT_PROFILES_DIR, then the project's own "
87
+ "profiles.yml, then dbt's default location."
88
+ ),
89
+ )
90
+ @click.option("--target", help="The profile target to run against.")
91
+ @click.option(
92
+ "--select",
93
+ "selectors",
94
+ multiple=True,
95
+ help=(
96
+ "Run only the cases that match: a macro name, or macro::case. * and ? stand for any "
97
+ "characters, and the option can be given more than once."
98
+ ),
99
+ )
100
+ @click.option(
101
+ "--list",
102
+ "list_only",
103
+ is_flag=True,
104
+ help="Print the cases that would run, as macro::case, and stop.",
105
+ )
106
+ @click.option(
107
+ "--keep-generated",
108
+ is_flag=True,
109
+ help="Keep the generated dbt project (a temporary directory) and print where it is.",
110
+ )
111
+ @click.option("--verbose", is_flag=True, help="Say what is carried over from the project.")
112
+ def run(
113
+ path: Path | None,
114
+ project_dir: Path | None,
115
+ profiles_dir: Path | None,
116
+ target: str | None,
117
+ selectors: tuple[str, ...],
118
+ list_only: bool,
119
+ keep_generated: bool,
120
+ verbose: bool,
121
+ ) -> None:
122
+ """Run the macro tests in PATH: a spec file or a directory (default: macro_test/).
123
+
124
+ Exit code 0 means every case passed, 1 that a case failed or errored, and 2
125
+ that the tests could not be run (an invalid spec, a wrong argument, no
126
+ project, dbt itself failing, or nothing matching --select).
127
+ """
128
+ root, path = _locate(project_dir, path)
129
+ spec_files = _load_and_select(path, selectors)
130
+ if list_only:
131
+ for identifier in case_ids(spec_files):
132
+ click.echo(identifier)
133
+ return
134
+
135
+ raw_config = read_project_config(root)
136
+ _check_arguments(spec_files, raw_config, root)
137
+
138
+ profiles = resolve_profiles_dir(profiles_dir, root, os.environ)
139
+ packages_dir = installed_packages_dir(raw_config, root)
140
+ test_dir = path if path.is_dir() else path.parent
141
+ install = (root / "packages.yml").is_file() and packages_dir is None
142
+ together, alone = split_isolated(spec_files)
143
+ with _workspace(keep_generated) as out_dir:
144
+ if verbose:
145
+ _say_what_is_carried_over(raw_config, root, packages_dir, profiles)
146
+ outcome = RunOutcome(passed=True)
147
+ project = out_dir
148
+ if together:
149
+ _generate(root, test_dir, together, raw_config, project, packages_dir)
150
+ outcome = _run_dbt(project, profiles, target, install)
151
+ _report_errors(outcome, project)
152
+ verdicts = [
153
+ _run_alone(
154
+ i,
155
+ spec,
156
+ (root, test_dir, raw_config, out_dir, packages_dir),
157
+ profiles,
158
+ target,
159
+ install,
160
+ )
161
+ for i, spec in enumerate(alone)
162
+ ]
163
+ _report(outcome, verdicts, out_dir if keep_generated else None)
164
+ passed = outcome.passed and all(v.passed for _, v in verdicts)
165
+ sys.exit(0 if passed else 1)
166
+
167
+
168
+ def _locate(project_dir: Path | None, path: Path | None) -> tuple[Path, Path]:
169
+ """The project and the specs to run: both may have to be found."""
170
+ try:
171
+ root = resolve_project_root(project_dir, path if path is not None else Path.cwd())
172
+ except ProjectNotFoundError as e:
173
+ raise CouldNotRun(str(e)) from e
174
+ if path is None:
175
+ path = root / "macro_test"
176
+ if not path.exists():
177
+ raise CouldNotRun(f"{path} does not exist; put the specs there or give their path")
178
+ return root, path
179
+
180
+
181
+ def _load_and_select(path: Path, selectors: tuple[str, ...]) -> list[SpecFile]:
182
+ """The specs at `path` reduced to the cases the selectors pick."""
183
+ try:
184
+ spec_files = load_specs(path)
185
+ except SpecError as e:
186
+ raise CouldNotRun(str(e)) from e
187
+ everything = case_ids(spec_files)
188
+ spec_files = select_cases(spec_files, selectors)
189
+ chosen = case_ids(spec_files)
190
+ if not chosen:
191
+ raise CouldNotRun(
192
+ f"no case matches {', '.join(selectors)}; the cases are: {', '.join(everything)}"
193
+ )
194
+ if selectors:
195
+ click.echo(f"Selected {len(chosen)} of {len(everything)} cases.", err=True)
196
+ return spec_files
197
+
198
+
199
+ def _check_arguments(spec_files: list[SpecFile], raw_config: dict[str, Any], root: Path) -> None:
200
+ problems = check_arguments(spec_files, macro_directories(raw_config, root))
201
+ if problems:
202
+ raise CouldNotRun("\n".join(problems))
203
+
204
+
205
+ def _say_what_is_carried_over(
206
+ raw_config: dict[str, Any], root: Path, packages_dir: Path | None, profiles: ProfilesChoice
207
+ ) -> None:
208
+ click.echo("Carried over from the project:", err=True)
209
+ for line in carried_over(raw_config, root, packages_dir):
210
+ click.echo(f" {line}", err=True)
211
+ click.echo(f" profiles.yml from: {profiles.source}", err=True)
212
+
213
+
214
+ def _run_dbt(
215
+ project: Path, profiles: ProfilesChoice, target: str | None, install_packages: bool
216
+ ) -> RunOutcome:
217
+ try:
218
+ return run_unit_tests(
219
+ project,
220
+ profiles_dir=profiles.directory,
221
+ target=target,
222
+ install_packages=install_packages,
223
+ )
224
+ except DbtError as e:
225
+ raise CouldNotRun(f"{e.command} could not run; see dbt's message above") from e
226
+
227
+
228
+ def _report_errors(outcome: RunOutcome, project: Path) -> None:
229
+ """The SQL generated for each case that errored without being expected to."""
230
+ for model in outcome.errored_models:
231
+ sql = (project / "models" / f"{model}.sql").read_text().strip()
232
+ click.echo(f"\nSQL generated for the case that errored ({model}):\n {sql}", err=True)
233
+
234
+
235
+ def _judge(case: Case, raw: RawRun) -> Verdict:
236
+ """What came of a case that ran alone: it expected an error, or a warning with its rows."""
237
+ if isinstance(case.expect, ExpectedError):
238
+ return judge_error(case.expect.message, raw)
239
+ assert case.warning is not None, "a case runs alone only to give an error or a warning"
240
+ return judge_warning(case.warning.message, raw)
241
+
242
+
243
+ def _run_alone(
244
+ index: int,
245
+ spec: SpecFile,
246
+ generation: tuple[Path, Path, dict[str, Any], Path, Path | None],
247
+ profiles: ProfilesChoice,
248
+ target: str | None,
249
+ install_packages: bool,
250
+ ) -> tuple[str, Verdict]:
251
+ """Run the one case of `spec` in a dbt run of its own, and judge what came of it."""
252
+ root, test_dir, raw_config, out_dir, packages_dir = generation
253
+ (macro_spec,) = spec.macros
254
+ (case,) = macro_spec.cases
255
+ project = out_dir / "cases-run-alone" / str(index)
256
+ _generate(root, test_dir, [spec], raw_config, project, packages_dir)
257
+ try:
258
+ if install_packages:
259
+ run_deps(project, profiles_dir=profiles.directory, target=target)
260
+ raw = invoke_unit_tests(project, profiles_dir=profiles.directory, target=target, quiet=True)
261
+ except DbtError as e:
262
+ raise CouldNotRun(f"{e.command} could not run; see dbt's message above") from e
263
+ return case_id(macro_spec.macro, case.name), _judge(case, raw)
264
+
265
+
266
+ def _report(outcome: RunOutcome, verdicts: list[tuple[str, Verdict]], kept: Path | None) -> None:
267
+ """The cases that ran alone, then the summary of all of them, then where the project is."""
268
+ for identifier, verdict in verdicts:
269
+ word = "PASS" if verdict.passed else "FAIL"
270
+ click.echo(f"{word} {identifier}: {verdict.detail}", err=True)
271
+ counts = dict(outcome.counts)
272
+ for _, verdict in verdicts:
273
+ key = "pass" if verdict.passed else "fail"
274
+ counts[key] = counts.get(key, 0) + 1
275
+ click.echo(f"\n{RunOutcome(passed=True, counts=counts).summary()}", err=True)
276
+ if kept is not None:
277
+ click.echo(f"Generated project kept at {kept}", err=True)
278
+
279
+
280
+ def _generate(
281
+ root: Path,
282
+ test_dir: Path,
283
+ spec_files: list[SpecFile],
284
+ raw_config: dict[str, Any],
285
+ out_dir: Path,
286
+ packages_dir: Path | None,
287
+ ) -> Path:
288
+ try:
289
+ return generate_project(root, test_dir, spec_files, raw_config, out_dir, packages_dir)
290
+ except FixtureError as e:
291
+ raise CouldNotRun(str(e)) from e
@@ -0,0 +1,45 @@
1
+ from dbt_macro_test.engine.config import read_project_config
2
+ from dbt_macro_test.engine.judge import (
3
+ Verdict,
4
+ error_text,
5
+ errors_in,
6
+ judge_error,
7
+ judge_warning,
8
+ )
9
+ from dbt_macro_test.engine.runner import (
10
+ CaseResult,
11
+ DbtError,
12
+ RawRun,
13
+ RunOutcome,
14
+ invoke_unit_tests,
15
+ run_deps,
16
+ run_unit_tests,
17
+ )
18
+ from dbt_macro_test.engine.signature import (
19
+ Signature,
20
+ find_signatures,
21
+ problems_with,
22
+ signatures_in,
23
+ )
24
+ from dbt_macro_test.engine.validate import check_arguments
25
+
26
+ __all__ = [
27
+ "CaseResult",
28
+ "DbtError",
29
+ "RawRun",
30
+ "RunOutcome",
31
+ "Signature",
32
+ "Verdict",
33
+ "check_arguments",
34
+ "error_text",
35
+ "errors_in",
36
+ "find_signatures",
37
+ "invoke_unit_tests",
38
+ "judge_error",
39
+ "judge_warning",
40
+ "problems_with",
41
+ "read_project_config",
42
+ "run_deps",
43
+ "run_unit_tests",
44
+ "signatures_in",
45
+ ]
@@ -0,0 +1,9 @@
1
+ from pathlib import Path
2
+ from typing import Any
3
+
4
+ from dbt.config.project import load_raw_project
5
+
6
+
7
+ def read_project_config(root: Path) -> dict[str, Any]:
8
+ """The project's dbt_project.yml as dbt reads it, before Jinja is rendered."""
9
+ return load_raw_project(str(root))
@@ -0,0 +1,65 @@
1
+ from dataclasses import dataclass
2
+
3
+ from dbt_macro_test.engine.runner import RawRun
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class Verdict:
8
+ passed: bool
9
+ detail: str
10
+
11
+
12
+ def error_text(text: str) -> str:
13
+ """The message in one of dbt's errors, without its heading and its `> in macro ...` trail.
14
+
15
+ dbt writes a heading (`Compilation Error in model ...`), then the message, then lines that
16
+ start with `>` saying where it came from. A warehouse error has a heading and a few lines.
17
+ """
18
+ lines = [line.strip() for line in text.splitlines() if line.strip()]
19
+ body = [line for line in lines[1:] if not line.startswith(">")]
20
+ return " ".join(body) if body else (lines[0] if lines else "")
21
+
22
+
23
+ def errors_in(raw: RawRun) -> list[str]:
24
+ """The texts of the errors in a run: dbt stopping altogether, or a case that errored."""
25
+ if raw.exception is not None:
26
+ return [raw.exception]
27
+ return [case.message for case in raw.results if case.status == "error"]
28
+
29
+
30
+ def judge_error(expected: str, raw: RawRun) -> Verdict:
31
+ """Whether a run of one case ended in an error that contains `expected`."""
32
+ errors = errors_in(raw)
33
+ if not errors:
34
+ statuses = ", ".join(sorted({case.status for case in raw.results})) or "no result"
35
+ return Verdict(
36
+ False, f"expected an error containing {expected!r}, but there was none ({statuses})"
37
+ )
38
+ if any(expected in text for text in errors):
39
+ return Verdict(True, f"the error contains {expected!r}")
40
+ return Verdict(
41
+ False,
42
+ f"expected an error containing {expected!r}, but the error was: {error_text(errors[0])}",
43
+ )
44
+
45
+
46
+ def judge_warning(expected: str, raw: RawRun) -> Verdict:
47
+ """Whether a run of one case gave a warning that contains `expected`, and the case passed.
48
+
49
+ The warning comes with rows that must match as well, so a case that did not pass is a failure
50
+ whatever it warned, and the reason is said first.
51
+ """
52
+ problems = errors_in(raw)
53
+ if problems:
54
+ return Verdict(False, f"the case ended in an error: {error_text(problems[0])}")
55
+ not_passed = [case for case in raw.results if case.status != "pass"]
56
+ if not_passed:
57
+ return Verdict(False, f"the warning aside, the case did not pass ({not_passed[0].status})")
58
+ if any(expected in warning for warning in raw.warnings):
59
+ return Verdict(True, f"the warning contains {expected!r}")
60
+ if not raw.warnings:
61
+ return Verdict(False, f"expected a warning containing {expected!r}, but there was none")
62
+ given = " | ".join(raw.warnings)
63
+ return Verdict(
64
+ False, f"expected a warning containing {expected!r}, but the warnings were: {given}"
65
+ )
@@ -0,0 +1,149 @@
1
+ import os
2
+ import re
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from dbt.cli.main import dbtRunner, dbtRunnerResult
9
+
10
+ _ANSI = re.compile(r"\x1b\[[0-9;]*m")
11
+
12
+
13
+ class DbtError(Exception):
14
+ """dbt itself could not run (a compile error, for instance), as opposed to a test failing."""
15
+
16
+ def __init__(self, command: str, reason: object) -> None:
17
+ super().__init__(f"dbt {command} failed: {reason}")
18
+ self.command = f"dbt {command}"
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class RunOutcome:
23
+ passed: bool
24
+ errored_models: list[str] = field(default_factory=list)
25
+ counts: dict[str, int] = field(default_factory=dict)
26
+
27
+ def summary(self) -> str:
28
+ """For example `1 failed, 8 passed`; failures first."""
29
+ order = [("error", "errored"), ("fail", "failed"), ("pass", "passed")]
30
+ parts = [f"{self.counts[key]} {word}" for key, word in order if self.counts.get(key)]
31
+ return ", ".join(parts) if parts else "no cases ran"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class CaseResult:
36
+ """What dbt reported for one unit test."""
37
+
38
+ model: str
39
+ status: str
40
+ message: str
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class RawRun:
45
+ """What one `dbt test` came to, as dbt reported it, with nothing judged.
46
+
47
+ `exception` is set when dbt stopped altogether, before or while running the cases (an error
48
+ raised while the project is parsed, for instance); it is the text of the error. `warnings` are
49
+ the warnings dbt gave, each once and in the order they came.
50
+ """
51
+
52
+ success: bool
53
+ exception: str | None
54
+ results: list[CaseResult]
55
+ warnings: list[str] = field(default_factory=list)
56
+
57
+
58
+ def invoke_dbt(
59
+ args: list[str], callbacks: list[Callable[[Any], None]] | None = None
60
+ ) -> dbtRunnerResult:
61
+ """Run one dbt command in this process, and leave the working directory where it was.
62
+
63
+ dbt 1.8 moves into the project directory and stays there; the directory of a generated
64
+ project is deleted when the run is over, and the next dbt command, which asks for the
65
+ working directory, would fail. Later versions put it back themselves.
66
+ """
67
+ here = os.getcwd()
68
+ try:
69
+ return dbtRunner(callbacks=callbacks or []).invoke(args)
70
+ finally:
71
+ os.chdir(here)
72
+
73
+
74
+ def _common_args(project_dir: Path, profiles_dir: Path | None, target: str | None) -> list[str]:
75
+ common = ["--project-dir", str(project_dir)]
76
+ if profiles_dir is not None:
77
+ common += ["--profiles-dir", str(profiles_dir)]
78
+ if target is not None:
79
+ common += ["--target", target]
80
+ return common
81
+
82
+
83
+ def run_deps(
84
+ project_dir: Path, *, profiles_dir: Path | None = None, target: str | None = None
85
+ ) -> None:
86
+ """`dbt deps` for a generated project."""
87
+ deps = invoke_dbt(["deps", *_common_args(project_dir, profiles_dir, target)])
88
+ if deps.exception is not None:
89
+ raise DbtError("deps", deps.exception)
90
+
91
+
92
+ def invoke_unit_tests(
93
+ project_dir: Path,
94
+ *,
95
+ profiles_dir: Path | None = None,
96
+ target: str | None = None,
97
+ quiet: bool = False,
98
+ ) -> RawRun:
99
+ """Run the unit tests of a generated project and report what dbt said, even when it failed.
100
+
101
+ `quiet` keeps dbt from printing (`--log-level none`; `--quiet` still prints errors), for a
102
+ case whose error is the point and would otherwise look like a failure on the screen. What
103
+ dbt reported is still in the result.
104
+ """
105
+ args = ["test", "--select", "test_type:unit", *_common_args(project_dir, profiles_dir, target)]
106
+ if quiet:
107
+ args += ["--log-level", "none"]
108
+ warnings: list[str] = []
109
+
110
+ def collect(event: Any) -> None:
111
+ if event.info.level == "warn":
112
+ text = _ANSI.sub("", event.info.msg).removeprefix("[WARNING]: ").strip()
113
+ if text not in warnings:
114
+ warnings.append(text)
115
+
116
+ result = invoke_dbt(args, [collect])
117
+ results = []
118
+ for item in getattr(result.result, "results", []):
119
+ status = str(getattr(item.status, "value", item.status))
120
+ model = getattr(item.node, "model", None)
121
+ results.append(CaseResult(str(model), status, str(item.message or "")))
122
+ exception = None if result.exception is None else str(result.exception)
123
+ return RawRun(success=result.success, exception=exception, results=results, warnings=warnings)
124
+
125
+
126
+ def run_unit_tests(
127
+ project_dir: Path,
128
+ *,
129
+ profiles_dir: Path | None = None,
130
+ target: str | None = None,
131
+ install_packages: bool = False,
132
+ ) -> RunOutcome:
133
+ """Run the unit tests of a generated project through dbt.
134
+
135
+ `errored_models` names the models of the cases dbt could not run at all
136
+ (a SQL error, for instance), as opposed to cases whose rows did not match.
137
+ """
138
+ if install_packages:
139
+ run_deps(project_dir, profiles_dir=profiles_dir, target=target)
140
+
141
+ raw = invoke_unit_tests(project_dir, profiles_dir=profiles_dir, target=target)
142
+ if raw.exception is not None:
143
+ raise DbtError("test", raw.exception)
144
+
145
+ counts: dict[str, int] = {}
146
+ for case in raw.results:
147
+ counts[case.status] = counts.get(case.status, 0) + 1
148
+ errored = [case.model for case in raw.results if case.status == "error"]
149
+ return RunOutcome(passed=raw.success, errored_models=errored, counts=counts)
@@ -0,0 +1,77 @@
1
+ from collections.abc import Collection
2
+ from dataclasses import dataclass
3
+ from pathlib import Path
4
+
5
+ import jinja2
6
+ from dbt_common.clients import jinja as jinja_common
7
+ from dbt_common.exceptions import CompilationError
8
+ from jinja2 import nodes
9
+
10
+ _ENVIRONMENT = jinja2.Environment(extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"])
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Signature:
15
+ required: list[str]
16
+ optional: list[str]
17
+ accepts_any_name: bool
18
+
19
+ @property
20
+ def names(self) -> list[str]:
21
+ return [*self.required, *self.optional]
22
+
23
+
24
+ def signatures_in(source: str) -> dict[str, Signature]:
25
+ """The signature of every macro defined in a piece of Jinja source."""
26
+ found: dict[str, Signature] = {}
27
+ blocks = jinja_common.extract_toplevel_blocks(
28
+ source, allowed_blocks={"macro"}, collect_raw_data=False
29
+ )
30
+ for block in blocks:
31
+ if not isinstance(block, jinja_common.BlockTag) or block.full_block is None:
32
+ continue
33
+ for macro in _ENVIRONMENT.parse(block.full_block).find_all(nodes.Macro):
34
+ names = [arg.name for arg in macro.args]
35
+ split = len(names) - len(macro.defaults)
36
+ referenced = {name.name for name in macro.find_all(nodes.Name)}
37
+ found[macro.name] = Signature(
38
+ required=names[:split],
39
+ optional=names[split:],
40
+ accepts_any_name="kwargs" in referenced,
41
+ )
42
+ return found
43
+
44
+
45
+ def find_signatures(macro_dirs: Collection[Path]) -> dict[str, list[Signature]]:
46
+ """Every definition of every macro under the given directories, by macro name.
47
+
48
+ A file that cannot be read or parsed is skipped: dbt reports that itself
49
+ when it runs, and a macro that cannot be found is simply not checked.
50
+ """
51
+ found: dict[str, list[Signature]] = {}
52
+ for directory in macro_dirs:
53
+ for path in sorted(directory.rglob("*.sql")):
54
+ try:
55
+ signatures = signatures_in(path.read_text())
56
+ except (OSError, UnicodeDecodeError, jinja2.TemplateSyntaxError, CompilationError):
57
+ continue
58
+ for name, signature in signatures.items():
59
+ found.setdefault(name, []).append(signature)
60
+ return found
61
+
62
+
63
+ def problems_with(signature: Signature, given: Collection[str]) -> list[str]:
64
+ """What is wrong with passing these argument names to a macro, if anything."""
65
+ problems = []
66
+ if not signature.accepts_any_name:
67
+ unknown = [name for name in given if name not in signature.names]
68
+ for name in unknown:
69
+ problems.append(f"unknown argument {name!r} (the macro takes: {_listed(signature)})")
70
+ for name in signature.required:
71
+ if name not in given:
72
+ problems.append(f"missing argument {name!r}, which has no default")
73
+ return problems
74
+
75
+
76
+ def _listed(signature: Signature) -> str:
77
+ return ", ".join(signature.names) if signature.names else "no arguments"
@@ -0,0 +1,28 @@
1
+ from collections.abc import Collection
2
+ from pathlib import Path
3
+
4
+ from dbt_macro_test.engine.signature import find_signatures, problems_with
5
+ from dbt_macro_test.spec import SpecFile
6
+
7
+
8
+ def check_arguments(spec_files: list[SpecFile], macro_dirs: Collection[Path]) -> list[str]:
9
+ """Problems with the arguments the specs pass, found before dbt is run.
10
+
11
+ Only macros defined in the project's own macro directories are checked,
12
+ and only when the name is defined once. A macro from a package, a
13
+ qualified name or an unknown name is passed through to dbt.
14
+ """
15
+ definitions = find_signatures(macro_dirs)
16
+ problems = []
17
+ for spec_file in spec_files:
18
+ for macro_spec in spec_file.macros:
19
+ found = definitions.get(macro_spec.macro, [])
20
+ if len(found) != 1:
21
+ continue
22
+ for case in macro_spec.cases:
23
+ for problem in problems_with(found[0], list(case.arguments)):
24
+ problems.append(
25
+ f"{spec_file.path}: macro {macro_spec.macro!r}, case {case.name!r}: "
26
+ f"{problem}"
27
+ )
28
+ return problems