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