Programming/Unittest
Assertion
c29130811
2024. 9. 13. 22:04
메서드 | 내용 | 버전 |
assertEqual(a, b) | a == b | |
assertNotEqual(a, b) | a != b | |
assertTrue(x) | bool(x) is True | |
assertFalse(x) | bool(x) is False | |
assertIs(a, b) | a is b | 3.1 |
assertIsNot(a, b) | a is not b | 3.1 |
assertIsNone(x) | x is None | 3.1 |
assertIsNotNone(x) | x is not None | 3.1 |
assertIn(a, b) | a in b | 3.1 |
assertNotIn(a, b) | a not in b | 3.1 |
assertIsInstance(a, b) | isinstance(a, b) | 3.2 |
assertNotIsInstance(a, b) | not isinstance(a, b) | 3.2 |
docs.python.org에 있는 내용인데 상위 4개를 제외한 나머지는 버전에 따른 이슈가 있긴 하지만
unnitest가 현재 3.12.X 버전이기 때문에 구버전이 아니라면 다 사용이 가능함.
assert 메서드는 msg 를 사용 할 수 있으나, 기본이 None이다. msg는 실패 시 에러 메세지로 사용 됨
import unittest
# 테스트할 함수
def add(x, y):
return x + y
# 테스트 케이스 정의
class TestMathOperations(unittest.TestCase):
def test_add(self):
result = add(10, 5)
self.assertEqual(result, 19, msg="15 여야 함") # 기대 값과 실제 값이 같은지 확인
# 테스트 실행
if __name__ == '__main__':
unittest.main()
세번째 인자로 15를 넣으면, 실패했을때 AssertionError와 함께 15 != 19 : 15 형태로 나오게 되는데,
FAIL: test_add (__main__.TestMathOperations.test_add)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/june/Documents/Study/pytest/test_1.py", line 33, in test_add
self.assertEqual(result, 19, msg="15 여야 함") # 기대 값과 실제 값이 같은지 확인
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: 15 != 19 : 15 여야 함
요런 식으로 나온다.
말고 asssertRaises도 있고 Regex도 있는데 그건 다음 편
728x90