考虑一下这个小的交互式Python会话:
>>> a = 'a'
>>> b = 'b'
>>> ab = a + b
>>> ab
'ab'有什么办法可以用编程的方式吗?我想注入一行一行和单元测试的结果在最后。我不能像往常一样创建Python脚本并执行它,因为在交互式Python中有一些反应不同的代码(例如,inspect.getcomments())。我想在交互式Python中测试这种行为。我更喜欢Python3解决方案,但我怀疑该解决方案不会与Python2中的解决方案不同。
发布于 2013-10-22 03:21:25
要做到这一点,一种方法是使用Python的博士考试模块。它本质上像在Python中一样解析代码,然后断言输出与在该REPL中编写的内容相匹配。
$ cat foo
>>> a = 'a'
>>> b = 'b'
>>> ab = a + b
>>> ab
'ab'
$ python -m doctest foo
$ cat > bar
>>> a = 'a'
>>> b = 'b'
>>> ab = b + a # oops
>>> ab
'ab'
$ python -m doctest bar
**********************************************************************
File "bar", line 4, in bar
Failed example:
ab
Expected:
'ab'
Got:
'ba'
**********************************************************************
1 items had failures:
1 of 4 in bar
***Test Failed*** 1 failures.https://stackoverflow.com/questions/19508028
复制相似问题