You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1315 lines
60 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. # Allow direct execution
  5. import os
  6. import sys
  7. import unittest
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. # Various small unit tests
  10. import io
  11. import json
  12. import xml.etree.ElementTree
  13. from youtube_dl.utils import (
  14. age_restricted,
  15. args_to_str,
  16. encode_base_n,
  17. clean_html,
  18. date_from_str,
  19. DateRange,
  20. detect_exe_version,
  21. determine_ext,
  22. dict_get,
  23. encode_compat_str,
  24. encodeFilename,
  25. escape_rfc3986,
  26. escape_url,
  27. extract_attributes,
  28. ExtractorError,
  29. find_xpath_attr,
  30. fix_xml_ampersands,
  31. get_element_by_class,
  32. get_element_by_attribute,
  33. get_elements_by_class,
  34. get_elements_by_attribute,
  35. InAdvancePagedList,
  36. intlist_to_bytes,
  37. is_html,
  38. js_to_json,
  39. limit_length,
  40. mimetype2ext,
  41. month_by_name,
  42. multipart_encode,
  43. ohdave_rsa_encrypt,
  44. OnDemandPagedList,
  45. orderedSet,
  46. parse_age_limit,
  47. parse_duration,
  48. parse_filesize,
  49. parse_count,
  50. parse_iso8601,
  51. parse_resolution,
  52. pkcs1pad,
  53. read_batch_urls,
  54. sanitize_filename,
  55. sanitize_path,
  56. sanitize_url,
  57. expand_path,
  58. prepend_extension,
  59. replace_extension,
  60. remove_start,
  61. remove_end,
  62. remove_quotes,
  63. shell_quote,
  64. smuggle_url,
  65. str_to_int,
  66. strip_jsonp,
  67. timeconvert,
  68. unescapeHTML,
  69. unified_strdate,
  70. unified_timestamp,
  71. unsmuggle_url,
  72. uppercase_escape,
  73. lowercase_escape,
  74. url_basename,
  75. base_url,
  76. urljoin,
  77. urlencode_postdata,
  78. urshift,
  79. update_url_query,
  80. version_tuple,
  81. xpath_with_ns,
  82. xpath_element,
  83. xpath_text,
  84. xpath_attr,
  85. render_table,
  86. match_str,
  87. parse_dfxp_time_expr,
  88. dfxp2srt,
  89. cli_option,
  90. cli_valueless_option,
  91. cli_bool_option,
  92. parse_codecs,
  93. )
  94. from youtube_dl.compat import (
  95. compat_chr,
  96. compat_etree_fromstring,
  97. compat_getenv,
  98. compat_os_name,
  99. compat_setenv,
  100. compat_urlparse,
  101. compat_parse_qs,
  102. )
  103. class TestUtil(unittest.TestCase):
  104. def test_timeconvert(self):
  105. self.assertTrue(timeconvert('') is None)
  106. self.assertTrue(timeconvert('bougrg') is None)
  107. def test_sanitize_filename(self):
  108. self.assertEqual(sanitize_filename('abc'), 'abc')
  109. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  110. self.assertEqual(sanitize_filename('123'), '123')
  111. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  112. self.assertFalse('/' in sanitize_filename('abc/de///'))
  113. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  114. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  115. self.assertEqual('yes no', sanitize_filename('yes? no'))
  116. self.assertEqual('this - that', sanitize_filename('this: that'))
  117. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  118. aumlaut = 'ä'
  119. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  120. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  121. self.assertEqual(sanitize_filename(tests), tests)
  122. self.assertEqual(
  123. sanitize_filename('New World record at 0:12:34'),
  124. 'New World record at 0_12_34')
  125. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  126. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  127. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  128. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  129. forbidden = '"\0\\/'
  130. for fc in forbidden:
  131. for fbc in forbidden:
  132. self.assertTrue(fbc not in sanitize_filename(fc))
  133. def test_sanitize_filename_restricted(self):
  134. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  135. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  136. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  137. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  138. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  139. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  140. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  141. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  142. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  143. tests = 'aäb\u4e2d\u56fd\u7684c'
  144. self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
  145. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  146. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  147. for fc in forbidden:
  148. for fbc in forbidden:
  149. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  150. # Handle a common case more neatly
  151. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  152. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  153. # .. but make sure the file name is never empty
  154. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  155. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  156. self.assertEqual(sanitize_filename(
  157. 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
  158. 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYPssaaaaaaaeceeeeiiiionooooooooeuuuuuypy')
  159. def test_sanitize_ids(self):
  160. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  161. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  162. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  163. def test_sanitize_path(self):
  164. if sys.platform != 'win32':
  165. return
  166. self.assertEqual(sanitize_path('abc'), 'abc')
  167. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  168. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  169. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  170. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  171. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  172. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  173. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  174. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  175. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  176. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  177. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  178. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  179. self.assertEqual(
  180. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  181. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  182. self.assertEqual(
  183. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  184. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  185. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  186. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  187. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  188. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  189. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  190. self.assertEqual(sanitize_path('./abc'), 'abc')
  191. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  192. def test_sanitize_url(self):
  193. self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
  194. self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
  195. self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
  196. self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
  197. def test_expand_path(self):
  198. def env(var):
  199. return '%{0}%'.format(var) if sys.platform == 'win32' else '${0}'.format(var)
  200. compat_setenv('YOUTUBE_DL_EXPATH_PATH', 'expanded')
  201. self.assertEqual(expand_path(env('YOUTUBE_DL_EXPATH_PATH')), 'expanded')
  202. self.assertEqual(expand_path(env('HOME')), compat_getenv('HOME'))
  203. self.assertEqual(expand_path('~'), compat_getenv('HOME'))
  204. self.assertEqual(
  205. expand_path('~/%s' % env('YOUTUBE_DL_EXPATH_PATH')),
  206. '%s/expanded' % compat_getenv('HOME'))
  207. def test_prepend_extension(self):
  208. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  209. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  210. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  211. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  212. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  213. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  214. def test_replace_extension(self):
  215. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  216. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  217. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  218. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  219. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  220. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  221. def test_remove_start(self):
  222. self.assertEqual(remove_start(None, 'A - '), None)
  223. self.assertEqual(remove_start('A - B', 'A - '), 'B')
  224. self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
  225. def test_remove_end(self):
  226. self.assertEqual(remove_end(None, ' - B'), None)
  227. self.assertEqual(remove_end('A - B', ' - B'), 'A')
  228. self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
  229. def test_remove_quotes(self):
  230. self.assertEqual(remove_quotes(None), None)
  231. self.assertEqual(remove_quotes('"'), '"')
  232. self.assertEqual(remove_quotes("'"), "'")
  233. self.assertEqual(remove_quotes(';'), ';')
  234. self.assertEqual(remove_quotes('";'), '";')
  235. self.assertEqual(remove_quotes('""'), '')
  236. self.assertEqual(remove_quotes('";"'), ';')
  237. def test_ordered_set(self):
  238. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  239. self.assertEqual(orderedSet([]), [])
  240. self.assertEqual(orderedSet([1]), [1])
  241. # keep the list ordered
  242. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  243. def test_unescape_html(self):
  244. self.assertEqual(unescapeHTML('%20;'), '%20;')
  245. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  246. self.assertEqual(unescapeHTML('&#47;'), '/')
  247. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  248. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  249. self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
  250. # HTML5 entities
  251. self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
  252. def test_date_from_str(self):
  253. self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
  254. self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
  255. self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
  256. self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
  257. self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
  258. def test_daterange(self):
  259. _20century = DateRange("19000101", "20000101")
  260. self.assertFalse("17890714" in _20century)
  261. _ac = DateRange("00010101")
  262. self.assertTrue("19690721" in _ac)
  263. _firstmilenium = DateRange(end="10000101")
  264. self.assertTrue("07110427" in _firstmilenium)
  265. def test_unified_dates(self):
  266. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  267. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  268. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  269. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  270. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  271. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  272. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  273. self.assertEqual(
  274. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  275. '20141126')
  276. self.assertEqual(
  277. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  278. '20150202')
  279. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  280. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  281. self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
  282. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  283. self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
  284. self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
  285. self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
  286. self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
  287. def test_unified_timestamps(self):
  288. self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
  289. self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
  290. self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
  291. self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
  292. self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
  293. self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
  294. self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
  295. self.assertEqual(
  296. unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
  297. 1417001400)
  298. self.assertEqual(
  299. unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
  300. 1422902860)
  301. self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
  302. self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
  303. self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
  304. self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
  305. self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
  306. self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
  307. self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
  308. self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
  309. self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
  310. self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
  311. def test_determine_ext(self):
  312. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  313. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  314. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  315. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  316. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  317. def test_find_xpath_attr(self):
  318. testxml = '''<root>
  319. <node/>
  320. <node x="a"/>
  321. <node x="a" y="c" />
  322. <node x="b" y="d" />
  323. <node x="" />
  324. </root>'''
  325. doc = compat_etree_fromstring(testxml)
  326. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  327. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  328. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  329. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  330. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  331. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  332. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  333. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  334. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  335. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  336. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  337. def test_xpath_with_ns(self):
  338. testxml = '''<root xmlns:media="http://example.com/">
  339. <media:song>
  340. <media:author>The Author</media:author>
  341. <url>http://server.com/download.mp3</url>
  342. </media:song>
  343. </root>'''
  344. doc = compat_etree_fromstring(testxml)
  345. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  346. self.assertTrue(find('media:song') is not None)
  347. self.assertEqual(find('media:song/media:author').text, 'The Author')
  348. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  349. def test_xpath_element(self):
  350. doc = xml.etree.ElementTree.Element('root')
  351. div = xml.etree.ElementTree.SubElement(doc, 'div')
  352. p = xml.etree.ElementTree.SubElement(div, 'p')
  353. p.text = 'Foo'
  354. self.assertEqual(xpath_element(doc, 'div/p'), p)
  355. self.assertEqual(xpath_element(doc, ['div/p']), p)
  356. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  357. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  358. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  359. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  360. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  361. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  362. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  363. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  364. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  365. def test_xpath_text(self):
  366. testxml = '''<root>
  367. <div>
  368. <p>Foo</p>
  369. </div>
  370. </root>'''
  371. doc = compat_etree_fromstring(testxml)
  372. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  373. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  374. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  375. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  376. def test_xpath_attr(self):
  377. testxml = '''<root>
  378. <div>
  379. <p x="a">Foo</p>
  380. </div>
  381. </root>'''
  382. doc = compat_etree_fromstring(testxml)
  383. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  384. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  385. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  386. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  387. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  388. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  389. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  390. def test_smuggle_url(self):
  391. data = {"ö": "ö", "abc": [3]}
  392. url = 'https://foo.bar/baz?x=y#a'
  393. smug_url = smuggle_url(url, data)
  394. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  395. self.assertEqual(url, unsmug_url)
  396. self.assertEqual(data, unsmug_data)
  397. res_url, res_data = unsmuggle_url(url)
  398. self.assertEqual(res_url, url)
  399. self.assertEqual(res_data, None)
  400. smug_url = smuggle_url(url, {'a': 'b'})
  401. smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
  402. res_url, res_data = unsmuggle_url(smug_smug_url)
  403. self.assertEqual(res_url, url)
  404. self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
  405. def test_shell_quote(self):
  406. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  407. self.assertEqual(
  408. shell_quote(args),
  409. """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
  410. def test_str_to_int(self):
  411. self.assertEqual(str_to_int('123,456'), 123456)
  412. self.assertEqual(str_to_int('123.456'), 123456)
  413. def test_url_basename(self):
  414. self.assertEqual(url_basename('http://foo.de/'), '')
  415. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  416. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  417. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  418. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  419. self.assertEqual(
  420. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  421. 'trailer.mp4')
  422. def test_base_url(self):
  423. self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
  424. self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
  425. self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
  426. self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
  427. self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
  428. def test_urljoin(self):
  429. self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  430. self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  431. self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  432. self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  433. self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
  434. self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  435. self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  436. self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  437. self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  438. self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  439. self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  440. self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  441. self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  442. self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  443. self.assertEqual(urljoin('http://foo.de/', None), None)
  444. self.assertEqual(urljoin('http://foo.de/', ''), None)
  445. self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
  446. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
  447. def test_parse_age_limit(self):
  448. self.assertEqual(parse_age_limit(None), None)
  449. self.assertEqual(parse_age_limit(False), None)
  450. self.assertEqual(parse_age_limit('invalid'), None)
  451. self.assertEqual(parse_age_limit(0), 0)
  452. self.assertEqual(parse_age_limit(18), 18)
  453. self.assertEqual(parse_age_limit(21), 21)
  454. self.assertEqual(parse_age_limit(22), None)
  455. self.assertEqual(parse_age_limit('18'), 18)
  456. self.assertEqual(parse_age_limit('18+'), 18)
  457. self.assertEqual(parse_age_limit('PG-13'), 13)
  458. self.assertEqual(parse_age_limit('TV-14'), 14)
  459. self.assertEqual(parse_age_limit('TV-MA'), 17)
  460. def test_parse_duration(self):
  461. self.assertEqual(parse_duration(None), None)
  462. self.assertEqual(parse_duration(False), None)
  463. self.assertEqual(parse_duration('invalid'), None)
  464. self.assertEqual(parse_duration('1'), 1)
  465. self.assertEqual(parse_duration('1337:12'), 80232)
  466. self.assertEqual(parse_duration('9:12:43'), 33163)
  467. self.assertEqual(parse_duration('12:00'), 720)
  468. self.assertEqual(parse_duration('00:01:01'), 61)
  469. self.assertEqual(parse_duration('x:y'), None)
  470. self.assertEqual(parse_duration('3h11m53s'), 11513)
  471. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  472. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  473. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  474. self.assertEqual(parse_duration('62m45s'), 3765)
  475. self.assertEqual(parse_duration('6m59s'), 419)
  476. self.assertEqual(parse_duration('49s'), 49)
  477. self.assertEqual(parse_duration('0h0m0s'), 0)
  478. self.assertEqual(parse_duration('0m0s'), 0)
  479. self.assertEqual(parse_duration('0s'), 0)
  480. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  481. self.assertEqual(parse_duration('T30M38S'), 1838)
  482. self.assertEqual(parse_duration('5 s'), 5)
  483. self.assertEqual(parse_duration('3 min'), 180)
  484. self.assertEqual(parse_duration('2.5 hours'), 9000)
  485. self.assertEqual(parse_duration('02:03:04'), 7384)
  486. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  487. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  488. self.assertEqual(parse_duration('87 Min.'), 5220)
  489. self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
  490. self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
  491. self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
  492. def test_fix_xml_ampersands(self):
  493. self.assertEqual(
  494. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  495. self.assertEqual(
  496. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  497. '"&amp;x=y&amp;wrong;&amp;z=a')
  498. self.assertEqual(
  499. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  500. '&amp;&apos;&gt;&lt;&quot;')
  501. self.assertEqual(
  502. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  503. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  504. def test_paged_list(self):
  505. def testPL(size, pagesize, sliceargs, expected):
  506. def get_page(pagenum):
  507. firstid = pagenum * pagesize
  508. upto = min(size, pagenum * pagesize + pagesize)
  509. for i in range(firstid, upto):
  510. yield i
  511. pl = OnDemandPagedList(get_page, pagesize)
  512. got = pl.getslice(*sliceargs)
  513. self.assertEqual(got, expected)
  514. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  515. got = iapl.getslice(*sliceargs)
  516. self.assertEqual(got, expected)
  517. testPL(5, 2, (), [0, 1, 2, 3, 4])
  518. testPL(5, 2, (1,), [1, 2, 3, 4])
  519. testPL(5, 2, (2,), [2, 3, 4])
  520. testPL(5, 2, (4,), [4])
  521. testPL(5, 2, (0, 3), [0, 1, 2])
  522. testPL(5, 2, (1, 4), [1, 2, 3])
  523. testPL(5, 2, (2, 99), [2, 3, 4])
  524. testPL(5, 2, (20, 99), [])
  525. def test_read_batch_urls(self):
  526. f = io.StringIO('''\xef\xbb\xbf foo
  527. bar\r
  528. baz
  529. # More after this line\r
  530. ; or after this
  531. bam''')
  532. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  533. def test_urlencode_postdata(self):
  534. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  535. self.assertTrue(isinstance(data, bytes))
  536. def test_update_url_query(self):
  537. def query_dict(url):
  538. return compat_parse_qs(compat_urlparse.urlparse(url).query)
  539. self.assertEqual(query_dict(update_url_query(
  540. 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
  541. query_dict('http://example.com/path?quality=HD&format=mp4'))
  542. self.assertEqual(query_dict(update_url_query(
  543. 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
  544. query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
  545. self.assertEqual(query_dict(update_url_query(
  546. 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
  547. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  548. self.assertEqual(query_dict(update_url_query(
  549. 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
  550. query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
  551. self.assertEqual(query_dict(update_url_query(
  552. 'http://example.com/path?manifest=f4m', {'manifest': []})),
  553. query_dict('http://example.com/path'))
  554. self.assertEqual(query_dict(update_url_query(
  555. 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
  556. query_dict('http://example.com/path?system=LINUX'))
  557. self.assertEqual(query_dict(update_url_query(
  558. 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
  559. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  560. self.assertEqual(query_dict(update_url_query(
  561. 'http://example.com/path', {'width': 1080, 'height': 720})),
  562. query_dict('http://example.com/path?width=1080&height=720'))
  563. self.assertEqual(query_dict(update_url_query(
  564. 'http://example.com/path', {'bitrate': 5020.43})),
  565. query_dict('http://example.com/path?bitrate=5020.43'))
  566. self.assertEqual(query_dict(update_url_query(
  567. 'http://example.com/path', {'test': '第二行тест'})),
  568. query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
  569. def test_multipart_encode(self):
  570. self.assertEqual(
  571. multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
  572. b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
  573. self.assertEqual(
  574. multipart_encode({'欄位'.encode('utf-8'): ''.encode('utf-8')}, boundary='AAAAAA')[0],
  575. b'--AAAAAA\r\nContent-Disposition: form-data; name="\xe6\xac\x84\xe4\xbd\x8d"\r\n\r\n\xe5\x80\xbc\r\n--AAAAAA--\r\n')
  576. self.assertRaises(
  577. ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
  578. def test_dict_get(self):
  579. FALSE_VALUES = {
  580. 'none': None,
  581. 'false': False,
  582. 'zero': 0,
  583. 'empty_string': '',
  584. 'empty_list': [],
  585. }
  586. d = FALSE_VALUES.copy()
  587. d['a'] = 42
  588. self.assertEqual(dict_get(d, 'a'), 42)
  589. self.assertEqual(dict_get(d, 'b'), None)
  590. self.assertEqual(dict_get(d, 'b', 42), 42)
  591. self.assertEqual(dict_get(d, ('a', )), 42)
  592. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  593. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  594. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  595. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  596. for key, false_value in FALSE_VALUES.items():
  597. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  598. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  599. def test_encode_compat_str(self):
  600. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  601. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  602. def test_parse_iso8601(self):
  603. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  604. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  605. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  606. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  607. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  608. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  609. def test_strip_jsonp(self):
  610. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  611. d = json.loads(stripped)
  612. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  613. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  614. d = json.loads(stripped)
  615. self.assertEqual(d, {'STATUS': 'OK'})
  616. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  617. d = json.loads(stripped)
  618. self.assertEqual(d, {'status': 'success'})
  619. stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
  620. d = json.loads(stripped)
  621. self.assertEqual(d, {'status': 'success'})
  622. stripped = strip_jsonp('window.cb && cb({"status": "success"});')
  623. d = json.loads(stripped)
  624. self.assertEqual(d, {'status': 'success'})
  625. def test_uppercase_escape(self):
  626. self.assertEqual(uppercase_escape(''), '')
  627. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  628. def test_lowercase_escape(self):
  629. self.assertEqual(lowercase_escape(''), '')
  630. self.assertEqual(lowercase_escape('\\u0026'), '&')
  631. def test_limit_length(self):
  632. self.assertEqual(limit_length(None, 12), None)
  633. self.assertEqual(limit_length('foo', 12), 'foo')
  634. self.assertTrue(
  635. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  636. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  637. def test_mimetype2ext(self):
  638. self.assertEqual(mimetype2ext(None), None)
  639. self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
  640. self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
  641. self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
  642. self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
  643. self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
  644. def test_month_by_name(self):
  645. self.assertEqual(month_by_name(None), None)
  646. self.assertEqual(month_by_name('December', 'en'), 12)
  647. self.assertEqual(month_by_name('décembre', 'fr'), 12)
  648. self.assertEqual(month_by_name('December'), 12)
  649. self.assertEqual(month_by_name('décembre'), None)
  650. self.assertEqual(month_by_name('Unknown', 'unknown'), None)
  651. def test_parse_codecs(self):
  652. self.assertEqual(parse_codecs(''), {})
  653. self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
  654. 'vcodec': 'avc1.77.30',
  655. 'acodec': 'mp4a.40.2',
  656. })
  657. self.assertEqual(parse_codecs('mp4a.40.2'), {
  658. 'vcodec': 'none',
  659. 'acodec': 'mp4a.40.2',
  660. })
  661. self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
  662. 'vcodec': 'avc1.42001e',
  663. 'acodec': 'mp4a.40.5',
  664. })
  665. self.assertEqual(parse_codecs('avc3.640028'), {
  666. 'vcodec': 'avc3.640028',
  667. 'acodec': 'none',
  668. })
  669. self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
  670. 'vcodec': 'h264',
  671. 'acodec': 'aac',
  672. })
  673. def test_escape_rfc3986(self):
  674. reserved = "!*'();:@&=+$,/?#[]"
  675. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  676. self.assertEqual(escape_rfc3986(reserved), reserved)
  677. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  678. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  679. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  680. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  681. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  682. def test_escape_url(self):
  683. self.assertEqual(
  684. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  685. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  686. )
  687. self.assertEqual(
  688. escape_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
  689. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  690. )
  691. self.assertEqual(
  692. escape_url('http://тест.рф/фрагмент'),
  693. 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  694. )
  695. self.assertEqual(
  696. escape_url('http://тест.рф/абв?абв=абв#абв'),
  697. 'http://xn--e1aybc.xn--p1ai/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
  698. )
  699. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  700. def test_js_to_json_realworld(self):
  701. inp = '''{
  702. 'clip':{'provider':'pseudo'}
  703. }'''
  704. self.assertEqual(js_to_json(inp), '''{
  705. "clip":{"provider":"pseudo"}
  706. }''')
  707. json.loads(js_to_json(inp))
  708. inp = '''{
  709. 'playlist':[{'controls':{'all':null}}]
  710. }'''
  711. self.assertEqual(js_to_json(inp), '''{
  712. "playlist":[{"controls":{"all":null}}]
  713. }''')
  714. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  715. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  716. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  717. json_code = js_to_json(inp)
  718. self.assertEqual(json.loads(json_code), json.loads(inp))
  719. inp = '''{
  720. 0:{src:'skipped', type: 'application/dash+xml'},
  721. 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
  722. }'''
  723. self.assertEqual(js_to_json(inp), '''{
  724. "0":{"src":"skipped", "type": "application/dash+xml"},
  725. "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
  726. }''')
  727. inp = '''{"foo":101}'''
  728. self.assertEqual(js_to_json(inp), '''{"foo":101}''')
  729. inp = '''{"duration": "00:01:07"}'''
  730. self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
  731. inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
  732. self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
  733. def test_js_to_json_edgecases(self):
  734. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  735. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  736. on = js_to_json('{"abc": true}')
  737. self.assertEqual(json.loads(on), {'abc': True})
  738. # Ignore JavaScript code as well
  739. on = js_to_json('''{
  740. "x": 1,
  741. y: "a",
  742. z: some.code
  743. }''')
  744. d = json.loads(on)
  745. self.assertEqual(d['x'], 1)
  746. self.assertEqual(d['y'], 'a')
  747. on = js_to_json('["abc", "def",]')
  748. self.assertEqual(json.loads(on), ['abc', 'def'])
  749. on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
  750. self.assertEqual(json.loads(on), ['abc', 'def'])
  751. on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
  752. self.assertEqual(json.loads(on), ['abc', 'def'])
  753. on = js_to_json('{"abc": "def",}')
  754. self.assertEqual(json.loads(on), {'abc': 'def'})
  755. on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
  756. self.assertEqual(json.loads(on), {'abc': 'def'})
  757. on = js_to_json('{ 0: /* " \n */ ",]" , }')
  758. self.assertEqual(json.loads(on), {'0': ',]'})
  759. on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
  760. self.assertEqual(json.loads(on), {'0': ',]'})
  761. on = js_to_json('{ 0: // comment\n1 }')
  762. self.assertEqual(json.loads(on), {'0': 1})
  763. on = js_to_json(r'["<p>x<\/p>"]')
  764. self.assertEqual(json.loads(on), ['<p>x</p>'])
  765. on = js_to_json(r'["\xaa"]')
  766. self.assertEqual(json.loads(on), ['\u00aa'])
  767. on = js_to_json("['a\\\nb']")
  768. self.assertEqual(json.loads(on), ['ab'])
  769. on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
  770. self.assertEqual(json.loads(on), ['ab'])
  771. on = js_to_json('{0xff:0xff}')
  772. self.assertEqual(json.loads(on), {'255': 255})
  773. on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
  774. self.assertEqual(json.loads(on), {'255': 255})
  775. on = js_to_json('{077:077}')
  776. self.assertEqual(json.loads(on), {'63': 63})
  777. on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
  778. self.assertEqual(json.loads(on), {'63': 63})
  779. on = js_to_json('{42:42}')
  780. self.assertEqual(json.loads(on), {'42': 42})
  781. on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
  782. self.assertEqual(json.loads(on), {'42': 42})
  783. on = js_to_json('{42:4.2e1}')
  784. self.assertEqual(json.loads(on), {'42': 42.0})
  785. def test_js_to_json_malformed(self):
  786. self.assertEqual(js_to_json('42a1'), '42"a1"')
  787. self.assertEqual(js_to_json('42a-1'), '42"a"-1')
  788. def test_extract_attributes(self):
  789. self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
  790. self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
  791. self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
  792. self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
  793. self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
  794. self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
  795. self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
  796. self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
  797. self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
  798. self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
  799. self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
  800. self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
  801. self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
  802. self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
  803. self.assertEqual(extract_attributes('<e x >'), {'x': None})
  804. self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
  805. self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
  806. self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
  807. self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
  808. self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
  809. self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
  810. self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
  811. self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
  812. self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
  813. self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
  814. self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
  815. self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
  816. self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
  817. # "Narrow" Python builds don't support unicode code points outside BMP.
  818. try:
  819. compat_chr(0x10000)
  820. supports_outside_bmp = True
  821. except ValueError:
  822. supports_outside_bmp = False
  823. if supports_outside_bmp:
  824. self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
  825. # Malformed HTML should not break attributes extraction on older Python
  826. self.assertEqual(extract_attributes('<mal"formed/>'), {})
  827. def test_clean_html(self):
  828. self.assertEqual(clean_html('a:\nb'), 'a: b')
  829. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  830. self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
  831. def test_intlist_to_bytes(self):
  832. self.assertEqual(
  833. intlist_to_bytes([0, 1, 127, 128, 255]),
  834. b'\x00\x01\x7f\x80\xff')
  835. def test_args_to_str(self):
  836. self.assertEqual(
  837. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  838. 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
  839. )
  840. def test_parse_filesize(self):
  841. self.assertEqual(parse_filesize(None), None)
  842. self.assertEqual(parse_filesize(''), None)
  843. self.assertEqual(parse_filesize('91 B'), 91)
  844. self.assertEqual(parse_filesize('foobar'), None)
  845. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  846. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  847. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  848. self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
  849. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  850. self.assertEqual(parse_filesize('1,24 kb'), 1240)
  851. self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
  852. def test_parse_count(self):
  853. self.assertEqual(parse_count(None), None)
  854. self.assertEqual(parse_count(''), None)
  855. self.assertEqual(parse_count('0'), 0)
  856. self.assertEqual(parse_count('1000'), 1000)
  857. self.assertEqual(parse_count('1.000'), 1000)
  858. self.assertEqual(parse_count('1.1k'), 1100)
  859. self.assertEqual(parse_count('1.1kk'), 1100000)
  860. self.assertEqual(parse_count('1.1kk '), 1100000)
  861. self.assertEqual(parse_count('1.1kk views'), 1100000)
  862. def test_parse_resolution(self):
  863. self.assertEqual(parse_resolution(None), {})
  864. self.assertEqual(parse_resolution(''), {})
  865. self.assertEqual(parse_resolution('1920x1080'), {'width': 1920, 'height': 1080})
  866. self.assertEqual(parse_resolution('1920×1080'), {'width': 1920, 'height': 1080})
  867. self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
  868. self.assertEqual(parse_resolution('720p'), {'height': 720})
  869. self.assertEqual(parse_resolution('4k'), {'height': 2160})
  870. self.assertEqual(parse_resolution('8K'), {'height': 4320})
  871. def test_version_tuple(self):
  872. self.assertEqual(version_tuple('1'), (1,))
  873. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  874. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  875. def test_detect_exe_version(self):
  876. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  877. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  878. configuration: --prefix=/usr --extra-'''), '1.2.1')
  879. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  880. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  881. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  882. Trying to open render node...
  883. Success at /dev/dri/renderD128.
  884. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  885. def test_age_restricted(self):
  886. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  887. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  888. self.assertFalse(age_restricted(8, 10))
  889. self.assertTrue(age_restricted(18, 14))
  890. self.assertFalse(age_restricted(18, 18))
  891. def test_is_html(self):
  892. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  893. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  894. self.assertTrue(is_html( # UTF-8 with BOM
  895. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  896. self.assertTrue(is_html( # UTF-16-LE
  897. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  898. ))
  899. self.assertTrue(is_html( # UTF-16-BE
  900. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  901. ))
  902. self.assertTrue(is_html( # UTF-32-BE
  903. b'\x00\x00\xFE\xFF\x00\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4'))
  904. self.assertTrue(is_html( # UTF-32-LE
  905. b'\xFF\xFE\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4\x00\x00\x00'))
  906. def test_render_table(self):
  907. self.assertEqual(
  908. render_table(
  909. ['a', 'bcd'],
  910. [[123, 4], [9999, 51]]),
  911. 'a bcd\n'
  912. '123 4\n'
  913. '9999 51')
  914. def test_match_str(self):
  915. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  916. self.assertFalse(match_str('xy', {'x': 1200}))
  917. self.assertTrue(match_str('!xy', {'x': 1200}))
  918. self.assertTrue(match_str('x', {'x': 1200}))
  919. self.assertFalse(match_str('!x', {'x': 1200}))
  920. self.assertTrue(match_str('x', {'x': 0}))
  921. self.assertFalse(match_str('x>0', {'x': 0}))
  922. self.assertFalse(match_str('x>0', {}))
  923. self.assertTrue(match_str('x>?0', {}))
  924. self.assertTrue(match_str('x>1K', {'x': 1200}))
  925. self.assertFalse(match_str('x>2K', {'x': 1200}))
  926. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  927. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  928. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  929. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  930. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  931. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  932. self.assertFalse(match_str(
  933. 'like_count > 100 & dislike_count <? 50 & description',
  934. {'like_count': 90, 'description': 'foo'}))
  935. self.assertTrue(match_str(
  936. 'like_count > 100 & dislike_count <? 50 & description',
  937. {'like_count': 190, 'description': 'foo'}))
  938. self.assertFalse(match_str(
  939. 'like_count > 100 & dislike_count <? 50 & description',
  940. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  941. self.assertFalse(match_str(
  942. 'like_count > 100 & dislike_count <? 50 & description',
  943. {'like_count': 190, 'dislike_count': 10}))
  944. def test_parse_dfxp_time_expr(self):
  945. self.assertEqual(parse_dfxp_time_expr(None), None)
  946. self.assertEqual(parse_dfxp_time_expr(''), None)
  947. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  948. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  949. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  950. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  951. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  952. def test_dfxp2srt(self):
  953. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  954. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  955. <body>
  956. <div xml:lang="en">
  957. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  958. <p begin="1" end="2"><br/></p>
  959. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  960. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  961. <p begin="-1" end="-1">Ignore, two</p>
  962. <p begin="3" dur="-1">Ignored, three</p>
  963. </div>
  964. </body>
  965. </tt>'''.encode('utf-8')
  966. srt_data = '''1
  967. 00:00:00,000 --> 00:00:01,000
  968. The following line contains Chinese characters and special symbols
  969. 2
  970. 00:00:01,000 --> 00:00:02,000
  971. 3
  972. 00:00:02,000 --> 00:00:03,000
  973. Third
  974. Line
  975. '''
  976. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  977. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  978. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  979. <body>
  980. <div xml:lang="en">
  981. <p begin="0" end="1">The first line</p>
  982. </div>
  983. </body>
  984. </tt>'''.encode('utf-8')
  985. srt_data = '''1
  986. 00:00:00,000 --> 00:00:01,000
  987. The first line
  988. '''
  989. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  990. dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
  991. <tt xmlns="http://www.w3.org/2006/10/ttaf1" xmlns:ttp="http://www.w3.org/2006/10/ttaf1#parameter" ttp:timeBase="media" xmlns:tts="http://www.w3.org/2006/10/ttaf1#style" xml:lang="en" xmlns:ttm="http://www.w3.org/2006/10/ttaf1#metadata">
  992. <head>
  993. <styling>
  994. <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
  995. <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
  996. <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
  997. <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
  998. </styling>
  999. </head>
  1000. <body tts:textAlign="center" style="s0">
  1001. <div>
  1002. <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
  1003. <p style="s2" begin="00:00:02.08" id="p0" end="00:00:05.84"><span tts:color="lime">part 1<br /></span><span tts:color="cyan">part 2</span></p>
  1004. <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
  1005. <p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
  1006. </div>
  1007. </body>
  1008. </tt>'''.encode('utf-8')
  1009. srt_data = '''1
  1010. 00:00:02,080 --> 00:00:05,839
  1011. <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
  1012. 2
  1013. 00:00:02,080 --> 00:00:05,839
  1014. <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
  1015. </font>part 2</font></b>
  1016. 3
  1017. 00:00:05,839 --> 00:00:09,560
  1018. <u><font color="lime">line 3
  1019. part 3</font></u>
  1020. 4
  1021. 00:00:09,560 --> 00:00:12,359
  1022. <i><u><font color="yellow"><font color="lime">inner
  1023. </font>style</font></u></i>
  1024. '''
  1025. self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
  1026. dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
  1027. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1028. <body>
  1029. <div xml:lang="en">
  1030. <p begin="0" end="1">Line 1</p>
  1031. <p begin="1" end="2"></p>
  1032. </div>
  1033. </body>
  1034. </tt>'''.encode('utf-16')
  1035. srt_data = '''1
  1036. 00:00:00,000 --> 00:00:01,000
  1037. Line 1
  1038. 2
  1039. 00:00:01,000 --> 00:00:02,000
  1040. '''
  1041. self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
  1042. def test_cli_option(self):
  1043. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  1044. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  1045. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  1046. self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
  1047. def test_cli_valueless_option(self):
  1048. self.assertEqual(cli_valueless_option(
  1049. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  1050. self.assertEqual(cli_valueless_option(
  1051. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  1052. self.assertEqual(cli_valueless_option(
  1053. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  1054. self.assertEqual(cli_valueless_option(
  1055. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  1056. self.assertEqual(cli_valueless_option(
  1057. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  1058. self.assertEqual(cli_valueless_option(
  1059. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  1060. def test_cli_bool_option(self):
  1061. self.assertEqual(
  1062. cli_bool_option(
  1063. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  1064. ['--no-check-certificate', 'true'])
  1065. self.assertEqual(
  1066. cli_bool_option(
  1067. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  1068. ['--no-check-certificate=true'])
  1069. self.assertEqual(
  1070. cli_bool_option(
  1071. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1072. ['--check-certificate', 'false'])
  1073. self.assertEqual(
  1074. cli_bool_option(
  1075. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1076. ['--check-certificate=false'])
  1077. self.assertEqual(
  1078. cli_bool_option(
  1079. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1080. ['--check-certificate', 'true'])
  1081. self.assertEqual(
  1082. cli_bool_option(
  1083. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1084. ['--check-certificate=true'])
  1085. self.assertEqual(
  1086. cli_bool_option(
  1087. {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1088. [])
  1089. def test_ohdave_rsa_encrypt(self):
  1090. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  1091. e = 65537
  1092. self.assertEqual(
  1093. ohdave_rsa_encrypt(b'aa111222', e, N),
  1094. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  1095. def test_pkcs1pad(self):
  1096. data = [1, 2, 3]
  1097. padded_data = pkcs1pad(data, 32)
  1098. self.assertEqual(padded_data[:2], [0, 2])
  1099. self.assertEqual(padded_data[28:], [0, 1, 2, 3])
  1100. self.assertRaises(ValueError, pkcs1pad, data, 8)
  1101. def test_encode_base_n(self):
  1102. self.assertEqual(encode_base_n(0, 30), '0')
  1103. self.assertEqual(encode_base_n(80, 30), '2k')
  1104. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  1105. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  1106. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  1107. self.assertRaises(ValueError, encode_base_n, 0, 70)
  1108. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  1109. def test_urshift(self):
  1110. self.assertEqual(urshift(3, 1), 1)
  1111. self.assertEqual(urshift(-3, 1), 2147483646)
  1112. def test_get_element_by_class(self):
  1113. html = '''
  1114. <span class="foo bar">nice</span>
  1115. '''
  1116. self.assertEqual(get_element_by_class('foo', html), 'nice')
  1117. self.assertEqual(get_element_by_class('no-such-class', html), None)
  1118. def test_get_element_by_attribute(self):
  1119. html = '''
  1120. <span class="foo bar">nice</span>
  1121. '''
  1122. self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
  1123. self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
  1124. self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
  1125. html = '''
  1126. <div itemprop="author" itemscope>foo</div>
  1127. '''
  1128. self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
  1129. def test_get_elements_by_class(self):
  1130. html = '''
  1131. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1132. '''
  1133. self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
  1134. self.assertEqual(get_elements_by_class('no-such-class', html), [])
  1135. def test_get_elements_by_attribute(self):
  1136. html = '''
  1137. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1138. '''
  1139. self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
  1140. self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
  1141. self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
  1142. if __name__ == '__main__':
  1143. unittest.main()