2013-10-22 82 views
1

考虑这个小交互式Python会话:如何以编程方式向交互式Python注入行?

>>> a = 'a' 
>>> b = 'b' 
>>> ab = a + b 
>>> ab 
'ab' 

有没有办法做到这一点编程?我想在每行中注入行,并在最后单元测试结果。我无法创建Python脚本并像往常一样执行它,因为有一些代码在交互式Python中反应不同(例如,inspect.getcomments())。我想测试交互式Python中的行为。我更喜欢Python3解决方案,但我怀疑该解决方案与Python2中的解决方案不同。要做到这一点

+0

我不知道我跟......你可以给更多的细节?你为什么单元测试用户输入的代码? – SethMMorton

+0

[Doctest](http://docs.python.org/2/library/doctest.html)? – kojiro

+0

@SethMMorton:例如:http://bugs.python.org/issue16355。我想单元测试交互式python中的inspect.getcomments()的行为。 – vajrasky

回答

3

一种方法是用Python的doctest模块。它本质上是将代码解析为Python REPL,然后声明输出与该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. 
相关问题