coverage_utils.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright 2013 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import distutils.version
  5. import os
  6. import sys
  7. import textwrap
  8. import unittest
  9. ROOT_PATH = os.path.abspath(os.path.join(
  10. os.path.dirname(os.path.dirname(__file__))))
  11. def native_error(msg, version):
  12. print textwrap.dedent("""\
  13. ERROR: Native python-coverage (version: %s) is required to be
  14. installed on your PYTHONPATH to run this test. Recommendation:
  15. sudo pip install python-coverage
  16. %s""") % (version, msg)
  17. sys.exit(1)
  18. def covered_main(includes, require_native=None):
  19. """Equivalent of unittest.main(), except that it gathers coverage data, and
  20. asserts if the test is not at 100% coverage.
  21. Args:
  22. includes (list(str) or str) - List of paths to include in coverage report.
  23. May also be a single path instead of a list.
  24. require_native (str) - If non-None, will require that
  25. at least |require_native| version of coverage is installed on the
  26. system with CTracer.
  27. """
  28. try:
  29. import coverage
  30. if require_native is not None:
  31. got_ver = coverage.__version__
  32. if not coverage.collector.CTracer:
  33. native_error((
  34. "Native python-coverage module required.\n"
  35. "Pure-python implementation (version: %s) found: %s"
  36. ) % (got_ver, coverage), require_native)
  37. if got_ver < distutils.version.LooseVersion(require_native):
  38. native_error("Wrong version (%s) found: %s" % (got_ver, coverage),
  39. require_native)
  40. except ImportError:
  41. if require_native is None:
  42. sys.path.insert(0, os.path.join(ROOT_PATH, 'third_party'))
  43. import coverage
  44. else:
  45. print ("ERROR: python-coverage (%s) is required to be installed on your "
  46. "PYTHONPATH to run this test." % require_native)
  47. sys.exit(1)
  48. COVERAGE = coverage.coverage(include=includes)
  49. COVERAGE.start()
  50. retcode = 0
  51. try:
  52. unittest.main()
  53. except SystemExit as e:
  54. retcode = e.code or retcode
  55. COVERAGE.stop()
  56. if COVERAGE.report() != 100.0:
  57. print 'FATAL: not at 100% coverage.'
  58. retcode = 2
  59. return retcode