gpt4 book ai didi

python - 如何为使用类型函数的方法编写python polyglot unittest?

转载 作者:行者123 更新时间:2023-12-04 09:36:36 25 4
gpt4 key购买 nike

我正在尝试编写使用类型函数的 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 polyglot unittest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62556372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com