2014-10-02 46 views
2

在Python 2.6中,我一直在阅读unittest documentation。但我仍然没有找到答案。python -m 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') 
+0

'python -m unittest your_test_module_name'。 – falsetru 2014-10-02 14:40:54

+0

@falsetru是的,这将工作,但我不想实际指定每个测试...'''''''python -m unittest -h'似乎暗示有一个“默认”...那么这是什么默认... – Petriborg 2014-10-02 14:43:16

+0

如果你使用Python 2.7+,你可以使用'python -m unittest discover'。但是这是在Python 2.7中引入的。如何使用'py.test' /'nose'? – falsetru 2014-10-02 14:43:59

回答

1

python -m something执行模块something为脚本。即从python --help

-m MOD:运行库模块作为一个脚本(终止选项列表)

unittest模块can be run as a script - 而你传递给它确定它测试哪些文件的参数。命令行界面也记录在the language reference中。

+0

嗯,我看到'-m unittest'记录在2.7中(我被2.6所困)。似乎我卡住写我自己的发现小工具...现在我只需要得到我当前的代码为'-m unittest'工作... – Petriborg 2014-10-02 14:57:02