如何测试DBT宏?AWS Snowflake场景下测试问题排查
正确测试DBT宏的方法
先说明:DBT的宏本身不属于dbt test默认扫描的节点类型(默认扫描的是schema测试、数据测试),所以直接用dbt test --select指定宏相关的测试名会找不到节点。下面是两种可行的测试方案:
方案1:用测试模型验证宏输出
这种方式是创建专门的测试模型,调用宏后对比结果是否符合预期:
- 在
models/tests目录下新建测试模型文件(比如test_get_customer_active.sql) - 在模型中调用
get_customer宏,生成结果后和预期值对比,示例代码:
{{ config(materialized='view') }} -- 调用宏获取结果 with macro_result as ( {{ get_customer(is_active=True) }} ), -- 按业务逻辑定义预期结果 expected_result as ( select customer_id, customer_name from {{ source('source', 'customer') }} where is_active = True ) -- 对比宏结果和预期,返回差异(有差异则测试失败) select m.* from macro_result m full outer join expected_result e on m.customer_id = e.customer_id where m.customer_id is null or e.customer_id is null
- 运行命令执行这个测试模型:
dbt run --select test_get_customer_active,如果模型返回非空结果,说明宏输出不符合预期。 - 若要把这类模型纳入dbt测试流程,可在
dbt_project.yml中配置:
models: your_project_name: tests: +tags: ["macro_test"]
之后用dbt run --select tag:macro_test就能批量运行所有宏测试模型。
方案2:使用DBT单元测试(推荐)
DBT 1.5及以上版本支持单元测试,可直接对宏进行测试:
- 在
tests/unit目录下新建测试文件(比如test_get_customer.yml) - 编写单元测试配置,指定宏、参数和预期输出:
unit_tests: - name: test_get_customer_active description: 验证get_customer宏在is_active=True时的输出SQL macro: get_customer args: is_active: True expect: sql: "select customer_id, customer_name from source.customer where is_active = True"
- 运行单元测试命令:
dbt test --select test_get_customer_active,DBT会自动对比宏生成的SQL和你指定的预期SQL,验证是否一致。
关于你之前的问题
你之前创建的get_customer_active测试应该是schema测试(比如tests目录下的.yml或.sql schema测试),这类测试是绑定到模型的,无法直接关联宏,所以DBT找不到对应节点,需要改成上面两种针对宏的测试方式。
内容的提问来源于stack exchange,提问作者Anson
相关产品推荐
相关产品推荐

