110
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)
112
252
def __getattr__(self, name):
113
253
def queue_call(*args, **kwargs):
114
254
self.calls.append((name, args, kwargs))
115
255
return queue_call
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.
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))
118
853
class LowLevelKnitIndexTests(TestCase):
120
def test_no_such_file(self):
121
transport = MockTransport()
123
self.assertRaises(NoSuchFile, _KnitIndex, transport, "filename", "r")
124
self.assertRaises(NoSuchFile, _KnitIndex, transport,
125
"filename", "w", create=False)
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)
127
862
def test_create_file(self):
128
863
transport = MockTransport()
130
index = _KnitIndex(transport, "filename", "w",
131
file_mode="wb", create=True)
133
("put_bytes_non_atomic",
134
("filename", index.HEADER), {"mode": "wb"}),
135
transport.calls.pop(0))
137
def test_delay_create_file(self):
138
transport = MockTransport()
140
index = _KnitIndex(transport, "filename", "w",
141
create=True, file_mode="wb", create_parent_dir=True,
142
delay_create=True, dir_mode=0777)
143
self.assertEqual([], transport.calls)
145
index.add_versions([])
146
name, (filename, f), kwargs = transport.calls.pop(0)
147
self.assertEqual("put_file_non_atomic", name)
149
{"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
151
self.assertEqual("filename", filename)
152
self.assertEqual(index.HEADER, f.read())
154
index.add_versions([])
155
self.assertEqual(("append_bytes", ("filename", ""), {}),
156
transport.calls.pop(0))
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])
158
875
def test_read_utf8_version_id(self):
159
876
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
160
877
utf8_revision_id = unicode_revision_id.encode('utf-8')
161
878
transport = MockTransport([
163
880
'%s option 0 1 :' % (utf8_revision_id,)
165
index = _KnitIndex(transport, "filename", "r")
166
# _KnitIndex is a private class, and deals in utf8 revision_ids, not
882
index = self.get_knit_index(transport, "filename", "r")
883
# _KndxIndex is a private class, and deals in utf8 revision_ids, not
167
884
# Unicode revision_ids.
168
self.assertTrue(index.has_version(utf8_revision_id))
169
self.assertFalse(index.has_version(unicode_revision_id))
885
self.assertEqual({(utf8_revision_id,):()},
886
index.get_parent_map(index.keys()))
887
self.assertFalse((unicode_revision_id,) in index.keys())
171
889
def test_read_utf8_parents(self):
172
890
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
173
891
utf8_revision_id = unicode_revision_id.encode('utf-8')
174
892
transport = MockTransport([
176
894
"version option 0 1 .%s :" % (utf8_revision_id,)
178
index = _KnitIndex(transport, "filename", "r")
179
self.assertEqual([utf8_revision_id],
180
index.get_parents_with_ghosts("version"))
896
index = self.get_knit_index(transport, "filename", "r")
897
self.assertEqual({("version",):((utf8_revision_id,),)},
898
index.get_parent_map(index.keys()))
182
900
def test_read_ignore_corrupted_lines(self):
183
901
transport = MockTransport([
186
904
"corrupted options 0 1 .b .c ",
187
905
"version options 0 1 :"
189
index = _KnitIndex(transport, "filename", "r")
190
self.assertEqual(1, index.num_versions())
191
self.assertTrue(index.has_version("version"))
907
index = self.get_knit_index(transport, "filename", "r")
908
self.assertEqual(1, len(index.keys()))
909
self.assertEqual(set([("version",)]), index.keys())
193
911
def test_read_corrupted_header(self):
194
912
transport = MockTransport(['not a bzr knit index header\n'])
195
self.assertRaises(KnitHeaderError,
196
_KnitIndex, transport, "filename", "r")
913
index = self.get_knit_index(transport, "filename", "r")
914
self.assertRaises(KnitHeaderError, index.keys)
198
916
def test_read_duplicate_entries(self):
199
917
transport = MockTransport([
201
919
"parent options 0 1 :",
202
920
"version options1 0 1 0 :",
203
921
"version options2 1 2 .other :",
204
922
"version options3 3 4 0 .other :"
206
index = _KnitIndex(transport, "filename", "r")
207
self.assertEqual(2, index.num_versions())
208
self.assertEqual(1, index.lookup("version"))
209
self.assertEqual((3, 4), index.get_position("version"))
210
self.assertEqual(["options3"], index.get_options("version"))
211
self.assertEqual(["parent", "other"],
212
index.get_parents_with_ghosts("version"))
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",)]))
214
934
def test_read_compressed_parents(self):
215
935
transport = MockTransport([
217
937
"a option 0 1 :",
218
938
"b option 0 1 0 :",
219
939
"c option 0 1 1 0 :",
221
index = _KnitIndex(transport, "filename", "r")
222
self.assertEqual(["a"], index.get_parents("b"))
223
self.assertEqual(["b", "a"], index.get_parents("c"))
941
index = self.get_knit_index(transport, "filename", "r")
942
self.assertEqual({("b",):(("a",),), ("c",):(("b",), ("a",))},
943
index.get_parent_map([("b",), ("c",)]))
225
945
def test_write_utf8_version_id(self):
226
946
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
227
947
utf8_revision_id = unicode_revision_id.encode('utf-8')
228
948
transport = MockTransport([
231
index = _KnitIndex(transport, "filename", "r")
232
index.add_version(utf8_revision_id, ["option"], 0, 1, [])
233
self.assertEqual(("append_bytes", ("filename",
234
"\n%s option 0 1 :" % (utf8_revision_id,)),
236
transport.calls.pop(0))
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])
238
964
def test_write_utf8_parents(self):
239
965
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
240
966
utf8_revision_id = unicode_revision_id.encode('utf-8')
241
967
transport = MockTransport([
244
index = _KnitIndex(transport, "filename", "r")
245
index.add_version("version", ["option"], 0, 1, [utf8_revision_id])
246
self.assertEqual(("append_bytes", ("filename",
247
"\nversion option 0 1 .%s :" % (utf8_revision_id,)),
249
transport.calls.pop(0))
251
def test_get_graph(self):
252
transport = MockTransport()
253
index = _KnitIndex(transport, "filename", "w", create=True)
254
self.assertEqual([], index.get_graph())
256
index.add_version("a", ["option"], 0, 1, ["b"])
257
self.assertEqual([("a", ["b"])], index.get_graph())
259
index.add_version("c", ["option"], 0, 1, ["d"])
260
self.assertEqual([("a", ["b"]), ("c", ["d"])],
261
sorted(index.get_graph()))
263
def test_get_ancestry(self):
264
transport = MockTransport([
267
"b option 0 1 0 .e :",
268
"c option 0 1 1 0 :",
269
"d option 0 1 2 .f :"
271
index = _KnitIndex(transport, "filename", "r")
273
self.assertEqual([], index.get_ancestry([]))
274
self.assertEqual(["a"], index.get_ancestry(["a"]))
275
self.assertEqual(["a", "b"], index.get_ancestry(["b"]))
276
self.assertEqual(["a", "b", "c"], index.get_ancestry(["c"]))
277
self.assertEqual(["a", "b", "c", "d"], index.get_ancestry(["d"]))
278
self.assertEqual(["a", "b"], index.get_ancestry(["a", "b"]))
279
self.assertEqual(["a", "b", "c"], index.get_ancestry(["a", "c"]))
281
self.assertRaises(RevisionNotPresent, index.get_ancestry, ["e"])
283
def test_get_ancestry_with_ghosts(self):
284
transport = MockTransport([
287
"b option 0 1 0 .e :",
288
"c option 0 1 0 .f .g :",
289
"d option 0 1 2 .h .j .k :"
291
index = _KnitIndex(transport, "filename", "r")
293
self.assertEqual([], index.get_ancestry_with_ghosts([]))
294
self.assertEqual(["a"], index.get_ancestry_with_ghosts(["a"]))
295
self.assertEqual(["a", "e", "b"],
296
index.get_ancestry_with_ghosts(["b"]))
297
self.assertEqual(["a", "g", "f", "c"],
298
index.get_ancestry_with_ghosts(["c"]))
299
self.assertEqual(["a", "g", "f", "c", "k", "j", "h", "d"],
300
index.get_ancestry_with_ghosts(["d"]))
301
self.assertEqual(["a", "e", "b"],
302
index.get_ancestry_with_ghosts(["a", "b"]))
303
self.assertEqual(["a", "g", "f", "c"],
304
index.get_ancestry_with_ghosts(["a", "c"]))
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:
305
1032
self.assertEqual(
306
["a", "g", "f", "c", "e", "b", "k", "j", "h", "d"],
307
index.get_ancestry_with_ghosts(["b", "d"]))
309
self.assertRaises(RevisionNotPresent,
310
index.get_ancestry_with_ghosts, ["e"])
312
def test_num_versions(self):
313
transport = MockTransport([
316
index = _KnitIndex(transport, "filename", "r")
318
self.assertEqual(0, index.num_versions())
319
self.assertEqual(0, len(index))
321
index.add_version("a", ["option"], 0, 1, [])
322
self.assertEqual(1, index.num_versions())
323
self.assertEqual(1, len(index))
325
index.add_version("a", ["option2"], 1, 2, [])
326
self.assertEqual(1, index.num_versions())
327
self.assertEqual(1, len(index))
329
index.add_version("b", ["option"], 0, 1, [])
330
self.assertEqual(2, index.num_versions())
331
self.assertEqual(2, len(index))
333
def test_get_versions(self):
334
transport = MockTransport([
337
index = _KnitIndex(transport, "filename", "r")
339
self.assertEqual([], index.get_versions())
341
index.add_version("a", ["option"], 0, 1, [])
342
self.assertEqual(["a"], index.get_versions())
344
index.add_version("a", ["option"], 0, 1, [])
345
self.assertEqual(["a"], index.get_versions())
347
index.add_version("b", ["option"], 0, 1, [])
348
self.assertEqual(["a", "b"], index.get_versions())
350
def test_idx_to_name(self):
351
transport = MockTransport([
356
index = _KnitIndex(transport, "filename", "r")
358
self.assertEqual("a", index.idx_to_name(0))
359
self.assertEqual("b", index.idx_to_name(1))
360
self.assertEqual("b", index.idx_to_name(-1))
361
self.assertEqual("a", index.idx_to_name(-2))
363
def test_lookup(self):
364
transport = MockTransport([
369
index = _KnitIndex(transport, "filename", "r")
371
self.assertEqual(0, index.lookup("a"))
372
self.assertEqual(1, index.lookup("b"))
374
def test_add_version(self):
375
transport = MockTransport([
378
index = _KnitIndex(transport, "filename", "r")
380
index.add_version("a", ["option"], 0, 1, ["b"])
381
self.assertEqual(("append_bytes",
382
("filename", "\na option 0 1 .b :"),
383
{}), transport.calls.pop(0))
384
self.assertTrue(index.has_version("a"))
385
self.assertEqual(1, index.num_versions())
386
self.assertEqual((0, 1), index.get_position("a"))
387
self.assertEqual(["option"], index.get_options("a"))
388
self.assertEqual(["b"], index.get_parents_with_ghosts("a"))
390
index.add_version("a", ["opt"], 1, 2, ["c"])
391
self.assertEqual(("append_bytes",
392
("filename", "\na opt 1 2 .c :"),
393
{}), transport.calls.pop(0))
394
self.assertTrue(index.has_version("a"))
395
self.assertEqual(1, index.num_versions())
396
self.assertEqual((1, 2), index.get_position("a"))
397
self.assertEqual(["opt"], index.get_options("a"))
398
self.assertEqual(["c"], index.get_parents_with_ghosts("a"))
400
index.add_version("b", ["option"], 2, 3, ["a"])
401
self.assertEqual(("append_bytes",
402
("filename", "\nb option 2 3 0 :"),
403
{}), transport.calls.pop(0))
404
self.assertTrue(index.has_version("b"))
405
self.assertEqual(2, index.num_versions())
406
self.assertEqual((2, 3), index.get_position("b"))
407
self.assertEqual(["option"], index.get_options("b"))
408
self.assertEqual(["a"], index.get_parents_with_ghosts("b"))
410
def test_add_versions(self):
411
transport = MockTransport([
414
index = _KnitIndex(transport, "filename", "r")
417
("a", ["option"], 0, 1, ["b"]),
418
("a", ["opt"], 1, 2, ["c"]),
419
("b", ["option"], 2, 3, ["a"])
421
self.assertEqual(("append_bytes", ("filename",
422
1034
"\na option 0 1 .b :"
423
1035
"\na opt 1 2 .c :"
425
), {}), transport.calls.pop(0))
426
self.assertTrue(index.has_version("a"))
427
self.assertTrue(index.has_version("b"))
428
self.assertEqual(2, index.num_versions())
429
self.assertEqual((1, 2), index.get_position("a"))
430
self.assertEqual((2, 3), index.get_position("b"))
431
self.assertEqual(["opt"], index.get_options("a"))
432
self.assertEqual(["option"], index.get_options("b"))
433
self.assertEqual(["c"], index.get_parents_with_ghosts("a"))
434
self.assertEqual(["a"], index.get_parents_with_ghosts("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)
436
1048
def test_delay_create_and_add_versions(self):
437
1049
transport = MockTransport()
439
index = _KnitIndex(transport, "filename", "w",
440
create=True, file_mode="wb", create_parent_dir=True,
441
delay_create=True, dir_mode=0777)
1051
index = self.get_knit_index(transport, "filename", "w")
442
1053
self.assertEqual([], transport.calls)
445
("a", ["option"], 0, 1, ["b"]),
446
("a", ["opt"], 1, 2, ["c"]),
447
("b", ["option"], 2, 3, ["a"])
449
name, (filename, f), kwargs = transport.calls.pop(0)
450
self.assertEqual("put_file_non_atomic", name)
452
{"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
454
self.assertEqual("filename", filename)
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:
457
1074
"\na option 0 1 .b :"
458
1075
"\na opt 1 2 .c :"
459
1076
"\nb option 2 3 0 :",
462
def test_has_version(self):
463
transport = MockTransport([
467
index = _KnitIndex(transport, "filename", "r")
469
self.assertTrue(index.has_version("a"))
470
self.assertFalse(index.has_version("b"))
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)
472
1100
def test_get_position(self):
473
1101
transport = MockTransport([
475
1103
"a option 0 1 :",
476
1104
"b option 1 2 :"
478
index = _KnitIndex(transport, "filename", "r")
1106
index = self.get_knit_index(transport, "filename", "r")
480
self.assertEqual((0, 1), index.get_position("a"))
481
self.assertEqual((1, 2), index.get_position("b"))
1108
self.assertEqual((("a",), 0, 1), index.get_position(("a",)))
1109
self.assertEqual((("b",), 1, 2), index.get_position(("b",)))
483
1111
def test_get_method(self):
484
1112
transport = MockTransport([
486
1114
"a fulltext,unknown 0 1 :",
487
1115
"b unknown,line-delta 1 2 :",
490
index = _KnitIndex(transport, "filename", "r")
1118
index = self.get_knit_index(transport, "filename", "r")
492
1120
self.assertEqual("fulltext", index.get_method("a"))
493
1121
self.assertEqual("line-delta", index.get_method("b"))
496
1124
def test_get_options(self):
497
1125
transport = MockTransport([
500
1128
"b opt2,opt3 1 2 :"
502
index = _KnitIndex(transport, "filename", "r")
1130
index = self.get_knit_index(transport, "filename", "r")
504
1132
self.assertEqual(["opt1"], index.get_options("a"))
505
1133
self.assertEqual(["opt2", "opt3"], index.get_options("b"))
507
def test_get_parents(self):
508
transport = MockTransport([
511
"b option 1 2 0 .c :",
512
"c option 1 2 1 0 .e :"
514
index = _KnitIndex(transport, "filename", "r")
516
self.assertEqual([], index.get_parents("a"))
517
self.assertEqual(["a", "c"], index.get_parents("b"))
518
self.assertEqual(["b", "a"], index.get_parents("c"))
520
def test_get_parents_with_ghosts(self):
521
transport = MockTransport([
524
"b option 1 2 0 .c :",
525
"c option 1 2 1 0 .e :"
527
index = _KnitIndex(transport, "filename", "r")
529
self.assertEqual([], index.get_parents_with_ghosts("a"))
530
self.assertEqual(["a", "c"], index.get_parents_with_ghosts("b"))
531
self.assertEqual(["b", "a", "e"],
532
index.get_parents_with_ghosts("c"))
534
def test_check_versions_present(self):
535
transport = MockTransport([
540
index = _KnitIndex(transport, "filename", "r")
542
check = index.check_versions_present
548
self.assertRaises(RevisionNotPresent, check, ["c"])
549
self.assertRaises(RevisionNotPresent, check, ["a", "b", "c"])
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))
552
1462
class KnitTests(TestCaseWithTransport):
553
1463
"""Class containing knit test helper routines."""
555
def make_test_knit(self, annotate=False, delay_create=False):
557
factory = KnitPlainFactory()
560
return KnitVersionedFile('test', get_transport('.'), access_mode='w',
561
factory=factory, create=True,
562
delay_create=delay_create)
565
class BasicKnitTests(KnitTests):
567
def add_stock_one_and_one_a(self, k):
568
k.add_lines('text-1', [], split_lines(TEXT_1))
569
k.add_lines('text-1a', ['text-1'], split_lines(TEXT_1A))
571
def test_knit_constructor(self):
572
"""Construct empty k"""
573
self.make_test_knit()
575
def test_knit_add(self):
576
"""Store one text in knit and retrieve"""
577
k = self.make_test_knit()
578
k.add_lines('text-1', [], split_lines(TEXT_1))
579
self.assertTrue(k.has_version('text-1'))
580
self.assertEqualDiff(''.join(k.get_lines('text-1')), TEXT_1)
582
def test_knit_reload(self):
583
# test that the content in a reloaded knit is correct
584
k = self.make_test_knit()
585
k.add_lines('text-1', [], split_lines(TEXT_1))
587
k2 = KnitVersionedFile('test', get_transport('.'), access_mode='r', factory=KnitPlainFactory(), create=True)
588
self.assertTrue(k2.has_version('text-1'))
589
self.assertEqualDiff(''.join(k2.get_lines('text-1')), TEXT_1)
591
def test_knit_several(self):
592
"""Store several texts in a knit"""
593
k = self.make_test_knit()
594
k.add_lines('text-1', [], split_lines(TEXT_1))
595
k.add_lines('text-2', [], split_lines(TEXT_2))
596
self.assertEqualDiff(''.join(k.get_lines('text-1')), TEXT_1)
597
self.assertEqualDiff(''.join(k.get_lines('text-2')), TEXT_2)
599
def test_repeated_add(self):
600
"""Knit traps attempt to replace existing version"""
601
k = self.make_test_knit()
602
k.add_lines('text-1', [], split_lines(TEXT_1))
603
self.assertRaises(RevisionAlreadyPresent,
605
'text-1', [], split_lines(TEXT_1))
607
def test_empty(self):
608
k = self.make_test_knit(True)
609
k.add_lines('text-1', [], [])
610
self.assertEquals(k.get_lines('text-1'), [])
612
def test_incomplete(self):
613
"""Test if texts without a ending line-end can be inserted and
615
k = KnitVersionedFile('test', get_transport('.'), delta=False, create=True)
616
k.add_lines('text-1', [], ['a\n', 'b' ])
617
k.add_lines('text-2', ['text-1'], ['a\rb\n', 'b\n'])
618
# reopening ensures maximum room for confusion
619
k = KnitVersionedFile('test', get_transport('.'), delta=False, create=True)
620
self.assertEquals(k.get_lines('text-1'), ['a\n', 'b' ])
621
self.assertEquals(k.get_lines('text-2'), ['a\rb\n', 'b\n'])
623
def test_delta(self):
624
"""Expression of knit delta as lines"""
625
k = self.make_test_knit()
626
td = list(line_delta(TEXT_1.splitlines(True),
627
TEXT_1A.splitlines(True)))
628
self.assertEqualDiff(''.join(td), delta_1_1a)
629
out = apply_line_delta(TEXT_1.splitlines(True), td)
630
self.assertEqualDiff(''.join(out), TEXT_1A)
632
def test_add_with_parents(self):
633
"""Store in knit with parents"""
634
k = self.make_test_knit()
635
self.add_stock_one_and_one_a(k)
636
self.assertEquals(k.get_parents('text-1'), [])
637
self.assertEquals(k.get_parents('text-1a'), ['text-1'])
639
def test_ancestry(self):
640
"""Store in knit with parents"""
641
k = self.make_test_knit()
642
self.add_stock_one_and_one_a(k)
643
self.assertEquals(set(k.get_ancestry(['text-1a'])), set(['text-1a', 'text-1']))
645
def test_add_delta(self):
646
"""Store in knit with parents"""
647
k = KnitVersionedFile('test', get_transport('.'), factory=KnitPlainFactory(),
648
delta=True, create=True)
649
self.add_stock_one_and_one_a(k)
651
self.assertEqualDiff(''.join(k.get_lines('text-1a')), TEXT_1A)
653
def test_annotate(self):
655
k = KnitVersionedFile('knit', get_transport('.'), factory=KnitAnnotateFactory(),
656
delta=True, create=True)
657
self.insert_and_test_small_annotate(k)
659
def insert_and_test_small_annotate(self, k):
660
"""test annotation with k works correctly."""
661
k.add_lines('text-1', [], ['a\n', 'b\n'])
662
k.add_lines('text-2', ['text-1'], ['a\n', 'c\n'])
664
origins = k.annotate('text-2')
665
self.assertEquals(origins[0], ('text-1', 'a\n'))
666
self.assertEquals(origins[1], ('text-2', 'c\n'))
668
def test_annotate_fulltext(self):
670
k = KnitVersionedFile('knit', get_transport('.'), factory=KnitAnnotateFactory(),
671
delta=False, create=True)
672
self.insert_and_test_small_annotate(k)
674
def test_annotate_merge_1(self):
675
k = self.make_test_knit(True)
676
k.add_lines('text-a1', [], ['a\n', 'b\n'])
677
k.add_lines('text-a2', [], ['d\n', 'c\n'])
678
k.add_lines('text-am', ['text-a1', 'text-a2'], ['d\n', 'b\n'])
679
origins = k.annotate('text-am')
680
self.assertEquals(origins[0], ('text-a2', 'd\n'))
681
self.assertEquals(origins[1], ('text-a1', 'b\n'))
683
def test_annotate_merge_2(self):
684
k = self.make_test_knit(True)
685
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
686
k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
687
k.add_lines('text-am', ['text-a1', 'text-a2'], ['a\n', 'y\n', 'c\n'])
688
origins = k.annotate('text-am')
689
self.assertEquals(origins[0], ('text-a1', 'a\n'))
690
self.assertEquals(origins[1], ('text-a2', 'y\n'))
691
self.assertEquals(origins[2], ('text-a1', 'c\n'))
693
def test_annotate_merge_9(self):
694
k = self.make_test_knit(True)
695
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
696
k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
697
k.add_lines('text-am', ['text-a1', 'text-a2'], ['k\n', 'y\n', 'c\n'])
698
origins = k.annotate('text-am')
699
self.assertEquals(origins[0], ('text-am', 'k\n'))
700
self.assertEquals(origins[1], ('text-a2', 'y\n'))
701
self.assertEquals(origins[2], ('text-a1', 'c\n'))
703
def test_annotate_merge_3(self):
704
k = self.make_test_knit(True)
705
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
706
k.add_lines('text-a2', [] ,['x\n', 'y\n', 'z\n'])
707
k.add_lines('text-am', ['text-a1', 'text-a2'], ['k\n', 'y\n', 'z\n'])
708
origins = k.annotate('text-am')
709
self.assertEquals(origins[0], ('text-am', 'k\n'))
710
self.assertEquals(origins[1], ('text-a2', 'y\n'))
711
self.assertEquals(origins[2], ('text-a2', 'z\n'))
713
def test_annotate_merge_4(self):
714
k = self.make_test_knit(True)
715
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
716
k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
717
k.add_lines('text-a3', ['text-a1'], ['a\n', 'b\n', 'p\n'])
718
k.add_lines('text-am', ['text-a2', 'text-a3'], ['a\n', 'b\n', 'z\n'])
719
origins = k.annotate('text-am')
720
self.assertEquals(origins[0], ('text-a1', 'a\n'))
721
self.assertEquals(origins[1], ('text-a1', 'b\n'))
722
self.assertEquals(origins[2], ('text-a2', 'z\n'))
724
def test_annotate_merge_5(self):
725
k = self.make_test_knit(True)
726
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
727
k.add_lines('text-a2', [], ['d\n', 'e\n', 'f\n'])
728
k.add_lines('text-a3', [], ['x\n', 'y\n', 'z\n'])
729
k.add_lines('text-am',
730
['text-a1', 'text-a2', 'text-a3'],
731
['a\n', 'e\n', 'z\n'])
732
origins = k.annotate('text-am')
733
self.assertEquals(origins[0], ('text-a1', 'a\n'))
734
self.assertEquals(origins[1], ('text-a2', 'e\n'))
735
self.assertEquals(origins[2], ('text-a3', 'z\n'))
737
def test_annotate_file_cherry_pick(self):
738
k = self.make_test_knit(True)
739
k.add_lines('text-1', [], ['a\n', 'b\n', 'c\n'])
740
k.add_lines('text-2', ['text-1'], ['d\n', 'e\n', 'f\n'])
741
k.add_lines('text-3', ['text-2', 'text-1'], ['a\n', 'b\n', 'c\n'])
742
origins = k.annotate('text-3')
743
self.assertEquals(origins[0], ('text-1', 'a\n'))
744
self.assertEquals(origins[1], ('text-1', 'b\n'))
745
self.assertEquals(origins[2], ('text-1', 'c\n'))
747
def test_knit_join(self):
748
"""Store in knit with parents"""
749
k1 = KnitVersionedFile('test1', get_transport('.'), factory=KnitPlainFactory(), create=True)
750
k1.add_lines('text-a', [], split_lines(TEXT_1))
751
k1.add_lines('text-b', ['text-a'], split_lines(TEXT_1))
753
k1.add_lines('text-c', [], split_lines(TEXT_1))
754
k1.add_lines('text-d', ['text-c'], split_lines(TEXT_1))
756
k1.add_lines('text-m', ['text-b', 'text-d'], split_lines(TEXT_1))
758
k2 = KnitVersionedFile('test2', get_transport('.'), factory=KnitPlainFactory(), create=True)
759
count = k2.join(k1, version_ids=['text-m'])
760
self.assertEquals(count, 5)
761
self.assertTrue(k2.has_version('text-a'))
762
self.assertTrue(k2.has_version('text-c'))
764
def test_reannotate(self):
765
k1 = KnitVersionedFile('knit1', get_transport('.'),
766
factory=KnitAnnotateFactory(), create=True)
768
k1.add_lines('text-a', [], ['a\n', 'b\n'])
770
k1.add_lines('text-b', ['text-a'], ['a\n', 'c\n'])
772
k2 = KnitVersionedFile('test2', get_transport('.'),
773
factory=KnitAnnotateFactory(), create=True)
774
k2.join(k1, version_ids=['text-b'])
777
k1.add_lines('text-X', ['text-b'], ['a\n', 'b\n'])
779
k2.add_lines('text-c', ['text-b'], ['z\n', 'c\n'])
781
k2.add_lines('text-Y', ['text-b'], ['b\n', 'c\n'])
783
# test-c will have index 3
784
k1.join(k2, version_ids=['text-c'])
786
lines = k1.get_lines('text-c')
787
self.assertEquals(lines, ['z\n', 'c\n'])
789
origins = k1.annotate('text-c')
790
self.assertEquals(origins[0], ('text-c', 'z\n'))
791
self.assertEquals(origins[1], ('text-b', 'c\n'))
793
def test_get_line_delta_texts(self):
794
"""Make sure we can call get_texts on text with reused line deltas"""
795
k1 = KnitVersionedFile('test1', get_transport('.'),
796
factory=KnitPlainFactory(), create=True)
801
parents = ['%d' % (t-1)]
802
k1.add_lines('%d' % t, parents, ['hello\n'] * t)
803
k1.get_texts(('%d' % t) for t in range(3))
805
def test_iter_lines_reads_in_order(self):
806
t = MemoryTransport()
807
instrumented_t = TransportLogger(t)
808
k1 = KnitVersionedFile('id', instrumented_t, create=True, delta=True)
809
self.assertEqual([('id.kndx',)], instrumented_t._calls)
810
# add texts with no required ordering
811
k1.add_lines('base', [], ['text\n'])
812
k1.add_lines('base2', [], ['text2\n'])
814
instrumented_t._calls = []
815
# request a last-first iteration
816
results = list(k1.iter_lines_added_or_present_in_versions(['base2', 'base']))
817
self.assertEqual([('id.knit', [(0, 87), (87, 89)])], instrumented_t._calls)
818
self.assertEqual(['text\n', 'text2\n'], results)
820
def test_create_empty_annotated(self):
821
k1 = self.make_test_knit(True)
823
k1.add_lines('text-a', [], ['a\n', 'b\n'])
824
k2 = k1.create_empty('t', MemoryTransport())
825
self.assertTrue(isinstance(k2.factory, KnitAnnotateFactory))
826
self.assertEqual(k1.delta, k2.delta)
827
# the generic test checks for empty content and file class
829
def test_knit_format(self):
830
# this tests that a new knit index file has the expected content
831
# and that is writes the data we expect as records are added.
832
knit = self.make_test_knit(True)
833
# Now knit files are not created until we first add data to them
834
self.assertFileEqual("# bzr knit index 8\n", 'test.kndx')
835
knit.add_lines_with_ghosts('revid', ['a_ghost'], ['a\n'])
836
self.assertFileEqual(
837
"# bzr knit index 8\n"
839
"revid fulltext 0 84 .a_ghost :",
841
knit.add_lines_with_ghosts('revid2', ['revid'], ['a\n'])
842
self.assertFileEqual(
843
"# bzr knit index 8\n"
844
"\nrevid fulltext 0 84 .a_ghost :"
845
"\nrevid2 line-delta 84 82 0 :",
847
# we should be able to load this file again
848
knit = KnitVersionedFile('test', get_transport('.'), access_mode='r')
849
self.assertEqual(['revid', 'revid2'], knit.versions())
850
# write a short write to the file and ensure that its ignored
851
indexfile = file('test.kndx', 'at')
852
indexfile.write('\nrevid3 line-delta 166 82 1 2 3 4 5 .phwoar:demo ')
854
# we should be able to load this file again
855
knit = KnitVersionedFile('test', get_transport('.'), access_mode='w')
856
self.assertEqual(['revid', 'revid2'], knit.versions())
857
# and add a revision with the same id the failed write had
858
knit.add_lines('revid3', ['revid2'], ['a\n'])
859
# and when reading it revid3 should now appear.
860
knit = KnitVersionedFile('test', get_transport('.'), access_mode='r')
861
self.assertEqual(['revid', 'revid2', 'revid3'], knit.versions())
862
self.assertEqual(['revid2'], knit.get_parents('revid3'))
864
def test_delay_create(self):
865
"""Test that passing delay_create=True creates files late"""
866
knit = self.make_test_knit(annotate=True, delay_create=True)
867
self.failIfExists('test.knit')
868
self.failIfExists('test.kndx')
869
knit.add_lines_with_ghosts('revid', ['a_ghost'], ['a\n'])
870
self.failUnlessExists('test.knit')
871
self.assertFileEqual(
872
"# bzr knit index 8\n"
874
"revid fulltext 0 84 .a_ghost :",
877
def test_create_parent_dir(self):
878
"""create_parent_dir can create knits in nonexistant dirs"""
879
# Has no effect if we don't set 'delay_create'
880
trans = get_transport('.')
881
self.assertRaises(NoSuchFile, KnitVersionedFile, 'dir/test',
882
trans, access_mode='w', factory=None,
883
create=True, create_parent_dir=True)
884
# Nothing should have changed yet
885
knit = KnitVersionedFile('dir/test', trans, access_mode='w',
886
factory=None, create=True,
887
create_parent_dir=True,
889
self.failIfExists('dir/test.knit')
890
self.failIfExists('dir/test.kndx')
891
self.failIfExists('dir')
892
knit.add_lines('revid', [], ['a\n'])
893
self.failUnlessExists('dir')
894
self.failUnlessExists('dir/test.knit')
895
self.assertFileEqual(
896
"# bzr knit index 8\n"
898
"revid fulltext 0 84 :",
901
def test_create_mode_700(self):
902
trans = get_transport('.')
903
if not trans._can_roundtrip_unix_modebits():
904
# Can't roundtrip, so no need to run this test
906
knit = KnitVersionedFile('dir/test', trans, access_mode='w',
907
factory=None, create=True,
908
create_parent_dir=True,
912
knit.add_lines('revid', [], ['a\n'])
913
self.assertTransportMode(trans, 'dir', 0700)
914
self.assertTransportMode(trans, 'dir/test.knit', 0600)
915
self.assertTransportMode(trans, 'dir/test.kndx', 0600)
917
def test_create_mode_770(self):
918
trans = get_transport('.')
919
if not trans._can_roundtrip_unix_modebits():
920
# Can't roundtrip, so no need to run this test
922
knit = KnitVersionedFile('dir/test', trans, access_mode='w',
923
factory=None, create=True,
924
create_parent_dir=True,
928
knit.add_lines('revid', [], ['a\n'])
929
self.assertTransportMode(trans, 'dir', 0770)
930
self.assertTransportMode(trans, 'dir/test.knit', 0660)
931
self.assertTransportMode(trans, 'dir/test.kndx', 0660)
933
def test_create_mode_777(self):
934
trans = get_transport('.')
935
if not trans._can_roundtrip_unix_modebits():
936
# Can't roundtrip, so no need to run this test
938
knit = KnitVersionedFile('dir/test', trans, access_mode='w',
939
factory=None, create=True,
940
create_parent_dir=True,
944
knit.add_lines('revid', [], ['a\n'])
945
self.assertTransportMode(trans, 'dir', 0777)
946
self.assertTransportMode(trans, 'dir/test.knit', 0666)
947
self.assertTransportMode(trans, 'dir/test.kndx', 0666)
949
def test_plan_merge(self):
950
my_knit = self.make_test_knit(annotate=True)
951
my_knit.add_lines('text1', [], split_lines(TEXT_1))
952
my_knit.add_lines('text1a', ['text1'], split_lines(TEXT_1A))
953
my_knit.add_lines('text1b', ['text1'], split_lines(TEXT_1B))
954
plan = list(my_knit.plan_merge('text1a', 'text1b'))
955
for plan_line, expected_line in zip(plan, AB_MERGE):
956
self.assertEqual(plan_line, expected_line)
968
Banana cup cake recipe
978
Banana cup cake recipe
980
- bananas (do not use plantains!!!)
987
Banana cup cake recipe
1003
AB_MERGE_TEXT="""unchanged|Banana cup cake recipe
1008
new-b|- bananas (do not use plantains!!!)
1009
unchanged|- broken tea cups
1010
new-a|- self-raising flour
1013
AB_MERGE=[tuple(l.split('|')) for l in AB_MERGE_TEXT.splitlines(True)]
1016
def line_delta(from_lines, to_lines):
1017
"""Generate line-based delta from one text to another"""
1018
s = difflib.SequenceMatcher(None, from_lines, to_lines)
1019
for op in s.get_opcodes():
1020
if op[0] == 'equal':
1022
yield '%d,%d,%d\n' % (op[1], op[2], op[4]-op[3])
1023
for i in range(op[3], op[4]):
1027
def apply_line_delta(basis_lines, delta_lines):
1028
"""Apply a line-based perfect diff
1030
basis_lines -- text to apply the patch to
1031
delta_lines -- diff instructions and content
1033
out = basis_lines[:]
1036
while i < len(delta_lines):
1038
a, b, c = map(long, l.split(','))
1040
out[offset+a:offset+b] = delta_lines[i:i+c]
1042
offset = offset + (b - a) + c
1046
class TestWeaveToKnit(KnitTests):
1048
def test_weave_to_knit_matches(self):
1049
# check that the WeaveToKnit is_compatible function
1050
# registers True for a Weave to a Knit.
1052
k = self.make_test_knit()
1053
self.failUnless(WeaveToKnit.is_compatible(w, k))
1054
self.failIf(WeaveToKnit.is_compatible(k, w))
1055
self.failIf(WeaveToKnit.is_compatible(w, w))
1056
self.failIf(WeaveToKnit.is_compatible(k, k))
1059
class TestKnitCaching(KnitTests):
1061
def create_knit(self, cache_add=False):
1062
k = self.make_test_knit(True)
1066
k.add_lines('text-1', [], split_lines(TEXT_1))
1067
k.add_lines('text-2', [], split_lines(TEXT_2))
1070
def test_no_caching(self):
1071
k = self.create_knit()
1072
# Nothing should be cached without setting 'enable_cache'
1073
self.assertEqual({}, k._data._cache)
1075
def test_cache_add_and_clear(self):
1076
k = self.create_knit(True)
1078
self.assertEqual(['text-1', 'text-2'], sorted(k._data._cache.keys()))
1081
self.assertEqual({}, k._data._cache)
1083
def test_cache_data_read_raw(self):
1084
k = self.create_knit()
1086
# Now cache and read
1089
def read_one_raw(version):
1090
pos_map = k._get_components_positions([version])
1091
method, pos, size, next = pos_map[version]
1092
lst = list(k._data.read_records_iter_raw([(version, pos, size)]))
1093
self.assertEqual(1, len(lst))
1096
val = read_one_raw('text-1')
1097
self.assertEqual({'text-1':val[1]}, k._data._cache)
1100
# After clear, new reads are not cached
1101
self.assertEqual({}, k._data._cache)
1103
val2 = read_one_raw('text-1')
1104
self.assertEqual(val, val2)
1105
self.assertEqual({}, k._data._cache)
1107
def test_cache_data_read(self):
1108
k = self.create_knit()
1110
def read_one(version):
1111
pos_map = k._get_components_positions([version])
1112
method, pos, size, next = pos_map[version]
1113
lst = list(k._data.read_records_iter([(version, pos, size)]))
1114
self.assertEqual(1, len(lst))
1117
# Now cache and read
1120
val = read_one('text-2')
1121
self.assertEqual(['text-2'], k._data._cache.keys())
1122
self.assertEqual('text-2', val[0])
1123
content, digest = k._data._parse_record('text-2',
1124
k._data._cache['text-2'])
1125
self.assertEqual(content, val[1])
1126
self.assertEqual(digest, val[2])
1129
self.assertEqual({}, k._data._cache)
1131
val2 = read_one('text-2')
1132
self.assertEqual(val, val2)
1133
self.assertEqual({}, k._data._cache)
1135
def test_cache_read(self):
1136
k = self.create_knit()
1139
text = k.get_text('text-1')
1140
self.assertEqual(TEXT_1, text)
1141
self.assertEqual(['text-1'], k._data._cache.keys())
1144
self.assertEqual({}, k._data._cache)
1146
text = k.get_text('text-1')
1147
self.assertEqual(TEXT_1, text)
1148
self.assertEqual({}, k._data._cache)
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 ")
1151
1497
class TestKnitIndex(KnitTests):
1191
1543
knit = self.make_test_knit()
1192
1544
idx = knit._index
1193
idx.add_version('a-1', ['fulltext'], 0, 0, [])
1545
idx.add_records([(('a-1',), ['fulltext'], (('a-1',), 0, 0), [])])
1195
1547
class StopEarly(Exception):
1198
1550
def generate_failure():
1199
1551
"""Add some entries and then raise an exception"""
1200
yield ('a-2', ['fulltext'], 0, 0, ['a-1'])
1201
yield ('a-3', ['fulltext'], 0, 0, ['a-2'])
1552
yield (('a-2',), ['fulltext'], (None, 0, 0), ('a-1',))
1553
yield (('a-3',), ['fulltext'], (None, 0, 0), ('a-2',))
1202
1554
raise StopEarly()
1204
1556
# Assert the pre-condition
1205
self.assertEqual(['a-1'], idx._history)
1206
self.assertEqual({'a-1':('a-1', ['fulltext'], 0, 0, [], 0)}, idx._cache)
1208
self.assertRaises(StopEarly, idx.add_versions, generate_failure())
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())
1210
1566
# And it shouldn't be modified
1211
self.assertEqual(['a-1'], idx._history)
1212
self.assertEqual({'a-1':('a-1', ['fulltext'], 0, 0, [], 0)}, idx._cache)
1214
1569
def test_knit_index_ignores_empty_files(self):
1215
1570
# There was a race condition in older bzr, where a ^C at the right time
1216
1571
# could leave an empty .kndx file, which bzr would later claim was a
1217
1572
# corrupted file since the header was not present. In reality, the file
1218
1573
# just wasn't created, so it should be ignored.
1219
t = get_transport('.')
1574
t = transport.get_transport('.')
1220
1575
t.put_bytes('test.kndx', '')
1222
1577
knit = self.make_test_knit()
1224
1579
def test_knit_index_checks_header(self):
1225
t = get_transport('.')
1580
t = transport.get_transport('.')
1226
1581
t.put_bytes('test.kndx', '# not really a knit header\n\n')
1228
self.assertRaises(KnitHeaderError, self.make_test_knit)
1582
k = self.make_test_knit()
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)