我正在尝试编写使用类型函数的 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'>
这里的目的是验证我的函数引发的异常消息。例如,
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 中失败。
最佳答案
像这样的变化是 assertRaisesRegexp
的动机来自标准 unittest
模块的函数(您可能应该使用它)。 (注意拼写:Python 3 支持 2 中唯一的拼写(使用 p
),所以这就是您想要的。)
关于python - 如何使用类型函数为方法编写 python 多语言单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556372/