coverage_utils.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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(
  58. "ERROR: python-coverage (%s) is required to be installed on "
  59. "your PYTHONPATH to run this test." % require_native)
  60. sys.exit(1)
  61. COVERAGE = coverage.coverage(include=includes)
  62. COVERAGE.start()
  63. retcode = 0
  64. try:
  65. unittest.main()
  66. except SystemExit as e:
  67. retcode = e.code or retcode
  68. COVERAGE.stop()
  69. if COVERAGE.report() < required_percentage:
  70. print('FATAL: not at required %f%% coverage.' % required_percentage)
  71. retcode = 2
  72. return retcode