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.

503 lines
21 KiB

10 years ago
10 years ago
10 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. clean_html,
  17. DateRange,
  18. detect_exe_version,
  19. encodeFilename,
  20. escape_rfc3986,
  21. escape_url,
  22. find_xpath_attr,
  23. fix_xml_ampersands,
  24. InAdvancePagedList,
  25. intlist_to_bytes,
  26. is_html,
  27. js_to_json,
  28. limit_length,
  29. OnDemandPagedList,
  30. orderedSet,
  31. parse_duration,
  32. parse_filesize,
  33. parse_iso8601,
  34. read_batch_urls,
  35. sanitize_filename,
  36. shell_quote,
  37. smuggle_url,
  38. str_to_int,
  39. strip_jsonp,
  40. struct_unpack,
  41. timeconvert,
  42. unescapeHTML,
  43. unified_strdate,
  44. unsmuggle_url,
  45. uppercase_escape,
  46. url_basename,
  47. urlencode_postdata,
  48. version_tuple,
  49. xpath_with_ns,
  50. render_table,
  51. match_str,
  52. )
  53. class TestUtil(unittest.TestCase):
  54. def test_timeconvert(self):
  55. self.assertTrue(timeconvert('') is None)
  56. self.assertTrue(timeconvert('bougrg') is None)
  57. def test_sanitize_filename(self):
  58. self.assertEqual(sanitize_filename('abc'), 'abc')
  59. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  60. self.assertEqual(sanitize_filename('123'), '123')
  61. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  62. self.assertFalse('/' in sanitize_filename('abc/de///'))
  63. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  64. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  65. self.assertEqual('yes no', sanitize_filename('yes? no'))
  66. self.assertEqual('this - that', sanitize_filename('this: that'))
  67. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  68. aumlaut = 'ä'
  69. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  70. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  71. self.assertEqual(sanitize_filename(tests), tests)
  72. self.assertEqual(
  73. sanitize_filename('New World record at 0:12:34'),
  74. 'New World record at 0_12_34')
  75. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  76. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  77. forbidden = '"\0\\/'
  78. for fc in forbidden:
  79. for fbc in forbidden:
  80. self.assertTrue(fbc not in sanitize_filename(fc))
  81. def test_sanitize_filename_restricted(self):
  82. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  83. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  84. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  85. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  86. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  87. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  88. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  89. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  90. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  91. tests = 'a\xe4b\u4e2d\u56fd\u7684c'
  92. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  93. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  94. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  95. for fc in forbidden:
  96. for fbc in forbidden:
  97. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  98. # Handle a common case more neatly
  99. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  100. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  101. # .. but make sure the file name is never empty
  102. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  103. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  104. def test_sanitize_ids(self):
  105. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  106. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  107. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  108. def test_ordered_set(self):
  109. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  110. self.assertEqual(orderedSet([]), [])
  111. self.assertEqual(orderedSet([1]), [1])
  112. # keep the list ordered
  113. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  114. def test_unescape_html(self):
  115. self.assertEqual(unescapeHTML('%20;'), '%20;')
  116. self.assertEqual(
  117. unescapeHTML('&eacute;'), 'é')
  118. def test_daterange(self):
  119. _20century = DateRange("19000101", "20000101")
  120. self.assertFalse("17890714" in _20century)
  121. _ac = DateRange("00010101")
  122. self.assertTrue("19690721" in _ac)
  123. _firstmilenium = DateRange(end="10000101")
  124. self.assertTrue("07110427" in _firstmilenium)
  125. def test_unified_dates(self):
  126. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  127. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  128. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  129. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  130. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  131. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  132. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  133. self.assertEqual(
  134. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  135. '20141126')
  136. self.assertEqual(
  137. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  138. '20150202')
  139. def test_find_xpath_attr(self):
  140. testxml = '''<root>
  141. <node/>
  142. <node x="a"/>
  143. <node x="a" y="c" />
  144. <node x="b" y="d" />
  145. </root>'''
  146. doc = xml.etree.ElementTree.fromstring(testxml)
  147. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  148. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  149. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  150. def test_xpath_with_ns(self):
  151. testxml = '''<root xmlns:media="http://example.com/">
  152. <media:song>
  153. <media:author>The Author</media:author>
  154. <url>http://server.com/download.mp3</url>
  155. </media:song>
  156. </root>'''
  157. doc = xml.etree.ElementTree.fromstring(testxml)
  158. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  159. self.assertTrue(find('media:song') is not None)
  160. self.assertEqual(find('media:song/media:author').text, 'The Author')
  161. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  162. def test_smuggle_url(self):
  163. data = {"ö": "ö", "abc": [3]}
  164. url = 'https://foo.bar/baz?x=y#a'
  165. smug_url = smuggle_url(url, data)
  166. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  167. self.assertEqual(url, unsmug_url)
  168. self.assertEqual(data, unsmug_data)
  169. res_url, res_data = unsmuggle_url(url)
  170. self.assertEqual(res_url, url)
  171. self.assertEqual(res_data, None)
  172. def test_shell_quote(self):
  173. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  174. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  175. def test_str_to_int(self):
  176. self.assertEqual(str_to_int('123,456'), 123456)
  177. self.assertEqual(str_to_int('123.456'), 123456)
  178. def test_url_basename(self):
  179. self.assertEqual(url_basename('http://foo.de/'), '')
  180. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  181. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  182. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  183. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  184. self.assertEqual(
  185. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  186. 'trailer.mp4')
  187. def test_parse_duration(self):
  188. self.assertEqual(parse_duration(None), None)
  189. self.assertEqual(parse_duration(False), None)
  190. self.assertEqual(parse_duration('invalid'), None)
  191. self.assertEqual(parse_duration('1'), 1)
  192. self.assertEqual(parse_duration('1337:12'), 80232)
  193. self.assertEqual(parse_duration('9:12:43'), 33163)
  194. self.assertEqual(parse_duration('12:00'), 720)
  195. self.assertEqual(parse_duration('00:01:01'), 61)
  196. self.assertEqual(parse_duration('x:y'), None)
  197. self.assertEqual(parse_duration('3h11m53s'), 11513)
  198. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  199. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  200. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  201. self.assertEqual(parse_duration('62m45s'), 3765)
  202. self.assertEqual(parse_duration('6m59s'), 419)
  203. self.assertEqual(parse_duration('49s'), 49)
  204. self.assertEqual(parse_duration('0h0m0s'), 0)
  205. self.assertEqual(parse_duration('0m0s'), 0)
  206. self.assertEqual(parse_duration('0s'), 0)
  207. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  208. self.assertEqual(parse_duration('T30M38S'), 1838)
  209. self.assertEqual(parse_duration('5 s'), 5)
  210. self.assertEqual(parse_duration('3 min'), 180)
  211. self.assertEqual(parse_duration('2.5 hours'), 9000)
  212. self.assertEqual(parse_duration('02:03:04'), 7384)
  213. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  214. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  215. def test_fix_xml_ampersands(self):
  216. self.assertEqual(
  217. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  218. self.assertEqual(
  219. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  220. '"&amp;x=y&amp;wrong;&amp;z=a')
  221. self.assertEqual(
  222. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  223. '&amp;&apos;&gt;&lt;&quot;')
  224. self.assertEqual(
  225. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  226. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  227. def test_paged_list(self):
  228. def testPL(size, pagesize, sliceargs, expected):
  229. def get_page(pagenum):
  230. firstid = pagenum * pagesize
  231. upto = min(size, pagenum * pagesize + pagesize)
  232. for i in range(firstid, upto):
  233. yield i
  234. pl = OnDemandPagedList(get_page, pagesize)
  235. got = pl.getslice(*sliceargs)
  236. self.assertEqual(got, expected)
  237. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  238. got = iapl.getslice(*sliceargs)
  239. self.assertEqual(got, expected)
  240. testPL(5, 2, (), [0, 1, 2, 3, 4])
  241. testPL(5, 2, (1,), [1, 2, 3, 4])
  242. testPL(5, 2, (2,), [2, 3, 4])
  243. testPL(5, 2, (4,), [4])
  244. testPL(5, 2, (0, 3), [0, 1, 2])
  245. testPL(5, 2, (1, 4), [1, 2, 3])
  246. testPL(5, 2, (2, 99), [2, 3, 4])
  247. testPL(5, 2, (20, 99), [])
  248. def test_struct_unpack(self):
  249. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  250. def test_read_batch_urls(self):
  251. f = io.StringIO('''\xef\xbb\xbf foo
  252. bar\r
  253. baz
  254. # More after this line\r
  255. ; or after this
  256. bam''')
  257. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  258. def test_urlencode_postdata(self):
  259. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  260. self.assertTrue(isinstance(data, bytes))
  261. def test_parse_iso8601(self):
  262. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  263. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  264. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  265. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  266. def test_strip_jsonp(self):
  267. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  268. d = json.loads(stripped)
  269. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  270. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  271. d = json.loads(stripped)
  272. self.assertEqual(d, {'STATUS': 'OK'})
  273. def test_uppercase_escape(self):
  274. self.assertEqual(uppercase_escape(''), '')
  275. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  276. def test_limit_length(self):
  277. self.assertEqual(limit_length(None, 12), None)
  278. self.assertEqual(limit_length('foo', 12), 'foo')
  279. self.assertTrue(
  280. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  281. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  282. def test_escape_rfc3986(self):
  283. reserved = "!*'();:@&=+$,/?#[]"
  284. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  285. self.assertEqual(escape_rfc3986(reserved), reserved)
  286. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  287. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  288. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  289. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  290. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  291. def test_escape_url(self):
  292. self.assertEqual(
  293. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  294. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  295. )
  296. self.assertEqual(
  297. 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'),
  298. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  299. )
  300. self.assertEqual(
  301. escape_url('http://тест.рф/фрагмент'),
  302. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  303. )
  304. self.assertEqual(
  305. escape_url('http://тест.рф/абв?абв=абв#абв'),
  306. 'http://тест.рф/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
  307. )
  308. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  309. def test_js_to_json_realworld(self):
  310. inp = '''{
  311. 'clip':{'provider':'pseudo'}
  312. }'''
  313. self.assertEqual(js_to_json(inp), '''{
  314. "clip":{"provider":"pseudo"}
  315. }''')
  316. json.loads(js_to_json(inp))
  317. inp = '''{
  318. 'playlist':[{'controls':{'all':null}}]
  319. }'''
  320. self.assertEqual(js_to_json(inp), '''{
  321. "playlist":[{"controls":{"all":null}}]
  322. }''')
  323. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  324. json_code = js_to_json(inp)
  325. self.assertEqual(json.loads(json_code), json.loads(inp))
  326. def test_js_to_json_edgecases(self):
  327. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  328. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  329. on = js_to_json('{"abc": true}')
  330. self.assertEqual(json.loads(on), {'abc': True})
  331. # Ignore JavaScript code as well
  332. on = js_to_json('''{
  333. "x": 1,
  334. y: "a",
  335. z: some.code
  336. }''')
  337. d = json.loads(on)
  338. self.assertEqual(d['x'], 1)
  339. self.assertEqual(d['y'], 'a')
  340. def test_clean_html(self):
  341. self.assertEqual(clean_html('a:\nb'), 'a: b')
  342. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  343. def test_intlist_to_bytes(self):
  344. self.assertEqual(
  345. intlist_to_bytes([0, 1, 127, 128, 255]),
  346. b'\x00\x01\x7f\x80\xff')
  347. def test_args_to_str(self):
  348. self.assertEqual(
  349. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  350. 'foo ba/r -baz \'2 be\' \'\''
  351. )
  352. def test_parse_filesize(self):
  353. self.assertEqual(parse_filesize(None), None)
  354. self.assertEqual(parse_filesize(''), None)
  355. self.assertEqual(parse_filesize('91 B'), 91)
  356. self.assertEqual(parse_filesize('foobar'), None)
  357. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  358. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  359. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  360. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  361. def test_version_tuple(self):
  362. self.assertEqual(version_tuple('1'), (1,))
  363. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  364. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  365. def test_detect_exe_version(self):
  366. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  367. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  368. configuration: --prefix=/usr --extra-'''), '1.2.1')
  369. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  370. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  371. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  372. Trying to open render node...
  373. Success at /dev/dri/renderD128.
  374. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  375. def test_age_restricted(self):
  376. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  377. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  378. self.assertFalse(age_restricted(8, 10))
  379. self.assertTrue(age_restricted(18, 14))
  380. self.assertFalse(age_restricted(18, 18))
  381. def test_is_html(self):
  382. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  383. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  384. self.assertTrue(is_html( # UTF-8 with BOM
  385. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  386. self.assertTrue(is_html( # UTF-16-LE
  387. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  388. ))
  389. self.assertTrue(is_html( # UTF-16-BE
  390. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  391. ))
  392. self.assertTrue(is_html( # UTF-32-BE
  393. 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'))
  394. self.assertTrue(is_html( # UTF-32-LE
  395. 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'))
  396. def test_render_table(self):
  397. self.assertEqual(
  398. render_table(
  399. ['a', 'bcd'],
  400. [[123, 4], [9999, 51]]),
  401. 'a bcd\n'
  402. '123 4\n'
  403. '9999 51')
  404. def test_match_str(self):
  405. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  406. self.assertFalse(match_str('xy', {'x': 1200}))
  407. self.assertTrue(match_str('!xy', {'x': 1200}))
  408. self.assertTrue(match_str('x', {'x': 1200}))
  409. self.assertFalse(match_str('!x', {'x': 1200}))
  410. self.assertTrue(match_str('x', {'x': 0}))
  411. self.assertFalse(match_str('x>0', {'x': 0}))
  412. self.assertFalse(match_str('x>0', {}))
  413. self.assertTrue(match_str('x>?0', {}))
  414. self.assertTrue(match_str('x>1K', {'x': 1200}))
  415. self.assertFalse(match_str('x>2K', {'x': 1200}))
  416. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  417. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  418. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  419. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  420. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  421. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  422. self.assertFalse(match_str(
  423. 'like_count > 100 & dislike_count <? 50 & description',
  424. {'like_count': 90, 'description': 'foo'}))
  425. self.assertTrue(match_str(
  426. 'like_count > 100 & dislike_count <? 50 & description',
  427. {'like_count': 190, 'description': 'foo'}))
  428. self.assertFalse(match_str(
  429. 'like_count > 100 & dislike_count <? 50 & description',
  430. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  431. self.assertFalse(match_str(
  432. 'like_count > 100 & dislike_count <? 50 & description',
  433. {'like_count': 190, 'dislike_count': 10}))
  434. if __name__ == '__main__':
  435. unittest.main()