Airflow UnitTest with DAG BAG
6분 소요

DAG_BAG기반의 Airflow UnitTest와 Git Action을 활용하여 CI 설정에 대해 설명합니다. Airflow: 2.9.1
Unit Test 실행 시 Local (Airflow) 환경이 필요할 수 있습니다.
$ airflow db init
Overview
Airflow의 Test 같은 경우
airflow tasks test <task_id>와 같이 CLI를 통해서 각 Task를 테스트할 수 있습니다.
오늘은 DAG_BAG 기반의 unit test를 작성하고 git_action 기반의 CI 환경까지 구축해보겠습니다.
GitHub - seon99il/airflow-boilerplate — BoilerPlate seon99il/airflow-boilerplate
해당 Repository에 CI 및 Dag Bag 기반의 Unit Test Sample 코드가 있습니다.
What is DAG BAG?
DagBag은 이름 그대로 Airflow의 모든 DAG(Directed Acyclic Graph) 객체를 담고 있는 Bag(가방)입니다.
Airflow 스케줄러와 웹서버는 dags_folder에 있는 모든 Python 파일을 주기적으로 스캔(파싱)합니다. 이 과정에서 발견된 유효한 모든 DAG 객체를 수집하여 DagBag이라는 인메모리(in-memory) 컬렉션에 보관합니다
- DAG 파일에 Python 구문 오류가 있거나, import에 실패하면
DagBag은 해당 파일을 로드하지 못하고import_error로 기록합니다
DagBag을 활용한 DAG 유닛 테스트란 “내 DAG 파일이 최소한 Airflow에 의해 정상적으로 로드될 수 있는가?” 를 확인하는 것입니다
Unit Test
apache-airflow,pytest가 Test를 실행하는 환경에 설치되어 있어야 합니다.
$ pip install apache-airflow
$ pip install pytest
# Structure
.
├── README.md
├── pytest.ini # Test 환경 설정
├── src # Source Root Dir
│ ├── Dockerfile
│ ├── __init__.py
│ ├── config
│ ├── dags
│ ├── data
│ ├── docker-compose.yaml
│ ├── logs
│ ├── plugins
│ ├── requirements-base.txt
│ └── requirements.txt
├── tests # Test Root Dir
│ ├── test_dags.py
│ └── test_hello_world_dag.py
└── uv.lock
DAG 로딩 (Smoke Test)
가장 중요하고 기본적인 테스트입니다.
DagBag을 직접 임포트하여 대상 DAG 파일이 오류 없이 로드되는지 확인합니다.
import glob
import os
import pytest
from airflow.models import DagBag
DAG_PATH = os.path.join(os.path.dirname(__file__), "../src/dags")
DAG_FILE_PATH = os.path.join(DAG_PATH, "hello_world.py")
DAG_FILES = glob.glob(DAG_PATH, recursive=True)
@pytest.fixture
def dag_bag():
return DagBag(dag_folder=DAG_PATH, include_examples=False)
def test_dag_loaded(dag_bag):
assert not dag_bag.import_errors, f"DAG Import Errors: {dag_bag.import_errors}"
import_error가 없는지 확인
include_examples=False: Example DAG를 무시합니다.pytest.fixture: params으로 객체를 전달할 수 있음
DAG 속성 및 기본 설정 테스트
DAG가 잘 로드되었다면, 이제 세부 설정이 올바른지 확인합니다
테스트 목적: schedule_interval, retries, owner 등 DAG의 핵심 메타데이터가 의도대로 설정되었는지 보장합니다.
import glob
import os
import pytest
from airflow.models import DagBag
DAG_PATH = os.path.join(os.path.dirname(__file__), "../src/dags")
DAG_FILE_PATH = os.path.join(DAG_PATH, "hello_world.py")
DAG_FILES = glob.glob(DAG_PATH, recursive=True)
@pytest.fixture
def dag_bag():
return DagBag(dag_folder=DAG_PATH, include_examples=False)
def test_dag_loaded(dag_bag):
assert not dag_bag.import_errors, f"DAG Import Errors: {dag_bag.import_errors}"
def test_dag_id_exists_in_dagbag(dag_bag):
"""
예상하는 DAG ID가 DagBag에 존재하는지 확인
"""
expected_dag_id = "hello_world" # 실제 DAG 파일에 정의된 ID
dag = dag_bag.get_dag(expected_dag_id)
assert dag is not None, f"DAG '{expected_dag_id}' not found in DagBag."
assert dag.dag_id == expected_dag_id
print(dag.tasks)
def test_dag_default_args(dag_bag):
"""
DAG의 default_args가 올바르게 설정되었는지 확인
"""
my_dag = dag_bag.get_dag("hello_world")
assert my_dag.default_args['owner'] == 'data_team'
assert my_dag.default_args.get('retries') == 3
def test_dag_schedule_and_tags(dag_bag):
"""
스케줄 간격, 태그 등이 올바르게 설정되었는지 확인
"""
my_dag = dag_bag.get_dag("hello_world")
assert my_dag.schedule_interval == "0 12 * * *"
assert "production" in my_dag.tags
assert my_dag.catchup == False
- DAG:
dagbag.get_dag("hello_world")로 특정 DAG를 가져올 수 있음
Task 개수 및 존재 여부 테스트
DAG에 포함된 Task들이 누락되거나 추가되지 않았는지 확인합니다.
테스트 목적: 리팩토링 중 실수로 Task가 삭제되거나, 의도치 않은 Task가 추가되는 것을 방지할 수 있습니다.
import os
import pytest
from airflow.models import DagBag
DAG_PATH = os.path.join(os.path.dirname(__file__), "../src/dags")
@pytest.fixture
def dag_bag():
return DagBag(dag_folder=DAG_PATH, include_examples=False)
@pytest.fixture
def hello_world_dag(dag_bag):
return dag_bag.get_dag("hello_world")
def test_task_count(hello_world_dag):
"""
DAG에 정의된 총 Task의 개수가 맞는지 확인
"""
assert len(hello_world_dag.tasks) == 2
def test_tasks_exist(hello_world_dag):
"""
필수 Task ID들이 DAG에 존재하는지 확인
"""
expected_task_ids = ["print_hello", "print_hello2"]
# task_ids는 list 자료형
for task_id in expected_task_ids:
assert task_id in hello_world_dag.task_ids
Task 의존성 (구조) 테스트
DAG의 핵심인 Task 간의 순서(의존성)가 올바르게 설정되었는지 확인
테스트 목적: 데이터 파이프라인의 흐름(Graph)이 비즈니스 로직과 일치하는지 검증합니다.
def test_task_dependencies(hello_world_dag):
"""
Task 간의 업스트림/다운스트림 관계가 올바른지 확인
"""
process_task = hello_world_dag.get_task("print_hello")
assert len(process_task.upstream_task_ids) == 0
assert "print_hello2" in process_task.downstream_task_ids
Operator 상세 설정 테스트
개별 Task(Operator)가 사용하는 인자(e.g.,
bash_command,sql)가 올바른지 확인합니다.
테스트 목적: Operator의 핵심 로직(실행할 커맨드, 쿼리 등)이 정확하게 설정되었는지 확인합니다.
def test_bash_operator_command(hello_world_dag):
"""
Operator가 올바르게 설정되었는지 확인
"""
print_hello_task = hello_world_dag.get_task("print_hello")
assert print_hello_task.operator_name == "PythonOperator"
Task 내부 로직 테스트 (Pure Unit Test)
만약
@task데코레이터(TaskFlow API)나PythonOperator를 사용하여 복잡한 Python 함수를 실행한다면, 그 함수 자체를 별도로 테스트할 수 있습니다.
테스트 목적: Airflow 프레임워크와 분리하여, 함수의 비즈니스 로직만을 순수하게 테스트합니다.
def test_dag_loaded():
from dags.hello_world import return_name
expected_name = "John Doe"
assert return_name(expected_name) == expected_name
- import 오류를 해결하기 위해서 pytest.ini에
pythonpath를 설정해줘야 하며, pytest를 project root에서 실행하는 것이 안전합니다.
# ./pytest.ini
[pytest]
pythonpath = . src
Git Action 기반의 CI workflow
이제 작성한 test를 기반으로 CI 로직을 작성해보겠습니다.
name: Airflow DAG CI
on:
push:
branches: [ "main", "dev" ]
pull_request:
branches: [ "main", "dev" ]
jobs:
ci-test:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.10.12"
- name: Set commit range for diff
id: commit-range
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
echo "range=${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}" >> $GITHUB_OUTPUT
echo "Checking PR changes: ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}"
elif [ "${{ github.event_name }}" = "push" ]; then
echo "range=${{ github.event.before }}...${{ github.event.after }}" >> $GITHUB_OUTPUT
echo "Checking push changes: ${{ github.event.before }}...${{ github.event.after }}"
else
echo "range=HEAD~1...HEAD" >> $GITHUB_OUTPUT
echo "Defaulting to changes in last commit"
fi
- name: 🔎 Check for changed requirements
id: changed-reqs
run: |
CHANGED_FILES=$(git diff --name-only ${{ steps.commit-range.outputs.range }} -- src/requirements-base.txt src/requirements.txt || true)
if [ -z "$CHANGED_FILES" ]; then
echo "✅ No requirement files changed in this commit range."
echo "Cache *should* be a HIT (if a cache exists)."
else
echo "⚠️ Found changed requirement files (cache *may* be a MISS):"
echo "$CHANGED_FILES"
fi
- name: Get pip cache dir
id: pip-cache
run: |
echo "dir=$(pip cache dir)" >> $GITHUB_OUTPUT
- name: Cache base dependencies
uses: actions/cache@v4
id: cache-base
with:
path: ${{ steps.pip-cache.outputs.dir }}
key: ${{ runner.os }}-pip-base-${{ hashFiles('src/requirements-base.txt') }}
restore-keys: |
${{ runner.os }}-pip-base-
- name: Cache all dependencies
uses: actions/cache@v4
id: cache-full
with:
path: ${{ steps.pip-cache.outputs.dir }}
key: ${{ runner.os }}-pip-full-${{ hashFiles('src/requirements-base.txt', 'src/requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-base-${{ hashFiles('src/requirements-base.txt') }}
${{ runner.os }}-pip-base-
- name: Install dependencies
working-directory: src
run: |
python -m pip install --upgrade pip
pip install -r requirements-base.txt
pip install -r requirements.txt
- name: Mock Airflow Env
run: |
airflow db init
- name: Run pytest
run: |
pytest -v --disable-warnings
- name: 📋 Report cache status
if: always()
run: |
echo "--- Cache Status Report ---"
echo "Base Cache (requirements-base.txt): ${{ steps.cache-base.outputs.cache-hit == 'true' && '✅ HIT' || '❌ MISS' }}"
echo "Full Cache (requirements.txt): ${{ steps.cache-full.outputs.cache-hit == 'true' && '✅ HIT' || '❌ MISS' }}"
echo "---------------------------"
- 파이썬 Airflow 의존성 작업은 자주 변경되지 않기 때문에
requirements-base.txt로 분리하여 캐싱 - airflow db init을 통해 메타데이터베이스를 설정해 줘야 합니다