1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Tests for the Repository facility that are not interface tests.
19
For interface tests see tests/per_repository/*.py.
21
For concrete class tests see this file, and for storage formats tests
25
from stat import S_ISDIR
28
from breezy.errors import (
30
UnsupportedFormatError,
36
from breezy.bzr import (
40
repository as bzrrepository,
45
from breezy.bzr.btree_index import BTreeBuilder, BTreeGraphIndex
46
from breezy.bzr.index import GraphIndex
47
from breezy.repository import RepositoryFormat
48
from breezy.tests import (
50
TestCaseWithTransport,
57
revision as _mod_revision,
61
from breezy.bzr import (
69
class TestDefaultFormat(TestCase):
71
def test_get_set_default_format(self):
72
old_default = controldir.format_registry.get('default')
73
private_default = old_default().repository_format.__class__
74
old_format = repository.format_registry.get_default()
75
self.assertTrue(isinstance(old_format, private_default))
76
def make_sample_bzrdir():
77
my_bzrdir = bzrdir.BzrDirMetaFormat1()
78
my_bzrdir.repository_format = SampleRepositoryFormat()
80
controldir.format_registry.remove('default')
81
controldir.format_registry.register('sample', make_sample_bzrdir, '')
82
controldir.format_registry.set_default('sample')
83
# creating a repository should now create an instrumented dir.
85
# the default branch format is used by the meta dir format
86
# which is not the default bzrdir format at this point
87
dir = bzrdir.BzrDirMetaFormat1().initialize('memory:///')
88
result = dir.create_repository()
89
self.assertEqual(result, 'A bzr repository dir')
91
controldir.format_registry.remove('default')
92
controldir.format_registry.remove('sample')
93
controldir.format_registry.register('default', old_default, '')
94
self.assertIsInstance(repository.format_registry.get_default(),
98
class SampleRepositoryFormat(bzrrepository.RepositoryFormatMetaDir):
101
this format is initializable, unsupported to aid in testing the
102
open and open(unsupported=True) routines.
106
def get_format_string(cls):
107
"""See RepositoryFormat.get_format_string()."""
108
return b"Sample .bzr repository format."
110
def initialize(self, a_controldir, shared=False):
111
"""Initialize a repository in a BzrDir"""
112
t = a_controldir.get_repository_transport(self)
113
t.put_bytes('format', self.get_format_string())
114
return 'A bzr repository dir'
116
def is_supported(self):
119
def open(self, a_controldir, _found=False):
120
return "opened repository."
123
class SampleExtraRepositoryFormat(repository.RepositoryFormat):
124
"""A sample format that can not be used in a metadir
128
def get_format_string(self):
129
raise NotImplementedError
132
class TestRepositoryFormat(TestCaseWithTransport):
133
"""Tests for the Repository format detection used by the bzr meta dir facility.BzrBranchFormat facility."""
135
def test_find_format(self):
136
# is the right format object found for a repository?
137
# create a branch with a few known format objects.
138
# this is not quite the same as
139
self.build_tree(["foo/", "bar/"])
140
def check_format(format, url):
141
dir = format._matchingcontroldir.initialize(url)
142
format.initialize(dir)
143
t = transport.get_transport_from_path(url)
144
found_format = bzrrepository.RepositoryFormatMetaDir.find_format(dir)
145
self.assertIsInstance(found_format, format.__class__)
146
check_format(repository.format_registry.get_default(), "bar")
148
def test_find_format_no_repository(self):
149
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
150
self.assertRaises(errors.NoRepositoryPresent,
151
bzrrepository.RepositoryFormatMetaDir.find_format,
154
def test_from_string(self):
155
self.assertIsInstance(
156
SampleRepositoryFormat.from_string(
157
b"Sample .bzr repository format."),
158
SampleRepositoryFormat)
159
self.assertRaises(AssertionError,
160
SampleRepositoryFormat.from_string,
161
b"Different .bzr repository format.")
163
def test_find_format_unknown_format(self):
164
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
165
SampleRepositoryFormat().initialize(dir)
166
self.assertRaises(UnknownFormatError,
167
bzrrepository.RepositoryFormatMetaDir.find_format,
170
def test_find_format_with_features(self):
171
tree = self.make_branch_and_tree('.', format='2a')
172
tree.branch.repository.update_feature_flags({b"name": b"necessity"})
173
found_format = bzrrepository.RepositoryFormatMetaDir.find_format(tree.controldir)
174
self.assertIsInstance(found_format, bzrrepository.RepositoryFormatMetaDir)
175
self.assertEqual(found_format.features.get(b"name"), b"necessity")
176
self.assertRaises(bzrdir.MissingFeature, found_format.check_support_status,
178
self.addCleanup(bzrrepository.RepositoryFormatMetaDir.unregister_feature,
180
bzrrepository.RepositoryFormatMetaDir.register_feature(b"name")
181
found_format.check_support_status(True)
184
class TestRepositoryFormatRegistry(TestCase):
187
super(TestRepositoryFormatRegistry, self).setUp()
188
self.registry = repository.RepositoryFormatRegistry()
190
def test_register_unregister_format(self):
191
format = SampleRepositoryFormat()
192
self.registry.register(format)
193
self.assertEqual(format, self.registry.get(b"Sample .bzr repository format."))
194
self.registry.remove(format)
195
self.assertRaises(KeyError, self.registry.get, b"Sample .bzr repository format.")
197
def test_get_all(self):
198
format = SampleRepositoryFormat()
199
self.assertEqual([], self.registry._get_all())
200
self.registry.register(format)
201
self.assertEqual([format], self.registry._get_all())
203
def test_register_extra(self):
204
format = SampleExtraRepositoryFormat()
205
self.assertEqual([], self.registry._get_all())
206
self.registry.register_extra(format)
207
self.assertEqual([format], self.registry._get_all())
209
def test_register_extra_lazy(self):
210
self.assertEqual([], self.registry._get_all())
211
self.registry.register_extra_lazy("breezy.tests.test_repository",
212
"SampleExtraRepositoryFormat")
213
formats = self.registry._get_all()
214
self.assertEqual(1, len(formats))
215
self.assertIsInstance(formats[0], SampleExtraRepositoryFormat)
218
class TestFormatKnit1(TestCaseWithTransport):
220
def test_attribute__fetch_order(self):
221
"""Knits need topological data insertion."""
222
repo = self.make_repository('.',
223
format=controldir.format_registry.get('knit')())
224
self.assertEqual('topological', repo._format._fetch_order)
226
def test_attribute__fetch_uses_deltas(self):
227
"""Knits reuse deltas."""
228
repo = self.make_repository('.',
229
format=controldir.format_registry.get('knit')())
230
self.assertEqual(True, repo._format._fetch_uses_deltas)
232
def test_disk_layout(self):
233
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
234
repo = knitrepo.RepositoryFormatKnit1().initialize(control)
235
# in case of side effects of locking.
239
# format 'Bazaar-NG Knit Repository Format 1'
240
# lock: is a directory
241
# inventory.weave == empty_weave
242
# empty revision-store directory
243
# empty weaves directory
244
t = control.get_repository_transport(None)
245
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
246
t.get('format').read())
247
# XXX: no locks left when unlocked at the moment
248
# self.assertEqualDiff('', t.get('lock').read())
249
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
251
# Check per-file knits.
252
branch = control.create_branch()
253
tree = control.create_workingtree()
254
tree.add(['foo'], ['Nasty-IdC:'], ['file'])
255
tree.put_file_bytes_non_atomic('foo', '')
256
tree.commit('1st post', rev_id=b'foo')
257
self.assertHasKnit(t, 'knits/e8/%254easty-%2549d%2543%253a',
258
'\nfoo fulltext 0 81 :')
260
def assertHasKnit(self, t, knit_name, extra_content=''):
261
"""Assert that knit_name exists on t."""
262
self.assertEqualDiff('# bzr knit index 8\n' + extra_content,
263
t.get(knit_name + '.kndx').read())
265
def check_knits(self, t):
266
"""check knit content for a repository."""
267
self.assertHasKnit(t, 'inventory')
268
self.assertHasKnit(t, 'revisions')
269
self.assertHasKnit(t, 'signatures')
271
def test_shared_disk_layout(self):
272
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
273
repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
275
# format 'Bazaar-NG Knit Repository Format 1'
276
# lock: is a directory
277
# inventory.weave == empty_weave
278
# empty revision-store directory
279
# empty weaves directory
280
# a 'shared-storage' marker file.
281
t = control.get_repository_transport(None)
282
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
283
t.get('format').read())
284
# XXX: no locks left when unlocked at the moment
285
# self.assertEqualDiff('', t.get('lock').read())
286
self.assertEqualDiff('', t.get('shared-storage').read())
287
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
290
def test_shared_no_tree_disk_layout(self):
291
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
292
repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
293
repo.set_make_working_trees(False)
295
# format 'Bazaar-NG Knit Repository Format 1'
297
# inventory.weave == empty_weave
298
# empty revision-store directory
299
# empty weaves directory
300
# a 'shared-storage' marker file.
301
t = control.get_repository_transport(None)
302
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
303
t.get('format').read())
304
# XXX: no locks left when unlocked at the moment
305
# self.assertEqualDiff('', t.get('lock').read())
306
self.assertEqualDiff('', t.get('shared-storage').read())
307
self.assertEqualDiff('', t.get('no-working-trees').read())
308
repo.set_make_working_trees(True)
309
self.assertFalse(t.has('no-working-trees'))
310
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
313
def test_deserialise_sets_root_revision(self):
314
"""We must have a inventory.root.revision
316
Old versions of the XML5 serializer did not set the revision_id for
317
the whole inventory. So we grab the one from the expected text. Which
318
is valid when the api is not being abused.
320
repo = self.make_repository('.',
321
format=controldir.format_registry.get('knit')())
322
inv_xml = '<inventory format="5">\n</inventory>\n'
323
inv = repo._deserialise_inventory('test-rev-id', inv_xml)
324
self.assertEqual('test-rev-id', inv.root.revision)
326
def test_deserialise_uses_global_revision_id(self):
327
"""If it is set, then we re-use the global revision id"""
328
repo = self.make_repository('.',
329
format=controldir.format_registry.get('knit')())
330
inv_xml = ('<inventory format="5" revision_id="other-rev-id">\n'
332
# Arguably, the deserialise_inventory should detect a mismatch, and
333
# raise an error, rather than silently using one revision_id over the
335
self.assertRaises(AssertionError, repo._deserialise_inventory,
336
'test-rev-id', inv_xml)
337
inv = repo._deserialise_inventory('other-rev-id', inv_xml)
338
self.assertEqual('other-rev-id', inv.root.revision)
340
def test_supports_external_lookups(self):
341
repo = self.make_repository('.',
342
format=controldir.format_registry.get('knit')())
343
self.assertFalse(repo._format.supports_external_lookups)
346
class DummyRepository(object):
347
"""A dummy repository for testing."""
352
def supports_rich_root(self):
353
if self._format is not None:
354
return self._format.rich_root_data
358
raise NotImplementedError
360
def get_parent_map(self, revision_ids):
361
raise NotImplementedError
364
class InterDummy(repository.InterRepository):
365
"""An inter-repository optimised code path for DummyRepository.
367
This is for use during testing where we use DummyRepository as repositories
368
so that none of the default regsitered inter-repository classes will
373
def is_compatible(repo_source, repo_target):
374
"""InterDummy is compatible with DummyRepository."""
375
return (isinstance(repo_source, DummyRepository) and
376
isinstance(repo_target, DummyRepository))
379
class TestInterRepository(TestCaseWithTransport):
381
def test_get_default_inter_repository(self):
382
# test that the InterRepository.get(repo_a, repo_b) probes
383
# for a inter_repo class where is_compatible(repo_a, repo_b) returns
384
# true and returns a default inter_repo otherwise.
385
# This also tests that the default registered optimised interrepository
386
# classes do not barf inappropriately when a surprising repository type
388
dummy_a = DummyRepository()
389
dummy_a._format = RepositoryFormat()
390
dummy_a._format.supports_full_versioned_files = True
391
dummy_b = DummyRepository()
392
dummy_b._format = RepositoryFormat()
393
dummy_b._format.supports_full_versioned_files = True
394
self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
396
def assertGetsDefaultInterRepository(self, repo_a, repo_b):
397
"""Asserts that InterRepository.get(repo_a, repo_b) -> the default.
399
The effective default is now InterSameDataRepository because there is
400
no actual sane default in the presence of incompatible data models.
402
inter_repo = repository.InterRepository.get(repo_a, repo_b)
403
self.assertEqual(vf_repository.InterSameDataRepository,
404
inter_repo.__class__)
405
self.assertEqual(repo_a, inter_repo.source)
406
self.assertEqual(repo_b, inter_repo.target)
408
def test_register_inter_repository_class(self):
409
# test that a optimised code path provider - a
410
# InterRepository subclass can be registered and unregistered
411
# and that it is correctly selected when given a repository
412
# pair that it returns true on for the is_compatible static method
414
dummy_a = DummyRepository()
415
dummy_a._format = RepositoryFormat()
416
dummy_b = DummyRepository()
417
dummy_b._format = RepositoryFormat()
418
repo = self.make_repository('.')
419
# hack dummies to look like repo somewhat.
420
dummy_a._serializer = repo._serializer
421
dummy_a._format.supports_tree_reference = repo._format.supports_tree_reference
422
dummy_a._format.rich_root_data = repo._format.rich_root_data
423
dummy_a._format.supports_full_versioned_files = repo._format.supports_full_versioned_files
424
dummy_b._serializer = repo._serializer
425
dummy_b._format.supports_tree_reference = repo._format.supports_tree_reference
426
dummy_b._format.rich_root_data = repo._format.rich_root_data
427
dummy_b._format.supports_full_versioned_files = repo._format.supports_full_versioned_files
428
repository.InterRepository.register_optimiser(InterDummy)
430
# we should get the default for something InterDummy returns False
432
self.assertFalse(InterDummy.is_compatible(dummy_a, repo))
433
self.assertGetsDefaultInterRepository(dummy_a, repo)
434
# and we should get an InterDummy for a pair it 'likes'
435
self.assertTrue(InterDummy.is_compatible(dummy_a, dummy_b))
436
inter_repo = repository.InterRepository.get(dummy_a, dummy_b)
437
self.assertEqual(InterDummy, inter_repo.__class__)
438
self.assertEqual(dummy_a, inter_repo.source)
439
self.assertEqual(dummy_b, inter_repo.target)
441
repository.InterRepository.unregister_optimiser(InterDummy)
442
# now we should get the default InterRepository object again.
443
self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
446
class TestRepositoryFormat1(knitrepo.RepositoryFormatKnit1):
449
def get_format_string(cls):
450
return b"Test Format 1"
453
class TestRepositoryFormat2(knitrepo.RepositoryFormatKnit1):
456
def get_format_string(cls):
457
return b"Test Format 2"
460
class TestRepositoryConverter(TestCaseWithTransport):
462
def test_convert_empty(self):
463
source_format = TestRepositoryFormat1()
464
target_format = TestRepositoryFormat2()
465
repository.format_registry.register(source_format)
466
self.addCleanup(repository.format_registry.remove,
468
repository.format_registry.register(target_format)
469
self.addCleanup(repository.format_registry.remove,
471
t = self.get_transport()
472
t.mkdir('repository')
473
repo_dir = bzrdir.BzrDirMetaFormat1().initialize('repository')
474
repo = TestRepositoryFormat1().initialize(repo_dir)
475
converter = repository.CopyConverter(target_format)
476
with breezy.ui.ui_factory.nested_progress_bar() as pb:
477
converter.convert(repo, pb)
478
repo = repo_dir.open_repository()
479
self.assertTrue(isinstance(target_format, repo._format.__class__))
482
class TestRepositoryFormatKnit3(TestCaseWithTransport):
484
def test_attribute__fetch_order(self):
485
"""Knits need topological data insertion."""
486
format = bzrdir.BzrDirMetaFormat1()
487
format.repository_format = knitrepo.RepositoryFormatKnit3()
488
repo = self.make_repository('.', format=format)
489
self.assertEqual('topological', repo._format._fetch_order)
491
def test_attribute__fetch_uses_deltas(self):
492
"""Knits reuse deltas."""
493
format = bzrdir.BzrDirMetaFormat1()
494
format.repository_format = knitrepo.RepositoryFormatKnit3()
495
repo = self.make_repository('.', format=format)
496
self.assertEqual(True, repo._format._fetch_uses_deltas)
498
def test_convert(self):
499
"""Ensure the upgrade adds weaves for roots"""
500
format = bzrdir.BzrDirMetaFormat1()
501
format.repository_format = knitrepo.RepositoryFormatKnit1()
502
tree = self.make_branch_and_tree('.', format)
503
tree.commit("Dull commit", rev_id="dull")
504
revision_tree = tree.branch.repository.revision_tree('dull')
505
revision_tree.lock_read()
507
self.assertRaises(errors.NoSuchFile, revision_tree.get_file_lines,
508
u'', revision_tree.get_root_id())
510
revision_tree.unlock()
511
format = bzrdir.BzrDirMetaFormat1()
512
format.repository_format = knitrepo.RepositoryFormatKnit3()
513
upgrade.Convert('.', format)
514
tree = workingtree.WorkingTree.open('.')
515
revision_tree = tree.branch.repository.revision_tree('dull')
516
revision_tree.lock_read()
518
revision_tree.get_file_lines(u'', revision_tree.get_root_id())
520
revision_tree.unlock()
521
tree.commit("Another dull commit", rev_id=b'dull2')
522
revision_tree = tree.branch.repository.revision_tree('dull2')
523
revision_tree.lock_read()
524
self.addCleanup(revision_tree.unlock)
525
self.assertEqual('dull',
526
revision_tree.get_file_revision(u'', revision_tree.get_root_id()))
528
def test_supports_external_lookups(self):
529
format = bzrdir.BzrDirMetaFormat1()
530
format.repository_format = knitrepo.RepositoryFormatKnit3()
531
repo = self.make_repository('.', format=format)
532
self.assertFalse(repo._format.supports_external_lookups)
535
class Test2a(tests.TestCaseWithMemoryTransport):
537
def test_chk_bytes_uses_custom_btree_parser(self):
538
mt = self.make_branch_and_memory_tree('test', format='2a')
540
self.addCleanup(mt.unlock)
541
mt.add([''], [b'root-id'])
543
index = mt.branch.repository.chk_bytes._index._graph_index._indices[0]
544
self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
545
# It should also work if we re-open the repo
546
repo = mt.branch.repository.controldir.open_repository()
548
self.addCleanup(repo.unlock)
549
index = repo.chk_bytes._index._graph_index._indices[0]
550
self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
552
def test_fetch_combines_groups(self):
553
builder = self.make_branch_builder('source', format='2a')
554
builder.start_series()
555
builder.build_snapshot(None, [
556
('add', ('', b'root-id', 'directory', '')),
557
('add', ('file', b'file-id', 'file', b'content\n'))],
559
builder.build_snapshot([b'1'], [
560
('modify', ('file', b'content-2\n'))],
562
builder.finish_series()
563
source = builder.get_branch()
564
target = self.make_repository('target', format='2a')
565
target.fetch(source.repository)
567
self.addCleanup(target.unlock)
568
details = target.texts._index.get_build_details(
569
[(b'file-id', b'1',), (b'file-id', b'2',)])
570
file_1_details = details[(b'file-id', b'1')]
571
file_2_details = details[(b'file-id', b'2')]
572
# The index, and what to read off disk, should be the same for both
573
# versions of the file.
574
self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
576
def test_fetch_combines_groups(self):
577
builder = self.make_branch_builder('source', format='2a')
578
builder.start_series()
579
builder.build_snapshot(None, [
580
('add', ('', b'root-id', 'directory', '')),
581
('add', ('file', b'file-id', 'file', 'content\n'))],
583
builder.build_snapshot([b'1'], [
584
('modify', ('file', b'content-2\n'))],
586
builder.finish_series()
587
source = builder.get_branch()
588
target = self.make_repository('target', format='2a')
589
target.fetch(source.repository)
591
self.addCleanup(target.unlock)
592
details = target.texts._index.get_build_details(
593
[(b'file-id', b'1',), (b'file-id', b'2',)])
594
file_1_details = details[(b'file-id', b'1')]
595
file_2_details = details[(b'file-id', b'2')]
596
# The index, and what to read off disk, should be the same for both
597
# versions of the file.
598
self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
600
def test_fetch_combines_groups(self):
601
builder = self.make_branch_builder('source', format='2a')
602
builder.start_series()
603
builder.build_snapshot(None, [
604
('add', ('', b'root-id', 'directory', '')),
605
('add', ('file', b'file-id', 'file', 'content\n'))],
607
builder.build_snapshot([b'1'], [
608
('modify', ('file', b'content-2\n'))],
610
builder.finish_series()
611
source = builder.get_branch()
612
target = self.make_repository('target', format='2a')
613
target.fetch(source.repository)
615
self.addCleanup(target.unlock)
616
details = target.texts._index.get_build_details(
617
[(b'file-id', b'1',), (b'file-id', b'2',)])
618
file_1_details = details[(b'file-id', b'1')]
619
file_2_details = details[(b'file-id', b'2')]
620
# The index, and what to read off disk, should be the same for both
621
# versions of the file.
622
self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
624
def test_format_pack_compresses_True(self):
625
repo = self.make_repository('repo', format='2a')
626
self.assertTrue(repo._format.pack_compresses)
628
def test_inventories_use_chk_map_with_parent_base_dict(self):
629
tree = self.make_branch_and_memory_tree('repo', format="2a")
631
tree.add([''], [b'TREE_ROOT'])
632
revid = tree.commit("foo")
635
self.addCleanup(tree.unlock)
636
inv = tree.branch.repository.get_inventory(revid)
637
self.assertNotEqual(None, inv.parent_id_basename_to_file_id)
638
inv.parent_id_basename_to_file_id._ensure_root()
639
inv.id_to_entry._ensure_root()
640
self.assertEqual(65536, inv.id_to_entry._root_node.maximum_size)
641
self.assertEqual(65536,
642
inv.parent_id_basename_to_file_id._root_node.maximum_size)
644
def test_autopack_unchanged_chk_nodes(self):
645
# at 20 unchanged commits, chk pages are packed that are split into
646
# two groups such that the new pack being made doesn't have all its
647
# pages in the source packs (though they are in the repository).
648
# Use a memory backed repository, we don't need to hit disk for this
649
tree = self.make_branch_and_memory_tree('tree', format='2a')
651
self.addCleanup(tree.unlock)
652
tree.add([''], [b'TREE_ROOT'])
653
for pos in range(20):
654
tree.commit(str(pos))
656
def test_pack_with_hint(self):
657
tree = self.make_branch_and_memory_tree('tree', format='2a')
659
self.addCleanup(tree.unlock)
660
tree.add([''], [b'TREE_ROOT'])
661
# 1 commit to leave untouched
663
to_keep = tree.branch.repository._pack_collection.names()
667
all = tree.branch.repository._pack_collection.names()
668
combine = list(set(all) - set(to_keep))
669
self.assertLength(3, all)
670
self.assertLength(2, combine)
671
tree.branch.repository.pack(hint=combine)
672
final = tree.branch.repository._pack_collection.names()
673
self.assertLength(2, final)
674
self.assertFalse(combine[0] in final)
675
self.assertFalse(combine[1] in final)
676
self.assertSubset(to_keep, final)
678
def test_stream_source_to_gc(self):
679
source = self.make_repository('source', format='2a')
680
target = self.make_repository('target', format='2a')
681
stream = source._get_source(target._format)
682
self.assertIsInstance(stream, groupcompress_repo.GroupCHKStreamSource)
684
def test_stream_source_to_non_gc(self):
685
source = self.make_repository('source', format='2a')
686
target = self.make_repository('target', format='rich-root-pack')
687
stream = source._get_source(target._format)
688
# We don't want the child GroupCHKStreamSource
689
self.assertIs(type(stream), vf_repository.StreamSource)
691
def test_get_stream_for_missing_keys_includes_all_chk_refs(self):
692
source_builder = self.make_branch_builder('source',
694
# We have to build a fairly large tree, so that we are sure the chk
695
# pages will have split into multiple pages.
696
entries = [('add', ('', b'a-root-id', 'directory', None))]
697
for i in 'abcdefghijklmnopqrstuvwxyz123456789':
698
for j in 'abcdefghijklmnopqrstuvwxyz123456789':
700
fid = fname.encode('utf-8') + b'-id'
701
content = 'content for %s\n' % (fname,)
702
entries.append(('add', (fname, fid, 'file', content)))
703
source_builder.start_series()
704
source_builder.build_snapshot(None, entries, revision_id=b'rev-1')
705
# Now change a few of them, so we get a few new pages for the second
707
source_builder.build_snapshot([b'rev-1'], [
708
('modify', ('aa', b'new content for aa-id\n')),
709
('modify', ('cc', b'new content for cc-id\n')),
710
('modify', ('zz', b'new content for zz-id\n')),
711
], revision_id=b'rev-2')
712
source_builder.finish_series()
713
source_branch = source_builder.get_branch()
714
source_branch.lock_read()
715
self.addCleanup(source_branch.unlock)
716
target = self.make_repository('target', format='2a')
717
source = source_branch.repository._get_source(target._format)
718
self.assertIsInstance(source, groupcompress_repo.GroupCHKStreamSource)
720
# On a regular pass, getting the inventories and chk pages for rev-2
721
# would only get the newly created chk pages
722
search = vf_search.SearchResult({b'rev-2'}, {b'rev-1'}, 1,
724
simple_chk_records = []
725
for vf_name, substream in source.get_stream(search):
726
if vf_name == 'chk_bytes':
727
for record in substream:
728
simple_chk_records.append(record.key)
732
# 3 pages, the root (InternalNode), + 2 pages which actually changed
733
self.assertEqual([('sha1:91481f539e802c76542ea5e4c83ad416bf219f73',),
734
('sha1:4ff91971043668583985aec83f4f0ab10a907d3f',),
735
('sha1:81e7324507c5ca132eedaf2d8414ee4bb2226187',),
736
('sha1:b101b7da280596c71a4540e9a1eeba8045985ee0',)],
738
# Now, when we do a similar call using 'get_stream_for_missing_keys'
739
# we should get a much larger set of pages.
740
missing = [('inventories', 'rev-2')]
741
full_chk_records = []
742
for vf_name, substream in source.get_stream_for_missing_keys(missing):
743
if vf_name == 'inventories':
744
for record in substream:
745
self.assertEqual(('rev-2',), record.key)
746
elif vf_name == 'chk_bytes':
747
for record in substream:
748
full_chk_records.append(record.key)
750
self.fail('Should not be getting a stream of %s' % (vf_name,))
751
# We have 257 records now. This is because we have 1 root page, and 256
752
# leaf pages in a complete listing.
753
self.assertEqual(257, len(full_chk_records))
754
self.assertSubset(simple_chk_records, full_chk_records)
756
def test_inconsistency_fatal(self):
757
repo = self.make_repository('repo', format='2a')
758
self.assertTrue(repo.revisions._index._inconsistency_fatal)
759
self.assertFalse(repo.texts._index._inconsistency_fatal)
760
self.assertFalse(repo.inventories._index._inconsistency_fatal)
761
self.assertFalse(repo.signatures._index._inconsistency_fatal)
762
self.assertFalse(repo.chk_bytes._index._inconsistency_fatal)
765
class TestKnitPackStreamSource(tests.TestCaseWithMemoryTransport):
767
def test_source_to_exact_pack_092(self):
768
source = self.make_repository('source', format='pack-0.92')
769
target = self.make_repository('target', format='pack-0.92')
770
stream_source = source._get_source(target._format)
771
self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
773
def test_source_to_exact_pack_rich_root_pack(self):
774
source = self.make_repository('source', format='rich-root-pack')
775
target = self.make_repository('target', format='rich-root-pack')
776
stream_source = source._get_source(target._format)
777
self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
779
def test_source_to_exact_pack_19(self):
780
source = self.make_repository('source', format='1.9')
781
target = self.make_repository('target', format='1.9')
782
stream_source = source._get_source(target._format)
783
self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
785
def test_source_to_exact_pack_19_rich_root(self):
786
source = self.make_repository('source', format='1.9-rich-root')
787
target = self.make_repository('target', format='1.9-rich-root')
788
stream_source = source._get_source(target._format)
789
self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
791
def test_source_to_remote_exact_pack_19(self):
792
trans = self.make_smart_server('target')
794
source = self.make_repository('source', format='1.9')
795
target = self.make_repository('target', format='1.9')
796
target = repository.Repository.open(trans.base)
797
stream_source = source._get_source(target._format)
798
self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
800
def test_stream_source_to_non_exact(self):
801
source = self.make_repository('source', format='pack-0.92')
802
target = self.make_repository('target', format='1.9')
803
stream = source._get_source(target._format)
804
self.assertIs(type(stream), vf_repository.StreamSource)
806
def test_stream_source_to_non_exact_rich_root(self):
807
source = self.make_repository('source', format='1.9')
808
target = self.make_repository('target', format='1.9-rich-root')
809
stream = source._get_source(target._format)
810
self.assertIs(type(stream), vf_repository.StreamSource)
812
def test_source_to_remote_non_exact_pack_19(self):
813
trans = self.make_smart_server('target')
815
source = self.make_repository('source', format='1.9')
816
target = self.make_repository('target', format='1.6')
817
target = repository.Repository.open(trans.base)
818
stream_source = source._get_source(target._format)
819
self.assertIs(type(stream_source), vf_repository.StreamSource)
821
def test_stream_source_to_knit(self):
822
source = self.make_repository('source', format='pack-0.92')
823
target = self.make_repository('target', format='dirstate')
824
stream = source._get_source(target._format)
825
self.assertIs(type(stream), vf_repository.StreamSource)
828
class TestDevelopment6FindParentIdsOfRevisions(TestCaseWithTransport):
829
"""Tests for _find_parent_ids_of_revisions."""
832
super(TestDevelopment6FindParentIdsOfRevisions, self).setUp()
833
self.builder = self.make_branch_builder('source')
834
self.builder.start_series()
835
self.builder.build_snapshot(None,
836
[('add', ('', 'tree-root', 'directory', None))],
837
revision_id='initial')
838
self.repo = self.builder.get_branch().repository
839
self.addCleanup(self.builder.finish_series)
841
def assertParentIds(self, expected_result, rev_set):
842
self.assertEqual(sorted(expected_result),
843
sorted(self.repo._find_parent_ids_of_revisions(rev_set)))
845
def test_simple(self):
846
self.builder.build_snapshot(None, [], revision_id='revid1')
847
self.builder.build_snapshot(['revid1'], [], revision_id='revid2')
849
self.assertParentIds(['revid1'], rev_set)
851
def test_not_first_parent(self):
852
self.builder.build_snapshot(None, [], revision_id='revid1')
853
self.builder.build_snapshot(['revid1'], [], revision_id='revid2')
854
self.builder.build_snapshot(['revid2'], [], revision_id='revid3')
855
rev_set = ['revid3', 'revid2']
856
self.assertParentIds(['revid1'], rev_set)
858
def test_not_null(self):
859
rev_set = ['initial']
860
self.assertParentIds([], rev_set)
862
def test_not_null_set(self):
863
self.builder.build_snapshot(None, [], revision_id='revid1')
864
rev_set = [_mod_revision.NULL_REVISION]
865
self.assertParentIds([], rev_set)
867
def test_ghost(self):
868
self.builder.build_snapshot(None, [], revision_id='revid1')
869
rev_set = ['ghost', 'revid1']
870
self.assertParentIds(['initial'], rev_set)
872
def test_ghost_parent(self):
873
self.builder.build_snapshot(None, [], revision_id='revid1')
874
self.builder.build_snapshot(['revid1', 'ghost'], [], revision_id='revid2')
875
rev_set = ['revid2', 'revid1']
876
self.assertParentIds(['ghost', 'initial'], rev_set)
878
def test_righthand_parent(self):
879
self.builder.build_snapshot(None, [], revision_id='revid1')
880
self.builder.build_snapshot(['revid1'], [], revision_id='revid2a')
881
self.builder.build_snapshot(['revid1'], [], revision_id='revid2b')
882
self.builder.build_snapshot(['revid2a', 'revid2b'], [],
883
revision_id='revid3')
884
rev_set = ['revid3', 'revid2a']
885
self.assertParentIds(['revid1', 'revid2b'], rev_set)
888
class TestWithBrokenRepo(TestCaseWithTransport):
889
"""These tests seem to be more appropriate as interface tests?"""
891
def make_broken_repository(self):
892
# XXX: This function is borrowed from Aaron's "Reconcile can fix bad
893
# parent references" branch which is due to land in bzr.dev soon. Once
894
# it does, this duplication should be removed.
895
repo = self.make_repository('broken-repo')
899
cleanups.append(repo.unlock)
900
repo.start_write_group()
901
cleanups.append(repo.commit_write_group)
902
# make rev1a: A well-formed revision, containing 'file1'
903
inv = inventory.Inventory(revision_id='rev1a')
904
inv.root.revision = 'rev1a'
905
self.add_file(repo, inv, 'file1', 'rev1a', [])
906
repo.texts.add_lines((inv.root.file_id, 'rev1a'), [], [])
907
repo.add_inventory('rev1a', inv, [])
908
revision = _mod_revision.Revision('rev1a',
909
committer='jrandom@example.com', timestamp=0,
910
inventory_sha1='', timezone=0, message='foo', parent_ids=[])
911
repo.add_revision('rev1a', revision, inv)
913
# make rev1b, which has no Revision, but has an Inventory, and
915
inv = inventory.Inventory(revision_id='rev1b')
916
inv.root.revision = 'rev1b'
917
self.add_file(repo, inv, 'file1', 'rev1b', [])
918
repo.add_inventory('rev1b', inv, [])
920
# make rev2, with file1 and file2
922
# file1 has 'rev1b' as an ancestor, even though this is not
923
# mentioned by 'rev1a', making it an unreferenced ancestor
924
inv = inventory.Inventory()
925
self.add_file(repo, inv, 'file1', 'rev2', ['rev1a', 'rev1b'])
926
self.add_file(repo, inv, 'file2', 'rev2', [])
927
self.add_revision(repo, 'rev2', inv, ['rev1a'])
929
# make ghost revision rev1c
930
inv = inventory.Inventory()
931
self.add_file(repo, inv, 'file2', 'rev1c', [])
933
# make rev3 with file2
934
# file2 refers to 'rev1c', which is a ghost in this repository, so
935
# file2 cannot have rev1c as its ancestor.
936
inv = inventory.Inventory()
937
self.add_file(repo, inv, 'file2', 'rev3', ['rev1c'])
938
self.add_revision(repo, 'rev3', inv, ['rev1c'])
941
for cleanup in reversed(cleanups):
944
def add_revision(self, repo, revision_id, inv, parent_ids):
945
inv.revision_id = revision_id
946
inv.root.revision = revision_id
947
repo.texts.add_lines((inv.root.file_id, revision_id), [], [])
948
repo.add_inventory(revision_id, inv, parent_ids)
949
revision = _mod_revision.Revision(revision_id,
950
committer='jrandom@example.com', timestamp=0, inventory_sha1='',
951
timezone=0, message='foo', parent_ids=parent_ids)
952
repo.add_revision(revision_id, revision, inv)
954
def add_file(self, repo, inv, filename, revision, parents):
955
file_id = filename + '-id'
956
entry = inventory.InventoryFile(file_id, filename, 'TREE_ROOT')
957
entry.revision = revision
960
text_key = (file_id, revision)
961
parent_keys = [(file_id, parent) for parent in parents]
962
repo.texts.add_lines(text_key, parent_keys, ['line\n'])
964
def test_insert_from_broken_repo(self):
965
"""Inserting a data stream from a broken repository won't silently
966
corrupt the target repository.
968
broken_repo = self.make_broken_repository()
969
empty_repo = self.make_repository('empty-repo')
971
empty_repo.fetch(broken_repo)
972
except (errors.RevisionNotPresent, errors.BzrCheckError):
973
# Test successful: compression parent not being copied leads to
976
empty_repo.lock_read()
977
self.addCleanup(empty_repo.unlock)
978
text = next(empty_repo.texts.get_record_stream(
979
[('file2-id', 'rev3')], 'topological', True))
980
self.assertEqual('line\n', text.get_bytes_as('fulltext'))
983
class TestRepositoryPackCollection(TestCaseWithTransport):
985
def get_format(self):
986
return controldir.format_registry.make_controldir('pack-0.92')
989
format = self.get_format()
990
repo = self.make_repository('.', format=format)
991
return repo._pack_collection
993
def make_packs_and_alt_repo(self, write_lock=False):
994
"""Create a pack repo with 3 packs, and access it via a second repo."""
995
tree = self.make_branch_and_tree('.', format=self.get_format())
997
self.addCleanup(tree.unlock)
998
rev1 = tree.commit('one')
999
rev2 = tree.commit('two')
1000
rev3 = tree.commit('three')
1001
r = repository.Repository.open('.')
1006
self.addCleanup(r.unlock)
1007
packs = r._pack_collection
1008
packs.ensure_loaded()
1009
return tree, r, packs, [rev1, rev2, rev3]
1011
def test__clear_obsolete_packs(self):
1012
packs = self.get_packs()
1013
obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1014
obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1015
obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1016
obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1017
obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1018
obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1019
res = packs._clear_obsolete_packs()
1020
self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1021
self.assertEqual([], obsolete_pack_trans.list_dir('.'))
1023
def test__clear_obsolete_packs_preserve(self):
1024
packs = self.get_packs()
1025
obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1026
obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1027
obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1028
obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1029
obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1030
obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1031
res = packs._clear_obsolete_packs(preserve={'a-pack'})
1032
self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1033
self.assertEqual(['a-pack.iix', 'a-pack.pack', 'a-pack.rix'],
1034
sorted(obsolete_pack_trans.list_dir('.')))
1036
def test__max_pack_count(self):
1037
"""The maximum pack count is a function of the number of revisions."""
1038
# no revisions - one pack, so that we can have a revision free repo
1039
# without it blowing up
1040
packs = self.get_packs()
1041
self.assertEqual(1, packs._max_pack_count(0))
1042
# after that the sum of the digits, - check the first 1-9
1043
self.assertEqual(1, packs._max_pack_count(1))
1044
self.assertEqual(2, packs._max_pack_count(2))
1045
self.assertEqual(3, packs._max_pack_count(3))
1046
self.assertEqual(4, packs._max_pack_count(4))
1047
self.assertEqual(5, packs._max_pack_count(5))
1048
self.assertEqual(6, packs._max_pack_count(6))
1049
self.assertEqual(7, packs._max_pack_count(7))
1050
self.assertEqual(8, packs._max_pack_count(8))
1051
self.assertEqual(9, packs._max_pack_count(9))
1052
# check the boundary cases with two digits for the next decade
1053
self.assertEqual(1, packs._max_pack_count(10))
1054
self.assertEqual(2, packs._max_pack_count(11))
1055
self.assertEqual(10, packs._max_pack_count(19))
1056
self.assertEqual(2, packs._max_pack_count(20))
1057
self.assertEqual(3, packs._max_pack_count(21))
1058
# check some arbitrary big numbers
1059
self.assertEqual(25, packs._max_pack_count(112894))
1061
def test_repr(self):
1062
packs = self.get_packs()
1063
self.assertContainsRe(repr(packs),
1064
'RepositoryPackCollection(.*Repository(.*))')
1066
def test__obsolete_packs(self):
1067
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1068
names = packs.names()
1069
pack = packs.get_pack_by_name(names[0])
1070
# Schedule this one for removal
1071
packs._remove_pack_from_memory(pack)
1072
# Simulate a concurrent update by renaming the .pack file and one of
1074
packs.transport.rename('packs/%s.pack' % (names[0],),
1075
'obsolete_packs/%s.pack' % (names[0],))
1076
packs.transport.rename('indices/%s.iix' % (names[0],),
1077
'obsolete_packs/%s.iix' % (names[0],))
1078
# Now trigger the obsoletion, and ensure that all the remaining files
1080
packs._obsolete_packs([pack])
1081
self.assertEqual([n + '.pack' for n in names[1:]],
1082
sorted(packs._pack_transport.list_dir('.')))
1083
# names[0] should not be present in the index anymore
1084
self.assertEqual(names[1:],
1085
sorted({osutils.splitext(n)[0] for n in
1086
packs._index_transport.list_dir('.')}))
1088
def test__obsolete_packs_missing_directory(self):
1089
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1090
r.control_transport.rmdir('obsolete_packs')
1091
names = packs.names()
1092
pack = packs.get_pack_by_name(names[0])
1093
# Schedule this one for removal
1094
packs._remove_pack_from_memory(pack)
1095
# Now trigger the obsoletion, and ensure that all the remaining files
1097
packs._obsolete_packs([pack])
1098
self.assertEqual([n + '.pack' for n in names[1:]],
1099
sorted(packs._pack_transport.list_dir('.')))
1100
# names[0] should not be present in the index anymore
1101
self.assertEqual(names[1:],
1102
sorted({osutils.splitext(n)[0] for n in
1103
packs._index_transport.list_dir('.')}))
1105
def test_pack_distribution_zero(self):
1106
packs = self.get_packs()
1107
self.assertEqual([0], packs.pack_distribution(0))
1109
def test_ensure_loaded_unlocked(self):
1110
packs = self.get_packs()
1111
self.assertRaises(errors.ObjectNotLocked,
1112
packs.ensure_loaded)
1114
def test_pack_distribution_one_to_nine(self):
1115
packs = self.get_packs()
1116
self.assertEqual([1],
1117
packs.pack_distribution(1))
1118
self.assertEqual([1, 1],
1119
packs.pack_distribution(2))
1120
self.assertEqual([1, 1, 1],
1121
packs.pack_distribution(3))
1122
self.assertEqual([1, 1, 1, 1],
1123
packs.pack_distribution(4))
1124
self.assertEqual([1, 1, 1, 1, 1],
1125
packs.pack_distribution(5))
1126
self.assertEqual([1, 1, 1, 1, 1, 1],
1127
packs.pack_distribution(6))
1128
self.assertEqual([1, 1, 1, 1, 1, 1, 1],
1129
packs.pack_distribution(7))
1130
self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1],
1131
packs.pack_distribution(8))
1132
self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1, 1],
1133
packs.pack_distribution(9))
1135
def test_pack_distribution_stable_at_boundaries(self):
1136
"""When there are multi-rev packs the counts are stable."""
1137
packs = self.get_packs()
1139
self.assertEqual([10], packs.pack_distribution(10))
1140
self.assertEqual([10, 1], packs.pack_distribution(11))
1141
self.assertEqual([10, 10], packs.pack_distribution(20))
1142
self.assertEqual([10, 10, 1], packs.pack_distribution(21))
1144
self.assertEqual([100], packs.pack_distribution(100))
1145
self.assertEqual([100, 1], packs.pack_distribution(101))
1146
self.assertEqual([100, 10, 1], packs.pack_distribution(111))
1147
self.assertEqual([100, 100], packs.pack_distribution(200))
1148
self.assertEqual([100, 100, 1], packs.pack_distribution(201))
1149
self.assertEqual([100, 100, 10, 1], packs.pack_distribution(211))
1151
def test_plan_pack_operations_2009_revisions_skip_all_packs(self):
1152
packs = self.get_packs()
1153
existing_packs = [(2000, "big"), (9, "medium")]
1154
# rev count - 2009 -> 2x1000 + 9x1
1155
pack_operations = packs.plan_autopack_combinations(
1156
existing_packs, [1000, 1000, 1, 1, 1, 1, 1, 1, 1, 1, 1])
1157
self.assertEqual([], pack_operations)
1159
def test_plan_pack_operations_2010_revisions_skip_all_packs(self):
1160
packs = self.get_packs()
1161
existing_packs = [(2000, "big"), (9, "medium"), (1, "single")]
1162
# rev count - 2010 -> 2x1000 + 1x10
1163
pack_operations = packs.plan_autopack_combinations(
1164
existing_packs, [1000, 1000, 10])
1165
self.assertEqual([], pack_operations)
1167
def test_plan_pack_operations_2010_combines_smallest_two(self):
1168
packs = self.get_packs()
1169
existing_packs = [(1999, "big"), (9, "medium"), (1, "single2"),
1171
# rev count - 2010 -> 2x1000 + 1x10 (3)
1172
pack_operations = packs.plan_autopack_combinations(
1173
existing_packs, [1000, 1000, 10])
1174
self.assertEqual([[2, ["single2", "single1"]]], pack_operations)
1176
def test_plan_pack_operations_creates_a_single_op(self):
1177
packs = self.get_packs()
1178
existing_packs = [(50, 'a'), (40, 'b'), (30, 'c'), (10, 'd'),
1179
(10, 'e'), (6, 'f'), (4, 'g')]
1180
# rev count 150 -> 1x100 and 5x10
1181
# The two size 10 packs do not need to be touched. The 50, 40, 30 would
1182
# be combined into a single 120 size pack, and the 6 & 4 would
1183
# becombined into a size 10 pack. However, if we have to rewrite them,
1184
# we save a pack file with no increased I/O by putting them into the
1186
distribution = packs.pack_distribution(150)
1187
pack_operations = packs.plan_autopack_combinations(existing_packs,
1189
self.assertEqual([[130, ['a', 'b', 'c', 'f', 'g']]], pack_operations)
1191
def test_all_packs_none(self):
1192
format = self.get_format()
1193
tree = self.make_branch_and_tree('.', format=format)
1195
self.addCleanup(tree.unlock)
1196
packs = tree.branch.repository._pack_collection
1197
packs.ensure_loaded()
1198
self.assertEqual([], packs.all_packs())
1200
def test_all_packs_one(self):
1201
format = self.get_format()
1202
tree = self.make_branch_and_tree('.', format=format)
1203
tree.commit('start')
1205
self.addCleanup(tree.unlock)
1206
packs = tree.branch.repository._pack_collection
1207
packs.ensure_loaded()
1209
packs.get_pack_by_name(packs.names()[0])],
1212
def test_all_packs_two(self):
1213
format = self.get_format()
1214
tree = self.make_branch_and_tree('.', format=format)
1215
tree.commit('start')
1216
tree.commit('continue')
1218
self.addCleanup(tree.unlock)
1219
packs = tree.branch.repository._pack_collection
1220
packs.ensure_loaded()
1222
packs.get_pack_by_name(packs.names()[0]),
1223
packs.get_pack_by_name(packs.names()[1]),
1224
], packs.all_packs())
1226
def test_get_pack_by_name(self):
1227
format = self.get_format()
1228
tree = self.make_branch_and_tree('.', format=format)
1229
tree.commit('start')
1231
self.addCleanup(tree.unlock)
1232
packs = tree.branch.repository._pack_collection
1234
packs.ensure_loaded()
1235
name = packs.names()[0]
1236
pack_1 = packs.get_pack_by_name(name)
1237
# the pack should be correctly initialised
1238
sizes = packs._names[name]
1239
rev_index = GraphIndex(packs._index_transport, name + '.rix', sizes[0])
1240
inv_index = GraphIndex(packs._index_transport, name + '.iix', sizes[1])
1241
txt_index = GraphIndex(packs._index_transport, name + '.tix', sizes[2])
1242
sig_index = GraphIndex(packs._index_transport, name + '.six', sizes[3])
1243
self.assertEqual(pack_repo.ExistingPack(packs._pack_transport,
1244
name, rev_index, inv_index, txt_index, sig_index), pack_1)
1245
# and the same instance should be returned on successive calls.
1246
self.assertTrue(pack_1 is packs.get_pack_by_name(name))
1248
def test_reload_pack_names_new_entry(self):
1249
tree, r, packs, revs = self.make_packs_and_alt_repo()
1250
names = packs.names()
1251
# Add a new pack file into the repository
1252
rev4 = tree.commit('four')
1253
new_names = tree.branch.repository._pack_collection.names()
1254
new_name = set(new_names).difference(names)
1255
self.assertEqual(1, len(new_name))
1256
new_name = new_name.pop()
1257
# The old collection hasn't noticed yet
1258
self.assertEqual(names, packs.names())
1259
self.assertTrue(packs.reload_pack_names())
1260
self.assertEqual(new_names, packs.names())
1261
# And the repository can access the new revision
1262
self.assertEqual({rev4:(revs[-1],)}, r.get_parent_map([rev4]))
1263
self.assertFalse(packs.reload_pack_names())
1265
def test_reload_pack_names_added_and_removed(self):
1266
tree, r, packs, revs = self.make_packs_and_alt_repo()
1267
names = packs.names()
1268
# Now repack the whole thing
1269
tree.branch.repository.pack()
1270
new_names = tree.branch.repository._pack_collection.names()
1271
# The other collection hasn't noticed yet
1272
self.assertEqual(names, packs.names())
1273
self.assertTrue(packs.reload_pack_names())
1274
self.assertEqual(new_names, packs.names())
1275
self.assertEqual({revs[-1]:(revs[-2],)}, r.get_parent_map([revs[-1]]))
1276
self.assertFalse(packs.reload_pack_names())
1278
def test_reload_pack_names_preserves_pending(self):
1279
# TODO: Update this to also test for pending-deleted names
1280
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1281
# We will add one pack (via start_write_group + insert_record_stream),
1282
# and remove another pack (via _remove_pack_from_memory)
1283
orig_names = packs.names()
1284
orig_at_load = packs._packs_at_load
1285
to_remove_name = next(iter(orig_names))
1286
r.start_write_group()
1287
self.addCleanup(r.abort_write_group)
1288
r.texts.insert_record_stream([versionedfile.FulltextContentFactory(
1289
('text', 'rev'), (), None, 'content\n')])
1290
new_pack = packs._new_pack
1291
self.assertTrue(new_pack.data_inserted())
1293
packs.allocate(new_pack)
1294
packs._new_pack = None
1295
removed_pack = packs.get_pack_by_name(to_remove_name)
1296
packs._remove_pack_from_memory(removed_pack)
1297
names = packs.names()
1298
all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
1299
new_names = {x[0][0] for x in new_nodes}
1300
self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1301
self.assertEqual(set(names) - set(orig_names), new_names)
1302
self.assertEqual({new_pack.name}, new_names)
1303
self.assertEqual([to_remove_name],
1304
sorted([x[0][0] for x in deleted_nodes]))
1305
packs.reload_pack_names()
1306
reloaded_names = packs.names()
1307
self.assertEqual(orig_at_load, packs._packs_at_load)
1308
self.assertEqual(names, reloaded_names)
1309
all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
1310
new_names = {x[0][0] for x in new_nodes}
1311
self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1312
self.assertEqual(set(names) - set(orig_names), new_names)
1313
self.assertEqual({new_pack.name}, new_names)
1314
self.assertEqual([to_remove_name],
1315
sorted([x[0][0] for x in deleted_nodes]))
1317
def test_autopack_obsoletes_new_pack(self):
1318
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1319
packs._max_pack_count = lambda x: 1
1320
packs.pack_distribution = lambda x: [10]
1321
r.start_write_group()
1322
r.revisions.insert_record_stream([versionedfile.FulltextContentFactory(
1323
('bogus-rev',), (), None, 'bogus-content\n')])
1324
# This should trigger an autopack, which will combine everything into a
1326
new_names = r.commit_write_group()
1327
names = packs.names()
1328
self.assertEqual(1, len(names))
1329
self.assertEqual([names[0] + '.pack'],
1330
packs._pack_transport.list_dir('.'))
1332
def test_autopack_reloads_and_stops(self):
1333
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1334
# After we have determined what needs to be autopacked, trigger a
1335
# full-pack via the other repo which will cause us to re-evaluate and
1336
# decide we don't need to do anything
1337
orig_execute = packs._execute_pack_operations
1338
def _munged_execute_pack_ops(*args, **kwargs):
1339
tree.branch.repository.pack()
1340
return orig_execute(*args, **kwargs)
1341
packs._execute_pack_operations = _munged_execute_pack_ops
1342
packs._max_pack_count = lambda x: 1
1343
packs.pack_distribution = lambda x: [10]
1344
self.assertFalse(packs.autopack())
1345
self.assertEqual(1, len(packs.names()))
1346
self.assertEqual(tree.branch.repository._pack_collection.names(),
1349
def test__save_pack_names(self):
1350
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1351
names = packs.names()
1352
pack = packs.get_pack_by_name(names[0])
1353
packs._remove_pack_from_memory(pack)
1354
packs._save_pack_names(obsolete_packs=[pack])
1355
cur_packs = packs._pack_transport.list_dir('.')
1356
self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1357
# obsolete_packs will also have stuff like .rix and .iix present.
1358
obsolete_packs = packs.transport.list_dir('obsolete_packs')
1359
obsolete_names = {osutils.splitext(n)[0] for n in obsolete_packs}
1360
self.assertEqual([pack.name], sorted(obsolete_names))
1362
def test__save_pack_names_already_obsoleted(self):
1363
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1364
names = packs.names()
1365
pack = packs.get_pack_by_name(names[0])
1366
packs._remove_pack_from_memory(pack)
1367
# We are going to simulate a concurrent autopack by manually obsoleting
1368
# the pack directly.
1369
packs._obsolete_packs([pack])
1370
packs._save_pack_names(clear_obsolete_packs=True,
1371
obsolete_packs=[pack])
1372
cur_packs = packs._pack_transport.list_dir('.')
1373
self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1374
# Note that while we set clear_obsolete_packs=True, it should not
1375
# delete a pack file that we have also scheduled for obsoletion.
1376
obsolete_packs = packs.transport.list_dir('obsolete_packs')
1377
obsolete_names = {osutils.splitext(n)[0] for n in obsolete_packs}
1378
self.assertEqual([pack.name], sorted(obsolete_names))
1380
def test_pack_no_obsolete_packs_directory(self):
1381
"""Bug #314314, don't fail if obsolete_packs directory does
1383
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1384
r.control_transport.rmdir('obsolete_packs')
1385
packs._clear_obsolete_packs()
1388
class TestPack(TestCaseWithTransport):
1389
"""Tests for the Pack object."""
1391
def assertCurrentlyEqual(self, left, right):
1392
self.assertTrue(left == right)
1393
self.assertTrue(right == left)
1394
self.assertFalse(left != right)
1395
self.assertFalse(right != left)
1397
def assertCurrentlyNotEqual(self, left, right):
1398
self.assertFalse(left == right)
1399
self.assertFalse(right == left)
1400
self.assertTrue(left != right)
1401
self.assertTrue(right != left)
1403
def test___eq____ne__(self):
1404
left = pack_repo.ExistingPack('', '', '', '', '', '')
1405
right = pack_repo.ExistingPack('', '', '', '', '', '')
1406
self.assertCurrentlyEqual(left, right)
1407
# change all attributes and ensure equality changes as we do.
1408
left.revision_index = 'a'
1409
self.assertCurrentlyNotEqual(left, right)
1410
right.revision_index = 'a'
1411
self.assertCurrentlyEqual(left, right)
1412
left.inventory_index = 'a'
1413
self.assertCurrentlyNotEqual(left, right)
1414
right.inventory_index = 'a'
1415
self.assertCurrentlyEqual(left, right)
1416
left.text_index = 'a'
1417
self.assertCurrentlyNotEqual(left, right)
1418
right.text_index = 'a'
1419
self.assertCurrentlyEqual(left, right)
1420
left.signature_index = 'a'
1421
self.assertCurrentlyNotEqual(left, right)
1422
right.signature_index = 'a'
1423
self.assertCurrentlyEqual(left, right)
1425
self.assertCurrentlyNotEqual(left, right)
1427
self.assertCurrentlyEqual(left, right)
1428
left.transport = 'a'
1429
self.assertCurrentlyNotEqual(left, right)
1430
right.transport = 'a'
1431
self.assertCurrentlyEqual(left, right)
1433
def test_file_name(self):
1434
pack = pack_repo.ExistingPack('', 'a_name', '', '', '', '')
1435
self.assertEqual('a_name.pack', pack.file_name())
1438
class TestNewPack(TestCaseWithTransport):
1439
"""Tests for pack_repo.NewPack."""
1441
def test_new_instance_attributes(self):
1442
upload_transport = self.get_transport('upload')
1443
pack_transport = self.get_transport('pack')
1444
index_transport = self.get_transport('index')
1445
upload_transport.mkdir('.')
1446
collection = pack_repo.RepositoryPackCollection(
1448
transport=self.get_transport('.'),
1449
index_transport=index_transport,
1450
upload_transport=upload_transport,
1451
pack_transport=pack_transport,
1452
index_builder_class=BTreeBuilder,
1453
index_class=BTreeGraphIndex,
1454
use_chk_index=False)
1455
pack = pack_repo.NewPack(collection)
1456
self.addCleanup(pack.abort) # Make sure the write stream gets closed
1457
self.assertIsInstance(pack.revision_index, BTreeBuilder)
1458
self.assertIsInstance(pack.inventory_index, BTreeBuilder)
1459
self.assertIsInstance(pack._hash, type(osutils.md5()))
1460
self.assertTrue(pack.upload_transport is upload_transport)
1461
self.assertTrue(pack.index_transport is index_transport)
1462
self.assertTrue(pack.pack_transport is pack_transport)
1463
self.assertEqual(None, pack.index_sizes)
1464
self.assertEqual(20, len(pack.random_name))
1465
self.assertIsInstance(pack.random_name, str)
1466
self.assertIsInstance(pack.start_time, float)
1469
class TestPacker(TestCaseWithTransport):
1470
"""Tests for the packs repository Packer class."""
1472
def test_pack_optimizes_pack_order(self):
1473
builder = self.make_branch_builder('.', format="1.9")
1474
builder.start_series()
1475
builder.build_snapshot(None, [
1476
('add', ('', 'root-id', 'directory', None)),
1477
('add', ('f', 'f-id', 'file', 'content\n'))],
1479
builder.build_snapshot(['A'],
1480
[('modify', ('f', 'new-content\n'))],
1482
builder.build_snapshot(['B'],
1483
[('modify', ('f', 'third-content\n'))],
1485
builder.build_snapshot(['C'],
1486
[('modify', ('f', 'fourth-content\n'))],
1488
b = builder.get_branch()
1490
builder.finish_series()
1491
self.addCleanup(b.unlock)
1492
# At this point, we should have 4 pack files available
1493
# Because of how they were built, they correspond to
1494
# ['D', 'C', 'B', 'A']
1495
packs = b.repository._pack_collection.packs
1496
packer = knitpack_repo.KnitPacker(b.repository._pack_collection,
1498
revision_ids=['B', 'C'])
1499
# Now, when we are copying the B & C revisions, their pack files should
1500
# be moved to the front of the stack
1501
# The new ordering moves B & C to the front of the .packs attribute,
1502
# and leaves the others in the original order.
1503
new_packs = [packs[1], packs[2], packs[0], packs[3]]
1504
new_pack = packer.pack()
1505
self.assertEqual(new_packs, packer.packs)
1508
class TestOptimisingPacker(TestCaseWithTransport):
1509
"""Tests for the OptimisingPacker class."""
1511
def get_pack_collection(self):
1512
repo = self.make_repository('.')
1513
return repo._pack_collection
1515
def test_open_pack_will_optimise(self):
1516
packer = knitpack_repo.OptimisingKnitPacker(self.get_pack_collection(),
1518
new_pack = packer.open_pack()
1519
self.addCleanup(new_pack.abort) # ensure cleanup
1520
self.assertIsInstance(new_pack, pack_repo.NewPack)
1521
self.assertTrue(new_pack.revision_index._optimize_for_size)
1522
self.assertTrue(new_pack.inventory_index._optimize_for_size)
1523
self.assertTrue(new_pack.text_index._optimize_for_size)
1524
self.assertTrue(new_pack.signature_index._optimize_for_size)
1527
class TestGCCHKPacker(TestCaseWithTransport):
1529
def make_abc_branch(self):
1530
builder = self.make_branch_builder('source')
1531
builder.start_series()
1532
builder.build_snapshot(None, [
1533
('add', ('', 'root-id', 'directory', None)),
1534
('add', ('file', 'file-id', 'file', 'content\n')),
1536
builder.build_snapshot(['A'], [
1537
('add', ('dir', 'dir-id', 'directory', None))],
1539
builder.build_snapshot(['B'], [
1540
('modify', ('file', 'new content\n'))],
1542
builder.finish_series()
1543
return builder.get_branch()
1545
def make_branch_with_disjoint_inventory_and_revision(self):
1546
"""a repo with separate packs for a revisions Revision and Inventory.
1548
There will be one pack file that holds the Revision content, and one
1549
for the Inventory content.
1551
:return: (repository,
1552
pack_name_with_rev_A_Revision,
1553
pack_name_with_rev_A_Inventory,
1554
pack_name_with_rev_C_content)
1556
b_source = self.make_abc_branch()
1557
b_base = b_source.controldir.sprout('base', revision_id='A').open_branch()
1558
b_stacked = b_base.controldir.sprout('stacked', stacked=True).open_branch()
1559
b_stacked.lock_write()
1560
self.addCleanup(b_stacked.unlock)
1561
b_stacked.fetch(b_source, 'B')
1562
# Now re-open the stacked repo directly (no fallbacks) so that we can
1563
# fill in the A rev.
1564
repo_not_stacked = b_stacked.controldir.open_repository()
1565
repo_not_stacked.lock_write()
1566
self.addCleanup(repo_not_stacked.unlock)
1567
# Now we should have a pack file with A's inventory, but not its
1569
self.assertEqual([('A',), ('B',)],
1570
sorted(repo_not_stacked.inventories.keys()))
1571
self.assertEqual([('B',)],
1572
sorted(repo_not_stacked.revisions.keys()))
1573
stacked_pack_names = repo_not_stacked._pack_collection.names()
1574
# We have a couple names here, figure out which has A's inventory
1575
for name in stacked_pack_names:
1576
pack = repo_not_stacked._pack_collection.get_pack_by_name(name)
1577
keys = [n[1] for n in pack.inventory_index.iter_all_entries()]
1579
inv_a_pack_name = name
1582
self.fail('Could not find pack containing A\'s inventory')
1583
repo_not_stacked.fetch(b_source.repository, 'A')
1584
self.assertEqual([('A',), ('B',)],
1585
sorted(repo_not_stacked.revisions.keys()))
1586
new_pack_names = set(repo_not_stacked._pack_collection.names())
1587
rev_a_pack_names = new_pack_names.difference(stacked_pack_names)
1588
self.assertEqual(1, len(rev_a_pack_names))
1589
rev_a_pack_name = list(rev_a_pack_names)[0]
1590
# Now fetch 'C', so we have a couple pack files to join
1591
repo_not_stacked.fetch(b_source.repository, 'C')
1592
rev_c_pack_names = set(repo_not_stacked._pack_collection.names())
1593
rev_c_pack_names = rev_c_pack_names.difference(new_pack_names)
1594
self.assertEqual(1, len(rev_c_pack_names))
1595
rev_c_pack_name = list(rev_c_pack_names)[0]
1596
return (repo_not_stacked, rev_a_pack_name, inv_a_pack_name,
1599
def test_pack_with_distant_inventories(self):
1600
# See https://bugs.launchpad.net/bzr/+bug/437003
1601
# When repacking, it is possible to have an inventory in a different
1602
# pack file than the associated revision. An autopack can then come
1603
# along, and miss that inventory, and complain.
1604
(repo, rev_a_pack_name, inv_a_pack_name, rev_c_pack_name
1605
) = self.make_branch_with_disjoint_inventory_and_revision()
1606
a_pack = repo._pack_collection.get_pack_by_name(rev_a_pack_name)
1607
c_pack = repo._pack_collection.get_pack_by_name(rev_c_pack_name)
1608
packer = groupcompress_repo.GCCHKPacker(repo._pack_collection,
1609
[a_pack, c_pack], '.test-pack')
1610
# This would raise ValueError in bug #437003, but should not raise an
1614
def test_pack_with_missing_inventory(self):
1615
# Similar to test_pack_with_missing_inventory, but this time, we force
1616
# the A inventory to actually be gone from the repository.
1617
(repo, rev_a_pack_name, inv_a_pack_name, rev_c_pack_name
1618
) = self.make_branch_with_disjoint_inventory_and_revision()
1619
inv_a_pack = repo._pack_collection.get_pack_by_name(inv_a_pack_name)
1620
repo._pack_collection._remove_pack_from_memory(inv_a_pack)
1621
packer = groupcompress_repo.GCCHKPacker(repo._pack_collection,
1622
repo._pack_collection.all_packs(), '.test-pack')
1623
e = self.assertRaises(ValueError, packer.pack)
1624
packer.new_pack.abort()
1625
self.assertContainsRe(str(e),
1626
r"We are missing inventories for revisions: .*'A'")
1629
class TestCrossFormatPacks(TestCaseWithTransport):
1631
def log_pack(self, hint=None):
1632
self.calls.append(('pack', hint))
1633
self.orig_pack(hint=hint)
1634
if self.expect_hint:
1635
self.assertTrue(hint)
1637
def run_stream(self, src_fmt, target_fmt, expect_pack_called):
1638
self.expect_hint = expect_pack_called
1640
source_tree = self.make_branch_and_tree('src', format=src_fmt)
1641
source_tree.lock_write()
1642
self.addCleanup(source_tree.unlock)
1643
tip = source_tree.commit('foo')
1644
target = self.make_repository('target', format=target_fmt)
1646
self.addCleanup(target.unlock)
1647
source = source_tree.branch.repository._get_source(target._format)
1648
self.orig_pack = target.pack
1649
self.overrideAttr(target, "pack", self.log_pack)
1650
search = target.search_missing_revision_ids(
1651
source_tree.branch.repository, revision_ids=[tip])
1652
stream = source.get_stream(search)
1653
from_format = source_tree.branch.repository._format
1654
sink = target._get_sink()
1655
sink.insert_stream(stream, from_format, [])
1656
if expect_pack_called:
1657
self.assertLength(1, self.calls)
1659
self.assertLength(0, self.calls)
1661
def run_fetch(self, src_fmt, target_fmt, expect_pack_called):
1662
self.expect_hint = expect_pack_called
1664
source_tree = self.make_branch_and_tree('src', format=src_fmt)
1665
source_tree.lock_write()
1666
self.addCleanup(source_tree.unlock)
1667
tip = source_tree.commit('foo')
1668
target = self.make_repository('target', format=target_fmt)
1670
self.addCleanup(target.unlock)
1671
source = source_tree.branch.repository
1672
self.orig_pack = target.pack
1673
self.overrideAttr(target, "pack", self.log_pack)
1674
target.fetch(source)
1675
if expect_pack_called:
1676
self.assertLength(1, self.calls)
1678
self.assertLength(0, self.calls)
1680
def test_sink_format_hint_no(self):
1681
# When the target format says packing makes no difference, pack is not
1683
self.run_stream('1.9', 'rich-root-pack', False)
1685
def test_sink_format_hint_yes(self):
1686
# When the target format says packing makes a difference, pack is
1688
self.run_stream('1.9', '2a', True)
1690
def test_sink_format_same_no(self):
1691
# When the formats are the same, pack is not called.
1692
self.run_stream('2a', '2a', False)
1694
def test_IDS_format_hint_no(self):
1695
# When the target format says packing makes no difference, pack is not
1697
self.run_fetch('1.9', 'rich-root-pack', False)
1699
def test_IDS_format_hint_yes(self):
1700
# When the target format says packing makes a difference, pack is
1702
self.run_fetch('1.9', '2a', True)
1704
def test_IDS_format_same_no(self):
1705
# When the formats are the same, pack is not called.
1706
self.run_fetch('2a', '2a', False)
1709
class Test_LazyListJoin(tests.TestCase):
1711
def test__repr__(self):
1712
lazy = repository._LazyListJoin(['a'], ['b'])
1713
self.assertEqual("breezy.repository._LazyListJoin((['a'], ['b']))",
1717
class TestFeatures(tests.TestCaseWithTransport):
1719
def test_open_with_present_feature(self):
1721
bzrrepository.RepositoryFormatMetaDir.unregister_feature,
1722
b"makes-cheese-sandwich")
1723
bzrrepository.RepositoryFormatMetaDir.register_feature(
1724
b"makes-cheese-sandwich")
1725
repo = self.make_repository('.')
1727
repo._format.features[b"makes-cheese-sandwich"] = b"required"
1728
repo._format.check_support_status(False)
1731
def test_open_with_missing_required_feature(self):
1732
repo = self.make_repository('.')
1734
repo._format.features[b"makes-cheese-sandwich"] = b"required"
1735
self.assertRaises(bzrdir.MissingFeature,
1736
repo._format.check_support_status, False)