helper.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from __future__ import unicode_literals
  2. import errno
  3. import io
  4. import hashlib
  5. import json
  6. import os.path
  7. import re
  8. import types
  9. import sys
  10. import youtube_dl.extractor
  11. from youtube_dl import YoutubeDL
  12. from youtube_dl.utils import (
  13. compat_str,
  14. preferredencoding,
  15. write_string,
  16. )
  17. def get_params(override=None):
  18. PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  19. "parameters.json")
  20. with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
  21. parameters = json.load(pf)
  22. if override:
  23. parameters.update(override)
  24. return parameters
  25. def try_rm(filename):
  26. """ Remove a file if it exists """
  27. try:
  28. os.remove(filename)
  29. except OSError as ose:
  30. if ose.errno != errno.ENOENT:
  31. raise
  32. def report_warning(message):
  33. '''
  34. Print the message to stderr, it will be prefixed with 'WARNING:'
  35. If stderr is a tty file the 'WARNING:' will be colored
  36. '''
  37. if sys.stderr.isatty() and os.name != 'nt':
  38. _msg_header = '\033[0;33mWARNING:\033[0m'
  39. else:
  40. _msg_header = 'WARNING:'
  41. output = '%s %s\n' % (_msg_header, message)
  42. if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
  43. output = output.encode(preferredencoding())
  44. sys.stderr.write(output)
  45. class FakeYDL(YoutubeDL):
  46. def __init__(self, override=None):
  47. # Different instances of the downloader can't share the same dictionary
  48. # some test set the "sublang" parameter, which would break the md5 checks.
  49. params = get_params(override=override)
  50. super(FakeYDL, self).__init__(params, auto_init=False)
  51. self.result = []
  52. def to_screen(self, s, skip_eol=None):
  53. print(s)
  54. def trouble(self, s, tb=None):
  55. raise Exception(s)
  56. def download(self, x):
  57. self.result.append(x)
  58. def expect_warning(self, regex):
  59. # Silence an expected warning matching a regex
  60. old_report_warning = self.report_warning
  61. def report_warning(self, message):
  62. if re.match(regex, message): return
  63. old_report_warning(message)
  64. self.report_warning = types.MethodType(report_warning, self)
  65. def gettestcases(include_onlymatching=False):
  66. for ie in youtube_dl.extractor.gen_extractors():
  67. t = getattr(ie, '_TEST', None)
  68. if t:
  69. assert not hasattr(ie, '_TESTS'), \
  70. '%s has _TEST and _TESTS' % type(ie).__name__
  71. tests = [t]
  72. else:
  73. tests = getattr(ie, '_TESTS', [])
  74. for t in tests:
  75. if not include_onlymatching and t.get('only_matching', False):
  76. continue
  77. t['name'] = type(ie).__name__[:-len('IE')]
  78. yield t
  79. md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
  80. def expect_info_dict(self, expected_dict, got_dict):
  81. for info_field, expected in expected_dict.items():
  82. if isinstance(expected, compat_str) and expected.startswith('re:'):
  83. got = got_dict.get(info_field)
  84. match_str = expected[len('re:'):]
  85. match_rex = re.compile(match_str)
  86. self.assertTrue(
  87. isinstance(got, compat_str),
  88. 'Expected a %s object, but got %s for field %s' % (
  89. compat_str.__name__, type(got).__name__, info_field))
  90. self.assertTrue(
  91. match_rex.match(got),
  92. 'field %s (value: %r) should match %r' % (info_field, got, match_str))
  93. elif isinstance(expected, type):
  94. got = got_dict.get(info_field)
  95. self.assertTrue(isinstance(got, expected),
  96. 'Expected type %r for field %s, but got value %r of type %r' % (expected, info_field, got, type(got)))
  97. else:
  98. if isinstance(expected, compat_str) and expected.startswith('md5:'):
  99. got = 'md5:' + md5(got_dict.get(info_field))
  100. else:
  101. got = got_dict.get(info_field)
  102. self.assertEqual(expected, got,
  103. 'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
  104. # Check for the presence of mandatory fields
  105. if got_dict.get('_type') != 'playlist':
  106. for key in ('id', 'url', 'title', 'ext'):
  107. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  108. # Check for mandatory fields that are automatically set by YoutubeDL
  109. for key in ['webpage_url', 'extractor', 'extractor_key']:
  110. self.assertTrue(got_dict.get(key), 'Missing field: %s' % key)
  111. # Are checkable fields missing from the test case definition?
  112. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  113. for key, value in got_dict.items()
  114. if value and key in ('title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location'))
  115. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  116. if missing_keys:
  117. def _repr(v):
  118. if isinstance(v, compat_str):
  119. return "'%s'" % v.replace('\\', '\\\\').replace("'", "\\'")
  120. else:
  121. return repr(v)
  122. info_dict_str = ''.join(
  123. ' %s: %s,\n' % (_repr(k), _repr(v))
  124. for k, v in test_info_dict.items())
  125. write_string(
  126. '\n\'info_dict\': {\n' + info_dict_str + '}\n', out=sys.stderr)
  127. self.assertFalse(
  128. missing_keys,
  129. 'Missing keys in test definition: %s' % (
  130. ', '.join(sorted(missing_keys))))
  131. def assertRegexpMatches(self, text, regexp, msg=None):
  132. if hasattr(self, 'assertRegexp'):
  133. return self.assertRegexp(text, regexp, msg)
  134. else:
  135. m = re.match(regexp, text)
  136. if not m:
  137. note = 'Regexp didn\'t match: %r not found in %r' % (regexp, text)
  138. if msg is None:
  139. msg = note
  140. else:
  141. msg = note + ', ' + msg
  142. self.assertTrue(m, msg)
  143. def assertGreaterEqual(self, got, expected, msg=None):
  144. if not (got >= expected):
  145. if msg is None:
  146. msg = '%r not greater than or equal to %r' % (got, expected)
  147. self.assertTrue(got >= expected, msg)
  148. def expect_warnings(ydl, warnings_re):
  149. real_warning = ydl.report_warning
  150. def _report_warning(w):
  151. if not any(re.search(w_re, w) for w_re in warnings_re):
  152. real_warning(w)
  153. ydl.report_warning = _report_warning