helper.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import errno
  2. import io
  3. import hashlib
  4. import json
  5. import os.path
  6. import re
  7. import types
  8. import sys
  9. import youtube_dl.extractor
  10. from youtube_dl import YoutubeDL
  11. from youtube_dl.utils import (
  12. compat_str,
  13. preferredencoding,
  14. )
  15. def get_params(override=None):
  16. PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  17. "parameters.json")
  18. with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
  19. parameters = json.load(pf)
  20. if override:
  21. parameters.update(override)
  22. return parameters
  23. def try_rm(filename):
  24. """ Remove a file if it exists """
  25. try:
  26. os.remove(filename)
  27. except OSError as ose:
  28. if ose.errno != errno.ENOENT:
  29. raise
  30. def report_warning(message):
  31. '''
  32. Print the message to stderr, it will be prefixed with 'WARNING:'
  33. If stderr is a tty file the 'WARNING:' will be colored
  34. '''
  35. if sys.stderr.isatty() and os.name != 'nt':
  36. _msg_header = u'\033[0;33mWARNING:\033[0m'
  37. else:
  38. _msg_header = u'WARNING:'
  39. output = u'%s %s\n' % (_msg_header, message)
  40. if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
  41. output = output.encode(preferredencoding())
  42. sys.stderr.write(output)
  43. class FakeYDL(YoutubeDL):
  44. def __init__(self, override=None):
  45. # Different instances of the downloader can't share the same dictionary
  46. # some test set the "sublang" parameter, which would break the md5 checks.
  47. params = get_params(override=override)
  48. super(FakeYDL, self).__init__(params)
  49. self.result = []
  50. def to_screen(self, s, skip_eol=None):
  51. print(s)
  52. def trouble(self, s, tb=None):
  53. raise Exception(s)
  54. def download(self, x):
  55. self.result.append(x)
  56. def expect_warning(self, regex):
  57. # Silence an expected warning matching a regex
  58. old_report_warning = self.report_warning
  59. def report_warning(self, message):
  60. if re.match(regex, message): return
  61. old_report_warning(message)
  62. self.report_warning = types.MethodType(report_warning, self)
  63. def gettestcases():
  64. for ie in youtube_dl.extractor.gen_extractors():
  65. t = getattr(ie, '_TEST', None)
  66. if t:
  67. t['name'] = type(ie).__name__[:-len('IE')]
  68. yield t
  69. for t in getattr(ie, '_TESTS', []):
  70. t['name'] = type(ie).__name__[:-len('IE')]
  71. yield t
  72. md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
  73. def expect_info_dict(self, expected_dict, got_dict):
  74. for info_field, expected in expected_dict.items():
  75. if isinstance(expected, compat_str) and expected.startswith('re:'):
  76. got = got_dict.get(info_field)
  77. match_str = expected[len('re:'):]
  78. match_rex = re.compile(match_str)
  79. self.assertTrue(
  80. isinstance(got, compat_str) and match_rex.match(got),
  81. u'field %s (value: %r) should match %r' % (info_field, got, match_str))
  82. elif isinstance(expected, type):
  83. got = got_dict.get(info_field)
  84. self.assertTrue(isinstance(got, expected),
  85. u'Expected type %r, but got value %r of type %r' % (expected, got, type(got)))
  86. else:
  87. if isinstance(expected, compat_str) and expected.startswith('md5:'):
  88. got = 'md5:' + md5(got_dict.get(info_field))
  89. else:
  90. got = got_dict.get(info_field)
  91. self.assertEqual(expected, got,
  92. u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
  93. # Check for the presence of mandatory fields
  94. for key in ('id', 'url', 'title', 'ext'):
  95. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  96. # Check for mandatory fields that are automatically set by YoutubeDL
  97. for key in ['webpage_url', 'extractor', 'extractor_key']:
  98. self.assertTrue(got_dict.get(key), u'Missing field: %s' % key)
  99. # Are checkable fields missing from the test case definition?
  100. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  101. for key, value in got_dict.items()
  102. if value and key in ('title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location'))
  103. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  104. if missing_keys:
  105. sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=4) + u'\n')
  106. self.assertFalse(
  107. missing_keys,
  108. 'Missing keys in test definition: %s' % (
  109. ', '.join(sorted(missing_keys))))