dbtのtestでは、
データの品質が確保されていることを確認するためのAssertionを行うことができます。

Add data tests to your DAG | dbt
https://docs.getdbt.com/docs/build/data-tests

unique, not_null等の他にカスタムのテストを書くことができますが、
テストの実体はSQLクエリの実行なので、
テストを増やせば増やすほど、処理時間やDBへの負荷の影響があります。
そのため、テストの負荷が悪影響を与えないことを評価してから、
本番環境にテストを適用する流れになるかと思います。

このエントリでは、このようなユースケースを想定して、
・テスト環境では全テスト実施
・本番環境では評価済みのテストのみ実施
するための方法を示したいと思います。

テストを絞り込む方法

テストを絞り込む方法は、selectかexcludeかのいずれかを使うことになります。
絞り込む対象を決める方法はタグを使うとよさそうです。

Node selector methods
https://docs.getdbt.com/reference/node-selection/methods

Exclude models from your run
https://docs.getdbt.com/reference/node-selection/exclude

方法①: 本番環境用テストにタグを付与 (select)

評価済みのテストにタグを付与して、対象を絞り込む方法です。

schema.yml

version: 2

models:
  - name: my_first_dbt_model
    description: "A starter dbt model"
    columns:
      - name: id
        description: "The primary key for this table"
        data_tests:
          - unique
          - not_null:
              tags: [prd]

  - name: my_second_dbt_model
    description: "A starter dbt model"
    columns:
      - name: id
        description: "The primary key for this table"
        data_tests:
          - unique
          - not_null
              tags: [prd]

テストの実行方法

dbt test --select "my_first_dbt_model,tag:prd"

このように「tag:prd」を付けると、 not_null_my_first_dbt_model_idのテストのみ実行します。

以下のように、テスト環境・本番環境でコマンドを使い分けると、 実行するテストを切り替えることができます。

  • 本番環境: dbt test --select "my_first_dbt_model,tag:prd"
  • テスト環境: dbt test --select "my_first_dbt_model"

方法②: テスト環境用テストにタグを付与 (exclude)

schema.yml

version: 2

models:
  - name: my_first_dbt_model
    description: "A starter dbt model"
    columns:
      - name: id
        description: "The primary key for this table"
        data_tests:
          - unique
              tags: [dev_only]
          - not_null:

  - name: my_second_dbt_model
    description: "A starter dbt model"
    columns:
      - name: id
        description: "The primary key for this table"
        data_tests:
          - unique
              tags: [dev_only]
          - not_null

テストの実行方法

dbt test --model my_first_dbt_model --exclude tag:dev_only

このように「tag:dev_only」を除外すると、 not_null_my_first_dbt_model_idのテストのみ実行します。

以下のように、テスト環境・本番環境でコマンドを使い分けると、 実行するテストを切り替えることができます。

  • 本番環境: dbt test --select "my_first_dbt_model" --exclude tag:dev_only
  • テスト環境: dbt test --select "my_first_dbt_model"

おわりに

このエントリの方法で、安全にテストを追加できると思います。

dbtのテストの仕組みは、
外部からデータを取り込む際の不備を検出する時などに、特に有効な仕組みかと思います。

本来のテストの用途からはズレるかもしれないですが、
このエントリの方法を使うとテスト環境のみで動かすテストを定義できるので、
クエリ変更時のデグレードを検知するなど、
データ品質では無くクエリの品質を確保するための仕組みとしても使えるかも知れません。

以上。