我正在開發一個更大的項目,其中每個方法都有一個具有docstrings測試的類。每個文檔字符串都包含一些示例/測試。文檔字符串經常在另一個模塊中使用一個函數,我想將其導入一次,並在每個文檔字符串函數測試中使用它。用於全班級文檔字符串測試的導入功能
例如,如果這是tests.py
class A(object):
def test1(self):
"""
>>> myfunc()
1
"""
pass
def test2(self):
"""
>>> myfunc()
1
"""
pass
這是funcs.py
from tests import A
# Do stuff with A
def myfunc():
return 1
我想避免上述代碼修改此:
class A(object):
def test1(self):
"""
>>> from funcs import myfunc
>>> myfunc()
1
"""
pass
def test2(self):
"""
>>> from funcs import myfunc
>>> myfunc()
1
"""
pass
,而是做像類級別的文檔字符串模塊導入。我也不能直接在模塊中導入函數,因爲在我的情況下會創建一個循環依賴。
文檔測試使用python -m doctest tests.py
具有這種誤差輸出調用:
File "tests.py", line 4, in tests.A.test
Failed example:
myfunc()
Exception raised:
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run
compileflags, 1) in test.globs
File "<doctest tests.A.test[0]>", line 1, in <module>
myfunc()
NameError: name 'myfunc' is not defined
********************************************
1 items had failures:
1 of 1 in tests.A.test
***Test Failed*** 1 failures.
它成功使用具有進口測試代碼。
對於任何人想知道爲什麼我可能想這樣做,我的真實世界代碼是https://github.com/EntilZha/ScalaFunctional/blob/master/functional/pipeline.py。我想導入的函數是seq
,因爲它是Sequence
類的入口點別名。我寧願在文檔字符串中使用seq
,因爲它們非常重要,它們用作文檔示例,seq
有其他行爲,我想開始將它們作爲測試套件運行,以確保它們保持最新狀態。
你可以調用'myfunc()',但是你定義了'myfunc(x)'。你是微妙的,還是一個錯字? –
這確實是一個錯字 – Keiga
你怎麼調用doctest? –