실전 예시

Python 테스트 입문

Alexander Levin

Data Scientist

데이터와 파이프라인

데이터: 데이터 사이언스 급여.

각 행에는 데이터 사이언스 종사자의 급여, 직함 등 정보가 있습니다.

ds 급여 테이블

파이프라인: 평균 급여 계산

  1. 데이터 읽기
  2. 고용 유형으로 필터링
  3. 평균 급여 계산
  4. 결과 저장
Python 테스트 입문

파이프라인 코드

import pandas as pd

# Fixture to get the data
@pytest.fixture
def read_df():
    return pd.read_csv('ds_salaries.csv')
# Function to filter the data
def filter_df(df):
    return df[df['employment_type'] == 'FT']
# Function to get the mean
def get_mean(df):   
    return df['salary_in_usd'].mean()
Python 테스트 입문

통합 테스트

테스트 케이스:

  • 데이터 읽기
  • 파일에 쓰기

코드:

def test_read_df(read_df):
    # Check the type of the dataframe
    assert isinstance(read_df, pd.DataFrame)
    # Check that df contains rows
    assert read_df.shape[0] > 0
Python 테스트 입문

통합 테스트

파이썬이 파일을 생성할 수 있는지 확인하는 예시입니다.

def test_write():
    # Opening a file in writing mode
    with open('temp.txt', 'w') as wfile:
        # Writing the text to the file
        wfile.write('Testing stuff is awesome')
    # Checking the file exists
    assert os.path.exists('temp.txt')
    # Don't forget to clean after yourself
    os.remove('temp.txt')
Python 테스트 입문

단위 테스트

테스트 케이스:

  • 필터링된 데이터셋에는 'FT' 고용 유형만 포함
  • get_mean() 함수는 숫자를 반환

코드:

def test_units(read_df):
    filtered = filter_df(read_df)
    assert filtered['employment_type'].unique() == ['FT']
    assert isinstance(get_mean(filtered), float)
Python 테스트 입문

기능 테스트

테스트 케이스:

  • 평균은 0보다 큼
  • 평균은 데이터셋의 최대 급여를 넘지 않음

코드:

def test_feature(read_df):
    # Filtering the data
    filtered = filter_df(read_df)
    # Test case: mean is greater than zero
    assert get_mean(filtered) > 0
    # Test case: mean is not bigger than the maximum
    assert get_mean(filtered) <= read_df['salary_in_usd'].max()
Python 테스트 입문

성능 테스트

테스트 케이스:

  • 파이프라인 시작부터 종료까지의 실행 시간

코드:

def test_performance(benchmark, read_df):
    # Benchmark decorator
    @benchmark
    # Function to measure
    def get_result():
        filtered = filter_df(read_df)
        return get_mean(filtered)
Python 테스트 입문

최종 테스트 스위트

import pytest

## Integration Tests
def test_read_df(read_df):
      # Check the type of the dataframe
    assert isinstance(read_df, pd.DataFrame)
    # Check that df contains rows
    assert read_df.shape[0] > 0
def test_write():
    with open('temp.txt', 'w') as wfile:
        wfile.write('12345')
    assert os.path.exists('temp.txt')
    os.remove('temp.txt')

## Unit Tests
def test_units(read_df):
    filtered = filter_df(read_df)
    assert filtered['employment_type'].unique() == ['FT']
    assert isinstance(get_mean(filtered), float)
## Feature Tests
def test_feature(read_df):
    # Filtering the data
    filtered = filter_df(read_df)
    # Test case: mean is greater than zero
    assert get_mean(filtered) > 0
    # Test case: mean is not bigger than the maximum
    assert get_mean(filtered) <= read_df['salary_in_usd'].max()

## Performance Tests
def test_performance(benchmark, read_df):
    # Benchmark decorator
    @benchmark
    # Function to measure
    def pipeline():
        filtered = filter_df(read_df)
        return get_mean(filtered)
Python 테스트 입문

연습해 봅시다!

Python 테스트 입문

Preparing Video For Download...