run_tests.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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='an extractor test, test path, 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. pytest_args = args.pytest_args or os.getenv('HATCH_TEST_ARGS', '')
  24. arguments = ['pytest', '-Werror', '--tb=short', *shlex.split(pytest_args)]
  25. if ci:
  26. arguments.append('--color=yes')
  27. if pattern:
  28. arguments.extend(['-k', pattern])
  29. if run_core:
  30. arguments.extend(['-m', 'not download'])
  31. elif run_download:
  32. arguments.extend(['-m', 'download'])
  33. else:
  34. arguments.extend(
  35. test if '/' in test
  36. else f'test/test_download.py::TestDownload::test_{fix_test_name(test)}'
  37. for test in tests)
  38. print(f'Running {arguments}', flush=True)
  39. try:
  40. return subprocess.call(arguments)
  41. except FileNotFoundError:
  42. pass
  43. arguments = [sys.executable, '-Werror', '-m', 'unittest']
  44. if pattern:
  45. arguments.extend(['-k', pattern])
  46. if run_core:
  47. print('"pytest" needs to be installed to run core tests', file=sys.stderr, flush=True)
  48. return 1
  49. elif run_download:
  50. arguments.append('test.test_download')
  51. else:
  52. arguments.extend(
  53. f'test.test_download.TestDownload.test_{test}' for test in tests)
  54. print(f'Running {arguments}', flush=True)
  55. return subprocess.call(arguments)
  56. if __name__ == '__main__':
  57. try:
  58. args = parse_args()
  59. os.chdir(Path(__file__).parent.parent)
  60. sys.exit(run_tests(*args.test, pattern=args.k, ci=bool(os.getenv('CI'))))
  61. except KeyboardInterrupt:
  62. pass