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

标签 python python-3.x python-2.7 unit-testing

我正在尝试编写使用类型函数的 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/

相关文章:

python - While 循环未检测到 msvcrt.getch() 按键

python - 使用标题/列名称使 CSV 文件更容易在 Python 中修改/导航?

Python每n个字符拆分字符串

Python - 写入 CSV 文件和 for 循环

python - BlockingIOError 异常被忽略;我应该担心吗?

python - 在 Django App 的控制台输出中显示警告

python - 放大 python shell wing_ide

python - Django:为foreignKey对象分配当前用户的值

python - 如何使用 NumPy 沿每一行和每一列应用我自己的函数

python - ValueError : Length mismatch: Expected axis has 23 elements, 新值有 2 个元素。 Pandas 长度不匹配