487
AB_MERGE_TEXT="""unchanged|Banana cup cake recipe
492
new-b|- bananas (do not use plantains!!!)
493
unchanged|- broken tea cups
494
new-a|- self-raising flour
497
AB_MERGE=[tuple(l.split('|')) for l in AB_MERGE_TEXT.splitlines(True)]
500
def line_delta(from_lines, to_lines):
501
"""Generate line-based delta from one text to another"""
502
s = difflib.SequenceMatcher(None, from_lines, to_lines)
503
for op in s.get_opcodes():
506
yield '%d,%d,%d\n' % (op[1], op[2], op[4]-op[3])
507
for i in range(op[3], op[4]):
511
def apply_line_delta(basis_lines, delta_lines):
512
"""Apply a line-based perfect diff
514
basis_lines -- text to apply the patch to
515
delta_lines -- diff instructions and content
177
class TestPlainKnitContent(TestCase, KnitContentTestsMixin):
179
def _make_content(self, lines):
180
annotated_content = AnnotatedKnitContent(lines)
181
return PlainKnitContent(annotated_content.text(), 'bogus')
183
def test_annotate(self):
184
content = self._make_content([])
185
self.assertEqual(content.annotate(), [])
187
content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
188
self.assertEqual(content.annotate(),
189
[("bogus", "text1"), ("bogus", "text2")])
191
def test_line_delta(self):
192
content1 = self._make_content([("", "a"), ("", "b")])
193
content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
194
self.assertEqual(content1.line_delta(content2),
195
[(1, 2, 2, ["a", "c"])])
197
def test_line_delta_iter(self):
198
content1 = self._make_content([("", "a"), ("", "b")])
199
content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
200
it = content1.line_delta_iter(content2)
201
self.assertEqual(it.next(), (1, 2, 2, ["a", "c"]))
202
self.assertRaises(StopIteration, it.next)
205
class TestAnnotatedKnitContent(TestCase, KnitContentTestsMixin):
207
def _make_content(self, lines):
208
return AnnotatedKnitContent(lines)
210
def test_annotate(self):
211
content = self._make_content([])
212
self.assertEqual(content.annotate(), [])
214
content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
215
self.assertEqual(content.annotate(),
216
[("origin1", "text1"), ("origin2", "text2")])
218
def test_line_delta(self):
219
content1 = self._make_content([("", "a"), ("", "b")])
220
content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
221
self.assertEqual(content1.line_delta(content2),
222
[(1, 2, 2, [("", "a"), ("", "c")])])
224
def test_line_delta_iter(self):
225
content1 = self._make_content([("", "a"), ("", "b")])
226
content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
227
it = content1.line_delta_iter(content2)
228
self.assertEqual(it.next(), (1, 2, 2, [("", "a"), ("", "c")]))
229
self.assertRaises(StopIteration, it.next)
232
class MockTransport(object):
234
def __init__(self, file_lines=None):
235
self.file_lines = file_lines
237
# We have no base directory for the MockTransport
240
def get(self, filename):
241
if self.file_lines is None:
242
raise NoSuchFile(filename)
244
return StringIO("\n".join(self.file_lines))
246
def readv(self, relpath, offsets):
247
fp = self.get(relpath)
248
for offset, size in offsets:
250
yield offset, fp.read(size)
252
def __getattr__(self, name):
253
def queue_call(*args, **kwargs):
254
self.calls.append((name, args, kwargs))
258
class MockReadvFailingTransport(MockTransport):
259
"""Fail in the middle of a readv() result.
261
This Transport will successfully yield the first two requested hunks, but
262
raise NoSuchFile for the rest.
520
while i < len(delta_lines):
522
a, b, c = map(long, l.split(','))
524
out[offset+a:offset+b] = delta_lines[i:i+c]
526
offset = offset + (b - a) + c
530
class TestWeaveToKnit(KnitTests):
532
def test_weave_to_knit_matches(self):
533
# check that the WeaveToKnit is_compatible function
534
# registers True for a Weave to a Knit.
265
def readv(self, relpath, offsets):
267
for result in MockTransport.readv(self, relpath, offsets):
269
# we use 2 because the first offset is the pack header, the second
270
# is the first actual content requset
272
raise errors.NoSuchFile(relpath)
276
class KnitRecordAccessTestsMixin(object):
277
"""Tests for getting and putting knit records."""
279
def test_add_raw_records(self):
280
"""Add_raw_records adds records retrievable later."""
281
access = self.get_access()
282
memos = access.add_raw_records([('key', 10)], '1234567890')
283
self.assertEqual(['1234567890'], list(access.get_raw_records(memos)))
285
def test_add_several_raw_records(self):
286
"""add_raw_records with many records and read some back."""
287
access = self.get_access()
288
memos = access.add_raw_records([('key', 10), ('key2', 2), ('key3', 5)],
290
self.assertEqual(['1234567890', '12', '34567'],
291
list(access.get_raw_records(memos)))
292
self.assertEqual(['1234567890'],
293
list(access.get_raw_records(memos[0:1])))
294
self.assertEqual(['12'],
295
list(access.get_raw_records(memos[1:2])))
296
self.assertEqual(['34567'],
297
list(access.get_raw_records(memos[2:3])))
298
self.assertEqual(['1234567890', '34567'],
299
list(access.get_raw_records(memos[0:1] + memos[2:3])))
302
class TestKnitKnitAccess(TestCaseWithMemoryTransport, KnitRecordAccessTestsMixin):
303
"""Tests for the .kndx implementation."""
305
def get_access(self):
306
"""Get a .knit style access instance."""
307
mapper = ConstantMapper("foo")
308
access = _KnitKeyAccess(self.get_transport(), mapper)
312
class _TestException(Exception):
313
"""Just an exception for local tests to use."""
316
class TestPackKnitAccess(TestCaseWithMemoryTransport, KnitRecordAccessTestsMixin):
317
"""Tests for the pack based access."""
319
def get_access(self):
320
return self._get_access()[0]
322
def _get_access(self, packname='packfile', index='FOO'):
323
transport = self.get_transport()
324
def write_data(bytes):
325
transport.append_bytes(packname, bytes)
326
writer = pack.ContainerWriter(write_data)
328
access = _DirectPackAccess({})
329
access.set_writer(writer, index, (transport, packname))
330
return access, writer
332
def make_pack_file(self):
333
"""Create a pack file with 2 records."""
334
access, writer = self._get_access(packname='packname', index='foo')
336
memos.extend(access.add_raw_records([('key1', 10)], '1234567890'))
337
memos.extend(access.add_raw_records([('key2', 5)], '12345'))
341
def make_vf_for_retrying(self):
342
"""Create 3 packs and a reload function.
344
Originally, 2 pack files will have the data, but one will be missing.
345
And then the third will be used in place of the first two if reload()
348
:return: (versioned_file, reload_counter)
349
versioned_file a KnitVersionedFiles using the packs for access
351
builder = self.make_branch_builder('.', format="1.9")
352
builder.start_series()
353
builder.build_snapshot('rev-1', None, [
354
('add', ('', 'root-id', 'directory', None)),
355
('add', ('file', 'file-id', 'file', 'content\nrev 1\n')),
357
builder.build_snapshot('rev-2', ['rev-1'], [
358
('modify', ('file-id', 'content\nrev 2\n')),
360
builder.build_snapshot('rev-3', ['rev-2'], [
361
('modify', ('file-id', 'content\nrev 3\n')),
363
builder.finish_series()
364
b = builder.get_branch()
366
self.addCleanup(b.unlock)
367
# Pack these three revisions into another pack file, but don't remove
370
collection = repo._pack_collection
371
collection.ensure_loaded()
372
orig_packs = collection.packs
373
packer = pack_repo.Packer(collection, orig_packs, '.testpack')
374
new_pack = packer.pack()
375
# forget about the new pack
379
# Set up a reload() function that switches to using the new pack file
380
new_index = new_pack.revision_index
381
access_tuple = new_pack.access_tuple()
382
reload_counter = [0, 0, 0]
384
reload_counter[0] += 1
385
if reload_counter[1] > 0:
386
# We already reloaded, nothing more to do
387
reload_counter[2] += 1
389
reload_counter[1] += 1
390
vf._index._graph_index._indices[:] = [new_index]
391
vf._access._indices.clear()
392
vf._access._indices[new_index] = access_tuple
394
# Delete one of the pack files so the data will need to be reloaded. We
395
# will delete the file with 'rev-2' in it
396
trans, name = orig_packs[1].access_tuple()
398
# We don't have the index trigger reloading because we want to test
399
# that we reload when the .pack disappears
400
vf._access._reload_func = reload
401
return vf, reload_counter
403
def make_reload_func(self, return_val=True):
406
reload_called[0] += 1
408
return reload_called, reload
410
def make_retry_exception(self):
411
# We raise a real exception so that sys.exc_info() is properly
414
raise _TestException('foobar')
415
except _TestException, e:
416
retry_exc = errors.RetryWithNewPacks(None, reload_occurred=False,
417
exc_info=sys.exc_info())
420
def test_read_from_several_packs(self):
421
access, writer = self._get_access()
423
memos.extend(access.add_raw_records([('key', 10)], '1234567890'))
425
access, writer = self._get_access('pack2', 'FOOBAR')
426
memos.extend(access.add_raw_records([('key', 5)], '12345'))
428
access, writer = self._get_access('pack3', 'BAZ')
429
memos.extend(access.add_raw_records([('key', 5)], 'alpha'))
431
transport = self.get_transport()
432
access = _DirectPackAccess({"FOO":(transport, 'packfile'),
433
"FOOBAR":(transport, 'pack2'),
434
"BAZ":(transport, 'pack3')})
435
self.assertEqual(['1234567890', '12345', 'alpha'],
436
list(access.get_raw_records(memos)))
437
self.assertEqual(['1234567890'],
438
list(access.get_raw_records(memos[0:1])))
439
self.assertEqual(['12345'],
440
list(access.get_raw_records(memos[1:2])))
441
self.assertEqual(['alpha'],
442
list(access.get_raw_records(memos[2:3])))
443
self.assertEqual(['1234567890', 'alpha'],
444
list(access.get_raw_records(memos[0:1] + memos[2:3])))
446
def test_set_writer(self):
447
"""The writer should be settable post construction."""
448
access = _DirectPackAccess({})
449
transport = self.get_transport()
450
packname = 'packfile'
452
def write_data(bytes):
453
transport.append_bytes(packname, bytes)
454
writer = pack.ContainerWriter(write_data)
456
access.set_writer(writer, index, (transport, packname))
457
memos = access.add_raw_records([('key', 10)], '1234567890')
459
self.assertEqual(['1234567890'], list(access.get_raw_records(memos)))
461
def test_missing_index_raises_retry(self):
462
memos = self.make_pack_file()
463
transport = self.get_transport()
464
reload_called, reload_func = self.make_reload_func()
465
# Note that the index key has changed from 'foo' to 'bar'
466
access = _DirectPackAccess({'bar':(transport, 'packname')},
467
reload_func=reload_func)
468
e = self.assertListRaises(errors.RetryWithNewPacks,
469
access.get_raw_records, memos)
470
# Because a key was passed in which does not match our index list, we
471
# assume that the listing was already reloaded
472
self.assertTrue(e.reload_occurred)
473
self.assertIsInstance(e.exc_info, tuple)
474
self.assertIs(e.exc_info[0], KeyError)
475
self.assertIsInstance(e.exc_info[1], KeyError)
477
def test_missing_index_raises_key_error_with_no_reload(self):
478
memos = self.make_pack_file()
479
transport = self.get_transport()
480
# Note that the index key has changed from 'foo' to 'bar'
481
access = _DirectPackAccess({'bar':(transport, 'packname')})
482
e = self.assertListRaises(KeyError, access.get_raw_records, memos)
484
def test_missing_file_raises_retry(self):
485
memos = self.make_pack_file()
486
transport = self.get_transport()
487
reload_called, reload_func = self.make_reload_func()
488
# Note that the 'filename' has been changed to 'different-packname'
489
access = _DirectPackAccess({'foo':(transport, 'different-packname')},
490
reload_func=reload_func)
491
e = self.assertListRaises(errors.RetryWithNewPacks,
492
access.get_raw_records, memos)
493
# The file has gone missing, so we assume we need to reload
494
self.assertFalse(e.reload_occurred)
495
self.assertIsInstance(e.exc_info, tuple)
496
self.assertIs(e.exc_info[0], errors.NoSuchFile)
497
self.assertIsInstance(e.exc_info[1], errors.NoSuchFile)
498
self.assertEqual('different-packname', e.exc_info[1].path)
500
def test_missing_file_raises_no_such_file_with_no_reload(self):
501
memos = self.make_pack_file()
502
transport = self.get_transport()
503
# Note that the 'filename' has been changed to 'different-packname'
504
access = _DirectPackAccess({'foo':(transport, 'different-packname')})
505
e = self.assertListRaises(errors.NoSuchFile,
506
access.get_raw_records, memos)
508
def test_failing_readv_raises_retry(self):
509
memos = self.make_pack_file()
510
transport = self.get_transport()
511
failing_transport = MockReadvFailingTransport(
512
[transport.get_bytes('packname')])
513
reload_called, reload_func = self.make_reload_func()
514
access = _DirectPackAccess({'foo':(failing_transport, 'packname')},
515
reload_func=reload_func)
516
# Asking for a single record will not trigger the Mock failure
517
self.assertEqual(['1234567890'],
518
list(access.get_raw_records(memos[:1])))
519
self.assertEqual(['12345'],
520
list(access.get_raw_records(memos[1:2])))
521
# A multiple offset readv() will fail mid-way through
522
e = self.assertListRaises(errors.RetryWithNewPacks,
523
access.get_raw_records, memos)
524
# The file has gone missing, so we assume we need to reload
525
self.assertFalse(e.reload_occurred)
526
self.assertIsInstance(e.exc_info, tuple)
527
self.assertIs(e.exc_info[0], errors.NoSuchFile)
528
self.assertIsInstance(e.exc_info[1], errors.NoSuchFile)
529
self.assertEqual('packname', e.exc_info[1].path)
531
def test_failing_readv_raises_no_such_file_with_no_reload(self):
532
memos = self.make_pack_file()
533
transport = self.get_transport()
534
failing_transport = MockReadvFailingTransport(
535
[transport.get_bytes('packname')])
536
reload_called, reload_func = self.make_reload_func()
537
access = _DirectPackAccess({'foo':(failing_transport, 'packname')})
538
# Asking for a single record will not trigger the Mock failure
539
self.assertEqual(['1234567890'],
540
list(access.get_raw_records(memos[:1])))
541
self.assertEqual(['12345'],
542
list(access.get_raw_records(memos[1:2])))
543
# A multiple offset readv() will fail mid-way through
544
e = self.assertListRaises(errors.NoSuchFile,
545
access.get_raw_records, memos)
547
def test_reload_or_raise_no_reload(self):
548
access = _DirectPackAccess({}, reload_func=None)
549
retry_exc = self.make_retry_exception()
550
# Without a reload_func, we will just re-raise the original exception
551
self.assertRaises(_TestException, access.reload_or_raise, retry_exc)
553
def test_reload_or_raise_reload_changed(self):
554
reload_called, reload_func = self.make_reload_func(return_val=True)
555
access = _DirectPackAccess({}, reload_func=reload_func)
556
retry_exc = self.make_retry_exception()
557
access.reload_or_raise(retry_exc)
558
self.assertEqual([1], reload_called)
559
retry_exc.reload_occurred=True
560
access.reload_or_raise(retry_exc)
561
self.assertEqual([2], reload_called)
563
def test_reload_or_raise_reload_no_change(self):
564
reload_called, reload_func = self.make_reload_func(return_val=False)
565
access = _DirectPackAccess({}, reload_func=reload_func)
566
retry_exc = self.make_retry_exception()
567
# If reload_occurred is False, then we consider it an error to have
568
# reload_func() return False (no changes).
569
self.assertRaises(_TestException, access.reload_or_raise, retry_exc)
570
self.assertEqual([1], reload_called)
571
retry_exc.reload_occurred=True
572
# If reload_occurred is True, then we assume nothing changed because
573
# it had changed earlier, but didn't change again
574
access.reload_or_raise(retry_exc)
575
self.assertEqual([2], reload_called)
577
def test_annotate_retries(self):
578
vf, reload_counter = self.make_vf_for_retrying()
579
# It is a little bit bogus to annotate the Revision VF, but it works,
580
# as we have ancestry stored there
582
reload_lines = vf.annotate(key)
583
self.assertEqual([1, 1, 0], reload_counter)
584
plain_lines = vf.annotate(key)
585
self.assertEqual([1, 1, 0], reload_counter) # No extra reloading
586
if reload_lines != plain_lines:
587
self.fail('Annotation was not identical with reloading.')
588
# Now delete the packs-in-use, which should trigger another reload, but
589
# this time we just raise an exception because we can't recover
590
for trans, name in vf._access._indices.itervalues():
592
self.assertRaises(errors.NoSuchFile, vf.annotate, key)
593
self.assertEqual([2, 1, 1], reload_counter)
595
def test__get_record_map_retries(self):
596
vf, reload_counter = self.make_vf_for_retrying()
597
keys = [('rev-1',), ('rev-2',), ('rev-3',)]
598
records = vf._get_record_map(keys)
599
self.assertEqual(keys, sorted(records.keys()))
600
self.assertEqual([1, 1, 0], reload_counter)
601
# Now delete the packs-in-use, which should trigger another reload, but
602
# this time we just raise an exception because we can't recover
603
for trans, name in vf._access._indices.itervalues():
605
self.assertRaises(errors.NoSuchFile, vf._get_record_map, keys)
606
self.assertEqual([2, 1, 1], reload_counter)
608
def test_get_record_stream_retries(self):
609
vf, reload_counter = self.make_vf_for_retrying()
610
keys = [('rev-1',), ('rev-2',), ('rev-3',)]
611
record_stream = vf.get_record_stream(keys, 'topological', False)
612
record = record_stream.next()
613
self.assertEqual(('rev-1',), record.key)
614
self.assertEqual([0, 0, 0], reload_counter)
615
record = record_stream.next()
616
self.assertEqual(('rev-2',), record.key)
617
self.assertEqual([1, 1, 0], reload_counter)
618
record = record_stream.next()
619
self.assertEqual(('rev-3',), record.key)
620
self.assertEqual([1, 1, 0], reload_counter)
621
# Now delete all pack files, and see that we raise the right error
622
for trans, name in vf._access._indices.itervalues():
624
self.assertListRaises(errors.NoSuchFile,
625
vf.get_record_stream, keys, 'topological', False)
627
def test_iter_lines_added_or_present_in_keys_retries(self):
628
vf, reload_counter = self.make_vf_for_retrying()
629
keys = [('rev-1',), ('rev-2',), ('rev-3',)]
630
# Unfortunately, iter_lines_added_or_present_in_keys iterates the
631
# result in random order (determined by the iteration order from a
632
# set()), so we don't have any solid way to trigger whether data is
633
# read before or after. However we tried to delete the middle node to
634
# exercise the code well.
635
# What we care about is that all lines are always yielded, but not
638
reload_lines = sorted(vf.iter_lines_added_or_present_in_keys(keys))
639
self.assertEqual([1, 1, 0], reload_counter)
640
# Now do it again, to make sure the result is equivalent
641
plain_lines = sorted(vf.iter_lines_added_or_present_in_keys(keys))
642
self.assertEqual([1, 1, 0], reload_counter) # No extra reloading
643
self.assertEqual(plain_lines, reload_lines)
644
self.assertEqual(21, len(plain_lines))
645
# Now delete all pack files, and see that we raise the right error
646
for trans, name in vf._access._indices.itervalues():
648
self.assertListRaises(errors.NoSuchFile,
649
vf.iter_lines_added_or_present_in_keys, keys)
650
self.assertEqual([2, 1, 1], reload_counter)
652
def test_get_record_stream_yields_disk_sorted_order(self):
653
# if we get 'unordered' pick a semi-optimal order for reading. The
654
# order should be grouped by pack file, and then by position in file
655
repo = self.make_repository('test', format='pack-0.92')
657
self.addCleanup(repo.unlock)
658
repo.start_write_group()
660
vf.add_lines(('f-id', 'rev-5'), [('f-id', 'rev-4')], ['lines\n'])
661
vf.add_lines(('f-id', 'rev-1'), [], ['lines\n'])
662
vf.add_lines(('f-id', 'rev-2'), [('f-id', 'rev-1')], ['lines\n'])
663
repo.commit_write_group()
664
# We inserted them as rev-5, rev-1, rev-2, we should get them back in
666
stream = vf.get_record_stream([('f-id', 'rev-1'), ('f-id', 'rev-5'),
667
('f-id', 'rev-2')], 'unordered', False)
668
keys = [r.key for r in stream]
669
self.assertEqual([('f-id', 'rev-5'), ('f-id', 'rev-1'),
670
('f-id', 'rev-2')], keys)
671
repo.start_write_group()
672
vf.add_lines(('f-id', 'rev-4'), [('f-id', 'rev-3')], ['lines\n'])
673
vf.add_lines(('f-id', 'rev-3'), [('f-id', 'rev-2')], ['lines\n'])
674
vf.add_lines(('f-id', 'rev-6'), [('f-id', 'rev-5')], ['lines\n'])
675
repo.commit_write_group()
676
# Request in random order, to make sure the output order isn't based on
678
request_keys = set(('f-id', 'rev-%d' % i) for i in range(1, 7))
679
stream = vf.get_record_stream(request_keys, 'unordered', False)
680
keys = [r.key for r in stream]
681
# We want to get the keys back in disk order, but it doesn't matter
682
# which pack we read from first. So this can come back in 2 orders
683
alt1 = [('f-id', 'rev-%d' % i) for i in [4, 3, 6, 5, 1, 2]]
684
alt2 = [('f-id', 'rev-%d' % i) for i in [5, 1, 2, 4, 3, 6]]
685
if keys != alt1 and keys != alt2:
686
self.fail('Returned key order did not match either expected order.'
687
' expected %s or %s, not %s'
688
% (alt1, alt2, keys))
691
class LowLevelKnitDataTests(TestCase):
693
def create_gz_content(self, text):
695
gz_file = tuned_gzip.GzipFile(mode='wb', fileobj=sio)
698
return sio.getvalue()
700
def make_multiple_records(self):
701
"""Create the content for multiple records."""
702
sha1sum = osutils.sha('foo\nbar\n').hexdigest()
704
gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
709
record_1 = (0, len(gz_txt), sha1sum)
710
total_txt.append(gz_txt)
711
sha1sum = osutils.sha('baz\n').hexdigest()
712
gz_txt = self.create_gz_content('version rev-id-2 1 %s\n'
716
record_2 = (record_1[1], len(gz_txt), sha1sum)
717
total_txt.append(gz_txt)
718
return total_txt, record_1, record_2
720
def test_valid_knit_data(self):
721
sha1sum = osutils.sha('foo\nbar\n').hexdigest()
722
gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
727
transport = MockTransport([gz_txt])
728
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
729
knit = KnitVersionedFiles(None, access)
730
records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
732
contents = list(knit._read_records_iter(records))
733
self.assertEqual([(('rev-id-1',), ['foo\n', 'bar\n'],
734
'4e48e2c9a3d2ca8a708cb0cc545700544efb5021')], contents)
736
raw_contents = list(knit._read_records_iter_raw(records))
737
self.assertEqual([(('rev-id-1',), gz_txt, sha1sum)], raw_contents)
739
def test_multiple_records_valid(self):
740
total_txt, record_1, record_2 = self.make_multiple_records()
741
transport = MockTransport([''.join(total_txt)])
742
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
743
knit = KnitVersionedFiles(None, access)
744
records = [(('rev-id-1',), (('rev-id-1',), record_1[0], record_1[1])),
745
(('rev-id-2',), (('rev-id-2',), record_2[0], record_2[1]))]
747
contents = list(knit._read_records_iter(records))
748
self.assertEqual([(('rev-id-1',), ['foo\n', 'bar\n'], record_1[2]),
749
(('rev-id-2',), ['baz\n'], record_2[2])],
752
raw_contents = list(knit._read_records_iter_raw(records))
753
self.assertEqual([(('rev-id-1',), total_txt[0], record_1[2]),
754
(('rev-id-2',), total_txt[1], record_2[2])],
757
def test_not_enough_lines(self):
758
sha1sum = osutils.sha('foo\n').hexdigest()
759
# record says 2 lines data says 1
760
gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
764
transport = MockTransport([gz_txt])
765
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
766
knit = KnitVersionedFiles(None, access)
767
records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
768
self.assertRaises(errors.KnitCorrupt, list,
769
knit._read_records_iter(records))
771
# read_records_iter_raw won't detect that sort of mismatch/corruption
772
raw_contents = list(knit._read_records_iter_raw(records))
773
self.assertEqual([(('rev-id-1',), gz_txt, sha1sum)], raw_contents)
775
def test_too_many_lines(self):
776
sha1sum = osutils.sha('foo\nbar\n').hexdigest()
777
# record says 1 lines data says 2
778
gz_txt = self.create_gz_content('version rev-id-1 1 %s\n'
783
transport = MockTransport([gz_txt])
784
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
785
knit = KnitVersionedFiles(None, access)
786
records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
787
self.assertRaises(errors.KnitCorrupt, list,
788
knit._read_records_iter(records))
790
# read_records_iter_raw won't detect that sort of mismatch/corruption
791
raw_contents = list(knit._read_records_iter_raw(records))
792
self.assertEqual([(('rev-id-1',), gz_txt, sha1sum)], raw_contents)
794
def test_mismatched_version_id(self):
795
sha1sum = osutils.sha('foo\nbar\n').hexdigest()
796
gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
801
transport = MockTransport([gz_txt])
802
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
803
knit = KnitVersionedFiles(None, access)
804
# We are asking for rev-id-2, but the data is rev-id-1
805
records = [(('rev-id-2',), (('rev-id-2',), 0, len(gz_txt)))]
806
self.assertRaises(errors.KnitCorrupt, list,
807
knit._read_records_iter(records))
809
# read_records_iter_raw detects mismatches in the header
810
self.assertRaises(errors.KnitCorrupt, list,
811
knit._read_records_iter_raw(records))
813
def test_uncompressed_data(self):
814
sha1sum = osutils.sha('foo\nbar\n').hexdigest()
815
txt = ('version rev-id-1 2 %s\n'
820
transport = MockTransport([txt])
821
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
822
knit = KnitVersionedFiles(None, access)
823
records = [(('rev-id-1',), (('rev-id-1',), 0, len(txt)))]
825
# We don't have valid gzip data ==> corrupt
826
self.assertRaises(errors.KnitCorrupt, list,
827
knit._read_records_iter(records))
829
# read_records_iter_raw will notice the bad data
830
self.assertRaises(errors.KnitCorrupt, list,
831
knit._read_records_iter_raw(records))
833
def test_corrupted_data(self):
834
sha1sum = osutils.sha('foo\nbar\n').hexdigest()
835
gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
840
# Change 2 bytes in the middle to \xff
841
gz_txt = gz_txt[:10] + '\xff\xff' + gz_txt[12:]
842
transport = MockTransport([gz_txt])
843
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
844
knit = KnitVersionedFiles(None, access)
845
records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
846
self.assertRaises(errors.KnitCorrupt, list,
847
knit._read_records_iter(records))
848
# read_records_iter_raw will barf on bad gz data
849
self.assertRaises(errors.KnitCorrupt, list,
850
knit._read_records_iter_raw(records))
853
class LowLevelKnitIndexTests(TestCase):
855
def get_knit_index(self, transport, name, mode):
856
mapper = ConstantMapper(name)
857
from bzrlib._knit_load_data_py import _load_data_py
858
self.overrideAttr(knit, '_load_data', _load_data_py)
859
allow_writes = lambda: 'w' in mode
860
return _KndxIndex(transport, mapper, lambda:None, allow_writes, lambda:True)
862
def test_create_file(self):
863
transport = MockTransport()
864
index = self.get_knit_index(transport, "filename", "w")
866
call = transport.calls.pop(0)
867
# call[1][1] is a StringIO - we can't test it by simple equality.
868
self.assertEqual('put_file_non_atomic', call[0])
869
self.assertEqual('filename.kndx', call[1][0])
870
# With no history, _KndxIndex writes a new index:
871
self.assertEqual(_KndxIndex.HEADER,
872
call[1][1].getvalue())
873
self.assertEqual({'create_parent_dir': True}, call[2])
875
def test_read_utf8_version_id(self):
876
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
877
utf8_revision_id = unicode_revision_id.encode('utf-8')
878
transport = MockTransport([
880
'%s option 0 1 :' % (utf8_revision_id,)
882
index = self.get_knit_index(transport, "filename", "r")
883
# _KndxIndex is a private class, and deals in utf8 revision_ids, not
884
# Unicode revision_ids.
885
self.assertEqual({(utf8_revision_id,):()},
886
index.get_parent_map(index.keys()))
887
self.assertFalse((unicode_revision_id,) in index.keys())
889
def test_read_utf8_parents(self):
890
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
891
utf8_revision_id = unicode_revision_id.encode('utf-8')
892
transport = MockTransport([
894
"version option 0 1 .%s :" % (utf8_revision_id,)
896
index = self.get_knit_index(transport, "filename", "r")
897
self.assertEqual({("version",):((utf8_revision_id,),)},
898
index.get_parent_map(index.keys()))
900
def test_read_ignore_corrupted_lines(self):
901
transport = MockTransport([
904
"corrupted options 0 1 .b .c ",
905
"version options 0 1 :"
907
index = self.get_knit_index(transport, "filename", "r")
908
self.assertEqual(1, len(index.keys()))
909
self.assertEqual(set([("version",)]), index.keys())
911
def test_read_corrupted_header(self):
912
transport = MockTransport(['not a bzr knit index header\n'])
913
index = self.get_knit_index(transport, "filename", "r")
914
self.assertRaises(KnitHeaderError, index.keys)
916
def test_read_duplicate_entries(self):
917
transport = MockTransport([
919
"parent options 0 1 :",
920
"version options1 0 1 0 :",
921
"version options2 1 2 .other :",
922
"version options3 3 4 0 .other :"
924
index = self.get_knit_index(transport, "filename", "r")
925
self.assertEqual(2, len(index.keys()))
926
# check that the index used is the first one written. (Specific
927
# to KnitIndex style indices.
928
self.assertEqual("1", index._dictionary_compress([("version",)]))
929
self.assertEqual((("version",), 3, 4), index.get_position(("version",)))
930
self.assertEqual(["options3"], index.get_options(("version",)))
931
self.assertEqual({("version",):(("parent",), ("other",))},
932
index.get_parent_map([("version",)]))
934
def test_read_compressed_parents(self):
935
transport = MockTransport([
939
"c option 0 1 1 0 :",
941
index = self.get_knit_index(transport, "filename", "r")
942
self.assertEqual({("b",):(("a",),), ("c",):(("b",), ("a",))},
943
index.get_parent_map([("b",), ("c",)]))
945
def test_write_utf8_version_id(self):
946
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
947
utf8_revision_id = unicode_revision_id.encode('utf-8')
948
transport = MockTransport([
951
index = self.get_knit_index(transport, "filename", "r")
953
((utf8_revision_id,), ["option"], ((utf8_revision_id,), 0, 1), [])])
954
call = transport.calls.pop(0)
955
# call[1][1] is a StringIO - we can't test it by simple equality.
956
self.assertEqual('put_file_non_atomic', call[0])
957
self.assertEqual('filename.kndx', call[1][0])
958
# With no history, _KndxIndex writes a new index:
959
self.assertEqual(_KndxIndex.HEADER +
960
"\n%s option 0 1 :" % (utf8_revision_id,),
961
call[1][1].getvalue())
962
self.assertEqual({'create_parent_dir': True}, call[2])
964
def test_write_utf8_parents(self):
965
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
966
utf8_revision_id = unicode_revision_id.encode('utf-8')
967
transport = MockTransport([
970
index = self.get_knit_index(transport, "filename", "r")
972
(("version",), ["option"], (("version",), 0, 1), [(utf8_revision_id,)])])
973
call = transport.calls.pop(0)
974
# call[1][1] is a StringIO - we can't test it by simple equality.
975
self.assertEqual('put_file_non_atomic', call[0])
976
self.assertEqual('filename.kndx', call[1][0])
977
# With no history, _KndxIndex writes a new index:
978
self.assertEqual(_KndxIndex.HEADER +
979
"\nversion option 0 1 .%s :" % (utf8_revision_id,),
980
call[1][1].getvalue())
981
self.assertEqual({'create_parent_dir': True}, call[2])
984
transport = MockTransport([
987
index = self.get_knit_index(transport, "filename", "r")
989
self.assertEqual(set(), index.keys())
991
index.add_records([(("a",), ["option"], (("a",), 0, 1), [])])
992
self.assertEqual(set([("a",)]), index.keys())
994
index.add_records([(("a",), ["option"], (("a",), 0, 1), [])])
995
self.assertEqual(set([("a",)]), index.keys())
997
index.add_records([(("b",), ["option"], (("b",), 0, 1), [])])
998
self.assertEqual(set([("a",), ("b",)]), index.keys())
1000
def add_a_b(self, index, random_id=None):
1002
if random_id is not None:
1003
kwargs["random_id"] = random_id
1005
(("a",), ["option"], (("a",), 0, 1), [("b",)]),
1006
(("a",), ["opt"], (("a",), 1, 2), [("c",)]),
1007
(("b",), ["option"], (("b",), 2, 3), [("a",)])
1010
def assertIndexIsAB(self, index):
1015
index.get_parent_map(index.keys()))
1016
self.assertEqual((("a",), 1, 2), index.get_position(("a",)))
1017
self.assertEqual((("b",), 2, 3), index.get_position(("b",)))
1018
self.assertEqual(["opt"], index.get_options(("a",)))
1020
def test_add_versions(self):
1021
transport = MockTransport([
1024
index = self.get_knit_index(transport, "filename", "r")
1027
call = transport.calls.pop(0)
1028
# call[1][1] is a StringIO - we can't test it by simple equality.
1029
self.assertEqual('put_file_non_atomic', call[0])
1030
self.assertEqual('filename.kndx', call[1][0])
1031
# With no history, _KndxIndex writes a new index:
1034
"\na option 0 1 .b :"
1036
"\nb option 2 3 0 :",
1037
call[1][1].getvalue())
1038
self.assertEqual({'create_parent_dir': True}, call[2])
1039
self.assertIndexIsAB(index)
1041
def test_add_versions_random_id_is_accepted(self):
1042
transport = MockTransport([
1045
index = self.get_knit_index(transport, "filename", "r")
1046
self.add_a_b(index, random_id=True)
1048
def test_delay_create_and_add_versions(self):
1049
transport = MockTransport()
1051
index = self.get_knit_index(transport, "filename", "w")
1053
self.assertEqual([], transport.calls)
1056
#[ {"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
1058
# Two calls: one during which we load the existing index (and when its
1059
# missing create it), then a second where we write the contents out.
1060
self.assertEqual(2, len(transport.calls))
1061
call = transport.calls.pop(0)
1062
self.assertEqual('put_file_non_atomic', call[0])
1063
self.assertEqual('filename.kndx', call[1][0])
1064
# With no history, _KndxIndex writes a new index:
1065
self.assertEqual(_KndxIndex.HEADER, call[1][1].getvalue())
1066
self.assertEqual({'create_parent_dir': True}, call[2])
1067
call = transport.calls.pop(0)
1068
# call[1][1] is a StringIO - we can't test it by simple equality.
1069
self.assertEqual('put_file_non_atomic', call[0])
1070
self.assertEqual('filename.kndx', call[1][0])
1071
# With no history, _KndxIndex writes a new index:
1074
"\na option 0 1 .b :"
1076
"\nb option 2 3 0 :",
1077
call[1][1].getvalue())
1078
self.assertEqual({'create_parent_dir': True}, call[2])
1080
def assertTotalBuildSize(self, size, keys, positions):
1081
self.assertEqual(size,
1082
knit._get_total_build_size(None, keys, positions))
1084
def test__get_total_build_size(self):
1086
('a',): (('fulltext', False), (('a',), 0, 100), None),
1087
('b',): (('line-delta', False), (('b',), 100, 21), ('a',)),
1088
('c',): (('line-delta', False), (('c',), 121, 35), ('b',)),
1089
('d',): (('line-delta', False), (('d',), 156, 12), ('b',)),
1091
self.assertTotalBuildSize(100, [('a',)], positions)
1092
self.assertTotalBuildSize(121, [('b',)], positions)
1093
# c needs both a & b
1094
self.assertTotalBuildSize(156, [('c',)], positions)
1095
# we shouldn't count 'b' twice
1096
self.assertTotalBuildSize(156, [('b',), ('c',)], positions)
1097
self.assertTotalBuildSize(133, [('d',)], positions)
1098
self.assertTotalBuildSize(168, [('c',), ('d',)], positions)
1100
def test_get_position(self):
1101
transport = MockTransport([
1106
index = self.get_knit_index(transport, "filename", "r")
1108
self.assertEqual((("a",), 0, 1), index.get_position(("a",)))
1109
self.assertEqual((("b",), 1, 2), index.get_position(("b",)))
1111
def test_get_method(self):
1112
transport = MockTransport([
1114
"a fulltext,unknown 0 1 :",
1115
"b unknown,line-delta 1 2 :",
1118
index = self.get_knit_index(transport, "filename", "r")
1120
self.assertEqual("fulltext", index.get_method("a"))
1121
self.assertEqual("line-delta", index.get_method("b"))
1122
self.assertRaises(errors.KnitIndexUnknownMethod, index.get_method, "c")
1124
def test_get_options(self):
1125
transport = MockTransport([
1130
index = self.get_knit_index(transport, "filename", "r")
1132
self.assertEqual(["opt1"], index.get_options("a"))
1133
self.assertEqual(["opt2", "opt3"], index.get_options("b"))
1135
def test_get_parent_map(self):
1136
transport = MockTransport([
1139
"b option 1 2 0 .c :",
1140
"c option 1 2 1 0 .e :"
1142
index = self.get_knit_index(transport, "filename", "r")
1146
("b",):(("a",), ("c",)),
1147
("c",):(("b",), ("a",), ("e",)),
1148
}, index.get_parent_map(index.keys()))
1150
def test_impossible_parent(self):
1151
"""Test we get KnitCorrupt if the parent couldn't possibly exist."""
1152
transport = MockTransport([
1155
"b option 0 1 4 :" # We don't have a 4th record
1157
index = self.get_knit_index(transport, 'filename', 'r')
1159
self.assertRaises(errors.KnitCorrupt, index.keys)
1160
except TypeError, e:
1161
if (str(e) == ('exceptions must be strings, classes, or instances,'
1162
' not exceptions.IndexError')
1163
and sys.version_info[0:2] >= (2,5)):
1164
self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1165
' raising new style exceptions with python'
1170
def test_corrupted_parent(self):
1171
transport = MockTransport([
1175
"c option 0 1 1v :", # Can't have a parent of '1v'
1177
index = self.get_knit_index(transport, 'filename', 'r')
1179
self.assertRaises(errors.KnitCorrupt, index.keys)
1180
except TypeError, e:
1181
if (str(e) == ('exceptions must be strings, classes, or instances,'
1182
' not exceptions.ValueError')
1183
and sys.version_info[0:2] >= (2,5)):
1184
self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1185
' raising new style exceptions with python'
1190
def test_corrupted_parent_in_list(self):
1191
transport = MockTransport([
1195
"c option 0 1 1 v :", # Can't have a parent of 'v'
1197
index = self.get_knit_index(transport, 'filename', 'r')
1199
self.assertRaises(errors.KnitCorrupt, index.keys)
1200
except TypeError, e:
1201
if (str(e) == ('exceptions must be strings, classes, or instances,'
1202
' not exceptions.ValueError')
1203
and sys.version_info[0:2] >= (2,5)):
1204
self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1205
' raising new style exceptions with python'
1210
def test_invalid_position(self):
1211
transport = MockTransport([
1215
index = self.get_knit_index(transport, 'filename', 'r')
1217
self.assertRaises(errors.KnitCorrupt, index.keys)
1218
except TypeError, e:
1219
if (str(e) == ('exceptions must be strings, classes, or instances,'
1220
' not exceptions.ValueError')
1221
and sys.version_info[0:2] >= (2,5)):
1222
self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1223
' raising new style exceptions with python'
1228
def test_invalid_size(self):
1229
transport = MockTransport([
1233
index = self.get_knit_index(transport, 'filename', 'r')
1235
self.assertRaises(errors.KnitCorrupt, index.keys)
1236
except TypeError, e:
1237
if (str(e) == ('exceptions must be strings, classes, or instances,'
1238
' not exceptions.ValueError')
1239
and sys.version_info[0:2] >= (2,5)):
1240
self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1241
' raising new style exceptions with python'
1246
def test_scan_unvalidated_index_not_implemented(self):
1247
transport = MockTransport()
1248
index = self.get_knit_index(transport, 'filename', 'r')
1250
NotImplementedError, index.scan_unvalidated_index,
1251
'dummy graph_index')
1253
NotImplementedError, index.get_missing_compression_parents)
1255
def test_short_line(self):
1256
transport = MockTransport([
1259
"b option 10 10 0", # This line isn't terminated, ignored
1261
index = self.get_knit_index(transport, "filename", "r")
1262
self.assertEqual(set([('a',)]), index.keys())
1264
def test_skip_incomplete_record(self):
1265
# A line with bogus data should just be skipped
1266
transport = MockTransport([
1269
"b option 10 10 0", # This line isn't terminated, ignored
1270
"c option 20 10 0 :", # Properly terminated, and starts with '\n'
1272
index = self.get_knit_index(transport, "filename", "r")
1273
self.assertEqual(set([('a',), ('c',)]), index.keys())
1275
def test_trailing_characters(self):
1276
# A line with bogus data should just be skipped
1277
transport = MockTransport([
1280
"b option 10 10 0 :a", # This line has extra trailing characters
1281
"c option 20 10 0 :", # Properly terminated, and starts with '\n'
1283
index = self.get_knit_index(transport, "filename", "r")
1284
self.assertEqual(set([('a',), ('c',)]), index.keys())
1287
class LowLevelKnitIndexTests_c(LowLevelKnitIndexTests):
1289
_test_needs_features = [compiled_knit_feature]
1291
def get_knit_index(self, transport, name, mode):
1292
mapper = ConstantMapper(name)
1293
from bzrlib._knit_load_data_pyx import _load_data_c
1294
self.overrideAttr(knit, '_load_data', _load_data_c)
1295
allow_writes = lambda: mode == 'w'
1296
return _KndxIndex(transport, mapper, lambda:None,
1297
allow_writes, lambda:True)
1300
class Test_KnitAnnotator(TestCaseWithMemoryTransport):
1302
def make_annotator(self):
1303
factory = knit.make_pack_factory(True, True, 1)
1304
vf = factory(self.get_transport())
1305
return knit._KnitAnnotator(vf)
1307
def test__expand_fulltext(self):
1308
ann = self.make_annotator()
1309
rev_key = ('rev-id',)
1310
ann._num_compression_children[rev_key] = 1
1311
res = ann._expand_record(rev_key, (('parent-id',),), None,
1312
['line1\n', 'line2\n'], ('fulltext', True))
1313
# The content object and text lines should be cached appropriately
1314
self.assertEqual(['line1\n', 'line2'], res)
1315
content_obj = ann._content_objects[rev_key]
1316
self.assertEqual(['line1\n', 'line2\n'], content_obj._lines)
1317
self.assertEqual(res, content_obj.text())
1318
self.assertEqual(res, ann._text_cache[rev_key])
1320
def test__expand_delta_comp_parent_not_available(self):
1321
# Parent isn't available yet, so we return nothing, but queue up this
1322
# node for later processing
1323
ann = self.make_annotator()
1324
rev_key = ('rev-id',)
1325
parent_key = ('parent-id',)
1326
record = ['0,1,1\n', 'new-line\n']
1327
details = ('line-delta', False)
1328
res = ann._expand_record(rev_key, (parent_key,), parent_key,
1330
self.assertEqual(None, res)
1331
self.assertTrue(parent_key in ann._pending_deltas)
1332
pending = ann._pending_deltas[parent_key]
1333
self.assertEqual(1, len(pending))
1334
self.assertEqual((rev_key, (parent_key,), record, details), pending[0])
1336
def test__expand_record_tracks_num_children(self):
1337
ann = self.make_annotator()
1338
rev_key = ('rev-id',)
1339
rev2_key = ('rev2-id',)
1340
parent_key = ('parent-id',)
1341
record = ['0,1,1\n', 'new-line\n']
1342
details = ('line-delta', False)
1343
ann._num_compression_children[parent_key] = 2
1344
ann._expand_record(parent_key, (), None, ['line1\n', 'line2\n'],
1345
('fulltext', False))
1346
res = ann._expand_record(rev_key, (parent_key,), parent_key,
1348
self.assertEqual({parent_key: 1}, ann._num_compression_children)
1349
# Expanding the second child should remove the content object, and the
1350
# num_compression_children entry
1351
res = ann._expand_record(rev2_key, (parent_key,), parent_key,
1353
self.assertFalse(parent_key in ann._content_objects)
1354
self.assertEqual({}, ann._num_compression_children)
1355
# We should not cache the content_objects for rev2 and rev, because
1356
# they do not have compression children of their own.
1357
self.assertEqual({}, ann._content_objects)
1359
def test__expand_delta_records_blocks(self):
1360
ann = self.make_annotator()
1361
rev_key = ('rev-id',)
1362
parent_key = ('parent-id',)
1363
record = ['0,1,1\n', 'new-line\n']
1364
details = ('line-delta', True)
1365
ann._num_compression_children[parent_key] = 2
1366
ann._expand_record(parent_key, (), None,
1367
['line1\n', 'line2\n', 'line3\n'],
1368
('fulltext', False))
1369
ann._expand_record(rev_key, (parent_key,), parent_key, record, details)
1370
self.assertEqual({(rev_key, parent_key): [(1, 1, 1), (3, 3, 0)]},
1371
ann._matching_blocks)
1372
rev2_key = ('rev2-id',)
1373
record = ['0,1,1\n', 'new-line\n']
1374
details = ('line-delta', False)
1375
ann._expand_record(rev2_key, (parent_key,), parent_key, record, details)
1376
self.assertEqual([(1, 1, 2), (3, 3, 0)],
1377
ann._matching_blocks[(rev2_key, parent_key)])
1379
def test__get_parent_ann_uses_matching_blocks(self):
1380
ann = self.make_annotator()
1381
rev_key = ('rev-id',)
1382
parent_key = ('parent-id',)
1383
parent_ann = [(parent_key,)]*3
1384
block_key = (rev_key, parent_key)
1385
ann._annotations_cache[parent_key] = parent_ann
1386
ann._matching_blocks[block_key] = [(0, 1, 1), (3, 3, 0)]
1387
# We should not try to access any parent_lines content, because we know
1388
# we already have the matching blocks
1389
par_ann, blocks = ann._get_parent_annotations_and_matches(rev_key,
1390
['1\n', '2\n', '3\n'], parent_key)
1391
self.assertEqual(parent_ann, par_ann)
1392
self.assertEqual([(0, 1, 1), (3, 3, 0)], blocks)
1393
self.assertEqual({}, ann._matching_blocks)
1395
def test__process_pending(self):
1396
ann = self.make_annotator()
1397
rev_key = ('rev-id',)
1400
record = ['0,1,1\n', 'new-line\n']
1401
details = ('line-delta', False)
1402
p1_record = ['line1\n', 'line2\n']
1403
ann._num_compression_children[p1_key] = 1
1404
res = ann._expand_record(rev_key, (p1_key,p2_key), p1_key,
1406
self.assertEqual(None, res)
1407
# self.assertTrue(p1_key in ann._pending_deltas)
1408
self.assertEqual({}, ann._pending_annotation)
1409
# Now insert p1, and we should be able to expand the delta
1410
res = ann._expand_record(p1_key, (), None, p1_record,
1411
('fulltext', False))
1412
self.assertEqual(p1_record, res)
1413
ann._annotations_cache[p1_key] = [(p1_key,)]*2
1414
res = ann._process_pending(p1_key)
1415
self.assertEqual([], res)
1416
self.assertFalse(p1_key in ann._pending_deltas)
1417
self.assertTrue(p2_key in ann._pending_annotation)
1418
self.assertEqual({p2_key: [(rev_key, (p1_key, p2_key))]},
1419
ann._pending_annotation)
1420
# Now fill in parent 2, and pending annotation should be satisfied
1421
res = ann._expand_record(p2_key, (), None, [], ('fulltext', False))
1422
ann._annotations_cache[p2_key] = []
1423
res = ann._process_pending(p2_key)
1424
self.assertEqual([rev_key], res)
1425
self.assertEqual({}, ann._pending_annotation)
1426
self.assertEqual({}, ann._pending_deltas)
1428
def test_record_delta_removes_basis(self):
1429
ann = self.make_annotator()
1430
ann._expand_record(('parent-id',), (), None,
1431
['line1\n', 'line2\n'], ('fulltext', False))
1432
ann._num_compression_children['parent-id'] = 2
1434
def test_annotate_special_text(self):
1435
ann = self.make_annotator()
1437
rev1_key = ('rev-1',)
1438
rev2_key = ('rev-2',)
1439
rev3_key = ('rev-3',)
1440
spec_key = ('special:',)
1441
vf.add_lines(rev1_key, [], ['initial content\n'])
1442
vf.add_lines(rev2_key, [rev1_key], ['initial content\n',
1445
vf.add_lines(rev3_key, [rev1_key], ['initial content\n',
1448
spec_text = ('initial content\n'
1452
ann.add_special_text(spec_key, [rev2_key, rev3_key], spec_text)
1453
anns, lines = ann.annotate(spec_key)
1454
self.assertEqual([(rev1_key,),
1455
(rev2_key, rev3_key),
1459
self.assertEqualDiff(spec_text, ''.join(lines))
1462
class KnitTests(TestCaseWithTransport):
1463
"""Class containing knit test helper routines."""
1465
def make_test_knit(self, annotate=False, name='test'):
1466
mapper = ConstantMapper(name)
1467
return make_file_factory(annotate, mapper)(self.get_transport())
1470
class TestBadShaError(KnitTests):
1471
"""Tests for handling of sha errors."""
1473
def test_sha_exception_has_text(self):
1474
# having the failed text included in the error allows for recovery.
1475
source = self.make_test_knit()
1476
target = self.make_test_knit(name="target")
1477
if not source._max_delta_chain:
1478
raise TestNotApplicable(
1479
"cannot get delta-caused sha failures without deltas.")
1482
broken = ('broken',)
1483
source.add_lines(basis, (), ['foo\n'])
1484
source.add_lines(broken, (basis,), ['foo\n', 'bar\n'])
1485
# Seed target with a bad basis text
1486
target.add_lines(basis, (), ['gam\n'])
1487
target.insert_record_stream(
1488
source.get_record_stream([broken], 'unordered', False))
1489
err = self.assertRaises(errors.KnitCorrupt,
1490
target.get_record_stream([broken], 'unordered', True
1491
).next().get_bytes_as, 'chunked')
1492
self.assertEqual(['gam\n', 'bar\n'], err.content)
1493
# Test for formatting with live data
1494
self.assertStartsWith(str(err), "Knit ")
1497
class TestKnitIndex(KnitTests):
1499
def test_add_versions_dictionary_compresses(self):
1500
"""Adding versions to the index should update the lookup dict"""
1501
knit = self.make_test_knit()
1503
idx.add_records([(('a-1',), ['fulltext'], (('a-1',), 0, 0), [])])
1504
self.check_file_contents('test.kndx',
1505
'# bzr knit index 8\n'
1507
'a-1 fulltext 0 0 :'
1510
(('a-2',), ['fulltext'], (('a-2',), 0, 0), [('a-1',)]),
1511
(('a-3',), ['fulltext'], (('a-3',), 0, 0), [('a-2',)]),
1513
self.check_file_contents('test.kndx',
1514
'# bzr knit index 8\n'
1516
'a-1 fulltext 0 0 :\n'
1517
'a-2 fulltext 0 0 0 :\n'
1518
'a-3 fulltext 0 0 1 :'
1520
self.assertEqual(set([('a-3',), ('a-1',), ('a-2',)]), idx.keys())
1522
('a-1',): ((('a-1',), 0, 0), None, (), ('fulltext', False)),
1523
('a-2',): ((('a-2',), 0, 0), None, (('a-1',),), ('fulltext', False)),
1524
('a-3',): ((('a-3',), 0, 0), None, (('a-2',),), ('fulltext', False)),
1525
}, idx.get_build_details(idx.keys()))
1526
self.assertEqual({('a-1',):(),
1527
('a-2',):(('a-1',),),
1528
('a-3',):(('a-2',),),},
1529
idx.get_parent_map(idx.keys()))
1531
def test_add_versions_fails_clean(self):
1532
"""If add_versions fails in the middle, it restores a pristine state.
1534
Any modifications that are made to the index are reset if all versions
1537
# This cheats a little bit by passing in a generator which will
1538
# raise an exception before the processing finishes
1539
# Other possibilities would be to have an version with the wrong number
1540
# of entries, or to make the backing transport unable to write any
1543
knit = self.make_test_knit()
1545
idx.add_records([(('a-1',), ['fulltext'], (('a-1',), 0, 0), [])])
1547
class StopEarly(Exception):
1550
def generate_failure():
1551
"""Add some entries and then raise an exception"""
1552
yield (('a-2',), ['fulltext'], (None, 0, 0), ('a-1',))
1553
yield (('a-3',), ['fulltext'], (None, 0, 0), ('a-2',))
1556
# Assert the pre-condition
1558
self.assertEqual(set([('a-1',)]), set(idx.keys()))
1560
{('a-1',): ((('a-1',), 0, 0), None, (), ('fulltext', False))},
1561
idx.get_build_details([('a-1',)]))
1562
self.assertEqual({('a-1',):()}, idx.get_parent_map(idx.keys()))
1565
self.assertRaises(StopEarly, idx.add_records, generate_failure())
1566
# And it shouldn't be modified
1569
def test_knit_index_ignores_empty_files(self):
1570
# There was a race condition in older bzr, where a ^C at the right time
1571
# could leave an empty .kndx file, which bzr would later claim was a
1572
# corrupted file since the header was not present. In reality, the file
1573
# just wasn't created, so it should be ignored.
1574
t = transport.get_transport('.')
1575
t.put_bytes('test.kndx', '')
1577
knit = self.make_test_knit()
1579
def test_knit_index_checks_header(self):
1580
t = transport.get_transport('.')
1581
t.put_bytes('test.kndx', '# not really a knit header\n\n')
536
1582
k = self.make_test_knit()
537
self.failUnless(WeaveToKnit.is_compatible(w, k))
538
self.failIf(WeaveToKnit.is_compatible(k, w))
539
self.failIf(WeaveToKnit.is_compatible(w, w))
540
self.failIf(WeaveToKnit.is_compatible(k, k))
543
class TestKnitCaching(KnitTests):
545
def create_knit(self, cache_add=False):
546
k = self.make_test_knit(True)
550
k.add_lines('text-1', [], split_lines(TEXT_1))
551
k.add_lines('text-2', [], split_lines(TEXT_2))
554
def test_no_caching(self):
555
k = self.create_knit()
556
# Nothing should be cached without setting 'enable_cache'
557
self.assertEqual({}, k._data._cache)
559
def test_cache_add_and_clear(self):
560
k = self.create_knit(True)
562
self.assertEqual(['text-1', 'text-2'], sorted(k._data._cache.keys()))
565
self.assertEqual({}, k._data._cache)
567
def test_cache_data_read_raw(self):
568
k = self.create_knit()
573
def read_one_raw(version):
574
pos_map = k._get_components_positions([version])
575
method, pos, size, next = pos_map[version]
576
lst = list(k._data.read_records_iter_raw([(version, pos, size)]))
577
self.assertEqual(1, len(lst))
580
val = read_one_raw('text-1')
581
self.assertEqual({'text-1':val[1]}, k._data._cache)
584
# After clear, new reads are not cached
585
self.assertEqual({}, k._data._cache)
587
val2 = read_one_raw('text-1')
588
self.assertEqual(val, val2)
589
self.assertEqual({}, k._data._cache)
591
def test_cache_data_read(self):
592
k = self.create_knit()
594
def read_one(version):
595
pos_map = k._get_components_positions([version])
596
method, pos, size, next = pos_map[version]
597
lst = list(k._data.read_records_iter([(version, pos, size)]))
598
self.assertEqual(1, len(lst))
604
val = read_one('text-2')
605
self.assertEqual(['text-2'], k._data._cache.keys())
606
self.assertEqual('text-2', val[0])
607
content, digest = k._data._parse_record('text-2',
608
k._data._cache['text-2'])
609
self.assertEqual(content, val[1])
610
self.assertEqual(digest, val[2])
613
self.assertEqual({}, k._data._cache)
615
val2 = read_one('text-2')
616
self.assertEqual(val, val2)
617
self.assertEqual({}, k._data._cache)
619
def test_cache_read(self):
620
k = self.create_knit()
623
text = k.get_text('text-1')
624
self.assertEqual(TEXT_1, text)
625
self.assertEqual(['text-1'], k._data._cache.keys())
628
self.assertEqual({}, k._data._cache)
630
text = k.get_text('text-1')
631
self.assertEqual(TEXT_1, text)
632
self.assertEqual({}, k._data._cache)
1583
self.assertRaises(KnitHeaderError, k.keys)
1586
class TestGraphIndexKnit(KnitTests):
1587
"""Tests for knits using a GraphIndex rather than a KnitIndex."""
1589
def make_g_index(self, name, ref_lists=0, nodes=[]):
1590
builder = GraphIndexBuilder(ref_lists)
1591
for node, references, value in nodes:
1592
builder.add_node(node, references, value)
1593
stream = builder.finish()
1594
trans = self.get_transport()
1595
size = trans.put_file(name, stream)
1596
return GraphIndex(trans, name, size)
1598
def two_graph_index(self, deltas=False, catch_adds=False):
1599
"""Build a two-graph index.
1601
:param deltas: If true, use underlying indices with two node-ref
1602
lists and 'parent' set to a delta-compressed against tail.
1604
# build a complex graph across several indices.
1606
# delta compression inn the index
1607
index1 = self.make_g_index('1', 2, [
1608
(('tip', ), 'N0 100', ([('parent', )], [], )),
1609
(('tail', ), '', ([], []))])
1610
index2 = self.make_g_index('2', 2, [
1611
(('parent', ), ' 100 78', ([('tail', ), ('ghost', )], [('tail', )])),
1612
(('separate', ), '', ([], []))])
1614
# just blob location and graph in the index.
1615
index1 = self.make_g_index('1', 1, [
1616
(('tip', ), 'N0 100', ([('parent', )], )),
1617
(('tail', ), '', ([], ))])
1618
index2 = self.make_g_index('2', 1, [
1619
(('parent', ), ' 100 78', ([('tail', ), ('ghost', )], )),
1620
(('separate', ), '', ([], ))])
1621
combined_index = CombinedGraphIndex([index1, index2])
1623
self.combined_index = combined_index
1624
self.caught_entries = []
1625
add_callback = self.catch_add
1628
return _KnitGraphIndex(combined_index, lambda:True, deltas=deltas,
1629
add_callback=add_callback)
1631
def test_keys(self):
1632
index = self.two_graph_index()
1633
self.assertEqual(set([('tail',), ('tip',), ('parent',), ('separate',)]),
1636
def test_get_position(self):
1637
index = self.two_graph_index()
1638
self.assertEqual((index._graph_index._indices[0], 0, 100), index.get_position(('tip',)))
1639
self.assertEqual((index._graph_index._indices[1], 100, 78), index.get_position(('parent',)))
1641
def test_get_method_deltas(self):
1642
index = self.two_graph_index(deltas=True)
1643
self.assertEqual('fulltext', index.get_method(('tip',)))
1644
self.assertEqual('line-delta', index.get_method(('parent',)))
1646
def test_get_method_no_deltas(self):
1647
# check that the parent-history lookup is ignored with deltas=False.
1648
index = self.two_graph_index(deltas=False)
1649
self.assertEqual('fulltext', index.get_method(('tip',)))
1650
self.assertEqual('fulltext', index.get_method(('parent',)))
1652
def test_get_options_deltas(self):
1653
index = self.two_graph_index(deltas=True)
1654
self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1655
self.assertEqual(['line-delta'], index.get_options(('parent',)))
1657
def test_get_options_no_deltas(self):
1658
# check that the parent-history lookup is ignored with deltas=False.
1659
index = self.two_graph_index(deltas=False)
1660
self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1661
self.assertEqual(['fulltext'], index.get_options(('parent',)))
1663
def test_get_parent_map(self):
1664
index = self.two_graph_index()
1665
self.assertEqual({('parent',):(('tail',), ('ghost',))},
1666
index.get_parent_map([('parent',), ('ghost',)]))
1668
def catch_add(self, entries):
1669
self.caught_entries.append(entries)
1671
def test_add_no_callback_errors(self):
1672
index = self.two_graph_index()
1673
self.assertRaises(errors.ReadOnlyError, index.add_records,
1674
[(('new',), 'fulltext,no-eol', (None, 50, 60), ['separate'])])
1676
def test_add_version_smoke(self):
1677
index = self.two_graph_index(catch_adds=True)
1678
index.add_records([(('new',), 'fulltext,no-eol', (None, 50, 60),
1680
self.assertEqual([[(('new', ), 'N50 60', ((('separate',),),))]],
1681
self.caught_entries)
1683
def test_add_version_delta_not_delta_index(self):
1684
index = self.two_graph_index(catch_adds=True)
1685
self.assertRaises(errors.KnitCorrupt, index.add_records,
1686
[(('new',), 'no-eol,line-delta', (None, 0, 100), [('parent',)])])
1687
self.assertEqual([], self.caught_entries)
1689
def test_add_version_same_dup(self):
1690
index = self.two_graph_index(catch_adds=True)
1691
# options can be spelt two different ways
1692
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
1693
index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [('parent',)])])
1694
# position/length are ignored (because each pack could have fulltext or
1695
# delta, and be at a different position.
1696
index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100),
1698
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000),
1700
# but neither should have added data:
1701
self.assertEqual([[], [], [], []], self.caught_entries)
1703
def test_add_version_different_dup(self):
1704
index = self.two_graph_index(deltas=True, catch_adds=True)
1706
self.assertRaises(errors.KnitCorrupt, index.add_records,
1707
[(('tip',), 'line-delta', (None, 0, 100), [('parent',)])])
1708
self.assertRaises(errors.KnitCorrupt, index.add_records,
1709
[(('tip',), 'fulltext', (None, 0, 100), [('parent',)])])
1711
self.assertRaises(errors.KnitCorrupt, index.add_records,
1712
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
1713
self.assertEqual([], self.caught_entries)
1715
def test_add_versions_nodeltas(self):
1716
index = self.two_graph_index(catch_adds=True)
1718
(('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)]),
1719
(('new2',), 'fulltext', (None, 0, 6), [('new',)]),
1721
self.assertEqual([(('new', ), 'N50 60', ((('separate',),),)),
1722
(('new2', ), ' 0 6', ((('new',),),))],
1723
sorted(self.caught_entries[0]))
1724
self.assertEqual(1, len(self.caught_entries))
1726
def test_add_versions_deltas(self):
1727
index = self.two_graph_index(deltas=True, catch_adds=True)
1729
(('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)]),
1730
(('new2',), 'line-delta', (None, 0, 6), [('new',)]),
1732
self.assertEqual([(('new', ), 'N50 60', ((('separate',),), ())),
1733
(('new2', ), ' 0 6', ((('new',),), (('new',),), ))],
1734
sorted(self.caught_entries[0]))
1735
self.assertEqual(1, len(self.caught_entries))
1737
def test_add_versions_delta_not_delta_index(self):
1738
index = self.two_graph_index(catch_adds=True)
1739
self.assertRaises(errors.KnitCorrupt, index.add_records,
1740
[(('new',), 'no-eol,line-delta', (None, 0, 100), [('parent',)])])
1741
self.assertEqual([], self.caught_entries)
1743
def test_add_versions_random_id_accepted(self):
1744
index = self.two_graph_index(catch_adds=True)
1745
index.add_records([], random_id=True)
1747
def test_add_versions_same_dup(self):
1748
index = self.two_graph_index(catch_adds=True)
1749
# options can be spelt two different ways
1750
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100),
1752
index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100),
1754
# position/length are ignored (because each pack could have fulltext or
1755
# delta, and be at a different position.
1756
index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100),
1758
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000),
1760
# but neither should have added data.
1761
self.assertEqual([[], [], [], []], self.caught_entries)
1763
def test_add_versions_different_dup(self):
1764
index = self.two_graph_index(deltas=True, catch_adds=True)
1766
self.assertRaises(errors.KnitCorrupt, index.add_records,
1767
[(('tip',), 'line-delta', (None, 0, 100), [('parent',)])])
1768
self.assertRaises(errors.KnitCorrupt, index.add_records,
1769
[(('tip',), 'fulltext', (None, 0, 100), [('parent',)])])
1771
self.assertRaises(errors.KnitCorrupt, index.add_records,
1772
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
1773
# change options in the second record
1774
self.assertRaises(errors.KnitCorrupt, index.add_records,
1775
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)]),
1776
(('tip',), 'line-delta', (None, 0, 100), [('parent',)])])
1777
self.assertEqual([], self.caught_entries)
1779
def make_g_index_missing_compression_parent(self):
1780
graph_index = self.make_g_index('missing_comp', 2,
1781
[(('tip', ), ' 100 78',
1782
([('missing-parent', ), ('ghost', )], [('missing-parent', )]))])
1785
def make_g_index_missing_parent(self):
1786
graph_index = self.make_g_index('missing_parent', 2,
1787
[(('parent', ), ' 100 78', ([], [])),
1788
(('tip', ), ' 100 78',
1789
([('parent', ), ('missing-parent', )], [('parent', )])),
1793
def make_g_index_no_external_refs(self):
1794
graph_index = self.make_g_index('no_external_refs', 2,
1795
[(('rev', ), ' 100 78',
1796
([('parent', ), ('ghost', )], []))])
1799
def test_add_good_unvalidated_index(self):
1800
unvalidated = self.make_g_index_no_external_refs()
1801
combined = CombinedGraphIndex([unvalidated])
1802
index = _KnitGraphIndex(combined, lambda: True, deltas=True)
1803
index.scan_unvalidated_index(unvalidated)
1804
self.assertEqual(frozenset(), index.get_missing_compression_parents())
1806
def test_add_missing_compression_parent_unvalidated_index(self):
1807
unvalidated = self.make_g_index_missing_compression_parent()
1808
combined = CombinedGraphIndex([unvalidated])
1809
index = _KnitGraphIndex(combined, lambda: True, deltas=True)
1810
index.scan_unvalidated_index(unvalidated)
1811
# This also checks that its only the compression parent that is
1812
# examined, otherwise 'ghost' would also be reported as a missing
1815
frozenset([('missing-parent',)]),
1816
index.get_missing_compression_parents())
1818
def test_add_missing_noncompression_parent_unvalidated_index(self):
1819
unvalidated = self.make_g_index_missing_parent()
1820
combined = CombinedGraphIndex([unvalidated])
1821
index = _KnitGraphIndex(combined, lambda: True, deltas=True,
1822
track_external_parent_refs=True)
1823
index.scan_unvalidated_index(unvalidated)
1825
frozenset([('missing-parent',)]), index.get_missing_parents())
1827
def test_track_external_parent_refs(self):
1828
g_index = self.make_g_index('empty', 2, [])
1829
combined = CombinedGraphIndex([g_index])
1830
index = _KnitGraphIndex(combined, lambda: True, deltas=True,
1831
add_callback=self.catch_add, track_external_parent_refs=True)
1832
self.caught_entries = []
1834
(('new-key',), 'fulltext,no-eol', (None, 50, 60),
1835
[('parent-1',), ('parent-2',)])])
1837
frozenset([('parent-1',), ('parent-2',)]),
1838
index.get_missing_parents())
1840
def test_add_unvalidated_index_with_present_external_references(self):
1841
index = self.two_graph_index(deltas=True)
1842
# Ugly hack to get at one of the underlying GraphIndex objects that
1843
# two_graph_index built.
1844
unvalidated = index._graph_index._indices[1]
1845
# 'parent' is an external ref of _indices[1] (unvalidated), but is
1846
# present in _indices[0].
1847
index.scan_unvalidated_index(unvalidated)
1848
self.assertEqual(frozenset(), index.get_missing_compression_parents())
1850
def make_new_missing_parent_g_index(self, name):
1851
missing_parent = name + '-missing-parent'
1852
graph_index = self.make_g_index(name, 2,
1853
[((name + 'tip', ), ' 100 78',
1854
([(missing_parent, ), ('ghost', )], [(missing_parent, )]))])
1857
def test_add_mulitiple_unvalidated_indices_with_missing_parents(self):
1858
g_index_1 = self.make_new_missing_parent_g_index('one')
1859
g_index_2 = self.make_new_missing_parent_g_index('two')
1860
combined = CombinedGraphIndex([g_index_1, g_index_2])
1861
index = _KnitGraphIndex(combined, lambda: True, deltas=True)
1862
index.scan_unvalidated_index(g_index_1)
1863
index.scan_unvalidated_index(g_index_2)
1865
frozenset([('one-missing-parent',), ('two-missing-parent',)]),
1866
index.get_missing_compression_parents())
1868
def test_add_mulitiple_unvalidated_indices_with_mutual_dependencies(self):
1869
graph_index_a = self.make_g_index('one', 2,
1870
[(('parent-one', ), ' 100 78', ([('non-compression-parent',)], [])),
1871
(('child-of-two', ), ' 100 78',
1872
([('parent-two',)], [('parent-two',)]))])
1873
graph_index_b = self.make_g_index('two', 2,
1874
[(('parent-two', ), ' 100 78', ([('non-compression-parent',)], [])),
1875
(('child-of-one', ), ' 100 78',
1876
([('parent-one',)], [('parent-one',)]))])
1877
combined = CombinedGraphIndex([graph_index_a, graph_index_b])
1878
index = _KnitGraphIndex(combined, lambda: True, deltas=True)
1879
index.scan_unvalidated_index(graph_index_a)
1880
index.scan_unvalidated_index(graph_index_b)
1882
frozenset([]), index.get_missing_compression_parents())
1885
class TestNoParentsGraphIndexKnit(KnitTests):
1886
"""Tests for knits using _KnitGraphIndex with no parents."""
1888
def make_g_index(self, name, ref_lists=0, nodes=[]):
1889
builder = GraphIndexBuilder(ref_lists)
1890
for node, references in nodes:
1891
builder.add_node(node, references)
1892
stream = builder.finish()
1893
trans = self.get_transport()
1894
size = trans.put_file(name, stream)
1895
return GraphIndex(trans, name, size)
1897
def test_add_good_unvalidated_index(self):
1898
unvalidated = self.make_g_index('unvalidated')
1899
combined = CombinedGraphIndex([unvalidated])
1900
index = _KnitGraphIndex(combined, lambda: True, parents=False)
1901
index.scan_unvalidated_index(unvalidated)
1902
self.assertEqual(frozenset(),
1903
index.get_missing_compression_parents())
1905
def test_parents_deltas_incompatible(self):
1906
index = CombinedGraphIndex([])
1907
self.assertRaises(errors.KnitError, _KnitGraphIndex, lambda:True,
1908
index, deltas=True, parents=False)
1910
def two_graph_index(self, catch_adds=False):
1911
"""Build a two-graph index.
1913
:param deltas: If true, use underlying indices with two node-ref
1914
lists and 'parent' set to a delta-compressed against tail.
1916
# put several versions in the index.
1917
index1 = self.make_g_index('1', 0, [
1918
(('tip', ), 'N0 100'),
1920
index2 = self.make_g_index('2', 0, [
1921
(('parent', ), ' 100 78'),
1922
(('separate', ), '')])
1923
combined_index = CombinedGraphIndex([index1, index2])
1925
self.combined_index = combined_index
1926
self.caught_entries = []
1927
add_callback = self.catch_add
1930
return _KnitGraphIndex(combined_index, lambda:True, parents=False,
1931
add_callback=add_callback)
1933
def test_keys(self):
1934
index = self.two_graph_index()
1935
self.assertEqual(set([('tail',), ('tip',), ('parent',), ('separate',)]),
1938
def test_get_position(self):
1939
index = self.two_graph_index()
1940
self.assertEqual((index._graph_index._indices[0], 0, 100),
1941
index.get_position(('tip',)))
1942
self.assertEqual((index._graph_index._indices[1], 100, 78),
1943
index.get_position(('parent',)))
1945
def test_get_method(self):
1946
index = self.two_graph_index()
1947
self.assertEqual('fulltext', index.get_method(('tip',)))
1948
self.assertEqual(['fulltext'], index.get_options(('parent',)))
1950
def test_get_options(self):
1951
index = self.two_graph_index()
1952
self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1953
self.assertEqual(['fulltext'], index.get_options(('parent',)))
1955
def test_get_parent_map(self):
1956
index = self.two_graph_index()
1957
self.assertEqual({('parent',):None},
1958
index.get_parent_map([('parent',), ('ghost',)]))
1960
def catch_add(self, entries):
1961
self.caught_entries.append(entries)
1963
def test_add_no_callback_errors(self):
1964
index = self.two_graph_index()
1965
self.assertRaises(errors.ReadOnlyError, index.add_records,
1966
[(('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)])])
1968
def test_add_version_smoke(self):
1969
index = self.two_graph_index(catch_adds=True)
1970
index.add_records([(('new',), 'fulltext,no-eol', (None, 50, 60), [])])
1971
self.assertEqual([[(('new', ), 'N50 60')]],
1972
self.caught_entries)
1974
def test_add_version_delta_not_delta_index(self):
1975
index = self.two_graph_index(catch_adds=True)
1976
self.assertRaises(errors.KnitCorrupt, index.add_records,
1977
[(('new',), 'no-eol,line-delta', (None, 0, 100), [])])
1978
self.assertEqual([], self.caught_entries)
1980
def test_add_version_same_dup(self):
1981
index = self.two_graph_index(catch_adds=True)
1982
# options can be spelt two different ways
1983
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
1984
index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [])])
1985
# position/length are ignored (because each pack could have fulltext or
1986
# delta, and be at a different position.
1987
index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100), [])])
1988
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000), [])])
1989
# but neither should have added data.
1990
self.assertEqual([[], [], [], []], self.caught_entries)
1992
def test_add_version_different_dup(self):
1993
index = self.two_graph_index(catch_adds=True)
1995
self.assertRaises(errors.KnitCorrupt, index.add_records,
1996
[(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
1997
self.assertRaises(errors.KnitCorrupt, index.add_records,
1998
[(('tip',), 'line-delta,no-eol', (None, 0, 100), [])])
1999
self.assertRaises(errors.KnitCorrupt, index.add_records,
2000
[(('tip',), 'fulltext', (None, 0, 100), [])])
2002
self.assertRaises(errors.KnitCorrupt, index.add_records,
2003
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
2004
self.assertEqual([], self.caught_entries)
2006
def test_add_versions(self):
2007
index = self.two_graph_index(catch_adds=True)
2009
(('new',), 'fulltext,no-eol', (None, 50, 60), []),
2010
(('new2',), 'fulltext', (None, 0, 6), []),
2012
self.assertEqual([(('new', ), 'N50 60'), (('new2', ), ' 0 6')],
2013
sorted(self.caught_entries[0]))
2014
self.assertEqual(1, len(self.caught_entries))
2016
def test_add_versions_delta_not_delta_index(self):
2017
index = self.two_graph_index(catch_adds=True)
2018
self.assertRaises(errors.KnitCorrupt, index.add_records,
2019
[(('new',), 'no-eol,line-delta', (None, 0, 100), [('parent',)])])
2020
self.assertEqual([], self.caught_entries)
2022
def test_add_versions_parents_not_parents_index(self):
2023
index = self.two_graph_index(catch_adds=True)
2024
self.assertRaises(errors.KnitCorrupt, index.add_records,
2025
[(('new',), 'no-eol,fulltext', (None, 0, 100), [('parent',)])])
2026
self.assertEqual([], self.caught_entries)
2028
def test_add_versions_random_id_accepted(self):
2029
index = self.two_graph_index(catch_adds=True)
2030
index.add_records([], random_id=True)
2032
def test_add_versions_same_dup(self):
2033
index = self.two_graph_index(catch_adds=True)
2034
# options can be spelt two different ways
2035
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
2036
index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [])])
2037
# position/length are ignored (because each pack could have fulltext or
2038
# delta, and be at a different position.
2039
index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100), [])])
2040
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000), [])])
2041
# but neither should have added data.
2042
self.assertEqual([[], [], [], []], self.caught_entries)
2044
def test_add_versions_different_dup(self):
2045
index = self.two_graph_index(catch_adds=True)
2047
self.assertRaises(errors.KnitCorrupt, index.add_records,
2048
[(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
2049
self.assertRaises(errors.KnitCorrupt, index.add_records,
2050
[(('tip',), 'line-delta,no-eol', (None, 0, 100), [])])
2051
self.assertRaises(errors.KnitCorrupt, index.add_records,
2052
[(('tip',), 'fulltext', (None, 0, 100), [])])
2054
self.assertRaises(errors.KnitCorrupt, index.add_records,
2055
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
2056
# change options in the second record
2057
self.assertRaises(errors.KnitCorrupt, index.add_records,
2058
[(('tip',), 'fulltext,no-eol', (None, 0, 100), []),
2059
(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
2060
self.assertEqual([], self.caught_entries)
2063
class TestKnitVersionedFiles(KnitTests):
2065
def assertGroupKeysForIo(self, exp_groups, keys, non_local_keys,
2066
positions, _min_buffer_size=None):
2067
kvf = self.make_test_knit()
2068
if _min_buffer_size is None:
2069
_min_buffer_size = knit._STREAM_MIN_BUFFER_SIZE
2070
self.assertEqual(exp_groups, kvf._group_keys_for_io(keys,
2071
non_local_keys, positions,
2072
_min_buffer_size=_min_buffer_size))
2074
def assertSplitByPrefix(self, expected_map, expected_prefix_order,
2076
split, prefix_order = KnitVersionedFiles._split_by_prefix(keys)
2077
self.assertEqual(expected_map, split)
2078
self.assertEqual(expected_prefix_order, prefix_order)
2080
def test__group_keys_for_io(self):
2081
ft_detail = ('fulltext', False)
2082
ld_detail = ('line-delta', False)
2090
f_a: (ft_detail, (f_a, 0, 100), None),
2091
f_b: (ld_detail, (f_b, 100, 21), f_a),
2092
f_c: (ld_detail, (f_c, 180, 15), f_b),
2093
g_a: (ft_detail, (g_a, 121, 35), None),
2094
g_b: (ld_detail, (g_b, 156, 12), g_a),
2095
g_c: (ld_detail, (g_c, 195, 13), g_a),
2097
self.assertGroupKeysForIo([([f_a], set())],
2098
[f_a], [], positions)
2099
self.assertGroupKeysForIo([([f_a], set([f_a]))],
2100
[f_a], [f_a], positions)
2101
self.assertGroupKeysForIo([([f_a, f_b], set([]))],
2102
[f_a, f_b], [], positions)
2103
self.assertGroupKeysForIo([([f_a, f_b], set([f_b]))],
2104
[f_a, f_b], [f_b], positions)
2105
self.assertGroupKeysForIo([([f_a, f_b, g_a, g_b], set())],
2106
[f_a, g_a, f_b, g_b], [], positions)
2107
self.assertGroupKeysForIo([([f_a, f_b, g_a, g_b], set())],
2108
[f_a, g_a, f_b, g_b], [], positions,
2109
_min_buffer_size=150)
2110
self.assertGroupKeysForIo([([f_a, f_b], set()), ([g_a, g_b], set())],
2111
[f_a, g_a, f_b, g_b], [], positions,
2112
_min_buffer_size=100)
2113
self.assertGroupKeysForIo([([f_c], set()), ([g_b], set())],
2114
[f_c, g_b], [], positions,
2115
_min_buffer_size=125)
2116
self.assertGroupKeysForIo([([g_b, f_c], set())],
2117
[g_b, f_c], [], positions,
2118
_min_buffer_size=125)
2120
def test__split_by_prefix(self):
2121
self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2122
'g': [('g', 'b'), ('g', 'a')],
2124
[('f', 'a'), ('g', 'b'),
2125
('g', 'a'), ('f', 'b')])
2127
self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2128
'g': [('g', 'b'), ('g', 'a')],
2130
[('f', 'a'), ('f', 'b'),
2131
('g', 'b'), ('g', 'a')])
2133
self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2134
'g': [('g', 'b'), ('g', 'a')],
2136
[('f', 'a'), ('f', 'b'),
2137
('g', 'b'), ('g', 'a')])
2139
self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2140
'g': [('g', 'b'), ('g', 'a')],
2141
'': [('a',), ('b',)]
2143
[('f', 'a'), ('g', 'b'),
2145
('g', 'a'), ('f', 'b')])
2148
class TestStacking(KnitTests):
2150
def get_basis_and_test_knit(self):
2151
basis = self.make_test_knit(name='basis')
2152
basis = RecordingVersionedFilesDecorator(basis)
2153
test = self.make_test_knit(name='test')
2154
test.add_fallback_versioned_files(basis)
2157
def test_add_fallback_versioned_files(self):
2158
basis = self.make_test_knit(name='basis')
2159
test = self.make_test_knit(name='test')
2160
# It must not error; other tests test that the fallback is referred to
2161
# when accessing data.
2162
test.add_fallback_versioned_files(basis)
2164
def test_add_lines(self):
2165
# lines added to the test are not added to the basis
2166
basis, test = self.get_basis_and_test_knit()
2168
key_basis = ('bar',)
2169
key_cross_border = ('quux',)
2170
key_delta = ('zaphod',)
2171
test.add_lines(key, (), ['foo\n'])
2172
self.assertEqual({}, basis.get_parent_map([key]))
2173
# lines added to the test that reference across the stack do a
2175
basis.add_lines(key_basis, (), ['foo\n'])
2177
test.add_lines(key_cross_border, (key_basis,), ['foo\n'])
2178
self.assertEqual('fulltext', test._index.get_method(key_cross_border))
2179
# we don't even need to look at the basis to see that this should be
2180
# stored as a fulltext
2181
self.assertEqual([], basis.calls)
2182
# Subsequent adds do delta.
2184
test.add_lines(key_delta, (key_cross_border,), ['foo\n'])
2185
self.assertEqual('line-delta', test._index.get_method(key_delta))
2186
self.assertEqual([], basis.calls)
2188
def test_annotate(self):
2189
# annotations from the test knit are answered without asking the basis
2190
basis, test = self.get_basis_and_test_knit()
2192
key_basis = ('bar',)
2193
key_missing = ('missing',)
2194
test.add_lines(key, (), ['foo\n'])
2195
details = test.annotate(key)
2196
self.assertEqual([(key, 'foo\n')], details)
2197
self.assertEqual([], basis.calls)
2198
# But texts that are not in the test knit are looked for in the basis
2200
basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
2202
details = test.annotate(key_basis)
2203
self.assertEqual([(key_basis, 'foo\n'), (key_basis, 'bar\n')], details)
2204
# Not optimised to date:
2205
# self.assertEqual([("annotate", key_basis)], basis.calls)
2206
self.assertEqual([('get_parent_map', set([key_basis])),
2207
('get_parent_map', set([key_basis])),
2208
('get_record_stream', [key_basis], 'topological', True)],
2211
def test_check(self):
2212
# At the moment checking a stacked knit does implicitly check the
2214
basis, test = self.get_basis_and_test_knit()
2217
def test_get_parent_map(self):
2218
# parents in the test knit are answered without asking the basis
2219
basis, test = self.get_basis_and_test_knit()
2221
key_basis = ('bar',)
2222
key_missing = ('missing',)
2223
test.add_lines(key, (), [])
2224
parent_map = test.get_parent_map([key])
2225
self.assertEqual({key: ()}, parent_map)
2226
self.assertEqual([], basis.calls)
2227
# But parents that are not in the test knit are looked for in the basis
2228
basis.add_lines(key_basis, (), [])
2230
parent_map = test.get_parent_map([key, key_basis, key_missing])
2231
self.assertEqual({key: (),
2232
key_basis: ()}, parent_map)
2233
self.assertEqual([("get_parent_map", set([key_basis, key_missing]))],
2236
def test_get_record_stream_unordered_fulltexts(self):
2237
# records from the test knit are answered without asking the basis:
2238
basis, test = self.get_basis_and_test_knit()
2240
key_basis = ('bar',)
2241
key_missing = ('missing',)
2242
test.add_lines(key, (), ['foo\n'])
2243
records = list(test.get_record_stream([key], 'unordered', True))
2244
self.assertEqual(1, len(records))
2245
self.assertEqual([], basis.calls)
2246
# Missing (from test knit) objects are retrieved from the basis:
2247
basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
2249
records = list(test.get_record_stream([key_basis, key_missing],
2251
self.assertEqual(2, len(records))
2252
calls = list(basis.calls)
2253
for record in records:
2254
self.assertSubset([record.key], (key_basis, key_missing))
2255
if record.key == key_missing:
2256
self.assertIsInstance(record, AbsentContentFactory)
2258
reference = list(basis.get_record_stream([key_basis],
2259
'unordered', True))[0]
2260
self.assertEqual(reference.key, record.key)
2261
self.assertEqual(reference.sha1, record.sha1)
2262
self.assertEqual(reference.storage_kind, record.storage_kind)
2263
self.assertEqual(reference.get_bytes_as(reference.storage_kind),
2264
record.get_bytes_as(record.storage_kind))
2265
self.assertEqual(reference.get_bytes_as('fulltext'),
2266
record.get_bytes_as('fulltext'))
2267
# It's not strictly minimal, but it seems reasonable for now for it to
2268
# ask which fallbacks have which parents.
2270
("get_parent_map", set([key_basis, key_missing])),
2271
("get_record_stream", [key_basis], 'unordered', True)],
2274
def test_get_record_stream_ordered_fulltexts(self):
2275
# ordering is preserved down into the fallback store.
2276
basis, test = self.get_basis_and_test_knit()
2278
key_basis = ('bar',)
2279
key_basis_2 = ('quux',)
2280
key_missing = ('missing',)
2281
test.add_lines(key, (key_basis,), ['foo\n'])
2282
# Missing (from test knit) objects are retrieved from the basis:
2283
basis.add_lines(key_basis, (key_basis_2,), ['foo\n', 'bar\n'])
2284
basis.add_lines(key_basis_2, (), ['quux\n'])
2286
# ask for in non-topological order
2287
records = list(test.get_record_stream(
2288
[key, key_basis, key_missing, key_basis_2], 'topological', True))
2289
self.assertEqual(4, len(records))
2291
for record in records:
2292
self.assertSubset([record.key],
2293
(key_basis, key_missing, key_basis_2, key))
2294
if record.key == key_missing:
2295
self.assertIsInstance(record, AbsentContentFactory)
2297
results.append((record.key, record.sha1, record.storage_kind,
2298
record.get_bytes_as('fulltext')))
2299
calls = list(basis.calls)
2300
order = [record[0] for record in results]
2301
self.assertEqual([key_basis_2, key_basis, key], order)
2302
for result in results:
2303
if result[0] == key:
2307
record = source.get_record_stream([result[0]], 'unordered',
2309
self.assertEqual(record.key, result[0])
2310
self.assertEqual(record.sha1, result[1])
2311
# We used to check that the storage kind matched, but actually it
2312
# depends on whether it was sourced from the basis, or in a single
2313
# group, because asking for full texts returns proxy objects to a
2314
# _ContentMapGenerator object; so checking the kind is unneeded.
2315
self.assertEqual(record.get_bytes_as('fulltext'), result[3])
2316
# It's not strictly minimal, but it seems reasonable for now for it to
2317
# ask which fallbacks have which parents.
2319
("get_parent_map", set([key_basis, key_basis_2, key_missing])),
2320
# topological is requested from the fallback, because that is what
2321
# was requested at the top level.
2322
("get_record_stream", [key_basis_2, key_basis], 'topological', True)],
2325
def test_get_record_stream_unordered_deltas(self):
2326
# records from the test knit are answered without asking the basis:
2327
basis, test = self.get_basis_and_test_knit()
2329
key_basis = ('bar',)
2330
key_missing = ('missing',)
2331
test.add_lines(key, (), ['foo\n'])
2332
records = list(test.get_record_stream([key], 'unordered', False))
2333
self.assertEqual(1, len(records))
2334
self.assertEqual([], basis.calls)
2335
# Missing (from test knit) objects are retrieved from the basis:
2336
basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
2338
records = list(test.get_record_stream([key_basis, key_missing],
2339
'unordered', False))
2340
self.assertEqual(2, len(records))
2341
calls = list(basis.calls)
2342
for record in records:
2343
self.assertSubset([record.key], (key_basis, key_missing))
2344
if record.key == key_missing:
2345
self.assertIsInstance(record, AbsentContentFactory)
2347
reference = list(basis.get_record_stream([key_basis],
2348
'unordered', False))[0]
2349
self.assertEqual(reference.key, record.key)
2350
self.assertEqual(reference.sha1, record.sha1)
2351
self.assertEqual(reference.storage_kind, record.storage_kind)
2352
self.assertEqual(reference.get_bytes_as(reference.storage_kind),
2353
record.get_bytes_as(record.storage_kind))
2354
# It's not strictly minimal, but it seems reasonable for now for it to
2355
# ask which fallbacks have which parents.
2357
("get_parent_map", set([key_basis, key_missing])),
2358
("get_record_stream", [key_basis], 'unordered', False)],
2361
def test_get_record_stream_ordered_deltas(self):
2362
# ordering is preserved down into the fallback store.
2363
basis, test = self.get_basis_and_test_knit()
2365
key_basis = ('bar',)
2366
key_basis_2 = ('quux',)
2367
key_missing = ('missing',)
2368
test.add_lines(key, (key_basis,), ['foo\n'])
2369
# Missing (from test knit) objects are retrieved from the basis:
2370
basis.add_lines(key_basis, (key_basis_2,), ['foo\n', 'bar\n'])
2371
basis.add_lines(key_basis_2, (), ['quux\n'])
2373
# ask for in non-topological order
2374
records = list(test.get_record_stream(
2375
[key, key_basis, key_missing, key_basis_2], 'topological', False))
2376
self.assertEqual(4, len(records))
2378
for record in records:
2379
self.assertSubset([record.key],
2380
(key_basis, key_missing, key_basis_2, key))
2381
if record.key == key_missing:
2382
self.assertIsInstance(record, AbsentContentFactory)
2384
results.append((record.key, record.sha1, record.storage_kind,
2385
record.get_bytes_as(record.storage_kind)))
2386
calls = list(basis.calls)
2387
order = [record[0] for record in results]
2388
self.assertEqual([key_basis_2, key_basis, key], order)
2389
for result in results:
2390
if result[0] == key:
2394
record = source.get_record_stream([result[0]], 'unordered',
2396
self.assertEqual(record.key, result[0])
2397
self.assertEqual(record.sha1, result[1])
2398
self.assertEqual(record.storage_kind, result[2])
2399
self.assertEqual(record.get_bytes_as(record.storage_kind), result[3])
2400
# It's not strictly minimal, but it seems reasonable for now for it to
2401
# ask which fallbacks have which parents.
2403
("get_parent_map", set([key_basis, key_basis_2, key_missing])),
2404
("get_record_stream", [key_basis_2, key_basis], 'topological', False)],
2407
def test_get_sha1s(self):
2408
# sha1's in the test knit are answered without asking the basis
2409
basis, test = self.get_basis_and_test_knit()
2411
key_basis = ('bar',)
2412
key_missing = ('missing',)
2413
test.add_lines(key, (), ['foo\n'])
2414
key_sha1sum = osutils.sha('foo\n').hexdigest()
2415
sha1s = test.get_sha1s([key])
2416
self.assertEqual({key: key_sha1sum}, sha1s)
2417
self.assertEqual([], basis.calls)
2418
# But texts that are not in the test knit are looked for in the basis
2419
# directly (rather than via text reconstruction) so that remote servers
2420
# etc don't have to answer with full content.
2421
basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
2422
basis_sha1sum = osutils.sha('foo\nbar\n').hexdigest()
2424
sha1s = test.get_sha1s([key, key_missing, key_basis])
2425
self.assertEqual({key: key_sha1sum,
2426
key_basis: basis_sha1sum}, sha1s)
2427
self.assertEqual([("get_sha1s", set([key_basis, key_missing]))],
2430
def test_insert_record_stream(self):
2431
# records are inserted as normal; insert_record_stream builds on
2432
# add_lines, so a smoke test should be all that's needed:
2434
key_basis = ('bar',)
2435
key_delta = ('zaphod',)
2436
basis, test = self.get_basis_and_test_knit()
2437
source = self.make_test_knit(name='source')
2438
basis.add_lines(key_basis, (), ['foo\n'])
2440
source.add_lines(key_basis, (), ['foo\n'])
2441
source.add_lines(key_delta, (key_basis,), ['bar\n'])
2442
stream = source.get_record_stream([key_delta], 'unordered', False)
2443
test.insert_record_stream(stream)
2444
# XXX: this does somewhat too many calls in making sure of whether it
2445
# has to recreate the full text.
2446
self.assertEqual([("get_parent_map", set([key_basis])),
2447
('get_parent_map', set([key_basis])),
2448
('get_record_stream', [key_basis], 'unordered', True)],
2450
self.assertEqual({key_delta:(key_basis,)},
2451
test.get_parent_map([key_delta]))
2452
self.assertEqual('bar\n', test.get_record_stream([key_delta],
2453
'unordered', True).next().get_bytes_as('fulltext'))
2455
def test_iter_lines_added_or_present_in_keys(self):
2456
# Lines from the basis are returned, and lines for a given key are only
2460
# all sources are asked for keys:
2461
basis, test = self.get_basis_and_test_knit()
2462
basis.add_lines(key1, (), ["foo"])
2464
lines = list(test.iter_lines_added_or_present_in_keys([key1]))
2465
self.assertEqual([("foo\n", key1)], lines)
2466
self.assertEqual([("iter_lines_added_or_present_in_keys", set([key1]))],
2468
# keys in both are not duplicated:
2469
test.add_lines(key2, (), ["bar\n"])
2470
basis.add_lines(key2, (), ["bar\n"])
2472
lines = list(test.iter_lines_added_or_present_in_keys([key2]))
2473
self.assertEqual([("bar\n", key2)], lines)
2474
self.assertEqual([], basis.calls)
2476
def test_keys(self):
2479
# all sources are asked for keys:
2480
basis, test = self.get_basis_and_test_knit()
2482
self.assertEqual(set(), set(keys))
2483
self.assertEqual([("keys",)], basis.calls)
2484
# keys from a basis are returned:
2485
basis.add_lines(key1, (), [])
2488
self.assertEqual(set([key1]), set(keys))
2489
self.assertEqual([("keys",)], basis.calls)
2490
# keys in both are not duplicated:
2491
test.add_lines(key2, (), [])
2492
basis.add_lines(key2, (), [])
2495
self.assertEqual(2, len(keys))
2496
self.assertEqual(set([key1, key2]), set(keys))
2497
self.assertEqual([("keys",)], basis.calls)
2499
def test_add_mpdiffs(self):
2500
# records are inserted as normal; add_mpdiff builds on
2501
# add_lines, so a smoke test should be all that's needed:
2503
key_basis = ('bar',)
2504
key_delta = ('zaphod',)
2505
basis, test = self.get_basis_and_test_knit()
2506
source = self.make_test_knit(name='source')
2507
basis.add_lines(key_basis, (), ['foo\n'])
2509
source.add_lines(key_basis, (), ['foo\n'])
2510
source.add_lines(key_delta, (key_basis,), ['bar\n'])
2511
diffs = source.make_mpdiffs([key_delta])
2512
test.add_mpdiffs([(key_delta, (key_basis,),
2513
source.get_sha1s([key_delta])[key_delta], diffs[0])])
2514
self.assertEqual([("get_parent_map", set([key_basis])),
2515
('get_record_stream', [key_basis], 'unordered', True),],
2517
self.assertEqual({key_delta:(key_basis,)},
2518
test.get_parent_map([key_delta]))
2519
self.assertEqual('bar\n', test.get_record_stream([key_delta],
2520
'unordered', True).next().get_bytes_as('fulltext'))
2522
def test_make_mpdiffs(self):
2523
# Generating an mpdiff across a stacking boundary should detect parent
2527
key_right = ('zaphod',)
2528
basis, test = self.get_basis_and_test_knit()
2529
basis.add_lines(key_left, (), ['bar\n'])
2530
basis.add_lines(key_right, (), ['zaphod\n'])
2532
test.add_lines(key, (key_left, key_right),
2533
['bar\n', 'foo\n', 'zaphod\n'])
2534
diffs = test.make_mpdiffs([key])
2536
multiparent.MultiParent([multiparent.ParentText(0, 0, 0, 1),
2537
multiparent.NewText(['foo\n']),
2538
multiparent.ParentText(1, 0, 2, 1)])],
2540
self.assertEqual(3, len(basis.calls))
2542
("get_parent_map", set([key_left, key_right])),
2543
("get_parent_map", set([key_left, key_right])),
2546
last_call = basis.calls[-1]
2547
self.assertEqual('get_record_stream', last_call[0])
2548
self.assertEqual(set([key_left, key_right]), set(last_call[1]))
2549
self.assertEqual('topological', last_call[2])
2550
self.assertEqual(True, last_call[3])
2553
class TestNetworkBehaviour(KnitTests):
2554
"""Tests for getting data out of/into knits over the network."""
2556
def test_include_delta_closure_generates_a_knit_delta_closure(self):
2557
vf = self.make_test_knit(name='test')
2558
# put in three texts, giving ft, delta, delta
2559
vf.add_lines(('base',), (), ['base\n', 'content\n'])
2560
vf.add_lines(('d1',), (('base',),), ['d1\n'])
2561
vf.add_lines(('d2',), (('d1',),), ['d2\n'])
2562
# But heuristics could interfere, so check what happened:
2563
self.assertEqual(['knit-ft-gz', 'knit-delta-gz', 'knit-delta-gz'],
2564
[record.storage_kind for record in
2565
vf.get_record_stream([('base',), ('d1',), ('d2',)],
2566
'topological', False)])
2567
# generate a stream of just the deltas include_delta_closure=True,
2568
# serialise to the network, and check that we get a delta closure on the wire.
2569
stream = vf.get_record_stream([('d1',), ('d2',)], 'topological', True)
2570
netb = [record.get_bytes_as(record.storage_kind) for record in stream]
2571
# The first bytes should be a memo from _ContentMapGenerator, and the
2572
# second bytes should be empty (because its a API proxy not something
2573
# for wire serialisation.
2574
self.assertEqual('', netb[1])
2576
kind, line_end = network_bytes_to_kind_and_offset(bytes)
2577
self.assertEqual('knit-delta-closure', kind)
2580
class TestContentMapGenerator(KnitTests):
2581
"""Tests for ContentMapGenerator"""
2583
def test_get_record_stream_gives_records(self):
2584
vf = self.make_test_knit(name='test')
2585
# put in three texts, giving ft, delta, delta
2586
vf.add_lines(('base',), (), ['base\n', 'content\n'])
2587
vf.add_lines(('d1',), (('base',),), ['d1\n'])
2588
vf.add_lines(('d2',), (('d1',),), ['d2\n'])
2589
keys = [('d1',), ('d2',)]
2590
generator = _VFContentMapGenerator(vf, keys,
2591
global_map=vf.get_parent_map(keys))
2592
for record in generator.get_record_stream():
2593
if record.key == ('d1',):
2594
self.assertEqual('d1\n', record.get_bytes_as('fulltext'))
2596
self.assertEqual('d2\n', record.get_bytes_as('fulltext'))
2598
def test_get_record_stream_kinds_are_raw(self):
2599
vf = self.make_test_knit(name='test')
2600
# put in three texts, giving ft, delta, delta
2601
vf.add_lines(('base',), (), ['base\n', 'content\n'])
2602
vf.add_lines(('d1',), (('base',),), ['d1\n'])
2603
vf.add_lines(('d2',), (('d1',),), ['d2\n'])
2604
keys = [('base',), ('d1',), ('d2',)]
2605
generator = _VFContentMapGenerator(vf, keys,
2606
global_map=vf.get_parent_map(keys))
2607
kinds = {('base',): 'knit-delta-closure',
2608
('d1',): 'knit-delta-closure-ref',
2609
('d2',): 'knit-delta-closure-ref',
2611
for record in generator.get_record_stream():
2612
self.assertEqual(kinds[record.key], record.storage_kind)