단위 테스트

Python으로 배우는 소프트웨어 공학 원칙

Adam Spannbauer

Machine Learning Engineer at Eastman

테스트가 필요한 이유

  • 코드가 의도대로 작동하는지 확인
  • 한 함수의 변경이 다른 함수에 영향을 미치지 않도록 보장
  • 의존성 변경으로부터 보호
Python으로 배우는 소프트웨어 공학 원칙

Python에서의 테스트

  • doctest
  • pytest

pytest 로고

Python으로 배우는 소프트웨어 공학 원칙

doctest 사용

def square(x):
    """Square the number x

    :param x: number to square
    :return: x squared

    >>> square(3)
    9
    """
    return x ** 3


import doctest doctest.testmod()
Failed example:
    square(3)
Expected:
    9
Got:
    27
Python으로 배우는 소프트웨어 공학 원칙

pytest 구조

테스트 구조

Python으로 배우는 소프트웨어 공학 원칙

pytest 구조

테스트 구조

Python으로 배우는 소프트웨어 공학 원칙

단위 테스트 작성

workdir/tests/test_document.py에서 작업 중

from text_analyzer import Document


# Test tokens attribute on Document object
def test_document_tokens():
    doc = Document('a e i o u')

    assert doc.tokens == ['a', 'e', 'i', 'o', 'u']

# Test edge case of blank document def test_document_empty(): doc = Document('') assert doc.tokens == [] assert doc.word_counts == Counter()
Python으로 배우는 소프트웨어 공학 원칙

단위 테스트 작성

# Create 2 identical Document objects
doc_a = Document('a e i o u')
doc_b = Document('a e i o u')

# Check if objects are ==
print(doc_a == doc_b)

# Check if attributes are == print(doc_a.tokens == doc_b.tokens) print(doc_a.word_counts == doc_b.word_counts)
False

True True
Python으로 배우는 소프트웨어 공학 원칙

pytest 실행

terminal에서 작업 중

datacamp@server:~/work_dir $ pytest
collected 2 items

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
Python으로 배우는 소프트웨어 공학 원칙

pytest 실행

terminal에서 작업 중

datacamp@server:~/work_dir $ pytest tests/test_document.py
collected 2 items

tests/test_document.py ..                     [100%]

========== 2 passed in 0.61 seconds ==========
Python으로 배우는 소프트웨어 공학 원칙

테스트 실패

terminal에서 작업 중

datacamp@server:~/work_dir $ pytest
collected 2 items

tests/test_document.py F.

============== FAILURES ==============
________ test_document_tokens ________

def test_document_tokens(): doc = Document('a e i o u')

assert doc.tokens == ['a', 'e', 'i', 'o']
E AssertionError: assert ['a', 'e', 'i', 'o', 'u'] == ['a', 'e', 'i', 'o']
E Left contains more items, first extra item: 'u'
E Use -v to get the full diff

tests/test_document.py:7: AssertionError
====== 1 failed in 0.57 seconds ======
Python으로 배우는 소프트웨어 공학 원칙

연습해 봅시다!

Python으로 배우는 소프트웨어 공학 원칙

Preparing Video For Download...