Python 是否可以运行所有单元测试?
我有两个模块,有两个不同的类和相应的测试类Python 是否可以运行所有单元测试?,python,unit-testing,python-unittest,Python,Unit Testing,Python Unittest,我有两个模块,有两个不同的类和相应的测试类 foo.py ------ class foo(object): def fooMethod(self): // smthg bar.py ------ class bar(object): def barMethod(self): // smthg fooTest.py ------ class fooTest(unittest.TestCase): def fo
foo.py
------
class foo(object):
def fooMethod(self):
// smthg
bar.py
------
class bar(object):
def barMethod(self):
// smthg
fooTest.py
------
class fooTest(unittest.TestCase):
def fooMethodTest(self):
// smthg
barTest.py
------
class barTest(unittest.TestCase):
def barMethodTest(self):
// smthg
在任何测试和源模块文件中,由于增强一致性和遵循面向对象的思想,I删除了if uuuu name\uuuuu==“uuuu main”:
和Java单元测试一样,我希望创建一个模块来运行所有的单元测试。比如说,
runAllTest.py
-------------
class runAllTest(unittest.TestCase):
?????
if __name__ == "__main__":
?????
我找了搜索引擎,但没有找到任何教程或示例。有可能吗?为什么?或者如何
注意:我正在windows计算机上使用eclipse和pydev发行版。如果块中的块:
import unittest
def create_suite():
test_suite = unittest.TestSuite()
test_suite.addTest(fooTest())
test_suite.addTest(barTest())
return test_suite
if __name__ == '__main__':
suite = create_suite()
runner=unittest.TextTestRunner()
runner.run(suite)
如果您不想手动创建测试用例,请查看,它基本上是动态创建测试用例的,或者使用类似于
unittest
模块的功能和选项的一些功能。我认为您要查找的是。有了它,您可以加载特定的测试或模块,或者加载给定目录下的所有内容。此外,post还提供了一些使用TestSuite
实例的有用示例
编辑:test.py中通常包含的代码:
if not popts.tests:
suite = unittest.TestLoader().discover(os.path.dirname(__file__)+'/tests')
#print(suite._tests)
# Print outline
lg.info(' * Going for Interactive net tests = '+str(not tvars.NOINTERACTIVE))
# Run
unittest.TextTestRunner(verbosity=popts.verbosity).run(suite)
else:
lg.info(' * Running specific tests')
suite = unittest.TestSuite()
# Load standard tests
for t in popts.tests:
test = unittest.TestLoader().loadTestsFromName("tests."+t)
suite.addTest(test)
# Run
unittest.TextTestRunner(verbosity=popts.verbosity).run(suite)
做两件事:
*\u test.py
。可以指定项目用于测试文件名的自定义模式,但我记得无法使其工作,因此我最终改名了测试
您还需要遵循惯例来使用nose。我不在Python中使用IDE,但您的IDE可能已经遵循了它——只要阅读PEP并检查一下即可
使用PEP 328目录/包结构,您可以按以下方式运行单个测试:
nosetests path.to.class_test
请注意,我使用的不是常用的目录分隔符(/
或\
),而是点
要运行所有测试,只需在项目根目录下调用
nosetests
。右键单击Eclipse中的文件夹,然后选择“运行方式->Python单元测试”。这将运行该文件夹中的所有测试(测试文件和方法的名称必须以“test”开头)我认为您可以在测试文件所在的文件夹下运行以下命令:
python -m unittest
如本文中所述,在项目运行的根级别上运行基于内置python unittest模块的单元测试时,“在没有参数的情况下执行时,将启动测试发现”
python -m unittest discover <module_name>
我会将测试文件重命名为“test\u foo.py”格式,并在测试目录中运行
nosetests
nose
将自动发现所有的测试文件和测试类。目前为止,这是最好、最简洁的方法。好提示,@mcguip
python -m unittest discover .