[英]How to write python polyglot unittest for method using type function?
我正在嘗試編寫使用 function 類型的 python2 和 python3 兼容代碼。 兩者都在 2 v/s 3 中返回不同的字符串,我必須在我的單元測試中斷言。
Python 3.7.4 (default, Oct 18 2019, 15:58:40)
>>> type(2)
<class 'int'>
Python 2.7.16 (default, Jul 24 2019, 16:45:12)
>>> type(2)
<type 'int'>
這里的目的是驗證從我的 function 引發的異常消息。 例如,
def func(arg1):
if not isinstance(arg1, int):
raise TypeError('Expected type %s but got %s' % (type(int), type(arg1)))
print("Function executed")
try:
func('str')
except TypeError as e:
assert e.args[0]== "Expected type <type 'type'> but got <type 'str'>"
print("Correct exception was raised")
這里的斷言在 python2 中通過,但在 python3 中失敗。
像這樣的變化是來自標准unittest
模塊(您可能應該使用)的assertRaisesRegexp
function 的動機。 (注意拼寫: Python 3 支持從 2 開始的唯一拼寫(帶有p
),所以這就是你想要的。)
在 python 中使用type()
幾乎任何東西都不靈活。 相反,您應該使用isinstance(var, type)
。 python 2.7 和 3 的兩個版本幾乎相同:
isinstance(2, int)
這每次都會在兩個版本中返回 True。
確保您不會不小心將類型放入字符串中:
不正確: 'int'
正確: int
或者:
print(type(2) is int)
將 output:
True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.