run_tests.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #!/usr/bin/env python3
  2. import argparse
  3. import functools
  4. import os
  5. import re
  6. import shlex
  7. import subprocess
  8. import sys
  9. from pathlib import Path
  10. fix_test_name = functools.partial(re.compile(r'IE(_all|_\d+)?$').sub, r'\1')
  11. def parse_args():
  12. parser = argparse.ArgumentParser(description='Run selected yt-dlp tests')
  13. parser.add_argument(
  14. 'test', help='a extractor tests, or one of "core" or "download"', nargs='*')
  15. parser.add_argument(
  16. '-k', help='run a test matching EXPRESSION. Same as "pytest -k"', metavar='EXPRESSION')
  17. parser.add_argument(
  18. '--pytest-args', help='arguments to passthrough to pytest')
  19. return parser.parse_args()
  20. def run_tests(*tests, pattern=None, ci=False):
  21. run_core = 'core' in tests or (not pattern and not tests)
  22. run_download = 'download' in tests
  23. tests = list(map(fix_test_name, tests))
  24. pytest_args = args.pytest_args or os.getenv('HATCH_TEST_ARGS', '')
  25. arguments = ['pytest', '-Werror', '--tb=short', *shlex.split(pytest_args)]
  26. if ci:
  27. arguments.append('--color=yes')
  28. if pattern:
  29. arguments.extend(['-k', pattern])
  30. if run_core:
  31. arguments.extend(['-m', 'not download'])
  32. elif run_download:
  33. arguments.extend(['-m', 'download'])
  34. else:
  35. arguments.extend(
  36. f'test/test_download.py::TestDownload::test_{test}' for test in tests)
  37. print(f'Running {arguments}', flush=True)
  38. try:
  39. return subprocess.call(arguments)
  40. except FileNotFoundError:
  41. pass
  42. arguments = [sys.executable, '-Werror', '-m', 'unittest']
  43. if pattern:
  44. arguments.extend(['-k', pattern])
  45. if run_core:
  46. print('"pytest" needs to be installed to run core tests', file=sys.stderr, flush=True)
  47. return 1
  48. elif run_download:
  49. arguments.append('test.test_download')
  50. else:
  51. arguments.extend(
  52. f'test.test_download.TestDownload.test_{test}' for test in tests)
  53. print(f'Running {arguments}', flush=True)
  54. return subprocess.call(arguments)
  55. if __name__ == '__main__':
  56. try:
  57. args = parse_args()
  58. os.chdir(Path(__file__).parent.parent)
  59. sys.exit(run_tests(*args.test, pattern=args.k, ci=bool(os.getenv('CI'))))
  60. except KeyboardInterrupt:
  61. pass