擅长:python、mysql、java
<p>虽然我不推荐这种方法(也不推荐您尝试做什么),但这里有一个简单的方法,它可以大致完成您想要的。在</p>
<p>在文件中“跑步者.py“(例如,与上述类似):
导入全局
导入单元测试</p>
<pre><code>testfiles = glob.glob('subdir/*.py')
for name in testfiles:
execfile(name)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>在subdir/file1.py文件中:</p>
^{pr2}$
<p>在subdir/file2.py文件中:</p>
<pre><code>class ClassB(unittest.TestCase):
def test01(self):
print self
</code></pre>
<p>运行时输出“跑步者.py“:</p>
<pre><code>C:\svn\stackoverflow>runner
test01 (__main__.ClassA)
.test01 (__main__.ClassB)
.
Ran 2 tests in 0.004s
OK
</code></pre>
<p>请注意,这基本上等同于在主文件中以文本方式包含所有测试文件,类似于C中#include“file.h”的工作方式。正如您所见,子文件的环境(命名空间)是调用execfile()的文件的环境(命名空间),这就是它们甚至不需要执行自己的“import unittest”调用的原因。如果它们不需要独立运行,那么这应该是可以的,或者如果它们确实需要独立运行,那么可以在每个文件中包含通常的unittest样板。你不能在包含的文件中有重复的类名,你可能会注意到其他的困难。在</p>
<p>不过,我很确定,您最好使用<a href="http://code.google.com/p/python-nose/" rel="nofollow noreferrer">nose</a>或{a2}之类的东西,它们比unittest做这种“测试集合”要好得多。在</p>