python doctest异常测试处理

Tra*_*acy 6 python testing doctest qa

我在一个名为的文件中有以下内容test2.txt.

>>> def faulty():  
... yield 5  
... return 7  
Traceback(most recent call last):  
SyntaxError: 'return' with argument inside generator(<doctest test.txt[0]>,line 3)  
Run Code Online (Sandbox Code Playgroud)

我调用了测试运行python -m test2.txt.以下结果完全超出我的预期.

终端输出的截图

我的想法是测试应该是成功的,因为我已经在我的test2.txt文件中写了预期的输出,它"几乎"与我从控制台输出得到的相匹配.我试过添加'File "G:\"'.... line?但测试仍然失败.

Dev*_*rre 9

doctest对预期异常的格式非常谨慎.你错过了一个空间:

Traceback(most recent call last): 应该 Traceback (most recent call last):

此外,这仍然会失败,因为您的回溯消息过于具体(并且还有不正确的空格)!使用ELLIPSISIGNORE_EXCEPTION_DETAIL标记doctest使doctest对匹配异常不那么挑剔,如下所示:

>>> def faulty(): # doctest: +IGNORE_EXCEPTION_DETAIL  
...     yield 5  
...     return 7  
Traceback (most recent call last):  
SyntaxError: 'return' with argument inside generator (...)
Run Code Online (Sandbox Code Playgroud)

(ELLIPSIS也会在这里工作)