본문 바로가기
프로그래밍언어/Python

파이썬 개발자라면 꼭 알아야 할 유닛 테스트의 모든 것

by plog 2024. 8. 26.

파이썬 유닛테스트

개요

유닛테스트란 무엇일까요?
유닛 테스트는 소프트웨어 개발에서 가장 작은 단위인 함수나 메서드 하나를 대상으로 정상적인 동작 여부를 검증하는 테스트 방법입니다. 마치 레고 블록 하나하나를 검사하여 완성된 레고 작품이 제대로 작동하는지 확인하는 것과 같습니다.

 

파이썬에서 유닛테스트를 위한 도구
파이썬에서는 unittest 모듈을 사용하여 유닛 테스트를 작성할 수 있습니다. unittest는 간단하면서도 강력한 기능을 제공하여 다양한 종류의 테스트 케이스를 작성할 수 있습니다. unittest모듈은 Python에 포함되어 있는 표준 라이브러리 입니다.

 

실습

1. tests 폴더
유닛테스트 파일 별도 관리하면 좋습니다. tests 폴더에 비어있는 __init__.py 파일 작성 합니다.

2. util, test 파일

# cal_util.py
class Calculator:
    def __init__(self):
        pass

    def add(self, x, y):
        return x + y 

    def multiply(self, x, y):
        return x * y 

    def __del__(self):
        pass
# test_cal_util.py
import unittest
import inspect

from utils.cal_util import Calculator

class TestCase(unittest.TestCase):
    
    # 테스트 시작 전 셋업한다. 각 test마다 매번 호출된다
    def setUp(self):        
        self.cal = Calculator()
        print(f'\n> setup')

     # 테스트 완료 후 정리한다. 각 test마다 매번 호출된다
    def tearDown(self):        
        del self.cal
        print(f'> tearDown')

    def test_plus(self):
        # 함수명은 test로 시작해야한다        
        assert self.cal.add(3, 4) == 7
        print(f'{inspect.stack()[0][3]}() is pass')

    def test_multiply(self):
        # 함수명은 test로 시작해야한다
        assert self.cal.multiply(3, 4) == 12
        print(f'{inspect.stack()[0][3]}() is pass')

 

3. 유닛테스트

실행 

python -m unittest -v tests.test_cal_util

결과화면

test_multiply (tests.test_cal_util.TestCase) ...
> setup
test_multiply() is pass
> tearDown
ok
test_plus (tests.test_cal_util.TestCase) ...
> setup
test_plus() is pass
> tearDown
ok
----------------------------------------------------------------------
Ran 2 tests in 0.015s

 

4. 패턴 유닛테스트

패턴으로 여러파일 테스트 실행 가능 합니다

python -m unittest discover -v -p "*"

 

5. 다양한 형태의 단위 테스트 실행방법
1) python -m unittest 모듈.클래스
2) python -m unittest 모듈.클래스.메소드

6. 권고사항
1) test*.py 명명규칙으로 파일관리 권고
2) 테스트 함수는 test*()로 만든다

 

7. unittest  파라미터

python.exe -m unittest discover [-h] [-v] [-q] [--locals] [-f] [-c] [-b] [-k TESTNAMEPATTERNS] [-s START] [-p PATTERN] [-t TOP]

 

1) discover
특정 디렉터리를 기준으로 하위 디렉터리를 탐색해나가면서 테스트 파일들을 찾습니다.

 

2) -p
"-p" 옵션은 테스트 파일의 패턴을 지정하는 옵션입니다. 예를 들어 "test*"


3) -v
테스트 결과를 자세히 출력합니다.

 

8. 기본 Assert
1) assertEqual(a,b): a==b 
2) assertNotEqual(a,b): a!=b 
3) assertTrue(x):  bool(x) is True 
4) assertFalse(x): bool(x) is False 

5) assertIs(a,b): a is b 
6) assertIsNot(a,b): a is not b 

7) assertIsNone(x): x is None 
8) assertIsNotNone(x): x is not None 
9) assertIn(a,b): a in b 
10) assertNotIn(a,b): a not in b 
11) assertIsInstance(a,b): isinstance(a,b) 
12) assertNotIsInstance(a,b): not isinstance(a,b) 

 

댓글