Debian Codegraph @

Lib/test/test_difflib.py

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