test_runner.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env python
  2. # Copyright (c) 2014 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. import unittest
  6. import sys
  7. import os
  8. import optparse
  9. __all__ = []
  10. def FilterSuite(suite, predicate):
  11. new_suite = suite.__class__()
  12. for x in suite:
  13. if isinstance(x, unittest.TestSuite):
  14. subsuite = FilterSuite(x, predicate)
  15. if subsuite.countTestCases() == 0:
  16. continue
  17. new_suite.addTest(subsuite)
  18. continue
  19. assert isinstance(x, unittest.TestCase)
  20. if predicate(x):
  21. new_suite.addTest(x)
  22. return new_suite
  23. class _TestLoader(unittest.TestLoader):
  24. def __init__(self, *args):
  25. super(_TestLoader, self).__init__(*args)
  26. self.discover_calls = []
  27. def loadTestsFromModule(self, module, use_load_tests=True):
  28. if module.__file__ != __file__:
  29. return super(_TestLoader, self).loadTestsFromModule(
  30. module, use_load_tests)
  31. suite = unittest.TestSuite()
  32. for discover_args in self.discover_calls:
  33. subsuite = self.discover(*discover_args)
  34. suite.addTest(subsuite)
  35. return suite
  36. class _RunnerImpl(unittest.TextTestRunner):
  37. def __init__(self, filters):
  38. super(_RunnerImpl, self).__init__(verbosity=2)
  39. self.filters = filters
  40. def ShouldTestRun(self, test):
  41. return not self.filters or any(name in test.id() for name in self.filters)
  42. def run(self, suite):
  43. filtered_test = FilterSuite(suite, self.ShouldTestRun)
  44. return super(_RunnerImpl, self).run(filtered_test)
  45. class TestRunner(object):
  46. def __init__(self):
  47. self._loader = _TestLoader()
  48. def AddDirectory(self, dir_path, test_file_pattern="*test.py"):
  49. assert os.path.isdir(dir_path)
  50. self._loader.discover_calls.append((dir_path, test_file_pattern, dir_path))
  51. def Main(self, argv=None):
  52. if argv is None:
  53. argv = sys.argv
  54. parser = optparse.OptionParser()
  55. options, args = parser.parse_args(argv[1:])
  56. runner = _RunnerImpl(filters=args)
  57. return unittest.main(module=__name__, argv=[sys.argv[0]],
  58. testLoader=self._loader,
  59. testRunner=runner)