test_difflib.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. import difflib
  2. from test.support import findfile
  3. import unittest
  4. import doctest
  5. import sys
  6. class TestWithAscii(unittest.TestCase):
  7. def test_one_insert(self):
  8. sm = difflib.SequenceMatcher(None, 'b' * 100, 'a' + 'b' * 100)
  9. self.assertAlmostEqual(sm.ratio(), 0.995, places=3)
  10. self.assertEqual(list(sm.get_opcodes()),
  11. [ ('insert', 0, 0, 0, 1),
  12. ('equal', 0, 100, 1, 101)])
  13. self.assertEqual(sm.bpopular, set())
  14. sm = difflib.SequenceMatcher(None, 'b' * 100, 'b' * 50 + 'a' + 'b' * 50)
  15. self.assertAlmostEqual(sm.ratio(), 0.995, places=3)
  16. self.assertEqual(list(sm.get_opcodes()),
  17. [ ('equal', 0, 50, 0, 50),
  18. ('insert', 50, 50, 50, 51),
  19. ('equal', 50, 100, 51, 101)])
  20. self.assertEqual(sm.bpopular, set())
  21. def test_one_delete(self):
  22. sm = difflib.SequenceMatcher(None, 'a' * 40 + 'c' + 'b' * 40, 'a' * 40 + 'b' * 40)
  23. self.assertAlmostEqual(sm.ratio(), 0.994, places=3)
  24. self.assertEqual(list(sm.get_opcodes()),
  25. [ ('equal', 0, 40, 0, 40),
  26. ('delete', 40, 41, 40, 40),
  27. ('equal', 41, 81, 40, 80)])
  28. def test_bjunk(self):
  29. sm = difflib.SequenceMatcher(isjunk=lambda x: x == ' ',
  30. a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40)
  31. self.assertEqual(sm.bjunk, set())
  32. sm = difflib.SequenceMatcher(isjunk=lambda x: x == ' ',
  33. a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40 + ' ' * 20)
  34. self.assertEqual(sm.bjunk, {' '})
  35. sm = difflib.SequenceMatcher(isjunk=lambda x: x in [' ', 'b'],
  36. a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40 + ' ' * 20)
  37. self.assertEqual(sm.bjunk, {' ', 'b'})
  38. class TestAutojunk(unittest.TestCase):
  39. """Tests for the autojunk parameter added in 2.7"""
  40. def test_one_insert_homogenous_sequence(self):
  41. # By default autojunk=True and the heuristic kicks in for a sequence
  42. # of length 200+
  43. seq1 = 'b' * 200
  44. seq2 = 'a' + 'b' * 200
  45. sm = difflib.SequenceMatcher(None, seq1, seq2)
  46. self.assertAlmostEqual(sm.ratio(), 0, places=3)
  47. self.assertEqual(sm.bpopular, {'b'})
  48. # Now turn the heuristic off
  49. sm = difflib.SequenceMatcher(None, seq1, seq2, autojunk=False)
  50. self.assertAlmostEqual(sm.ratio(), 0.9975, places=3)
  51. self.assertEqual(sm.bpopular, set())
  52. class TestSFbugs(unittest.TestCase):
  53. def test_ratio_for_null_seqn(self):
  54. # Check clearing of SF bug 763023
  55. s = difflib.SequenceMatcher(None, [], [])
  56. self.assertEqual(s.ratio(), 1)
  57. self.assertEqual(s.quick_ratio(), 1)
  58. self.assertEqual(s.real_quick_ratio(), 1)
  59. def test_comparing_empty_lists(self):
  60. # Check fix for bug #979794
  61. group_gen = difflib.SequenceMatcher(None, [], []).get_grouped_opcodes()
  62. self.assertRaises(StopIteration, next, group_gen)
  63. diff_gen = difflib.unified_diff([], [])
  64. self.assertRaises(StopIteration, next, diff_gen)
  65. def test_matching_blocks_cache(self):
  66. # Issue #21635
  67. s = difflib.SequenceMatcher(None, "abxcd", "abcd")
  68. first = s.get_matching_blocks()
  69. second = s.get_matching_blocks()
  70. self.assertEqual(second[0].size, 2)
  71. self.assertEqual(second[1].size, 2)
  72. self.assertEqual(second[2].size, 0)
  73. def test_added_tab_hint(self):
  74. # Check fix for bug #1488943
  75. diff = list(difflib.Differ().compare(["\tI am a buggy"],["\t\tI am a bug"]))
  76. self.assertEqual("- \tI am a buggy", diff[0])
  77. self.assertEqual("? \t --\n", diff[1])
  78. self.assertEqual("+ \t\tI am a bug", diff[2])
  79. self.assertEqual("? +\n", diff[3])
  80. def test_hint_indented_properly_with_tabs(self):
  81. diff = list(difflib.Differ().compare(["\t \t \t^"], ["\t \t \t^\n"]))
  82. self.assertEqual("- \t \t \t^", diff[0])
  83. self.assertEqual("+ \t \t \t^\n", diff[1])
  84. self.assertEqual("? \t \t \t +\n", diff[2])
  85. def test_mdiff_catch_stop_iteration(self):
  86. # Issue #33224
  87. self.assertEqual(
  88. list(difflib._mdiff(["2"], ["3"], 1)),
  89. [((1, '\x00-2\x01'), (1, '\x00+3\x01'), True)],
  90. )
  91. patch914575_from1 = """
  92. 1. Beautiful is beTTer than ugly.
  93. 2. Explicit is better than implicit.
  94. 3. Simple is better than complex.
  95. 4. Complex is better than complicated.
  96. """
  97. patch914575_to1 = """
  98. 1. Beautiful is better than ugly.
  99. 3. Simple is better than complex.
  100. 4. Complicated is better than complex.
  101. 5. Flat is better than nested.
  102. """
  103. patch914575_nonascii_from1 = """
  104. 1. Beautiful is beTTer than ugly.
  105. 2. Explicit is better than ımplıcıt.
  106. 3. Simple is better than complex.
  107. 4. Complex is better than complicated.
  108. """
  109. patch914575_nonascii_to1 = """
  110. 1. Beautiful is better than ügly.
  111. 3. Sımple is better than complex.
  112. 4. Complicated is better than cömplex.
  113. 5. Flat is better than nested.
  114. """
  115. patch914575_from2 = """
  116. \t\tLine 1: preceded by from:[tt] to:[ssss]
  117. \t\tLine 2: preceded by from:[sstt] to:[sssst]
  118. \t \tLine 3: preceded by from:[sstst] to:[ssssss]
  119. Line 4: \thas from:[sst] to:[sss] after :
  120. Line 5: has from:[t] to:[ss] at end\t
  121. """
  122. patch914575_to2 = """
  123. Line 1: preceded by from:[tt] to:[ssss]
  124. \tLine 2: preceded by from:[sstt] to:[sssst]
  125. Line 3: preceded by from:[sstst] to:[ssssss]
  126. Line 4: has from:[sst] to:[sss] after :
  127. Line 5: has from:[t] to:[ss] at end
  128. """
  129. patch914575_from3 = """line 0
  130. 1234567890123456789012345689012345
  131. line 1
  132. line 2
  133. line 3
  134. line 4 changed
  135. line 5 changed
  136. line 6 changed
  137. line 7
  138. line 8 subtracted
  139. line 9
  140. 1234567890123456789012345689012345
  141. short line
  142. just fits in!!
  143. just fits in two lines yup!!
  144. the end"""
  145. patch914575_to3 = """line 0
  146. 1234567890123456789012345689012345
  147. line 1
  148. line 2 added
  149. line 3
  150. line 4 chanGEd
  151. line 5a chanGed
  152. line 6a changEd
  153. line 7
  154. line 8
  155. line 9
  156. 1234567890
  157. another long line that needs to be wrapped
  158. just fitS in!!
  159. just fits in two lineS yup!!
  160. the end"""
  161. class TestSFpatches(unittest.TestCase):
  162. def test_html_diff(self):
  163. # Check SF patch 914575 for generating HTML differences
  164. f1a = ((patch914575_from1 + '123\n'*10)*3)
  165. t1a = (patch914575_to1 + '123\n'*10)*3
  166. f1b = '456\n'*10 + f1a
  167. t1b = '456\n'*10 + t1a
  168. f1a = f1a.splitlines()
  169. t1a = t1a.splitlines()
  170. f1b = f1b.splitlines()
  171. t1b = t1b.splitlines()
  172. f2 = patch914575_from2.splitlines()
  173. t2 = patch914575_to2.splitlines()
  174. f3 = patch914575_from3
  175. t3 = patch914575_to3
  176. i = difflib.HtmlDiff()
  177. j = difflib.HtmlDiff(tabsize=2)
  178. k = difflib.HtmlDiff(wrapcolumn=14)
  179. full = i.make_file(f1a,t1a,'from','to',context=False,numlines=5)
  180. tables = '\n'.join(
  181. [
  182. '<h2>Context (first diff within numlines=5(default))</h2>',
  183. i.make_table(f1a,t1a,'from','to',context=True),
  184. '<h2>Context (first diff after numlines=5(default))</h2>',
  185. i.make_table(f1b,t1b,'from','to',context=True),
  186. '<h2>Context (numlines=6)</h2>',
  187. i.make_table(f1a,t1a,'from','to',context=True,numlines=6),
  188. '<h2>Context (numlines=0)</h2>',
  189. i.make_table(f1a,t1a,'from','to',context=True,numlines=0),
  190. '<h2>Same Context</h2>',
  191. i.make_table(f1a,f1a,'from','to',context=True),
  192. '<h2>Same Full</h2>',
  193. i.make_table(f1a,f1a,'from','to',context=False),
  194. '<h2>Empty Context</h2>',
  195. i.make_table([],[],'from','to',context=True),
  196. '<h2>Empty Full</h2>',
  197. i.make_table([],[],'from','to',context=False),
  198. '<h2>tabsize=2</h2>',
  199. j.make_table(f2,t2),
  200. '<h2>tabsize=default</h2>',
  201. i.make_table(f2,t2),
  202. '<h2>Context (wrapcolumn=14,numlines=0)</h2>',
  203. k.make_table(f3.splitlines(),t3.splitlines(),context=True,numlines=0),
  204. '<h2>wrapcolumn=14,splitlines()</h2>',
  205. k.make_table(f3.splitlines(),t3.splitlines()),
  206. '<h2>wrapcolumn=14,splitlines(True)</h2>',
  207. k.make_table(f3.splitlines(True),t3.splitlines(True)),
  208. ])
  209. actual = full.replace('</body>','\n%s\n</body>' % tables)
  210. # temporarily uncomment next two lines to baseline this test
  211. #with open('test_difflib_expect.html','w') as fp:
  212. # fp.write(actual)
  213. with open(findfile('test_difflib_expect.html'), encoding="utf-8") as fp:
  214. self.assertEqual(actual, fp.read())
  215. def test_recursion_limit(self):
  216. # Check if the problem described in patch #1413711 exists.
  217. limit = sys.getrecursionlimit()
  218. old = [(i%2 and "K:%d" or "V:A:%d") % i for i in range(limit*2)]
  219. new = [(i%2 and "K:%d" or "V:B:%d") % i for i in range(limit*2)]
  220. difflib.SequenceMatcher(None, old, new).get_opcodes()
  221. def test_make_file_default_charset(self):
  222. html_diff = difflib.HtmlDiff()
  223. output = html_diff.make_file(patch914575_from1.splitlines(),
  224. patch914575_to1.splitlines())
  225. self.assertIn('content="text/html; charset=utf-8"', output)
  226. def test_make_file_iso88591_charset(self):
  227. html_diff = difflib.HtmlDiff()
  228. output = html_diff.make_file(patch914575_from1.splitlines(),
  229. patch914575_to1.splitlines(),
  230. charset='iso-8859-1')
  231. self.assertIn('content="text/html; charset=iso-8859-1"', output)
  232. def test_make_file_usascii_charset_with_nonascii_input(self):
  233. html_diff = difflib.HtmlDiff()
  234. output = html_diff.make_file(patch914575_nonascii_from1.splitlines(),
  235. patch914575_nonascii_to1.splitlines(),
  236. charset='us-ascii')
  237. self.assertIn('content="text/html; charset=us-ascii"', output)
  238. self.assertIn('&#305;mpl&#305;c&#305;t', output)
  239. class TestOutputFormat(unittest.TestCase):
  240. def test_tab_delimiter(self):
  241. args = ['one', 'two', 'Original', 'Current',
  242. '2005-01-26 23:30:50', '2010-04-02 10:20:52']
  243. ud = difflib.unified_diff(*args, lineterm='')
  244. self.assertEqual(list(ud)[0:2], [
  245. "--- Original\t2005-01-26 23:30:50",
  246. "+++ Current\t2010-04-02 10:20:52"])
  247. cd = difflib.context_diff(*args, lineterm='')
  248. self.assertEqual(list(cd)[0:2], [
  249. "*** Original\t2005-01-26 23:30:50",
  250. "--- Current\t2010-04-02 10:20:52"])
  251. def test_no_trailing_tab_on_empty_filedate(self):
  252. args = ['one', 'two', 'Original', 'Current']
  253. ud = difflib.unified_diff(*args, lineterm='')
  254. self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])
  255. cd = difflib.context_diff(*args, lineterm='')
  256. self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
  257. def test_range_format_unified(self):
  258. # Per the diff spec at http://www.unix.org/single_unix_specification/
  259. spec = '''\
  260. Each <range> field shall be of the form:
  261. %1d", <beginning line number> if the range contains exactly one line,
  262. and:
  263. "%1d,%1d", <beginning line number>, <number of lines> otherwise.
  264. If a range is empty, its beginning line number shall be the number of
  265. the line just before the range, or 0 if the empty range starts the file.
  266. '''
  267. fmt = difflib._format_range_unified
  268. self.assertEqual(fmt(3,3), '3,0')
  269. self.assertEqual(fmt(3,4), '4')
  270. self.assertEqual(fmt(3,5), '4,2')
  271. self.assertEqual(fmt(3,6), '4,3')
  272. self.assertEqual(fmt(0,0), '0,0')
  273. def test_range_format_context(self):
  274. # Per the diff spec at http://www.unix.org/single_unix_specification/
  275. spec = '''\
  276. The range of lines in file1 shall be written in the following format
  277. if the range contains two or more lines:
  278. "*** %d,%d ****\n", <beginning line number>, <ending line number>
  279. and the following format otherwise:
  280. "*** %d ****\n", <ending line number>
  281. The ending line number of an empty range shall be the number of the preceding line,
  282. or 0 if the range is at the start of the file.
  283. Next, the range of lines in file2 shall be written in the following format
  284. if the range contains two or more lines:
  285. "--- %d,%d ----\n", <beginning line number>, <ending line number>
  286. and the following format otherwise:
  287. "--- %d ----\n", <ending line number>
  288. '''
  289. fmt = difflib._format_range_context
  290. self.assertEqual(fmt(3,3), '3')
  291. self.assertEqual(fmt(3,4), '4')
  292. self.assertEqual(fmt(3,5), '4,5')
  293. self.assertEqual(fmt(3,6), '4,6')
  294. self.assertEqual(fmt(0,0), '0')
  295. class TestBytes(unittest.TestCase):
  296. # don't really care about the content of the output, just the fact
  297. # that it's bytes and we don't crash
  298. def check(self, diff):
  299. diff = list(diff) # trigger exceptions first
  300. for line in diff:
  301. self.assertIsInstance(
  302. line, bytes,
  303. "all lines of diff should be bytes, but got: %r" % line)
  304. def test_byte_content(self):
  305. # if we receive byte strings, we return byte strings
  306. a = [b'hello', b'andr\xe9'] # iso-8859-1 bytes
  307. b = [b'hello', b'andr\xc3\xa9'] # utf-8 bytes
  308. unified = difflib.unified_diff
  309. context = difflib.context_diff
  310. check = self.check
  311. check(difflib.diff_bytes(unified, a, a))
  312. check(difflib.diff_bytes(unified, a, b))
  313. # now with filenames (content and filenames are all bytes!)
  314. check(difflib.diff_bytes(unified, a, a, b'a', b'a'))
  315. check(difflib.diff_bytes(unified, a, b, b'a', b'b'))
  316. # and with filenames and dates
  317. check(difflib.diff_bytes(unified, a, a, b'a', b'a', b'2005', b'2013'))
  318. check(difflib.diff_bytes(unified, a, b, b'a', b'b', b'2005', b'2013'))
  319. # same all over again, with context diff
  320. check(difflib.diff_bytes(context, a, a))
  321. check(difflib.diff_bytes(context, a, b))
  322. check(difflib.diff_bytes(context, a, a, b'a', b'a'))
  323. check(difflib.diff_bytes(context, a, b, b'a', b'b'))
  324. check(difflib.diff_bytes(context, a, a, b'a', b'a', b'2005', b'2013'))
  325. check(difflib.diff_bytes(context, a, b, b'a', b'b', b'2005', b'2013'))
  326. def test_byte_filenames(self):
  327. # somebody renamed a file from ISO-8859-2 to UTF-8
  328. fna = b'\xb3odz.txt' # "łodz.txt"
  329. fnb = b'\xc5\x82odz.txt'
  330. # they transcoded the content at the same time
  331. a = [b'\xa3odz is a city in Poland.']
  332. b = [b'\xc5\x81odz is a city in Poland.']
  333. check = self.check
  334. unified = difflib.unified_diff
  335. context = difflib.context_diff
  336. check(difflib.diff_bytes(unified, a, b, fna, fnb))
  337. check(difflib.diff_bytes(context, a, b, fna, fnb))
  338. def assertDiff(expect, actual):
  339. # do not compare expect and equal as lists, because unittest
  340. # uses difflib to report difference between lists
  341. actual = list(actual)
  342. self.assertEqual(len(expect), len(actual))
  343. for e, a in zip(expect, actual):
  344. self.assertEqual(e, a)
  345. expect = [
  346. b'--- \xb3odz.txt',
  347. b'+++ \xc5\x82odz.txt',
  348. b'@@ -1 +1 @@',
  349. b'-\xa3odz is a city in Poland.',
  350. b'+\xc5\x81odz is a city in Poland.',
  351. ]
  352. actual = difflib.diff_bytes(unified, a, b, fna, fnb, lineterm=b'')
  353. assertDiff(expect, actual)
  354. # with dates (plain ASCII)
  355. datea = b'2005-03-18'
  356. dateb = b'2005-03-19'
  357. check(difflib.diff_bytes(unified, a, b, fna, fnb, datea, dateb))
  358. check(difflib.diff_bytes(context, a, b, fna, fnb, datea, dateb))
  359. expect = [
  360. # note the mixed encodings here: this is deeply wrong by every
  361. # tenet of Unicode, but it doesn't crash, it's parseable by
  362. # patch, and it's how UNIX(tm) diff behaves
  363. b'--- \xb3odz.txt\t2005-03-18',
  364. b'+++ \xc5\x82odz.txt\t2005-03-19',
  365. b'@@ -1 +1 @@',
  366. b'-\xa3odz is a city in Poland.',
  367. b'+\xc5\x81odz is a city in Poland.',
  368. ]
  369. actual = difflib.diff_bytes(unified, a, b, fna, fnb, datea, dateb,
  370. lineterm=b'')
  371. assertDiff(expect, actual)
  372. def test_mixed_types_content(self):
  373. # type of input content must be consistent: all str or all bytes
  374. a = [b'hello']
  375. b = ['hello']
  376. unified = difflib.unified_diff
  377. context = difflib.context_diff
  378. expect = "lines to compare must be str, not bytes (b'hello')"
  379. self._assert_type_error(expect, unified, a, b)
  380. self._assert_type_error(expect, unified, b, a)
  381. self._assert_type_error(expect, context, a, b)
  382. self._assert_type_error(expect, context, b, a)
  383. expect = "all arguments must be bytes, not str ('hello')"
  384. self._assert_type_error(expect, difflib.diff_bytes, unified, a, b)
  385. self._assert_type_error(expect, difflib.diff_bytes, unified, b, a)
  386. self._assert_type_error(expect, difflib.diff_bytes, context, a, b)
  387. self._assert_type_error(expect, difflib.diff_bytes, context, b, a)
  388. def test_mixed_types_filenames(self):
  389. # cannot pass filenames as bytes if content is str (this may not be
  390. # the right behaviour, but at least the test demonstrates how
  391. # things work)
  392. a = ['hello\n']
  393. b = ['ohell\n']
  394. fna = b'ol\xe9.txt' # filename transcoded from ISO-8859-1
  395. fnb = b'ol\xc3a9.txt' # to UTF-8
  396. self._assert_type_error(
  397. "all arguments must be str, not: b'ol\\xe9.txt'",
  398. difflib.unified_diff, a, b, fna, fnb)
  399. def test_mixed_types_dates(self):
  400. # type of dates must be consistent with type of contents
  401. a = [b'foo\n']
  402. b = [b'bar\n']
  403. datea = '1 fév'
  404. dateb = '3 fév'
  405. self._assert_type_error(
  406. "all arguments must be bytes, not str ('1 fév')",
  407. difflib.diff_bytes, difflib.unified_diff,
  408. a, b, b'a', b'b', datea, dateb)
  409. # if input is str, non-ASCII dates are fine
  410. a = ['foo\n']
  411. b = ['bar\n']
  412. list(difflib.unified_diff(a, b, 'a', 'b', datea, dateb))
  413. def _assert_type_error(self, msg, generator, *args):
  414. with self.assertRaises(TypeError) as ctx:
  415. list(generator(*args))
  416. self.assertEqual(msg, str(ctx.exception))
  417. class TestJunkAPIs(unittest.TestCase):
  418. def test_is_line_junk_true(self):
  419. for line in ['#', ' ', ' #', '# ', ' # ', '']:
  420. self.assertTrue(difflib.IS_LINE_JUNK(line), repr(line))
  421. def test_is_line_junk_false(self):
  422. for line in ['##', ' ##', '## ', 'abc ', 'abc #', 'Mr. Moose is up!']:
  423. self.assertFalse(difflib.IS_LINE_JUNK(line), repr(line))
  424. def test_is_line_junk_REDOS(self):
  425. evil_input = ('\t' * 1000000) + '##'
  426. self.assertFalse(difflib.IS_LINE_JUNK(evil_input))
  427. def test_is_character_junk_true(self):
  428. for char in [' ', '\t']:
  429. self.assertTrue(difflib.IS_CHARACTER_JUNK(char), repr(char))
  430. def test_is_character_junk_false(self):
  431. for char in ['a', '#', '\n', '\f', '\r', '\v']:
  432. self.assertFalse(difflib.IS_CHARACTER_JUNK(char), repr(char))
  433. class TestFindLongest(unittest.TestCase):
  434. def longer_match_exists(self, a, b, n):
  435. return any(b_part in a for b_part in
  436. [b[i:i + n + 1] for i in range(0, len(b) - n - 1)])
  437. def test_default_args(self):
  438. a = 'foo bar'
  439. b = 'foo baz bar'
  440. sm = difflib.SequenceMatcher(a=a, b=b)
  441. match = sm.find_longest_match()
  442. self.assertEqual(match.a, 0)
  443. self.assertEqual(match.b, 0)
  444. self.assertEqual(match.size, 6)
  445. self.assertEqual(a[match.a: match.a + match.size],
  446. b[match.b: match.b + match.size])
  447. self.assertFalse(self.longer_match_exists(a, b, match.size))
  448. match = sm.find_longest_match(alo=2, blo=4)
  449. self.assertEqual(match.a, 3)
  450. self.assertEqual(match.b, 7)
  451. self.assertEqual(match.size, 4)
  452. self.assertEqual(a[match.a: match.a + match.size],
  453. b[match.b: match.b + match.size])
  454. self.assertFalse(self.longer_match_exists(a[2:], b[4:], match.size))
  455. match = sm.find_longest_match(bhi=5, blo=1)
  456. self.assertEqual(match.a, 1)
  457. self.assertEqual(match.b, 1)
  458. self.assertEqual(match.size, 4)
  459. self.assertEqual(a[match.a: match.a + match.size],
  460. b[match.b: match.b + match.size])
  461. self.assertFalse(self.longer_match_exists(a, b[1:5], match.size))
  462. def test_longest_match_with_popular_chars(self):
  463. a = 'dabcd'
  464. b = 'd'*100 + 'abc' + 'd'*100 # length over 200 so popular used
  465. sm = difflib.SequenceMatcher(a=a, b=b)
  466. match = sm.find_longest_match(0, len(a), 0, len(b))
  467. self.assertEqual(match.a, 0)
  468. self.assertEqual(match.b, 99)
  469. self.assertEqual(match.size, 5)
  470. self.assertEqual(a[match.a: match.a + match.size],
  471. b[match.b: match.b + match.size])
  472. self.assertFalse(self.longer_match_exists(a, b, match.size))
  473. def setUpModule():
  474. difflib.HtmlDiff._default_prefix = 0
  475. def load_tests(loader, tests, pattern):
  476. tests.addTest(doctest.DocTestSuite(difflib))
  477. return tests
  478. if __name__ == '__main__':
  479. unittest.main()