coverage_utils.py 2.7 KB

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