autouse 픽스처

Python 테스트 입문

Alexander Levin

Data Scientist

Autouse 인자

  • 픽스처의 선택적 불리언 인자입니다
  • 픽스처 데코레이터에 전달할 수 있습니다
  • autouse=True이면 요청과 무관하게 픽스처 함수가 실행됩니다
  • 중복된 픽스처 호출을 줄입니다
Python 테스트 입문

사용 시점

모든 테스트에 동일한 환경 준비나 수정을 적용해야 할 때 사용합니다.

예를 들어 모든 테스트가 다음을 보장해야 할 때:

  • 같은 데이터를 사용
  • 같은 연결(데이터, API 등) 사용
  • 같은 환경 구성을 유지
  • 모니터링/로깅/프로파일링 적용

이런 경우는 모두 "autouse" 인자로 처리합니다.

Python 테스트 입문

Autouse 예시

"autouse"된 픽스처 예시:

import pytest
import pandas as pd

# Autoused fixture
@pytest.fixture(autouse=True)
def set_pd_options():
    pd.set_option('display.max_columns', 5000)

# Test function
def test_pd_options():
    assert pd.get_option('display.max_columns') == 5000
Python 테스트 입문

Autouse 잘못된 예시

잘못된 "autouse" 픽스처 예시:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture(autouse=True)
def wrong_fixture():
    return [1,2,3,4,5]

# Test function
def test_type():
    assert type(wrong_fixture) == list

수정된 픽스처 예시:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture
def correct_fixture():
    return [1,2,3,4,5]

# Test function
def test_type(correct_fixture):
    assert type(correct_fixture) == list
Python 테스트 입문

Autouse 예시: 출력

예시 출력:

autouse 예시 출력

Python 테스트 입문

요약

  • autouse 정의: 픽스처 데코레이터의 선택적 불리언 인자
  • 사용법: @pytest.fixture(autouse=True)
  • 장점: 중복된 픽스처 호출을 줄여 코드가 단순해집니다
  • 특징: autouse=True이면 요청과 무관하게 픽스처 함수가 실행됩니다
  • 사용 시기: 환경 준비나 변경을 적용해야 할 때
  • 사용 예:
    • 모든 테스트용 데이터 읽기/준비
    • 연결 및 환경 파라미터 설정
    • 모니터링, 로깅, 프로파일러 적용
Python 테스트 입문

연습해 봅시다!

Python 테스트 입문

Preparing Video For Download...