python 中的斷言 的使用

2022-09-22 04:57:12 字數 1699 閱讀 1055

一、python assert 斷言句語格式及用法很簡單。在沒完善乙個程式之前,我們不知道程式在**會出錯,與其讓它在執行最崩潰,不如在出現錯誤條件時就崩潰,這時候就需要assert斷言的幫助。

二、基本的斷言方法提供了測試結果是true還是false。所有的斷言方法都有乙個msg引數,如果指定msg引數的值,則將該資訊作為失敗的錯誤資訊返回。

快速參考

序號 斷言方法 斷言描述

1 assertequal(arg1, arg2, msg=none) 驗證arg1=arg2,不等則error

2 assertnotequal(arg1, arg2, msg=none) 驗證arg1 != arg2, 相等則error

3 asserttrue(expr, msg=none) 驗證expr是true,如果不是為error

4 assertfalse(expr,msg=none) 驗證expr是false,如果不是為error

5 assertis(arg1, arg2, msg=none) 驗證arg1、arg2是同乙個物件,不是則error

6 assertisnot(arg1, arg2, msg=none) 驗證arg1、arg2不是同乙個物件,是則error

7 assertisnone(expr, msg=none) 驗證expr是none,不是則error

8 assertisnotnone(expr, msg=none) 驗證expr不是none,是則error

9 assertin(arg1, arg2, msg=none) 驗證arg1是arg2的子串,不是則error

10 assertnotin(arg1, arg2, msg=none) 驗證arg1不是arg2的子串,是則error

11 assertisinstance(obj, cls, msg=none) 驗證obj是cls的例項,不是則error

12 assertnotisinstance(obj, cls, msg=none) 驗證obj不是cls的例項,是則error

三、unittest常用的斷言方法

1.assertequal(self, first, second, msg=none)

--判斷兩個引數相等:first == second

2.assertnotequal(self, first, second, msg=none)

--判斷兩個引數不相等:first != second

3.assertin(self, member, container, msg=none)

--判斷是字串是否包含:member in container

4.assertnotin(self, member, container, msg=none)

--判斷是字串是否不包含:member not in container

5.asserttrue(self, expr, msg=none)

--判斷是否為真:expr is true

6.assertfalse(self, expr, msg=none)

--判斷是否為假:expr is false

7.assertisnone(self, obj, msg=none)

--判斷是否為none:obj is none

8.assertisnotnone(self, obj, msg=none)

--判斷是否不為none:obj is not none

Python中的斷言

在python中,做出斷言的語句是assert,assert後面跟任何合法的表示式,assert語句做出乙個判斷,如果結果為true,則該語句不做任何事情,如果結果為false,assert語句會丟擲異常assertionerror,這個丟擲異常很有作用,我們可以在assert語句後加上解釋性語句,...

Python 斷言assert的使用

1 assert語句用來宣告某個條件是真的。2 如果你非常確信某個你使用的列表中至少有乙個元素,而你想要檢驗這一點,並且在它非真的時候引發乙個錯誤,那麼assert語句是應用在這種情形下的理想語句。3 當assert語句失敗的時候,會引發一assertionerror。測試程式 mylist ite...

Python 斷言的使用方法

自動化測試中尋找元素並進行操作,如果在元素好找的情況下,相信大家都可以較熟練地編寫用例指令碼了,但光進行操作可能還不夠,有時候也需要對預期結果進行判斷。這裡介紹幾個常用斷言的使用方法,可以一定程度上幫助大家對預期結果進行判斷。這裡介紹以下幾個斷言方法 assertequal assertnotequ...