本文將詳細介紹Python中常用的斷言函數,讓大家了解這些函數的作用及使用方法,以便於進行代碼測試和調試。
一、assertEqual函數
1、assertEqual函數是Python中unittest模塊中的一個方法,用於判斷兩個元素是否相同。
def assertEqual(self, first, second, msg=None): """ Fail if the two objects are unequal as determined by the '==' operator. """ if not first == second: standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second)) msg = self._formatMessage(msg, standardMsg) raise self.failureException(msg)
2、assertEqual方法在比較元素是否相等時,會用到“==”操作符。如果兩個元素不相等,則assertEqual方法會通過raise語句拋出一個異常。
二、assertTrue函數
1、assertTrue函數同樣是Python中unittest模塊中的一個方法,用於判斷一個元素是否為True。
def assertTrue(self, expr, msg=None): """Check that the expression is true.""" if not expr: msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr)) raise self.failureException(msg)
2、assertTrue方法會判斷一個表達式的值是否為True,如果不是True,則會拋出一個異常。
三、assertIn函數
1、assertIn函數同樣是Python中unittest模塊中的一個方法,用於判斷一個元素是否包含在另一個元素中。
def assertIn(self, member, container, msg=None): """ Just like self.assertTrue(a in b), but with a nicer default message. """ if member not in container: msg = self._formatMessage(msg, "%s not found in %s" % (safe_repr(member), safe_repr(container))) raise self.failureException(msg)
2、assertIn方法會判斷一個元素是否包含在另一個元素中。如果不包含,則會拋出一個異常。
四、assertRaises函數
1、assertRaises函數同樣是Python中unittest模塊中的一個方法,用於判斷一個指定的異常是否會被拋出。
def assertRaises(self, excClass, callableObj=None, *args, **kwargs): """ Fail unless an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unhandled exception. """ context = _AssertRaisesContext(excClass, self) if callableObj is None: return context with context: callableObj(*args, **kwargs)
2、assertRaises方法會判斷一個指定的異常是否會被拋出。如果沒有拋出指定的異常,則會拋出一個異常。
五、assertAlmostEqual函數
1、assertAlmostEqual函數同樣是Python中unittest模塊中的一個方法,用於判斷兩個浮點數是否在指定的精度範圍內相等。
def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None): """ Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signifcant digit). """ if first == second: return if delta is not None and abs(first-second) <= delta: return if places is None: places = self.DEFAULT_PRECISION if round(abs(second-first), places) == 0: return if msg is None: msg = '%r != %r within %r places' % (first, second, places) raise self.failureException(msg)
2、assertAlmostEqual方法會判斷兩個浮點數是否在指定的精度範圍內相等。如果不相等,則會拋出一個異常。
六、小結
本文詳細介紹了Python中常用的斷言函數,包括assertEqual、assertTrue、assertIn、assertRaises和assertAlmostEqual。這些斷言函數能夠幫助程序員進行代碼測試和調試,提高程序的穩定性和正確性。
原創文章,作者:OWXZU,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/373530.html