#!/usr/bin/env python2.7

# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Runs the unit test suite for systrace."""

# TODO(https://crbug.com/1262296): Update this after Python2 trybots retire.
# pylint: disable=deprecated-module
import optparse
import os
import sys
import unittest

_SYSTRACE_DIR = os.path.abspath(
    os.path.join(os.path.dirname(__file__), os.path.pardir))
sys.path.insert(0, _SYSTRACE_DIR)
from systrace import decorators


def main():
  # TODO(https://crbug.com/1262296): Update this after Python2 trybots retire.
  # pylint: disable=deprecated-module
  parser = optparse.OptionParser()
  parser.add_option("-d", "--device", dest="device",
                    help="device the test runs on", metavar="DEVICE")
  options, _args = parser.parse_args()  # pylint: disable=unused-variable
  loader = unittest.defaultTestLoader
  unfiltered_suite = loader.discover(
      _SYSTRACE_DIR,
      pattern = '*_unittest.py',
      top_level_dir=_SYSTRACE_DIR)
  suite = unittest.TestSuite()
  all_tests_loaded = True
  if hasattr(loader, 'errors') and loader.errors:
    sys.stderr.write(
        '%d errors on discovering tests:\n'
        % len(loader.errors))
    for error in loader.errors:
      sys.stderr.write(error)
    all_tests_loaded = False

  for test_group in unfiltered_suite._tests:
    for inner_group in test_group:
      if hasattr(unittest.loader, '_FailedTest') and \
          isinstance(inner_group, unittest.loader._FailedTest):
        continue
      for test in inner_group:
        method = getattr(
          test, test._testMethodName)  # pylint: disable=protected-access
        if not decorators.ShouldSkip(method, options.device):
          suite.addTest(test)
  result = unittest.TextTestRunner(verbosity=2).run(suite)
  if result.wasSuccessful() and all_tests_loaded:
    sys.exit(0)
  else:
    sys.exit(1)

if __name__ == '__main__':
  main()
