unittest
python 테스트 코드 작성 내장 패키지. 내장패키지로 따로 설치할 필요 없음.
import 후 사용 가능
테스트는 최대한 작은 단위로 쪼개서 하는 것이 유지보수 차원에서 좋다. (프로젝트 확장성 고려)
사용법
- unittest.TestCase를 상속받는 테스트 클래스 생성
- 클래스 메소드로 테스트 할 코드 작성
- assert*() 등의 테스트 메소드를 이용하여 원하는 코드가 동작하는지 체크
- assert에서 실패하면 에러로 취급하여 테스트 실패
- 아래 각각의 메소드는 독립적으로 테스트되며 서로 영향을 주지 않는다.
- 전체를 실행할 시에 테스트 메서드의 순서는 문자열 이름순으로 동작. (스프링과 차이점)
import unittest
class TestStringMethods(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')
    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())
    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)
if __name__ == '__main__':
    unittest.main()위 코드를 실행하여 에러가 없다면 아래와 같이 OK가 출력

테스트 전, 후 동작 코드
- setUp() 메서드를 통해 테스트 전에 실행하는 함수를 작성할 수 있다.
- tearDown() 메서드를 통해 테스트 후에 실행하는 함수를 작성할 수 있다.
class TestStringMethods(unittest.TestCase):
    def setUp(self) -> None:
        print('start')
    def tearDown(self) -> None:
        print('end')
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')
    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())
    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)
if __name__ == '__main__':
    unittest.main()위의 코드를 실행하면 각각의 세 가지 메서드를 테스트 하기 전에 start를 출력하고 테스트 후에 end를 출력

테스트 skip하기
unittest의 skip decoration으로 해당 메서드 테스트를 스킵할 수 있다.
- @unittest.skip(reason):조건없이 테스트를 건너 뛴다. reason은 str 값으로 건너뛴 이유를 작성한다.
- @unittest.skiplf(condition, reason): condition이 참이면 테스트를 건너 뛴다.
- @unittest.skipUnless(condition, reason): condition이 참이 아니면 테스트를 건너 뛴다.
import sys
import unittest
class TestStringMethods(unittest.TestCase):
    @unittest.skip("skip no reason.")
    def test1(self):
        pass
    @unittest.skipIf(sys.platform.startswith("darwin"), "requires darwin os")
    def test2(self):
        pass
    @unittest.skipUnless(sys.platform.startswith("win"), "requires windows")
    def test3(self):
        pass
if __name__ == '__main__':
    unittest.main()해당 테스트는 windows에서 진행

'IT > Python' 카테고리의 다른 글
| [Python] 파이썬 map(), map함수 (0) | 2023.11.15 | 
|---|---|
| [Python] 파이썬 언더스코어(_) (1) | 2023.11.14 | 
| [Python] 파이썬 반복문에서 언더바(_) 사용 (0) | 2023.11.14 | 
| [Python] python 동시성 (0) | 2023.11.07 | 
| [Python] pip 명령어, txt 파일로 관리 (0) | 2023.11.06 |