run_tests.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. # XXX: hatch uses `tests` if no arguments are passed
  22. run_core = 'core' in tests or 'tests' in tests or (not pattern and not tests)
  23. run_download = 'download' in 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. test if '/' in test
  37. else f'test/test_download.py::TestDownload::test_{fix_test_name(test)}'
  38. for test in tests)
  39. print(f'Running {arguments}', flush=True)
  40. try:
  41. return subprocess.call(arguments)
  42. except FileNotFoundError:
  43. pass
  44. arguments = [sys.executable, '-Werror', '-m', 'unittest']
  45. if pattern:
  46. arguments.extend(['-k', pattern])
  47. if run_core:
  48. print('"pytest" needs to be installed to run core tests', file=sys.stderr, flush=True)
  49. return 1
  50. elif run_download:
  51. arguments.append('test.test_download')
  52. else:
  53. arguments.extend(
  54. f'test.test_download.TestDownload.test_{test}' for test in tests)
  55. print(f'Running {arguments}', flush=True)
  56. return subprocess.call(arguments)
  57. if __name__ == '__main__':
  58. try:
  59. args = parse_args()
  60. os.chdir(Path(__file__).parent.parent)
  61. sys.exit(run_tests(*args.test, pattern=args.k, ci=bool(os.getenv('CI'))))
  62. except KeyboardInterrupt:
  63. pass