在python 2.6中,我一直在阅读unittest文档。但是我仍然没有找到这个答案。
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 something
将模块something
作为脚本执行。即来自python --help
:
-m mod:将库模块作为脚本运行(终止选项列表)
unittest模块可以作为脚本运行——传递给它的参数决定了它测试哪些文件。命令行界面也记录在语言参考中。