helper.py 5.8 KB

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