coverage_utils.py 2.5 KB

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