run_test.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python
  2. import argparse
  3. import os
  4. import sys
  5. import unittest
  6. from fnmatch import fnmatch
  7. def gather_test_cases(test_dir, pattern, list_tests):
  8. case_list = []
  9. for dirpath, dirnames, filenames in os.walk(test_dir):
  10. for file in filenames:
  11. if fnmatch(file, pattern):
  12. case_list.append(file)
  13. test_suite = unittest.TestSuite()
  14. for case in case_list:
  15. test_case = unittest.defaultTestLoader.discover(start_dir=test_dir, pattern=case)
  16. test_suite.addTest(test_case)
  17. if hasattr(test_case, '__iter__'):
  18. for subcase in test_case:
  19. if list_tests:
  20. print(subcase)
  21. else:
  22. if list_tests:
  23. print(test_case)
  24. return test_suite
  25. def main(args):
  26. runner = unittest.TextTestRunner()
  27. test_suite = gather_test_cases(os.path.abspath(args.test_dir), args.pattern, args.list_tests)
  28. if not args.list_tests:
  29. result = runner.run(test_suite)
  30. if len(result.failures) > 0:
  31. sys.exit(len(result.failures))
  32. if len(result.errors) > 0:
  33. sys.exit(len(result.errors))
  34. if __name__ == '__main__':
  35. parser = argparse.ArgumentParser('test runner')
  36. parser.add_argument('--list_tests', action='store_true', help='list all tests')
  37. parser.add_argument('--pattern', default='test_*.py', help='test file pattern')
  38. parser.add_argument('--test_dir', default='tests', help='directory to be tested')
  39. parser.add_argument('--disable_profile', action='store_true', help='disable profiling')
  40. args = parser.parse_args()
  41. print(f'working dir: {os.getcwd()}')
  42. main(args)