我所做的是一个包装脚本,它运行单独的测试文件:
主要的包装器 run_tests.py
:
#!/usr/bin/env python3
# Usage: ./run_tests.py -h http://example.com/ tests/**/*.py
import sys, unittest, argparse, inspect, logging
if __name__ == '__main__':
# Parse arguments.
parser = argparse.ArgumentParser(add_help=False)
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('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") and len(name) > len("FooTest"):
alltests.addTest(make_suite(obj))
# Run tests.
result = unittest.TextTestRunner(verbosity=2).run(alltests)
sys.exit(not result.wasSuccessful())
然后是测试的另一个包装器:
class FooTest(unittest.TestCase):
def __init__(self, *args, cargs=None, **kwargs):
super().__init__(*args, **kwargs)
self.vdisplay = Xvfb(width=1280, height=720)
self.vdisplay.start()
self.args=cargs
self.log=logging
def setUp(self):
self.site = webdriver.Firefox()
def kill(self):
self.vdisplay.stop()
然后,每个测试都会被保存在单独的文件中,看起来像这样:
import sys, os, unittest
from FooTest import FooTest
class FooTest1(FooTest):
def test_homepage(self):
self.site.get(self.base_url + "/")
log.debug("Home page loaded.")
然后你可以轻松地在命令行中运行测试,例如:
$ ./run_tests.py -h http://example.com/ test1.py test2.py
你可以使用通配符来指定某些目录中的所有文件,或者使用新的globbing选项(**
)递归运行所有测试(通过shopt -s globstar
启用)。