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.

478 lines
18 KiB

  1. import difflib
  2. from test.support import run_unittest, 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("? --\n", diff[1])
  78. self.assertEqual("+ \t\tI am a bug", diff[2])
  79. self.assertEqual("? +\n", diff[3])
  80. patch914575_from1 = """
  81. 1. Beautiful is beTTer than ugly.
  82. 2. Explicit is better than implicit.
  83. 3. Simple is better than complex.
  84. 4. Complex is better than complicated.
  85. """
  86. patch914575_to1 = """
  87. 1. Beautiful is better than ugly.
  88. 3. Simple is better than complex.
  89. 4. Complicated is better than complex.
  90. 5. Flat is better than nested.
  91. """
  92. patch914575_nonascii_from1 = """
  93. 1. Beautiful is beTTer than ugly.
  94. 2. Explicit is better than ımplıcıt.
  95. 3. Simple is better than complex.
  96. 4. Complex is better than complicated.
  97. """
  98. patch914575_nonascii_to1 = """
  99. 1. Beautiful is better than ügly.
  100. 3. Sımple is better than complex.
  101. 4. Complicated is better than cömplex.
  102. 5. Flat is better than nested.
  103. """
  104. patch914575_from2 = """
  105. \t\tLine 1: preceeded by from:[tt] to:[ssss]
  106. \t\tLine 2: preceeded by from:[sstt] to:[sssst]
  107. \t \tLine 3: preceeded by from:[sstst] to:[ssssss]
  108. Line 4: \thas from:[sst] to:[sss] after :
  109. Line 5: has from:[t] to:[ss] at end\t
  110. """
  111. patch914575_to2 = """
  112. Line 1: preceeded by from:[tt] to:[ssss]
  113. \tLine 2: preceeded by from:[sstt] to:[sssst]
  114. Line 3: preceeded by from:[sstst] to:[ssssss]
  115. Line 4: has from:[sst] to:[sss] after :
  116. Line 5: has from:[t] to:[ss] at end
  117. """
  118. patch914575_from3 = """line 0
  119. 1234567890123456789012345689012345
  120. line 1
  121. line 2
  122. line 3
  123. line 4 changed
  124. line 5 changed
  125. line 6 changed
  126. line 7
  127. line 8 subtracted
  128. line 9
  129. 1234567890123456789012345689012345
  130. short line
  131. just fits in!!
  132. just fits in two lines yup!!
  133. the end"""
  134. patch914575_to3 = """line 0
  135. 1234567890123456789012345689012345
  136. line 1
  137. line 2 added
  138. line 3
  139. line 4 chanGEd
  140. line 5a chanGed
  141. line 6a changEd
  142. line 7
  143. line 8
  144. line 9
  145. 1234567890
  146. another long line that needs to be wrapped
  147. just fitS in!!
  148. just fits in two lineS yup!!
  149. the end"""
  150. class TestSFpatches(unittest.TestCase):
  151. def test_html_diff(self):
  152. # Check SF patch 914575 for generating HTML differences
  153. f1a = ((patch914575_from1 + '123\n'*10)*3)
  154. t1a = (patch914575_to1 + '123\n'*10)*3
  155. f1b = '456\n'*10 + f1a
  156. t1b = '456\n'*10 + t1a
  157. f1a = f1a.splitlines()
  158. t1a = t1a.splitlines()
  159. f1b = f1b.splitlines()
  160. t1b = t1b.splitlines()
  161. f2 = patch914575_from2.splitlines()
  162. t2 = patch914575_to2.splitlines()
  163. f3 = patch914575_from3
  164. t3 = patch914575_to3
  165. i = difflib.HtmlDiff()
  166. j = difflib.HtmlDiff(tabsize=2)
  167. k = difflib.HtmlDiff(wrapcolumn=14)
  168. full = i.make_file(f1a,t1a,'from','to',context=False,numlines=5)
  169. tables = '\n'.join(
  170. [
  171. '<h2>Context (first diff within numlines=5(default))</h2>',
  172. i.make_table(f1a,t1a,'from','to',context=True),
  173. '<h2>Context (first diff after numlines=5(default))</h2>',
  174. i.make_table(f1b,t1b,'from','to',context=True),
  175. '<h2>Context (numlines=6)</h2>',
  176. i.make_table(f1a,t1a,'from','to',context=True,numlines=6),
  177. '<h2>Context (numlines=0)</h2>',
  178. i.make_table(f1a,t1a,'from','to',context=True,numlines=0),
  179. '<h2>Same Context</h2>',
  180. i.make_table(f1a,f1a,'from','to',context=True),
  181. '<h2>Same Full</h2>',
  182. i.make_table(f1a,f1a,'from','to',context=False),
  183. '<h2>Empty Context</h2>',
  184. i.make_table([],[],'from','to',context=True),
  185. '<h2>Empty Full</h2>',
  186. i.make_table([],[],'from','to',context=False),
  187. '<h2>tabsize=2</h2>',
  188. j.make_table(f2,t2),
  189. '<h2>tabsize=default</h2>',
  190. i.make_table(f2,t2),
  191. '<h2>Context (wrapcolumn=14,numlines=0)</h2>',
  192. k.make_table(f3.splitlines(),t3.splitlines(),context=True,numlines=0),
  193. '<h2>wrapcolumn=14,splitlines()</h2>',
  194. k.make_table(f3.splitlines(),t3.splitlines()),
  195. '<h2>wrapcolumn=14,splitlines(True)</h2>',
  196. k.make_table(f3.splitlines(True),t3.splitlines(True)),
  197. ])
  198. actual = full.replace('</body>','\n%s\n</body>' % tables)
  199. # temporarily uncomment next two lines to baseline this test
  200. #with open('test_difflib_expect.html','w') as fp:
  201. # fp.write(actual)
  202. with open(findfile('test_difflib_expect.html')) as fp:
  203. self.assertEqual(actual, fp.read())
  204. def test_recursion_limit(self):
  205. # Check if the problem described in patch #1413711 exists.
  206. limit = sys.getrecursionlimit()
  207. old = [(i%2 and "K:%d" or "V:A:%d") % i for i in range(limit*2)]
  208. new = [(i%2 and "K:%d" or "V:B:%d") % i for i in range(limit*2)]
  209. difflib.SequenceMatcher(None, old, new).get_opcodes()
  210. def test_make_file_default_charset(self):
  211. html_diff = difflib.HtmlDiff()
  212. output = html_diff.make_file(patch914575_from1.splitlines(),
  213. patch914575_to1.splitlines())
  214. self.assertIn('content="text/html; charset=utf-8"', output)
  215. def test_make_file_iso88591_charset(self):
  216. html_diff = difflib.HtmlDiff()
  217. output = html_diff.make_file(patch914575_from1.splitlines(),
  218. patch914575_to1.splitlines(),
  219. charset='iso-8859-1')
  220. self.assertIn('content="text/html; charset=iso-8859-1"', output)
  221. def test_make_file_usascii_charset_with_nonascii_input(self):
  222. html_diff = difflib.HtmlDiff()
  223. output = html_diff.make_file(patch914575_nonascii_from1.splitlines(),
  224. patch914575_nonascii_to1.splitlines(),
  225. charset='us-ascii')
  226. self.assertIn('content="text/html; charset=us-ascii"', output)
  227. self.assertIn('&#305;mpl&#305;c&#305;t', output)
  228. class TestOutputFormat(unittest.TestCase):
  229. def test_tab_delimiter(self):
  230. args = ['one', 'two', 'Original', 'Current',
  231. '2005-01-26 23:30:50', '2010-04-02 10:20:52']
  232. ud = difflib.unified_diff(*args, lineterm='')
  233. self.assertEqual(list(ud)[0:2], [
  234. "--- Original\t2005-01-26 23:30:50",
  235. "+++ Current\t2010-04-02 10:20:52"])
  236. cd = difflib.context_diff(*args, lineterm='')
  237. self.assertEqual(list(cd)[0:2], [
  238. "*** Original\t2005-01-26 23:30:50",
  239. "--- Current\t2010-04-02 10:20:52"])
  240. def test_no_trailing_tab_on_empty_filedate(self):
  241. args = ['one', 'two', 'Original', 'Current']
  242. ud = difflib.unified_diff(*args, lineterm='')
  243. self.assertEqual(list(ud)[0:2], ["--- Original", "+++ Current"])
  244. cd = difflib.context_diff(*args, lineterm='')
  245. self.assertEqual(list(cd)[0:2], ["*** Original", "--- Current"])
  246. def test_range_format_unified(self):
  247. # Per the diff spec at http://www.unix.org/single_unix_specification/
  248. spec = '''\
  249. Each <range> field shall be of the form:
  250. %1d", <beginning line number> if the range contains exactly one line,
  251. and:
  252. "%1d,%1d", <beginning line number>, <number of lines> otherwise.
  253. If a range is empty, its beginning line number shall be the number of
  254. the line just before the range, or 0 if the empty range starts the file.
  255. '''
  256. fmt = difflib._format_range_unified
  257. self.assertEqual(fmt(3,3), '3,0')
  258. self.assertEqual(fmt(3,4), '4')
  259. self.assertEqual(fmt(3,5), '4,2')
  260. self.assertEqual(fmt(3,6), '4,3')
  261. self.assertEqual(fmt(0,0), '0,0')
  262. def test_range_format_context(self):
  263. # Per the diff spec at http://www.unix.org/single_unix_specification/
  264. spec = '''\
  265. The range of lines in file1 shall be written in the following format
  266. if the range contains two or more lines:
  267. "*** %d,%d ****\n", <beginning line number>, <ending line number>
  268. and the following format otherwise:
  269. "*** %d ****\n", <ending line number>
  270. The ending line number of an empty range shall be the number of the preceding line,
  271. or 0 if the range is at the start of the file.
  272. Next, the range of lines in file2 shall be written in the following format
  273. if the range contains two or more lines:
  274. "--- %d,%d ----\n", <beginning line number>, <ending line number>
  275. and the following format otherwise:
  276. "--- %d ----\n", <ending line number>
  277. '''
  278. fmt = difflib._format_range_context
  279. self.assertEqual(fmt(3,3), '3')
  280. self.assertEqual(fmt(3,4), '4')
  281. self.assertEqual(fmt(3,5), '4,5')
  282. self.assertEqual(fmt(3,6), '4,6')
  283. self.assertEqual(fmt(0,0), '0')
  284. class TestBytes(unittest.TestCase):
  285. # don't really care about the content of the output, just the fact
  286. # that it's bytes and we don't crash
  287. def check(self, diff):
  288. diff = list(diff) # trigger exceptions first
  289. for line in diff:
  290. self.assertIsInstance(
  291. line, bytes,
  292. "all lines of diff should be bytes, but got: %r" % line)
  293. def test_byte_content(self):
  294. # if we receive byte strings, we return byte strings
  295. a = [b'hello', b'andr\xe9'] # iso-8859-1 bytes
  296. b = [b'hello', b'andr\xc3\xa9'] # utf-8 bytes
  297. unified = difflib.unified_diff
  298. context = difflib.context_diff
  299. check = self.check
  300. check(difflib.diff_bytes(unified, a, a))
  301. check(difflib.diff_bytes(unified, a, b))
  302. # now with filenames (content and filenames are all bytes!)
  303. check(difflib.diff_bytes(unified, a, a, b'a', b'a'))
  304. check(difflib.diff_bytes(unified, a, b, b'a', b'b'))
  305. # and with filenames and dates
  306. check(difflib.diff_bytes(unified, a, a, b'a', b'a', b'2005', b'2013'))
  307. check(difflib.diff_bytes(unified, a, b, b'a', b'b', b'2005', b'2013'))
  308. # same all over again, with context diff
  309. check(difflib.diff_bytes(context, a, a))
  310. check(difflib.diff_bytes(context, a, b))
  311. check(difflib.diff_bytes(context, a, a, b'a', b'a'))
  312. check(difflib.diff_bytes(context, a, b, b'a', b'b'))
  313. check(difflib.diff_bytes(context, a, a, b'a', b'a', b'2005', b'2013'))
  314. check(difflib.diff_bytes(context, a, b, b'a', b'b', b'2005', b'2013'))
  315. def test_byte_filenames(self):
  316. # somebody renamed a file from ISO-8859-2 to UTF-8
  317. fna = b'\xb3odz.txt' # "łodz.txt"
  318. fnb = b'\xc5\x82odz.txt'
  319. # they transcoded the content at the same time
  320. a = [b'\xa3odz is a city in Poland.']
  321. b = [b'\xc5\x81odz is a city in Poland.']
  322. check = self.check
  323. unified = difflib.unified_diff
  324. context = difflib.context_diff
  325. check(difflib.diff_bytes(unified, a, b, fna, fnb))
  326. check(difflib.diff_bytes(context, a, b, fna, fnb))
  327. def assertDiff(expect, actual):
  328. # do not compare expect and equal as lists, because unittest
  329. # uses difflib to report difference between lists
  330. actual = list(actual)
  331. self.assertEqual(len(expect), len(actual))
  332. for e, a in zip(expect, actual):
  333. self.assertEqual(e, a)
  334. expect = [
  335. b'--- \xb3odz.txt',
  336. b'+++ \xc5\x82odz.txt',
  337. b'@@ -1 +1 @@',
  338. b'-\xa3odz is a city in Poland.',
  339. b'+\xc5\x81odz is a city in Poland.',
  340. ]
  341. actual = difflib.diff_bytes(unified, a, b, fna, fnb, lineterm=b'')
  342. assertDiff(expect, actual)
  343. # with dates (plain ASCII)
  344. datea = b'2005-03-18'
  345. dateb = b'2005-03-19'
  346. check(difflib.diff_bytes(unified, a, b, fna, fnb, datea, dateb))
  347. check(difflib.diff_bytes(context, a, b, fna, fnb, datea, dateb))
  348. expect = [
  349. # note the mixed encodings here: this is deeply wrong by every
  350. # tenet of Unicode, but it doesn't crash, it's parseable by
  351. # patch, and it's how UNIX(tm) diff behaves
  352. b'--- \xb3odz.txt\t2005-03-18',
  353. b'+++ \xc5\x82odz.txt\t2005-03-19',
  354. b'@@ -1 +1 @@',
  355. b'-\xa3odz is a city in Poland.',
  356. b'+\xc5\x81odz is a city in Poland.',
  357. ]
  358. actual = difflib.diff_bytes(unified, a, b, fna, fnb, datea, dateb,
  359. lineterm=b'')
  360. assertDiff(expect, actual)
  361. def test_mixed_types_content(self):
  362. # type of input content must be consistent: all str or all bytes
  363. a = [b'hello']
  364. b = ['hello']
  365. unified = difflib.unified_diff
  366. context = difflib.context_diff
  367. expect = "lines to compare must be str, not bytes (b'hello')"
  368. self._assert_type_error(expect, unified, a, b)
  369. self._assert_type_error(expect, unified, b, a)
  370. self._assert_type_error(expect, context, a, b)
  371. self._assert_type_error(expect, context, b, a)
  372. expect = "all arguments must be bytes, not str ('hello')"
  373. self._assert_type_error(expect, difflib.diff_bytes, unified, a, b)
  374. self._assert_type_error(expect, difflib.diff_bytes, unified, b, a)
  375. self._assert_type_error(expect, difflib.diff_bytes, context, a, b)
  376. self._assert_type_error(expect, difflib.diff_bytes, context, b, a)
  377. def test_mixed_types_filenames(self):
  378. # cannot pass filenames as bytes if content is str (this may not be
  379. # the right behaviour, but at least the test demonstrates how
  380. # things work)
  381. a = ['hello\n']
  382. b = ['ohell\n']
  383. fna = b'ol\xe9.txt' # filename transcoded from ISO-8859-1
  384. fnb = b'ol\xc3a9.txt' # to UTF-8
  385. self._assert_type_error(
  386. "all arguments must be str, not: b'ol\\xe9.txt'",
  387. difflib.unified_diff, a, b, fna, fnb)
  388. def test_mixed_types_dates(self):
  389. # type of dates must be consistent with type of contents
  390. a = [b'foo\n']
  391. b = [b'bar\n']
  392. datea = '1 fév'
  393. dateb = '3 fév'
  394. self._assert_type_error(
  395. "all arguments must be bytes, not str ('1 fév')",
  396. difflib.diff_bytes, difflib.unified_diff,
  397. a, b, b'a', b'b', datea, dateb)
  398. # if input is str, non-ASCII dates are fine
  399. a = ['foo\n']
  400. b = ['bar\n']
  401. list(difflib.unified_diff(a, b, 'a', 'b', datea, dateb))
  402. def _assert_type_error(self, msg, generator, *args):
  403. with self.assertRaises(TypeError) as ctx:
  404. list(generator(*args))
  405. self.assertEqual(msg, str(ctx.exception))
  406. def test_main():
  407. difflib.HtmlDiff._default_prefix = 0
  408. Doctests = doctest.DocTestSuite(difflib)
  409. run_unittest(
  410. TestWithAscii, TestAutojunk, TestSFpatches, TestSFbugs,
  411. TestOutputFormat, TestBytes, Doctests)
  412. if __name__ == '__main__':
  413. test_main()