1. 程式人生 > >python的unittest單元測試框架斷言整理彙總

python的unittest單元測試框架斷言整理彙總

自動化指令碼最重要的是斷言,正確設定斷言以後才能幫助我們判斷測試用例執行結果。

在小同事的幫助下,整理了一份比較詳細的斷言方法。

一、先說說unittest常用的斷言吧

常用的就以下幾個,網上一搜一大堆。python版本2.7以上都可以呼叫了。

斷言語法 解釋
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
assertIsNot(a, b)  a is not b
assertIsNone(x)
 x is None
assertIsNotNone(x) x is not None
assertIn(a, b)  a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b) 
assertNotIsInstance(a, b)  not isinstance(a, b)

二、最近整理的一些

在官方文件裡面看到的整理一下,有些還來不及翻譯。

assertAlmostEqual(first, second[, places, ...])

適用於小數,place是應最少幾位相等布林值才為1(預設為

7),如果在place位以內不同則斷言失敗。

assertEqual(first, second[, msg])

前後兩個數不等的話,失敗

檢查表示式是否為假

self.assertTrue(a > b)用法一樣,但是多了設定條件 .

self.assertTrue(a > =b)用法一樣,但是多了設定條件 .

assertIn(member, container[, msg])

self.assertTrue(a in b)

assertIs(expr1, expr2[, msg])

assertTrue(a is b)

Isinstance(a,b)

Obj is none.

assertIsNot(expr1, expr2[, msg])

a is not b.

Obj is not none.

assertItemsEqual(expected_seq, actual_seq[, msg])

一個無序的序列特異性的比較。

Just like self.assertTrue(a < b), but with a nicer default message.

Just like self.assertTrue(a <= b), but with a nicer default message.

List1list2是否相等.

斷言,2個多行字串是相等的

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta.

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta.

Fail if the two objects are equal as determined by the ‘==’

Fail if the two objects are equal as determined by the ‘==’

assertNotIn(member, container[, msg])

Just like self.assertTrue(a not in b), but with a nicer default message.

Included for symmetry with assertIsInstance.

如果文字匹配正則表示式,將失敗。

assertRaises(excClass[, callableObj])

除非excclass類丟擲異常失敗

認為在引發異常的情況下訊息匹配一個正則表示式。

測試失敗,除非文字匹配正則表示式。

有序序列的相等斷言 (like lists and tuples).

A set-specific equality assertion.

Check that the expression is true.

A tuple-specific equality assertion.

assert_(expr[, msg])

Check that the expression is true.


三、在unittest包裡面看到的比較全的斷言