繁体   English   中英

如何为使用 function 类型的方法编写 python 多语言单元测试?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM