데이터 엔지니어 이것저것

dbt test 본문

오픈소스/dbt

dbt test

pastime 2023. 11. 14. 01:36
728x90
테스트는 프로젝트 모델 및 기타 리소스에 대해 수행하는 작업
이를 통해 각 모델에서 SQL의 무결성을 향상

 

dbt에서 테스트를 정의하는 방법에는 2가지가 있다.

  • 단일 테스트는 가장 간단한 형태로 테스트
    tests DIR에 실패한 행을 반환하는 SQL 쿼리를 작성
  • yml 파일에 test 작성

 

 

단일 테스트로는 테스트 하고자 하는 SQL을 tests DIR안에 작성하면 된다.

 

 

 

yml 파일에 작성

 

model을 작성한 yml 파일에 아래의 형태로 특정 컬럼에 테스트할 케이스를 작성하면 된다.

 

4개의 일반 테스트는 정의 되어 있다

  • unique
  • not_null
  • accepted_values
  • relationships

 

 

하나씩 테스트를 해보면


  • not_null
  - name: user_info
    columns:
      - name: full_name
        tests:
          - not_null

 

full_name 이라는 컬럼에 null 이 없어야한다

 

 

해당 명령어를 실행하면

dbt test

 

 

실패를 하였다는 메시지가 발생한다.

 

메시지에 있는 source_not_null_user_table_user_info_full_name.sql 을 확인해보면

select full_name
from "root"."source"."user_info"
where full_name is null

이런식으로 쿼리가 작성되어있다.

 

null로 된 값을 수정하여 다시 테스트 코드를 동작해보면

 

성공한것을 확인 할 수 있다

 


  • unique
  - name: id
    tests:
      - unique

 

이번에는 id 라는 컬럼이 중복 없는지 확인

 

select
    id as unique_field,
    count(*) as n_records

from "root"."source"."user_info"
where id is not null
group by id
having count(*) > 1

 

위의 방식과 똑같이 확인하면 문제 없는것을 확인할 수 있다.


  • accepted_values
  - name: gender
    tests:
      - accepted_values:
          values: ['Male', 'Female', 'Other']

 

이번에는 gender 라는 컬럼에 ['Male', 'Female', 'Other'] 3가지의 값만 있는지 확인하기 위한 코드 작성

 

실제 동작하는 쿼리

with all_values as (

    select
        gender as value_field,
        count(*) as n_records

    from "root"."source"."user_info"
    group by gender

)

select *
from all_values
where value_field not in (
    'Male','Female','Other'
)

 

 

 

만약 아래처럼 gender에 다른값이 들어갔을 경우에는

 

 

해당 방식으로 확인이 가능하다.


 

  • relationships
  - name: username
    tests:
      - relationships:
          to: source('user_table', 'users')
          field: user_name

 

이러한 형태로 작성을 할수 있는데

user_info 라는 테이블username이라는 컬럼

users 라는 테이블의        user_name 의 컬럼을 비교하는것이다

with child as (
    select username as from_field
    from "root"."source"."user_info"
    where username is not null
),

parent as (
    select user_name as to_field
    from "root"."source"."users"
)

select
    from_field

from child
left join parent
    on child.from_field = parent.to_field

where parent.to_field is null

 

두개의 테이블을 조인하여 좌측의 테이블 (user_info) 에는 존재하지만 우측의 테이블(users) 에는 없는것을 출력한다.

 


 

결과물을 db에 저장할수도 있는데

 dbt test --store-failures

 

이렇게 작성을 하면 새로운 스키마에 데이터가 저장이 된다

기본적으로 dbt_test__audit 라는 스키마가 생성이 되는데

 

테이블들을 확인하면 에러 내용들을 볼 수 있다

 

728x90

'오픈소스 > dbt' 카테고리의 다른 글

dbt macros  (0) 2023.11.15
dbt_project.yml  (0) 2023.11.15
dbt snapshot  (0) 2023.11.13
dbt sources  (1) 2023.11.12
dbt seeds  (0) 2023.11.12