2013-10-22 81 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. 
相關問題