Assertion là sanity-test khi bạn done với testing chương trình.
Assertion tương tự raise-if statement (hoặc chính xác hơn, raise-if-not statement). Một expression được test, và nếu result ra false, exception được raise. Assertions được carried out bằng cách dùng assert statement.
Programmers thường put assertions ở đầu function để check valid input, và sau function call để check valid output. Dùng assert statement:
Ví dụ
x, y = 8, 8 assert x < y, 'x and y are equal'
Kết quả
Traceback (most recent call last): File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception handling/assertionerror1.py", line 9, inassert x < y, 'x and y are equal' AssertionError: x and y are equal
Equivalent code không dùng assert statement cho cùng output:
Ví dụ
x, y = 8, 8
if not x < y:
raise AssertionError('x and y are equal')
Kết quả
Traceback (most recent call last): File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception handling/assertionerror1.py", line 7, inraise AssertionError('x and y are equal') AssertionError: x and y are equal