github.com/tiagovtristao/plz@v13.4.0+incompatible/tools/please_pex/test_main.py (about)

     1  """Customised test runner to output in JUnit-style XML."""
     2  
     3  import os
     4  import sys
     5  
     6  # This will get templated in by the build rules.
     7  TEST_NAMES = '__TEST_NAMES__'.split(',')
     8  
     9  
    10  def initialise_coverage():
    11      """Imports & initialises the coverage module."""
    12      import coverage
    13      from coverage import control as coverage_control
    14      _original_xml_file = coverage_control.XmlReporter.xml_file
    15      # Fix up paths in coverage output which are absolute; we want paths relative to
    16      # the repository root. Also skip empty __init__.py files.
    17      def _xml_file(self, fr, analysis):
    18          if '.pex' in fr.filename:
    19              fr.filename = fr.filename[fr.filename.index('.pex') + 5:]  # +5 to take off .pex/
    20          if not (fr.filename.endswith('__init__.py') and len(analysis.statements) <= 1):
    21              analysis.filename = fr.filename
    22              fr.relname = fr.filename
    23              _original_xml_file(self, fr, analysis)
    24      coverage_control.XmlReporter.xml_file = _xml_file
    25      return coverage
    26  
    27  
    28  def main():
    29      """Runs the tests. Returns an appropriate exit code."""
    30      args = [arg for arg in sys.argv[1:]]
    31      # Add .bootstrap dir to path, after the initial pex entry
    32      sys.path = sys.path[:1] + [os.path.join(sys.path[0], '.bootstrap')] + sys.path[1:]
    33      if os.getenv('COVERAGE'):
    34          # It's important that we run coverage while we load the tests otherwise
    35          # we get no coverage for import statements etc.
    36          cov = initialise_coverage().coverage()
    37          cov.start()
    38          result = run_tests(args)
    39          cov.stop()
    40          omissions = ['*/third_party/*', '*/.bootstrap/*', '*/test_main.py']
    41          # Exclude test code from coverage itself.
    42          omissions.extend('*/%s.py' % module.replace('.', '/') for module in args)
    43          import coverage
    44          try:
    45              cov.xml_report(outfile=os.getenv('COVERAGE_FILE'), omit=omissions, ignore_errors=True)
    46          except coverage.CoverageException as err:
    47              # This isn't fatal; the main time we've seen it is raised for "No data to report" which
    48              # isn't an exception as far as we're concerned.
    49              sys.stderr.write('Failed to calculate coverage: %s' % err)
    50          return result
    51      else:
    52          return run_tests(args)