coverage_utils.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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(
  10. os.path.join(os.path.dirname(os.path.dirname(__file__))))
  11. def native_error(msg, version):
  12. print(
  13. textwrap.dedent("""\
  14. ERROR: Native python-coverage (version: %s) is required to be
  15. installed on your PYTHONPATH to run this test. Recommendation:
  16. sudo apt-get install pip
  17. sudo pip install --upgrade coverage
  18. %s""") % (version, msg))
  19. sys.exit(1)
  20. def covered_main(includes,
  21. require_native=None,
  22. required_percentage=100.0,
  23. disable_coverage=True):
  24. """Equivalent of unittest.main(), except that it gathers coverage data, and
  25. asserts if the test is not at 100% coverage.
  26. Args:
  27. includes (list(str) or str) - List of paths to include in coverage
  28. report. May also be a single path instead of a list.
  29. require_native (str) - If non-None, will require that
  30. at least |require_native| version of coverage is installed on the
  31. system with CTracer.
  32. disable_coverage (bool) - If True, just run unittest.main() without any
  33. coverage tracking. Bug: crbug.com/662277
  34. """
  35. if disable_coverage:
  36. unittest.main()
  37. return
  38. try:
  39. import coverage
  40. if require_native is not None:
  41. got_ver = coverage.__version__
  42. if not getattr(coverage.collector, 'CTracer', None):
  43. native_error(
  44. ("Native python-coverage module required.\n"
  45. "Pure-python implementation (version: %s) found: %s") %
  46. (got_ver, coverage), require_native)
  47. if got_ver < distutils.version.LooseVersion(require_native):
  48. native_error(
  49. "Wrong version (%s) found: %s" % (got_ver, coverage),
  50. require_native)
  51. except ImportError:
  52. if require_native is None:
  53. sys.path.insert(0, os.path.join(ROOT_PATH, 'third_party'))
  54. import coverage
  55. else:
  56. print("ERROR: python-coverage (%s) is required to be installed on "
  57. "your PYTHONPATH to run this test." % require_native)
  58. sys.exit(1)
  59. COVERAGE = coverage.coverage(include=includes)
  60. COVERAGE.start()
  61. retcode = 0
  62. try:
  63. unittest.main()
  64. except SystemExit as e:
  65. retcode = e.code or retcode
  66. COVERAGE.stop()
  67. if COVERAGE.report() < required_percentage:
  68. print('FATAL: not at required %f%% coverage.' % required_percentage)
  69. retcode = 2
  70. return retcode