我有一个包含Python单元测试的目录。每个单元测试模块的格式是test_*.py。我正在尝试创建一个名为all_test.py的文件,您猜对了,它将以上述测试形式运行所有文件并返回结果。到目前为止,我尝试了两种方法;两者都失败了。我将展示这两种方法,我希望有人知道如何正确地做到这一点。

对于我的第一次勇敢的尝试,我想“如果我只是导入文件中的所有测试模块,然后调用这个unittest.main() doodad,它就会工作,对吗?”事实证明我错了。

import glob
import unittest

testSuite = unittest.TestSuite()
test_file_strings = glob.glob('test_*.py')
module_strings = [str[0:len(str)-3] for str in test_file_strings]

if __name__ == "__main__":
     unittest.main()

这并没有起作用,我得到的结果是:

$ python all_test.py 

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

对于我的第二次尝试,我想,好吧,也许我将尝试以一种更“手动”的方式来完成整个测试。所以我尝试如下:

import glob
import unittest

testSuite = unittest.TestSuite()
test_file_strings = glob.glob('test_*.py')
module_strings = [str[0:len(str)-3] for str in test_file_strings]
[__import__(str) for str in module_strings]
suites = [unittest.TestLoader().loadTestsFromName(str) for str in module_strings]
[testSuite.addTest(suite) for suite in suites]
print testSuite 

result = unittest.TestResult()
testSuite.run(result)
print result

#Ok, at this point I have a result
#How do I display it as the normal unit test command line output?
if __name__ == "__main__":
    unittest.main()

这也没有工作,但它似乎如此接近!

$ python all_test.py 
<unittest.TestSuite tests=[<unittest.TestSuite tests=[<unittest.TestSuite tests=[<test_main.TestMain testMethod=test_respondes_to_get>]>]>]>
<unittest.TestResult run=1 errors=0 failures=0>

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

我似乎有一个某种类型的套件,我可以执行结果。我有点担心这个事实,它说我只运行=1,似乎应该运行=2,但它是进步。但是我如何传递和显示结果的主要?或者说,我怎样才能让它工作,从而运行这个文件,并运行这个目录下的所有单元测试?


当前回答

因为测试发现似乎是一个完整的主题,所以有一些专门的框架来测试发现:

鼻子 Py。测试

更多阅读请点击:https://wiki.python.org/moin/PythonTestingToolsTaxonomy

其他回答

我使用PyDev/LiClipse,还没有真正弄清楚如何从GUI一次运行所有测试。(编辑:右键单击根测试文件夹并选择运行为-> Python unit-test

这是我目前的解决方案:

import unittest

def load_tests(loader, tests, pattern):
    return loader.discover('.')

if __name__ == '__main__':
    unittest.main()

我把这些代码放在一个名为all in我的测试目录的模块中。如果我从LiClipse运行这个模块作为单元测试,那么所有测试都将运行。如果我要求只重复特定或失败的测试,则只运行这些测试。它也不会干扰我的命令行测试运行器(nosetests)——它被忽略了。

您可能需要根据项目设置更改要发现的参数。

使用Python 2.7及更高版本时,你不需要编写新代码或使用第三方工具来完成这项工作;通过命令行执行递归测试是内置的。在你的测试目录中放入__init__.py,然后:

python -m unittest discover <test_directory>
# or
python -m unittest discover -s <directory> -p '*_test.py'

你可以在python 2.7中阅读更多内容 或者是python。X单元测试文档。


2021年更新:

许多现代python项目使用更高级的工具,如pytest。例如,下拉matplotlib或scikit-learn,您将看到它们都在使用它。

了解这些新工具非常重要,因为当您有超过7000个测试时,您需要:

更高级的方法来总结通过、跳过、警告和错误的内容 很容易看出他们是如何失败的 运行时的完成百分比 总运行时间 生成测试报告的方法 等等

通过研究上面的代码(特别是使用TextTestRunner和defaultTestLoader),我能够非常接近。最终,我通过将所有测试套件传递给单个套件构造函数来修复代码,而不是“手动”添加它们,这解决了我的其他问题。这就是我的解。

import glob
import unittest

test_files = glob.glob('test_*.py')
module_strings = [test_file[0:len(test_file)-3] for test_file in test_files]
suites = [unittest.defaultTestLoader.loadTestsFromName(test_file) for test_file in module_strings]
test_suite = unittest.TestSuite(suites)
test_runner = unittest.TextTestRunner().run(test_suite)

是的,用鼻子可能比用这个简单,但这不是重点。

下面是我通过创建一个包装器来从命令行运行测试的方法:

#!/usr/bin/env python3
import os, sys, unittest, argparse, inspect, logging

if __name__ == '__main__':
    # Parse arguments.
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-?", "--help",     action="help",                        help="show this help message and exit" )
    parser.add_argument("-v", "--verbose",  action="store_true", dest="verbose",  help="increase output verbosity" )
    parser.add_argument("-d", "--debug",    action="store_true", dest="debug",    help="show debug messages" )
    parser.add_argument("-h", "--host",     action="store",      dest="host",     help="Destination host" )
    parser.add_argument("-b", "--browser",  action="store",      dest="browser",  help="Browser driver.", choices=["Firefox", "Chrome", "IE", "Opera", "PhantomJS"] )
    parser.add_argument("-r", "--reports-dir", action="store",   dest="dir",      help="Directory to save screenshots.", default="reports")
    parser.add_argument('files', nargs='*')
    args = parser.parse_args()

    # Load files from the arguments.
    for filename in args.files:
        exec(open(filename).read())

    # See: http://codereview.stackexchange.com/q/88655/15346
    def make_suite(tc_class):
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(tc_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(tc_class(name, cargs=args))
        return suite

    # Add all tests.
    alltests = unittest.TestSuite()
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj) and name.startswith("FooTest"):
            alltests.addTest(make_suite(obj))

    # Set-up logger
    verbose = bool(os.environ.get('VERBOSE', args.verbose))
    debug   = bool(os.environ.get('DEBUG', args.debug))
    if verbose or debug:
        logging.basicConfig( stream=sys.stdout )
        root = logging.getLogger()
        root.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.INFO if verbose else logging.DEBUG)
        ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
        root.addHandler(ch)
    else:
        logging.basicConfig(stream=sys.stderr)

    # Run tests.
    result = unittest.TextTestRunner(verbosity=2).run(alltests)
    sys.exit(not result.wasSuccessful())

为了简单起见,请原谅我的非pep8编码标准。

然后你可以为所有测试的公共组件创建BaseTest类,这样你的每个测试看起来就像这样:

from BaseTest import BaseTest
class FooTestPagesBasic(BaseTest):
    def test_foo(self):
        driver = self.driver
        driver.get(self.base_url + "/")

要运行,你只需将测试作为命令行参数的一部分,例如:

./run_tests.py -h http://example.com/ tests/**/*.py

遇到了同样的问题。

解决方案是在每个文件夹中添加一个空的__init__.py,并使用python -m unittest discover -s

项目结构

tests/
  __init__.py
  domain/
    value_object/
      __init__.py
      test_name.py
    __init__.py
  presentation/
    __init__.py
    test_app.py

然后运行命令

python -m unittest discover -s tests/domain

得到预期的结果

.
----------------------------------------------------------------------
Ran 1 test in 0.007s