そこで、次のファイル(testlib.py)を作成して、すべてのdoctestを(ネストされたプロジェクトディレクトリ全体で)__tests__
tests.pyのディクショナリに自動的にロードします。
# ./testlib.py
import os, imp, re, inspect
from django.contrib.admin import site
def get_module_list(start):
all_files = os.walk(start)
file_list = [(i[0], (i[1], i[2])) for i in all_files]
file_dict = dict(file_list)
curr = start
modules = []
pathlist = []
pathstack = [[start]]
while pathstack is not None:
current_level = pathstack[len(pathstack)-1]
if len(current_level) == 0:
pathstack.pop()
if len(pathlist) == 0:
break
pathlist.pop()
continue
pathlist.append(current_level.pop())
curr = os.sep.join(pathlist)
local_files = []
for f in file_dict[curr][1]:
if f.endswith(".py") and os.path.basename(f) not in ('tests.py', 'models.py'):
local_file = re.sub('\.py$', '', f)
local_files.append(local_file)
for f in local_files:
# This is necessary because some of the imports are repopulating the registry, causing errors to be raised
site._registry.clear()
module = imp.load_module(f, *imp.find_module(f, [curr]))
modules.append(module)
pathstack.append([sub_dir for sub_dir in file_dict[curr][0] if sub_dir[0] != '.'])
return modules
def get_doc_objs(module):
ret_val = []
for obj_name in dir(module):
obj = getattr(module, obj_name)
if callable(obj):
ret_val.append(obj_name)
if inspect.isclass(obj):
ret_val.append(obj_name)
return ret_val
def has_doctest(docstring):
return ">>>" in docstring
def get_test_dict(package, locals):
test_dict = {}
for module in get_module_list(os.path.dirname(package.__file__)):
for method in get_doc_objs(module):
docstring = str(getattr(module, method).__doc__)
if has_doctest(docstring):
print "Found doctests(s) " + module.__name__ + '.' + method
# import the method itself, so doctest can find it
_temp = __import__(module.__name__, globals(), locals, [method])
locals[method] = getattr(_temp, method)
# Django looks in __test__ for doctests to run. Some extra information is
# added to the dictionary key, because otherwise the info would be hidden.
test_dict[method + "@" + module.__file__] = getattr(module, method)
return test_dict
クレジットが必要な場所にクレジットを与えるために、これの多くはここから来ました
私のtests.pyファイルには、次のコードがあります。
# ./project/tests.py
import testlib, project
__test__ = testlib.get_test_dict(project, locals())
これらはすべて、すべてのファイルとサブディレクトリからdoctestをロードするのに非常にうまく機能します。問題は、pdb.set_trace()をどこかにインポートして呼び出すと、これがすべて表示されることです。
(Pdb) l
(Pdb) args
(Pdb) n
(Pdb) n
(Pdb) l
(Pdb) cont
doctestは、出力自体をキャプチャして仲介しているようであり、テストの評価に出力を使用しています。したがって、テストの実行が完了すると、doctestの失敗レポート内のpdbシェルにいたときに出力されるべきすべてのものが表示されます。これは、doctest行内でpdb.set_trace()を呼び出すか、テスト対象の関数またはメソッド内で呼び出すかに関係なく発生します。
明らかに、これは大きな抵抗です。Doctestは素晴らしいですが、インタラクティブなpdbがないと、それらを修正するために検出している障害をデバッグすることはできません。
私の思考プロセスは、pdbの出力ストリームを、doctestによる出力のキャプチャを回避するものにリダイレクトすることですが、それを行うために必要な低レベルのioのものを理解するための助けが必要です。また、それが可能かどうかさえわかりませんし、doctestの内部に慣れていないため、どこから始めればよいのかわかりません。誰かがこれを成し遂げることができる提案、またはより良いいくつかのコードを持っていますか?