오늘도 개발

Python unittest 모듈로 Unit Test해보기 본문

웹 프로그래밍/Python3

Python unittest 모듈로 Unit Test해보기

Sueeeeeee 2022. 8. 5. 00:48

Unit Test란?

프로그램을 이루는 가장 작은 유닛을 테스트하는 것.

즉 함수 또는 클래스를 테스트하는 것.

python에서는 Unit Test를 할 수 있게 기본적으로 unittest 모듈을 제공한다.

기본 unittest 외에 pip로 설치해서 사용할 수 있는 pytest 모듈도 있다.

 

unittest가 제공하는 것

TestCase

파이썬 unittest 모듈의 기본 단위. 

새 테스트 생성 시 TestCase 클래스를 상속받아 작성할 수 있다.

 

Fixture

테스트를 위한 설정을 하는 작업을 Fixture라고 한다.

테스트를 위한 사전 준비 작업이 필요하면 setUp 메서드를,

테스트 후 테스트를 삭제하는 작업이 필요하면 tearDown 메서드를 사용할 수 있다.

TestCase에 setUp 메서드와 tearDown 메서드, 여러 test 메서드를 작성하면

파이썬이 각 test 메서드를 실행하기 전에 알아서 setUp을 실행하고

테스트 후에 tearDown을 실행한다.

 

Assertion

기대하는 결과를 입력해두고 테스트 후 실제 결과를 비교하는 것을 Assertion이라고 한다.

assert 메서드에는 assertEqual, assertTrue, assertFalse, assertRaises, assertRegex 등이 있다.

 

TestCase 만드는 법

<mycalc.py> : 테스트할 함수가 들어있는 파일

def add(a, b):
   # add인데 실수로 곱하기를 한 상황
   return a * b
   
def subtract(a, b):
   return a - b

<test.py> : 테스트 코드가 들어있는 파일. 테스트 할 메서드명은 test_로 시작해야 파이썬이 인식한다.

import unittest
import mycalc

class MyCalcTest(unittest.TestCase):
    # add 함수를 테스트하는 메서드
    def test_add(self):
        # mycalc 모듈의 add 함수에 20, 10을 넣은 결과를 c에 저장함
        c = mycalc.add(20, 10)

        # c가 30이면 ok가 나옴
        self.assertEqual(c, 30)

    # subtract 함수를 테스트하는 메서드
    def test_subtract(self):
        c = mycalc.subtract(20, 10)
        self.assertEqual(c, 10)

# test.py를 실행하는 경우 테스트 메서드를 호출
if __name__ == '__main__':
    unittest.main()

<터미널> : python test.py 실행

F는 assertEqual이 Fasle인 경우. 즉 add 함수에 오류가 있다는 뜻.

. 은 assertEqal이 True인 경우. 즉 subtract 함수는 문제가 없다는 뜻. 

F.
======================================================================
FAIL: test_add (__main__.MyCalcTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 11, in test_add
    self.assertEqual(c, 30)
AssertionError: 200 != 30

 

Fixture 사용하는 법

<test.py>

import unittest
import mycalc

class MyCalcTest(unittest.TestCase):
    def setUp(self):
        print('Executing setUp method')
        self.fixture = 'yay!'

    def tearDown(self):
        print('Executing tearDown method')
        self.fixture = None

    def test_add(self):
        print(f'Executing test_add. Fixture is {self.fixture}')
        c = mycalc.add(20, 10)
        self.assertEqual(c, 30)

    def test_subtract(self):
        print(f'Executing test_subtract. Fixture is {self.fixture}')
        c = mycalc.subtract(20, 10)
        self.assertEqual(c, 10)

if __name__ == '__main__':
    unittest.main()

<터미널> : test.py 실행

Executing setUp method
Executing test_add. Fixture is yay!
Executing tearDown method
FExecuting setUp method
Executing test_subtract. Fixture is yay!
Executing tearDown method
.
======================================================================
FAIL: test_add (__main__.MyCalcTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 16, in test_add
    self.assertEqual(c, 30)
AssertionError: 200 != 30

----------------------------------------------------------------------
Ran 2 tests in 0.001s

 

 

참고

예제로 배우는 파이썬 프로그래밍 - 유닛 테스트