【发布时间】:2014-10-02 14:37:55
【问题描述】:
在 python 2.6 中,我一直在阅读 unittest documentation。但是我还没有找到这个答案。
pyton -m unittest 执行什么功能?
例如,我将如何修改此代码,以便仅执行 python -m unittest 就能检测到它并运行测试?
import random
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.seq = range(10)
def test_shuffle(self):
# make sure the shuffled sequence does not lose any elements
random.shuffle(self.seq)
self.seq.sort()
self.assertEqual(self.seq, range(10))
def test_choice(self):
element = random.choice(self.seq)
self.assertTrue(element in self.seq)
def test_sample(self):
self.assertRaises(ValueError, random.sample, self.seq, 20)
for element in random.sample(self.seq, 5):
self.assertTrue(element in self.seq)
if __name__ == '__main__':
unittest.main()
编辑:
请注意,这只是一个示例,我实际上是想让它检测并作为一个套件运行多个测试,这是我的起点 - 但python -m unittest 没有检测到它,python -m unittest discovery 也没有使用它。我必须调用python discovery.py 来执行它。
discovery.py:
import os
import unittest
def makeSuite():
"""Function stores all the modules to be tested"""
modules_to_test = []
test_dir = os.listdir('.')
for test in test_dir:
if test.startswith('test') and test.endswith('.py'):
modules_to_test.append(test.rstrip('.py'))
all_tests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
module.testvars = ["variables you want to pass through"]
all_tests.addTest(unittest.findTestCases(module))
return all_tests
if __name__ == '__main__':
unittest.main(defaultTest='makeSuite')
【问题讨论】:
-
python -m unittest your_test_module_name. -
@falsetru 是的,这会起作用,但我不想实际指定每个测试......
python -m unittest -h似乎暗示有一个“默认值”......那么默认值是什么。 .. -
如果你使用 Python 2.7+,你可以使用
python -m unittest discover。但这是在 Python 2.7 中引入的。使用py.test/nose怎么样? -
我必须让
py.test或nose通过安检。如果我不必那样做......我会更快乐:-) 也许我可以写我自己的“发现”我想我已经完成了一半,但调用python -m unittest Suite或Suite.makeSuite失败了一些原因...