helper.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import errno
  2. import io
  3. import json
  4. import os.path
  5. import re
  6. import types
  7. import youtube_dl.extractor
  8. from youtube_dl import YoutubeDL, YoutubeDLHandler
  9. from youtube_dl.utils import (
  10. compat_cookiejar,
  11. compat_urllib_request,
  12. )
  13. youtube_dl._setup_opener(timeout=10)
  14. PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "parameters.json")
  15. with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
  16. parameters = json.load(pf)
  17. def try_rm(filename):
  18. """ Remove a file if it exists """
  19. try:
  20. os.remove(filename)
  21. except OSError as ose:
  22. if ose.errno != errno.ENOENT:
  23. raise
  24. class FakeYDL(YoutubeDL):
  25. def __init__(self):
  26. # Different instances of the downloader can't share the same dictionary
  27. # some test set the "sublang" parameter, which would break the md5 checks.
  28. params = dict(parameters)
  29. super(FakeYDL, self).__init__(params)
  30. self.result = []
  31. def to_screen(self, s, skip_eol=None):
  32. print(s)
  33. def trouble(self, s, tb=None):
  34. raise Exception(s)
  35. def download(self, x):
  36. self.result.append(x)
  37. def expect_warning(self, regex):
  38. # Silence an expected warning matching a regex
  39. old_report_warning = self.report_warning
  40. def report_warning(self, message):
  41. if re.match(regex, message): return
  42. old_report_warning(message)
  43. self.report_warning = types.MethodType(report_warning, self)
  44. def get_testcases():
  45. for ie in youtube_dl.extractor.gen_extractors():
  46. t = getattr(ie, '_TEST', None)
  47. if t:
  48. t['name'] = type(ie).__name__[:-len('IE')]
  49. yield t
  50. for t in getattr(ie, '_TESTS', []):
  51. t['name'] = type(ie).__name__[:-len('IE')]
  52. yield t