1
# Copyright (C) 2006-2010 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
29
from bzrlib.errors import (
32
UnsupportedFormatError,
41
from bzrlib.btree_index import BTreeBuilder, BTreeGraphIndex
42
from bzrlib.index import GraphIndex
43
from bzrlib.repository import RepositoryFormat
44
from bzrlib.tests import (
46
TestCaseWithTransport,
54
revision as _mod_revision,
59
from bzrlib.repofmt import (
67
class TestDefaultFormat(TestCase):
69
def test_get_set_default_format(self):
70
old_default = bzrdir.format_registry.get('default')
71
private_default = old_default().repository_format.__class__
72
old_format = repository.format_registry.get_default()
73
self.assertTrue(isinstance(old_format, private_default))
74
def make_sample_bzrdir():
75
my_bzrdir = bzrdir.BzrDirMetaFormat1()
76
my_bzrdir.repository_format = SampleRepositoryFormat()
78
bzrdir.format_registry.remove('default')
79
bzrdir.format_registry.register('sample', make_sample_bzrdir, '')
80
bzrdir.format_registry.set_default('sample')
81
# creating a repository should now create an instrumented dir.
83
# the default branch format is used by the meta dir format
84
# which is not the default bzrdir format at this point
85
dir = bzrdir.BzrDirMetaFormat1().initialize('memory:///')
86
result = dir.create_repository()
87
self.assertEqual(result, 'A bzr repository dir')
89
bzrdir.format_registry.remove('default')
90
bzrdir.format_registry.remove('sample')
91
bzrdir.format_registry.register('default', old_default, '')
92
self.assertIsInstance(repository.format_registry.get_default(),
96
class SampleRepositoryFormat(repository.RepositoryFormat):
99
this format is initializable, unsupported to aid in testing the
100
open and open(unsupported=True) routines.
103
def get_format_string(self):
104
"""See RepositoryFormat.get_format_string()."""
105
return "Sample .bzr repository format."
107
def initialize(self, a_bzrdir, shared=False):
108
"""Initialize a repository in a BzrDir"""
109
t = a_bzrdir.get_repository_transport(self)
110
t.put_bytes('format', self.get_format_string())
111
return 'A bzr repository dir'
113
def is_supported(self):
116
def open(self, a_bzrdir, _found=False):
117
return "opened repository."
120
class SampleExtraRepositoryFormat(repository.RepositoryFormat):
121
"""A sample format that can not be used in a metadir
125
def get_format_string(self):
126
raise NotImplementedError
129
class TestRepositoryFormat(TestCaseWithTransport):
130
"""Tests for the Repository format detection used by the bzr meta dir facility.BzrBranchFormat facility."""
132
def test_find_format(self):
133
# is the right format object found for a repository?
134
# create a branch with a few known format objects.
135
# this is not quite the same as
136
self.build_tree(["foo/", "bar/"])
137
def check_format(format, url):
138
dir = format._matchingbzrdir.initialize(url)
139
format.initialize(dir)
140
t = transport.get_transport(url)
141
found_format = repository.RepositoryFormat.find_format(dir)
142
self.failUnless(isinstance(found_format, format.__class__))
143
check_format(repository.format_registry.get_default(), "bar")
145
def test_find_format_no_repository(self):
146
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
147
self.assertRaises(errors.NoRepositoryPresent,
148
repository.RepositoryFormat.find_format,
151
def test_find_format_unknown_format(self):
152
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
153
SampleRepositoryFormat().initialize(dir)
154
self.assertRaises(UnknownFormatError,
155
repository.RepositoryFormat.find_format,
158
def test_register_unregister_format(self):
159
# Test deprecated format registration functions
160
format = SampleRepositoryFormat()
162
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
164
format.initialize(dir)
165
# register a format for it.
166
self.applyDeprecated(symbol_versioning.deprecated_in((2, 4, 0)),
167
repository.RepositoryFormat.register_format, format)
168
# which repository.Open will refuse (not supported)
169
self.assertRaises(UnsupportedFormatError, repository.Repository.open,
171
# but open(unsupported) will work
172
self.assertEqual(format.open(dir), "opened repository.")
173
# unregister the format
174
self.applyDeprecated(symbol_versioning.deprecated_in((2, 4, 0)),
175
repository.RepositoryFormat.unregister_format, format)
178
class TestRepositoryFormatRegistry(TestCase):
181
super(TestRepositoryFormatRegistry, self).setUp()
182
self.registry = repository.RepositoryFormatRegistry()
184
def test_register_unregister_format(self):
185
format = SampleRepositoryFormat()
186
self.registry.register(format)
187
self.assertEquals(format, self.registry.get("Sample .bzr repository format."))
188
self.registry.remove(format)
189
self.assertRaises(KeyError, self.registry.get, "Sample .bzr repository format.")
191
def test_get_all(self):
192
format = SampleRepositoryFormat()
193
self.assertEquals([], self.registry._get_all())
194
self.registry.register(format)
195
self.assertEquals([format], self.registry._get_all())
197
def test_register_extra(self):
198
format = SampleExtraRepositoryFormat()
199
self.assertEquals([], self.registry._get_all())
200
self.registry.register_extra(format)
201
self.assertEquals([format], self.registry._get_all())
203
def test_register_extra_lazy(self):
204
self.assertEquals([], self.registry._get_all())
205
self.registry.register_extra_lazy("bzrlib.tests.test_repository",
206
"SampleExtraRepositoryFormat")
207
formats = self.registry._get_all()
208
self.assertEquals(1, len(formats))
209
self.assertIsInstance(formats[0], SampleExtraRepositoryFormat)
212
class TestFormat6(TestCaseWithTransport):
214
def test_attribute__fetch_order(self):
215
"""Weaves need topological data insertion."""
216
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
217
repo = weaverepo.RepositoryFormat6().initialize(control)
218
self.assertEqual('topological', repo._format._fetch_order)
220
def test_attribute__fetch_uses_deltas(self):
221
"""Weaves do not reuse deltas."""
222
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
223
repo = weaverepo.RepositoryFormat6().initialize(control)
224
self.assertEqual(False, repo._format._fetch_uses_deltas)
226
def test_attribute__fetch_reconcile(self):
227
"""Weave repositories need a reconcile after fetch."""
228
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
229
repo = weaverepo.RepositoryFormat6().initialize(control)
230
self.assertEqual(True, repo._format._fetch_reconcile)
232
def test_no_ancestry_weave(self):
233
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
234
repo = weaverepo.RepositoryFormat6().initialize(control)
235
# We no longer need to create the ancestry.weave file
236
# since it is *never* used.
237
self.assertRaises(NoSuchFile,
238
control.transport.get,
241
def test_supports_external_lookups(self):
242
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
243
repo = weaverepo.RepositoryFormat6().initialize(control)
244
self.assertFalse(repo._format.supports_external_lookups)
247
class TestFormat7(TestCaseWithTransport):
249
def test_attribute__fetch_order(self):
250
"""Weaves need topological data insertion."""
251
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
252
repo = weaverepo.RepositoryFormat7().initialize(control)
253
self.assertEqual('topological', repo._format._fetch_order)
255
def test_attribute__fetch_uses_deltas(self):
256
"""Weaves do not reuse deltas."""
257
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
258
repo = weaverepo.RepositoryFormat7().initialize(control)
259
self.assertEqual(False, repo._format._fetch_uses_deltas)
261
def test_attribute__fetch_reconcile(self):
262
"""Weave repositories need a reconcile after fetch."""
263
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
264
repo = weaverepo.RepositoryFormat7().initialize(control)
265
self.assertEqual(True, repo._format._fetch_reconcile)
267
def test_disk_layout(self):
268
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
269
repo = weaverepo.RepositoryFormat7().initialize(control)
270
# in case of side effects of locking.
274
# format 'Bazaar-NG Repository format 7'
276
# inventory.weave == empty_weave
277
# empty revision-store directory
278
# empty weaves directory
279
t = control.get_repository_transport(None)
280
self.assertEqualDiff('Bazaar-NG Repository format 7',
281
t.get('format').read())
282
self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
283
self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
284
self.assertEqualDiff('# bzr weave file v5\n'
287
t.get('inventory.weave').read())
288
# Creating a file with id Foo:Bar results in a non-escaped file name on
290
control.create_branch()
291
tree = control.create_workingtree()
292
tree.add(['foo'], ['Foo:Bar'], ['file'])
293
tree.put_file_bytes_non_atomic('Foo:Bar', 'content\n')
295
tree.commit('first post', rev_id='first')
296
except errors.IllegalPath:
297
if sys.platform != 'win32':
299
self.knownFailure('Foo:Bar cannot be used as a file-id on windows'
302
self.assertEqualDiff(
303
'# bzr weave file v5\n'
305
'1 7fe70820e08a1aac0ef224d9c66ab66831cc4ab1\n'
313
t.get('weaves/74/Foo%3ABar.weave').read())
315
def test_shared_disk_layout(self):
316
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
317
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
319
# format 'Bazaar-NG Repository format 7'
320
# inventory.weave == empty_weave
321
# empty revision-store directory
322
# empty weaves directory
323
# a 'shared-storage' marker file.
324
# lock is not present when unlocked
325
t = control.get_repository_transport(None)
326
self.assertEqualDiff('Bazaar-NG Repository format 7',
327
t.get('format').read())
328
self.assertEqualDiff('', t.get('shared-storage').read())
329
self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
330
self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
331
self.assertEqualDiff('# bzr weave file v5\n'
334
t.get('inventory.weave').read())
335
self.assertFalse(t.has('branch-lock'))
337
def test_creates_lockdir(self):
338
"""Make sure it appears to be controlled by a LockDir existence"""
339
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
340
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
341
t = control.get_repository_transport(None)
342
# TODO: Should check there is a 'lock' toplevel directory,
343
# regardless of contents
344
self.assertFalse(t.has('lock/held/info'))
347
self.assertTrue(t.has('lock/held/info'))
349
# unlock so we don't get a warning about failing to do so
352
def test_uses_lockdir(self):
353
"""repo format 7 actually locks on lockdir"""
354
base_url = self.get_url()
355
control = bzrdir.BzrDirMetaFormat1().initialize(base_url)
356
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
357
t = control.get_repository_transport(None)
361
# make sure the same lock is created by opening it
362
repo = repository.Repository.open(base_url)
364
self.assertTrue(t.has('lock/held/info'))
366
self.assertFalse(t.has('lock/held/info'))
368
def test_shared_no_tree_disk_layout(self):
369
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
370
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
371
repo.set_make_working_trees(False)
373
# format 'Bazaar-NG Repository format 7'
375
# inventory.weave == empty_weave
376
# empty revision-store directory
377
# empty weaves directory
378
# a 'shared-storage' marker file.
379
t = control.get_repository_transport(None)
380
self.assertEqualDiff('Bazaar-NG Repository format 7',
381
t.get('format').read())
382
## self.assertEqualDiff('', t.get('lock').read())
383
self.assertEqualDiff('', t.get('shared-storage').read())
384
self.assertEqualDiff('', t.get('no-working-trees').read())
385
repo.set_make_working_trees(True)
386
self.assertFalse(t.has('no-working-trees'))
387
self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
388
self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
389
self.assertEqualDiff('# bzr weave file v5\n'
392
t.get('inventory.weave').read())
394
def test_supports_external_lookups(self):
395
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
396
repo = weaverepo.RepositoryFormat7().initialize(control)
397
self.assertFalse(repo._format.supports_external_lookups)
400
class TestFormatKnit1(TestCaseWithTransport):
402
def test_attribute__fetch_order(self):
403
"""Knits need topological data insertion."""
404
repo = self.make_repository('.',
405
format=bzrdir.format_registry.get('knit')())
406
self.assertEqual('topological', repo._format._fetch_order)
408
def test_attribute__fetch_uses_deltas(self):
409
"""Knits reuse deltas."""
410
repo = self.make_repository('.',
411
format=bzrdir.format_registry.get('knit')())
412
self.assertEqual(True, repo._format._fetch_uses_deltas)
414
def test_disk_layout(self):
415
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
416
repo = knitrepo.RepositoryFormatKnit1().initialize(control)
417
# in case of side effects of locking.
421
# format 'Bazaar-NG Knit Repository Format 1'
422
# lock: is a directory
423
# inventory.weave == empty_weave
424
# empty revision-store directory
425
# empty weaves directory
426
t = control.get_repository_transport(None)
427
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
428
t.get('format').read())
429
# XXX: no locks left when unlocked at the moment
430
# self.assertEqualDiff('', t.get('lock').read())
431
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
433
# Check per-file knits.
434
branch = control.create_branch()
435
tree = control.create_workingtree()
436
tree.add(['foo'], ['Nasty-IdC:'], ['file'])
437
tree.put_file_bytes_non_atomic('Nasty-IdC:', '')
438
tree.commit('1st post', rev_id='foo')
439
self.assertHasKnit(t, 'knits/e8/%254easty-%2549d%2543%253a',
440
'\nfoo fulltext 0 81 :')
442
def assertHasKnit(self, t, knit_name, extra_content=''):
443
"""Assert that knit_name exists on t."""
444
self.assertEqualDiff('# bzr knit index 8\n' + extra_content,
445
t.get(knit_name + '.kndx').read())
447
def check_knits(self, t):
448
"""check knit content for a repository."""
449
self.assertHasKnit(t, 'inventory')
450
self.assertHasKnit(t, 'revisions')
451
self.assertHasKnit(t, 'signatures')
453
def test_shared_disk_layout(self):
454
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
455
repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
457
# format 'Bazaar-NG Knit Repository Format 1'
458
# lock: is a directory
459
# inventory.weave == empty_weave
460
# empty revision-store directory
461
# empty weaves directory
462
# a 'shared-storage' marker file.
463
t = control.get_repository_transport(None)
464
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
465
t.get('format').read())
466
# XXX: no locks left when unlocked at the moment
467
# self.assertEqualDiff('', t.get('lock').read())
468
self.assertEqualDiff('', t.get('shared-storage').read())
469
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
472
def test_shared_no_tree_disk_layout(self):
473
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
474
repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
475
repo.set_make_working_trees(False)
477
# format 'Bazaar-NG Knit Repository Format 1'
479
# inventory.weave == empty_weave
480
# empty revision-store directory
481
# empty weaves directory
482
# a 'shared-storage' marker file.
483
t = control.get_repository_transport(None)
484
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
485
t.get('format').read())
486
# XXX: no locks left when unlocked at the moment
487
# self.assertEqualDiff('', t.get('lock').read())
488
self.assertEqualDiff('', t.get('shared-storage').read())
489
self.assertEqualDiff('', t.get('no-working-trees').read())
490
repo.set_make_working_trees(True)
491
self.assertFalse(t.has('no-working-trees'))
492
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
495
def test_deserialise_sets_root_revision(self):
496
"""We must have a inventory.root.revision
498
Old versions of the XML5 serializer did not set the revision_id for
499
the whole inventory. So we grab the one from the expected text. Which
500
is valid when the api is not being abused.
502
repo = self.make_repository('.',
503
format=bzrdir.format_registry.get('knit')())
504
inv_xml = '<inventory format="5">\n</inventory>\n'
505
inv = repo._deserialise_inventory('test-rev-id', inv_xml)
506
self.assertEqual('test-rev-id', inv.root.revision)
508
def test_deserialise_uses_global_revision_id(self):
509
"""If it is set, then we re-use the global revision id"""
510
repo = self.make_repository('.',
511
format=bzrdir.format_registry.get('knit')())
512
inv_xml = ('<inventory format="5" revision_id="other-rev-id">\n'
514
# Arguably, the deserialise_inventory should detect a mismatch, and
515
# raise an error, rather than silently using one revision_id over the
517
self.assertRaises(AssertionError, repo._deserialise_inventory,
518
'test-rev-id', inv_xml)
519
inv = repo._deserialise_inventory('other-rev-id', inv_xml)
520
self.assertEqual('other-rev-id', inv.root.revision)
522
def test_supports_external_lookups(self):
523
repo = self.make_repository('.',
524
format=bzrdir.format_registry.get('knit')())
525
self.assertFalse(repo._format.supports_external_lookups)
528
class DummyRepository(object):
529
"""A dummy repository for testing."""
534
def supports_rich_root(self):
535
if self._format is not None:
536
return self._format.rich_root_data
540
raise NotImplementedError
542
def get_parent_map(self, revision_ids):
543
raise NotImplementedError
546
class InterDummy(repository.InterRepository):
547
"""An inter-repository optimised code path for DummyRepository.
549
This is for use during testing where we use DummyRepository as repositories
550
so that none of the default regsitered inter-repository classes will
555
def is_compatible(repo_source, repo_target):
556
"""InterDummy is compatible with DummyRepository."""
557
return (isinstance(repo_source, DummyRepository) and
558
isinstance(repo_target, DummyRepository))
561
class TestInterRepository(TestCaseWithTransport):
563
def test_get_default_inter_repository(self):
564
# test that the InterRepository.get(repo_a, repo_b) probes
565
# for a inter_repo class where is_compatible(repo_a, repo_b) returns
566
# true and returns a default inter_repo otherwise.
567
# This also tests that the default registered optimised interrepository
568
# classes do not barf inappropriately when a surprising repository type
570
dummy_a = DummyRepository()
571
dummy_b = DummyRepository()
572
self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
574
def assertGetsDefaultInterRepository(self, repo_a, repo_b):
575
"""Asserts that InterRepository.get(repo_a, repo_b) -> the default.
577
The effective default is now InterSameDataRepository because there is
578
no actual sane default in the presence of incompatible data models.
580
inter_repo = repository.InterRepository.get(repo_a, repo_b)
581
self.assertEqual(repository.InterSameDataRepository,
582
inter_repo.__class__)
583
self.assertEqual(repo_a, inter_repo.source)
584
self.assertEqual(repo_b, inter_repo.target)
586
def test_register_inter_repository_class(self):
587
# test that a optimised code path provider - a
588
# InterRepository subclass can be registered and unregistered
589
# and that it is correctly selected when given a repository
590
# pair that it returns true on for the is_compatible static method
592
dummy_a = DummyRepository()
593
dummy_a._format = RepositoryFormat()
594
dummy_b = DummyRepository()
595
dummy_b._format = RepositoryFormat()
596
repo = self.make_repository('.')
597
# hack dummies to look like repo somewhat.
598
dummy_a._serializer = repo._serializer
599
dummy_a._format.supports_tree_reference = repo._format.supports_tree_reference
600
dummy_a._format.rich_root_data = repo._format.rich_root_data
601
dummy_b._serializer = repo._serializer
602
dummy_b._format.supports_tree_reference = repo._format.supports_tree_reference
603
dummy_b._format.rich_root_data = repo._format.rich_root_data
604
repository.InterRepository.register_optimiser(InterDummy)
606
# we should get the default for something InterDummy returns False
608
self.assertFalse(InterDummy.is_compatible(dummy_a, repo))
609
self.assertGetsDefaultInterRepository(dummy_a, repo)
610
# and we should get an InterDummy for a pair it 'likes'
611
self.assertTrue(InterDummy.is_compatible(dummy_a, dummy_b))
612
inter_repo = repository.InterRepository.get(dummy_a, dummy_b)
613
self.assertEqual(InterDummy, inter_repo.__class__)
614
self.assertEqual(dummy_a, inter_repo.source)
615
self.assertEqual(dummy_b, inter_repo.target)
617
repository.InterRepository.unregister_optimiser(InterDummy)
618
# now we should get the default InterRepository object again.
619
self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
622
class TestInterWeaveRepo(TestCaseWithTransport):
624
def test_is_compatible_and_registered(self):
625
# InterWeaveRepo is compatible when either side
626
# is a format 5/6/7 branch
627
from bzrlib.repofmt import knitrepo, weaverepo
628
formats = [weaverepo.RepositoryFormat5(),
629
weaverepo.RepositoryFormat6(),
630
weaverepo.RepositoryFormat7()]
631
incompatible_formats = [weaverepo.RepositoryFormat4(),
632
knitrepo.RepositoryFormatKnit1(),
634
repo_a = self.make_repository('a')
635
repo_b = self.make_repository('b')
636
is_compatible = weaverepo.InterWeaveRepo.is_compatible
637
for source in incompatible_formats:
638
# force incompatible left then right
639
repo_a._format = source
640
repo_b._format = formats[0]
641
self.assertFalse(is_compatible(repo_a, repo_b))
642
self.assertFalse(is_compatible(repo_b, repo_a))
643
for source in formats:
644
repo_a._format = source
645
for target in formats:
646
repo_b._format = target
647
self.assertTrue(is_compatible(repo_a, repo_b))
648
self.assertEqual(weaverepo.InterWeaveRepo,
649
repository.InterRepository.get(repo_a,
653
class TestRepositoryFormat1(knitrepo.RepositoryFormatKnit1):
655
def get_format_string(self):
656
return "Test Format 1"
659
class TestRepositoryFormat2(knitrepo.RepositoryFormatKnit1):
661
def get_format_string(self):
662
return "Test Format 2"
665
class TestRepositoryConverter(TestCaseWithTransport):
667
def test_convert_empty(self):
668
source_format = TestRepositoryFormat1()
669
target_format = TestRepositoryFormat2()
670
repository.format_registry.register(source_format)
671
self.addCleanup(repository.format_registry.remove,
673
repository.format_registry.register(target_format)
674
self.addCleanup(repository.format_registry.remove,
676
t = self.get_transport()
677
t.mkdir('repository')
678
repo_dir = bzrdir.BzrDirMetaFormat1().initialize('repository')
679
repo = TestRepositoryFormat1().initialize(repo_dir)
680
converter = repository.CopyConverter(target_format)
681
pb = bzrlib.ui.ui_factory.nested_progress_bar()
683
converter.convert(repo, pb)
686
repo = repo_dir.open_repository()
687
self.assertTrue(isinstance(target_format, repo._format.__class__))
690
class TestRepositoryFormatKnit3(TestCaseWithTransport):
692
def test_attribute__fetch_order(self):
693
"""Knits need topological data insertion."""
694
format = bzrdir.BzrDirMetaFormat1()
695
format.repository_format = knitrepo.RepositoryFormatKnit3()
696
repo = self.make_repository('.', format=format)
697
self.assertEqual('topological', repo._format._fetch_order)
699
def test_attribute__fetch_uses_deltas(self):
700
"""Knits reuse deltas."""
701
format = bzrdir.BzrDirMetaFormat1()
702
format.repository_format = knitrepo.RepositoryFormatKnit3()
703
repo = self.make_repository('.', format=format)
704
self.assertEqual(True, repo._format._fetch_uses_deltas)
706
def test_convert(self):
707
"""Ensure the upgrade adds weaves for roots"""
708
format = bzrdir.BzrDirMetaFormat1()
709
format.repository_format = knitrepo.RepositoryFormatKnit1()
710
tree = self.make_branch_and_tree('.', format)
711
tree.commit("Dull commit", rev_id="dull")
712
revision_tree = tree.branch.repository.revision_tree('dull')
713
revision_tree.lock_read()
715
self.assertRaises(errors.NoSuchFile, revision_tree.get_file_lines,
716
revision_tree.inventory.root.file_id)
718
revision_tree.unlock()
719
format = bzrdir.BzrDirMetaFormat1()
720
format.repository_format = knitrepo.RepositoryFormatKnit3()
721
upgrade.Convert('.', format)
722
tree = workingtree.WorkingTree.open('.')
723
revision_tree = tree.branch.repository.revision_tree('dull')
724
revision_tree.lock_read()
726
revision_tree.get_file_lines(revision_tree.inventory.root.file_id)
728
revision_tree.unlock()
729
tree.commit("Another dull commit", rev_id='dull2')
730
revision_tree = tree.branch.repository.revision_tree('dull2')
731
revision_tree.lock_read()
732
self.addCleanup(revision_tree.unlock)
733
self.assertEqual('dull', revision_tree.inventory.root.revision)
735
def test_supports_external_lookups(self):
736
format = bzrdir.BzrDirMetaFormat1()
737
format.repository_format = knitrepo.RepositoryFormatKnit3()
738
repo = self.make_repository('.', format=format)
739
self.assertFalse(repo._format.supports_external_lookups)
742
class Test2a(tests.TestCaseWithMemoryTransport):
744
def test_chk_bytes_uses_custom_btree_parser(self):
745
mt = self.make_branch_and_memory_tree('test', format='2a')
747
self.addCleanup(mt.unlock)
748
mt.add([''], ['root-id'])
750
index = mt.branch.repository.chk_bytes._index._graph_index._indices[0]
751
self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
752
# It should also work if we re-open the repo
753
repo = mt.branch.repository.bzrdir.open_repository()
755
self.addCleanup(repo.unlock)
756
index = repo.chk_bytes._index._graph_index._indices[0]
757
self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
759
def test_fetch_combines_groups(self):
760
builder = self.make_branch_builder('source', format='2a')
761
builder.start_series()
762
builder.build_snapshot('1', None, [
763
('add', ('', 'root-id', 'directory', '')),
764
('add', ('file', 'file-id', 'file', 'content\n'))])
765
builder.build_snapshot('2', ['1'], [
766
('modify', ('file-id', 'content-2\n'))])
767
builder.finish_series()
768
source = builder.get_branch()
769
target = self.make_repository('target', format='2a')
770
target.fetch(source.repository)
772
self.addCleanup(target.unlock)
773
details = target.texts._index.get_build_details(
774
[('file-id', '1',), ('file-id', '2',)])
775
file_1_details = details[('file-id', '1')]
776
file_2_details = details[('file-id', '2')]
777
# The index, and what to read off disk, should be the same for both
778
# versions of the file.
779
self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
781
def test_fetch_combines_groups(self):
782
builder = self.make_branch_builder('source', format='2a')
783
builder.start_series()
784
builder.build_snapshot('1', None, [
785
('add', ('', 'root-id', 'directory', '')),
786
('add', ('file', 'file-id', 'file', 'content\n'))])
787
builder.build_snapshot('2', ['1'], [
788
('modify', ('file-id', 'content-2\n'))])
789
builder.finish_series()
790
source = builder.get_branch()
791
target = self.make_repository('target', format='2a')
792
target.fetch(source.repository)
794
self.addCleanup(target.unlock)
795
details = target.texts._index.get_build_details(
796
[('file-id', '1',), ('file-id', '2',)])
797
file_1_details = details[('file-id', '1')]
798
file_2_details = details[('file-id', '2')]
799
# The index, and what to read off disk, should be the same for both
800
# versions of the file.
801
self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
803
def test_fetch_combines_groups(self):
804
builder = self.make_branch_builder('source', format='2a')
805
builder.start_series()
806
builder.build_snapshot('1', None, [
807
('add', ('', 'root-id', 'directory', '')),
808
('add', ('file', 'file-id', 'file', 'content\n'))])
809
builder.build_snapshot('2', ['1'], [
810
('modify', ('file-id', 'content-2\n'))])
811
builder.finish_series()
812
source = builder.get_branch()
813
target = self.make_repository('target', format='2a')
814
target.fetch(source.repository)
816
self.addCleanup(target.unlock)
817
details = target.texts._index.get_build_details(
818
[('file-id', '1',), ('file-id', '2',)])
819
file_1_details = details[('file-id', '1')]
820
file_2_details = details[('file-id', '2')]
821
# The index, and what to read off disk, should be the same for both
822
# versions of the file.
823
self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
825
def test_format_pack_compresses_True(self):
826
repo = self.make_repository('repo', format='2a')
827
self.assertTrue(repo._format.pack_compresses)
829
def test_inventories_use_chk_map_with_parent_base_dict(self):
830
tree = self.make_branch_and_memory_tree('repo', format="2a")
832
tree.add([''], ['TREE_ROOT'])
833
revid = tree.commit("foo")
836
self.addCleanup(tree.unlock)
837
inv = tree.branch.repository.get_inventory(revid)
838
self.assertNotEqual(None, inv.parent_id_basename_to_file_id)
839
inv.parent_id_basename_to_file_id._ensure_root()
840
inv.id_to_entry._ensure_root()
841
self.assertEqual(65536, inv.id_to_entry._root_node.maximum_size)
842
self.assertEqual(65536,
843
inv.parent_id_basename_to_file_id._root_node.maximum_size)
845
def test_autopack_unchanged_chk_nodes(self):
846
# at 20 unchanged commits, chk pages are packed that are split into
847
# two groups such that the new pack being made doesn't have all its
848
# pages in the source packs (though they are in the repository).
849
# Use a memory backed repository, we don't need to hit disk for this
850
tree = self.make_branch_and_memory_tree('tree', format='2a')
852
self.addCleanup(tree.unlock)
853
tree.add([''], ['TREE_ROOT'])
854
for pos in range(20):
855
tree.commit(str(pos))
857
def test_pack_with_hint(self):
858
tree = self.make_branch_and_memory_tree('tree', format='2a')
860
self.addCleanup(tree.unlock)
861
tree.add([''], ['TREE_ROOT'])
862
# 1 commit to leave untouched
864
to_keep = tree.branch.repository._pack_collection.names()
868
all = tree.branch.repository._pack_collection.names()
869
combine = list(set(all) - set(to_keep))
870
self.assertLength(3, all)
871
self.assertLength(2, combine)
872
tree.branch.repository.pack(hint=combine)
873
final = tree.branch.repository._pack_collection.names()
874
self.assertLength(2, final)
875
self.assertFalse(combine[0] in final)
876
self.assertFalse(combine[1] in final)
877
self.assertSubset(to_keep, final)
879
def test_stream_source_to_gc(self):
880
source = self.make_repository('source', format='2a')
881
target = self.make_repository('target', format='2a')
882
stream = source._get_source(target._format)
883
self.assertIsInstance(stream, groupcompress_repo.GroupCHKStreamSource)
885
def test_stream_source_to_non_gc(self):
886
source = self.make_repository('source', format='2a')
887
target = self.make_repository('target', format='rich-root-pack')
888
stream = source._get_source(target._format)
889
# We don't want the child GroupCHKStreamSource
890
self.assertIs(type(stream), repository.StreamSource)
892
def test_get_stream_for_missing_keys_includes_all_chk_refs(self):
893
source_builder = self.make_branch_builder('source',
895
# We have to build a fairly large tree, so that we are sure the chk
896
# pages will have split into multiple pages.
897
entries = [('add', ('', 'a-root-id', 'directory', None))]
898
for i in 'abcdefghijklmnopqrstuvwxyz123456789':
899
for j in 'abcdefghijklmnopqrstuvwxyz123456789':
902
content = 'content for %s\n' % (fname,)
903
entries.append(('add', (fname, fid, 'file', content)))
904
source_builder.start_series()
905
source_builder.build_snapshot('rev-1', None, entries)
906
# Now change a few of them, so we get a few new pages for the second
908
source_builder.build_snapshot('rev-2', ['rev-1'], [
909
('modify', ('aa-id', 'new content for aa-id\n')),
910
('modify', ('cc-id', 'new content for cc-id\n')),
911
('modify', ('zz-id', 'new content for zz-id\n')),
913
source_builder.finish_series()
914
source_branch = source_builder.get_branch()
915
source_branch.lock_read()
916
self.addCleanup(source_branch.unlock)
917
target = self.make_repository('target', format='2a')
918
source = source_branch.repository._get_source(target._format)
919
self.assertIsInstance(source, groupcompress_repo.GroupCHKStreamSource)
921
# On a regular pass, getting the inventories and chk pages for rev-2
922
# would only get the newly created chk pages
923
search = graph.SearchResult(set(['rev-2']), set(['rev-1']), 1,
925
simple_chk_records = []
926
for vf_name, substream in source.get_stream(search):
927
if vf_name == 'chk_bytes':
928
for record in substream:
929
simple_chk_records.append(record.key)
933
# 3 pages, the root (InternalNode), + 2 pages which actually changed
934
self.assertEqual([('sha1:91481f539e802c76542ea5e4c83ad416bf219f73',),
935
('sha1:4ff91971043668583985aec83f4f0ab10a907d3f',),
936
('sha1:81e7324507c5ca132eedaf2d8414ee4bb2226187',),
937
('sha1:b101b7da280596c71a4540e9a1eeba8045985ee0',)],
939
# Now, when we do a similar call using 'get_stream_for_missing_keys'
940
# we should get a much larger set of pages.
941
missing = [('inventories', 'rev-2')]
942
full_chk_records = []
943
for vf_name, substream in source.get_stream_for_missing_keys(missing):
944
if vf_name == 'inventories':
945
for record in substream:
946
self.assertEqual(('rev-2',), record.key)
947
elif vf_name == 'chk_bytes':
948
for record in substream:
949
full_chk_records.append(record.key)
951
self.fail('Should not be getting a stream of %s' % (vf_name,))
952
# We have 257 records now. This is because we have 1 root page, and 256
953
# leaf pages in a complete listing.
954
self.assertEqual(257, len(full_chk_records))
955
self.assertSubset(simple_chk_records, full_chk_records)
957
def test_inconsistency_fatal(self):
958
repo = self.make_repository('repo', format='2a')
959
self.assertTrue(repo.revisions._index._inconsistency_fatal)
960
self.assertFalse(repo.texts._index._inconsistency_fatal)
961
self.assertFalse(repo.inventories._index._inconsistency_fatal)
962
self.assertFalse(repo.signatures._index._inconsistency_fatal)
963
self.assertFalse(repo.chk_bytes._index._inconsistency_fatal)
966
class TestKnitPackStreamSource(tests.TestCaseWithMemoryTransport):
968
def test_source_to_exact_pack_092(self):
969
source = self.make_repository('source', format='pack-0.92')
970
target = self.make_repository('target', format='pack-0.92')
971
stream_source = source._get_source(target._format)
972
self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
974
def test_source_to_exact_pack_rich_root_pack(self):
975
source = self.make_repository('source', format='rich-root-pack')
976
target = self.make_repository('target', format='rich-root-pack')
977
stream_source = source._get_source(target._format)
978
self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
980
def test_source_to_exact_pack_19(self):
981
source = self.make_repository('source', format='1.9')
982
target = self.make_repository('target', format='1.9')
983
stream_source = source._get_source(target._format)
984
self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
986
def test_source_to_exact_pack_19_rich_root(self):
987
source = self.make_repository('source', format='1.9-rich-root')
988
target = self.make_repository('target', format='1.9-rich-root')
989
stream_source = source._get_source(target._format)
990
self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
992
def test_source_to_remote_exact_pack_19(self):
993
trans = self.make_smart_server('target')
995
source = self.make_repository('source', format='1.9')
996
target = self.make_repository('target', format='1.9')
997
target = repository.Repository.open(trans.base)
998
stream_source = source._get_source(target._format)
999
self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
1001
def test_stream_source_to_non_exact(self):
1002
source = self.make_repository('source', format='pack-0.92')
1003
target = self.make_repository('target', format='1.9')
1004
stream = source._get_source(target._format)
1005
self.assertIs(type(stream), repository.StreamSource)
1007
def test_stream_source_to_non_exact_rich_root(self):
1008
source = self.make_repository('source', format='1.9')
1009
target = self.make_repository('target', format='1.9-rich-root')
1010
stream = source._get_source(target._format)
1011
self.assertIs(type(stream), repository.StreamSource)
1013
def test_source_to_remote_non_exact_pack_19(self):
1014
trans = self.make_smart_server('target')
1016
source = self.make_repository('source', format='1.9')
1017
target = self.make_repository('target', format='1.6')
1018
target = repository.Repository.open(trans.base)
1019
stream_source = source._get_source(target._format)
1020
self.assertIs(type(stream_source), repository.StreamSource)
1022
def test_stream_source_to_knit(self):
1023
source = self.make_repository('source', format='pack-0.92')
1024
target = self.make_repository('target', format='dirstate')
1025
stream = source._get_source(target._format)
1026
self.assertIs(type(stream), repository.StreamSource)
1029
class TestDevelopment6FindParentIdsOfRevisions(TestCaseWithTransport):
1030
"""Tests for _find_parent_ids_of_revisions."""
1033
super(TestDevelopment6FindParentIdsOfRevisions, self).setUp()
1034
self.builder = self.make_branch_builder('source')
1035
self.builder.start_series()
1036
self.builder.build_snapshot('initial', None,
1037
[('add', ('', 'tree-root', 'directory', None))])
1038
self.repo = self.builder.get_branch().repository
1039
self.addCleanup(self.builder.finish_series)
1041
def assertParentIds(self, expected_result, rev_set):
1042
self.assertEqual(sorted(expected_result),
1043
sorted(self.repo._find_parent_ids_of_revisions(rev_set)))
1045
def test_simple(self):
1046
self.builder.build_snapshot('revid1', None, [])
1047
self.builder.build_snapshot('revid2', ['revid1'], [])
1048
rev_set = ['revid2']
1049
self.assertParentIds(['revid1'], rev_set)
1051
def test_not_first_parent(self):
1052
self.builder.build_snapshot('revid1', None, [])
1053
self.builder.build_snapshot('revid2', ['revid1'], [])
1054
self.builder.build_snapshot('revid3', ['revid2'], [])
1055
rev_set = ['revid3', 'revid2']
1056
self.assertParentIds(['revid1'], rev_set)
1058
def test_not_null(self):
1059
rev_set = ['initial']
1060
self.assertParentIds([], rev_set)
1062
def test_not_null_set(self):
1063
self.builder.build_snapshot('revid1', None, [])
1064
rev_set = [_mod_revision.NULL_REVISION]
1065
self.assertParentIds([], rev_set)
1067
def test_ghost(self):
1068
self.builder.build_snapshot('revid1', None, [])
1069
rev_set = ['ghost', 'revid1']
1070
self.assertParentIds(['initial'], rev_set)
1072
def test_ghost_parent(self):
1073
self.builder.build_snapshot('revid1', None, [])
1074
self.builder.build_snapshot('revid2', ['revid1', 'ghost'], [])
1075
rev_set = ['revid2', 'revid1']
1076
self.assertParentIds(['ghost', 'initial'], rev_set)
1078
def test_righthand_parent(self):
1079
self.builder.build_snapshot('revid1', None, [])
1080
self.builder.build_snapshot('revid2a', ['revid1'], [])
1081
self.builder.build_snapshot('revid2b', ['revid1'], [])
1082
self.builder.build_snapshot('revid3', ['revid2a', 'revid2b'], [])
1083
rev_set = ['revid3', 'revid2a']
1084
self.assertParentIds(['revid1', 'revid2b'], rev_set)
1087
class TestWithBrokenRepo(TestCaseWithTransport):
1088
"""These tests seem to be more appropriate as interface tests?"""
1090
def make_broken_repository(self):
1091
# XXX: This function is borrowed from Aaron's "Reconcile can fix bad
1092
# parent references" branch which is due to land in bzr.dev soon. Once
1093
# it does, this duplication should be removed.
1094
repo = self.make_repository('broken-repo')
1098
cleanups.append(repo.unlock)
1099
repo.start_write_group()
1100
cleanups.append(repo.commit_write_group)
1101
# make rev1a: A well-formed revision, containing 'file1'
1102
inv = inventory.Inventory(revision_id='rev1a')
1103
inv.root.revision = 'rev1a'
1104
self.add_file(repo, inv, 'file1', 'rev1a', [])
1105
repo.texts.add_lines((inv.root.file_id, 'rev1a'), [], [])
1106
repo.add_inventory('rev1a', inv, [])
1107
revision = _mod_revision.Revision('rev1a',
1108
committer='jrandom@example.com', timestamp=0,
1109
inventory_sha1='', timezone=0, message='foo', parent_ids=[])
1110
repo.add_revision('rev1a',revision, inv)
1112
# make rev1b, which has no Revision, but has an Inventory, and
1114
inv = inventory.Inventory(revision_id='rev1b')
1115
inv.root.revision = 'rev1b'
1116
self.add_file(repo, inv, 'file1', 'rev1b', [])
1117
repo.add_inventory('rev1b', inv, [])
1119
# make rev2, with file1 and file2
1121
# file1 has 'rev1b' as an ancestor, even though this is not
1122
# mentioned by 'rev1a', making it an unreferenced ancestor
1123
inv = inventory.Inventory()
1124
self.add_file(repo, inv, 'file1', 'rev2', ['rev1a', 'rev1b'])
1125
self.add_file(repo, inv, 'file2', 'rev2', [])
1126
self.add_revision(repo, 'rev2', inv, ['rev1a'])
1128
# make ghost revision rev1c
1129
inv = inventory.Inventory()
1130
self.add_file(repo, inv, 'file2', 'rev1c', [])
1132
# make rev3 with file2
1133
# file2 refers to 'rev1c', which is a ghost in this repository, so
1134
# file2 cannot have rev1c as its ancestor.
1135
inv = inventory.Inventory()
1136
self.add_file(repo, inv, 'file2', 'rev3', ['rev1c'])
1137
self.add_revision(repo, 'rev3', inv, ['rev1c'])
1140
for cleanup in reversed(cleanups):
1143
def add_revision(self, repo, revision_id, inv, parent_ids):
1144
inv.revision_id = revision_id
1145
inv.root.revision = revision_id
1146
repo.texts.add_lines((inv.root.file_id, revision_id), [], [])
1147
repo.add_inventory(revision_id, inv, parent_ids)
1148
revision = _mod_revision.Revision(revision_id,
1149
committer='jrandom@example.com', timestamp=0, inventory_sha1='',
1150
timezone=0, message='foo', parent_ids=parent_ids)
1151
repo.add_revision(revision_id,revision, inv)
1153
def add_file(self, repo, inv, filename, revision, parents):
1154
file_id = filename + '-id'
1155
entry = inventory.InventoryFile(file_id, filename, 'TREE_ROOT')
1156
entry.revision = revision
1159
text_key = (file_id, revision)
1160
parent_keys = [(file_id, parent) for parent in parents]
1161
repo.texts.add_lines(text_key, parent_keys, ['line\n'])
1163
def test_insert_from_broken_repo(self):
1164
"""Inserting a data stream from a broken repository won't silently
1165
corrupt the target repository.
1167
broken_repo = self.make_broken_repository()
1168
empty_repo = self.make_repository('empty-repo')
1170
empty_repo.fetch(broken_repo)
1171
except (errors.RevisionNotPresent, errors.BzrCheckError):
1172
# Test successful: compression parent not being copied leads to
1175
empty_repo.lock_read()
1176
self.addCleanup(empty_repo.unlock)
1177
text = empty_repo.texts.get_record_stream(
1178
[('file2-id', 'rev3')], 'topological', True).next()
1179
self.assertEqual('line\n', text.get_bytes_as('fulltext'))
1182
class TestRepositoryPackCollection(TestCaseWithTransport):
1184
def get_format(self):
1185
return bzrdir.format_registry.make_bzrdir('pack-0.92')
1187
def get_packs(self):
1188
format = self.get_format()
1189
repo = self.make_repository('.', format=format)
1190
return repo._pack_collection
1192
def make_packs_and_alt_repo(self, write_lock=False):
1193
"""Create a pack repo with 3 packs, and access it via a second repo."""
1194
tree = self.make_branch_and_tree('.', format=self.get_format())
1196
self.addCleanup(tree.unlock)
1197
rev1 = tree.commit('one')
1198
rev2 = tree.commit('two')
1199
rev3 = tree.commit('three')
1200
r = repository.Repository.open('.')
1205
self.addCleanup(r.unlock)
1206
packs = r._pack_collection
1207
packs.ensure_loaded()
1208
return tree, r, packs, [rev1, rev2, rev3]
1210
def test__clear_obsolete_packs(self):
1211
packs = self.get_packs()
1212
obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1213
obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1214
obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1215
obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1216
obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1217
obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1218
res = packs._clear_obsolete_packs()
1219
self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1220
self.assertEqual([], obsolete_pack_trans.list_dir('.'))
1222
def test__clear_obsolete_packs_preserve(self):
1223
packs = self.get_packs()
1224
obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1225
obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1226
obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1227
obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1228
obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1229
obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1230
res = packs._clear_obsolete_packs(preserve=set(['a-pack']))
1231
self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1232
self.assertEqual(['a-pack.iix', 'a-pack.pack', 'a-pack.rix'],
1233
sorted(obsolete_pack_trans.list_dir('.')))
1235
def test__max_pack_count(self):
1236
"""The maximum pack count is a function of the number of revisions."""
1237
# no revisions - one pack, so that we can have a revision free repo
1238
# without it blowing up
1239
packs = self.get_packs()
1240
self.assertEqual(1, packs._max_pack_count(0))
1241
# after that the sum of the digits, - check the first 1-9
1242
self.assertEqual(1, packs._max_pack_count(1))
1243
self.assertEqual(2, packs._max_pack_count(2))
1244
self.assertEqual(3, packs._max_pack_count(3))
1245
self.assertEqual(4, packs._max_pack_count(4))
1246
self.assertEqual(5, packs._max_pack_count(5))
1247
self.assertEqual(6, packs._max_pack_count(6))
1248
self.assertEqual(7, packs._max_pack_count(7))
1249
self.assertEqual(8, packs._max_pack_count(8))
1250
self.assertEqual(9, packs._max_pack_count(9))
1251
# check the boundary cases with two digits for the next decade
1252
self.assertEqual(1, packs._max_pack_count(10))
1253
self.assertEqual(2, packs._max_pack_count(11))
1254
self.assertEqual(10, packs._max_pack_count(19))
1255
self.assertEqual(2, packs._max_pack_count(20))
1256
self.assertEqual(3, packs._max_pack_count(21))
1257
# check some arbitrary big numbers
1258
self.assertEqual(25, packs._max_pack_count(112894))
1260
def test_repr(self):
1261
packs = self.get_packs()
1262
self.assertContainsRe(repr(packs),
1263
'RepositoryPackCollection(.*Repository(.*))')
1265
def test__obsolete_packs(self):
1266
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1267
names = packs.names()
1268
pack = packs.get_pack_by_name(names[0])
1269
# Schedule this one for removal
1270
packs._remove_pack_from_memory(pack)
1271
# Simulate a concurrent update by renaming the .pack file and one of
1273
packs.transport.rename('packs/%s.pack' % (names[0],),
1274
'obsolete_packs/%s.pack' % (names[0],))
1275
packs.transport.rename('indices/%s.iix' % (names[0],),
1276
'obsolete_packs/%s.iix' % (names[0],))
1277
# Now trigger the obsoletion, and ensure that all the remaining files
1279
packs._obsolete_packs([pack])
1280
self.assertEqual([n + '.pack' for n in names[1:]],
1281
sorted(packs._pack_transport.list_dir('.')))
1282
# names[0] should not be present in the index anymore
1283
self.assertEqual(names[1:],
1284
sorted(set([osutils.splitext(n)[0] for n in
1285
packs._index_transport.list_dir('.')])))
1287
def test_pack_distribution_zero(self):
1288
packs = self.get_packs()
1289
self.assertEqual([0], packs.pack_distribution(0))
1291
def test_ensure_loaded_unlocked(self):
1292
packs = self.get_packs()
1293
self.assertRaises(errors.ObjectNotLocked,
1294
packs.ensure_loaded)
1296
def test_pack_distribution_one_to_nine(self):
1297
packs = self.get_packs()
1298
self.assertEqual([1],
1299
packs.pack_distribution(1))
1300
self.assertEqual([1, 1],
1301
packs.pack_distribution(2))
1302
self.assertEqual([1, 1, 1],
1303
packs.pack_distribution(3))
1304
self.assertEqual([1, 1, 1, 1],
1305
packs.pack_distribution(4))
1306
self.assertEqual([1, 1, 1, 1, 1],
1307
packs.pack_distribution(5))
1308
self.assertEqual([1, 1, 1, 1, 1, 1],
1309
packs.pack_distribution(6))
1310
self.assertEqual([1, 1, 1, 1, 1, 1, 1],
1311
packs.pack_distribution(7))
1312
self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1],
1313
packs.pack_distribution(8))
1314
self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1, 1],
1315
packs.pack_distribution(9))
1317
def test_pack_distribution_stable_at_boundaries(self):
1318
"""When there are multi-rev packs the counts are stable."""
1319
packs = self.get_packs()
1321
self.assertEqual([10], packs.pack_distribution(10))
1322
self.assertEqual([10, 1], packs.pack_distribution(11))
1323
self.assertEqual([10, 10], packs.pack_distribution(20))
1324
self.assertEqual([10, 10, 1], packs.pack_distribution(21))
1326
self.assertEqual([100], packs.pack_distribution(100))
1327
self.assertEqual([100, 1], packs.pack_distribution(101))
1328
self.assertEqual([100, 10, 1], packs.pack_distribution(111))
1329
self.assertEqual([100, 100], packs.pack_distribution(200))
1330
self.assertEqual([100, 100, 1], packs.pack_distribution(201))
1331
self.assertEqual([100, 100, 10, 1], packs.pack_distribution(211))
1333
def test_plan_pack_operations_2009_revisions_skip_all_packs(self):
1334
packs = self.get_packs()
1335
existing_packs = [(2000, "big"), (9, "medium")]
1336
# rev count - 2009 -> 2x1000 + 9x1
1337
pack_operations = packs.plan_autopack_combinations(
1338
existing_packs, [1000, 1000, 1, 1, 1, 1, 1, 1, 1, 1, 1])
1339
self.assertEqual([], pack_operations)
1341
def test_plan_pack_operations_2010_revisions_skip_all_packs(self):
1342
packs = self.get_packs()
1343
existing_packs = [(2000, "big"), (9, "medium"), (1, "single")]
1344
# rev count - 2010 -> 2x1000 + 1x10
1345
pack_operations = packs.plan_autopack_combinations(
1346
existing_packs, [1000, 1000, 10])
1347
self.assertEqual([], pack_operations)
1349
def test_plan_pack_operations_2010_combines_smallest_two(self):
1350
packs = self.get_packs()
1351
existing_packs = [(1999, "big"), (9, "medium"), (1, "single2"),
1353
# rev count - 2010 -> 2x1000 + 1x10 (3)
1354
pack_operations = packs.plan_autopack_combinations(
1355
existing_packs, [1000, 1000, 10])
1356
self.assertEqual([[2, ["single2", "single1"]]], pack_operations)
1358
def test_plan_pack_operations_creates_a_single_op(self):
1359
packs = self.get_packs()
1360
existing_packs = [(50, 'a'), (40, 'b'), (30, 'c'), (10, 'd'),
1361
(10, 'e'), (6, 'f'), (4, 'g')]
1362
# rev count 150 -> 1x100 and 5x10
1363
# The two size 10 packs do not need to be touched. The 50, 40, 30 would
1364
# be combined into a single 120 size pack, and the 6 & 4 would
1365
# becombined into a size 10 pack. However, if we have to rewrite them,
1366
# we save a pack file with no increased I/O by putting them into the
1368
distribution = packs.pack_distribution(150)
1369
pack_operations = packs.plan_autopack_combinations(existing_packs,
1371
self.assertEqual([[130, ['a', 'b', 'c', 'f', 'g']]], pack_operations)
1373
def test_all_packs_none(self):
1374
format = self.get_format()
1375
tree = self.make_branch_and_tree('.', format=format)
1377
self.addCleanup(tree.unlock)
1378
packs = tree.branch.repository._pack_collection
1379
packs.ensure_loaded()
1380
self.assertEqual([], packs.all_packs())
1382
def test_all_packs_one(self):
1383
format = self.get_format()
1384
tree = self.make_branch_and_tree('.', format=format)
1385
tree.commit('start')
1387
self.addCleanup(tree.unlock)
1388
packs = tree.branch.repository._pack_collection
1389
packs.ensure_loaded()
1391
packs.get_pack_by_name(packs.names()[0])],
1394
def test_all_packs_two(self):
1395
format = self.get_format()
1396
tree = self.make_branch_and_tree('.', format=format)
1397
tree.commit('start')
1398
tree.commit('continue')
1400
self.addCleanup(tree.unlock)
1401
packs = tree.branch.repository._pack_collection
1402
packs.ensure_loaded()
1404
packs.get_pack_by_name(packs.names()[0]),
1405
packs.get_pack_by_name(packs.names()[1]),
1406
], packs.all_packs())
1408
def test_get_pack_by_name(self):
1409
format = self.get_format()
1410
tree = self.make_branch_and_tree('.', format=format)
1411
tree.commit('start')
1413
self.addCleanup(tree.unlock)
1414
packs = tree.branch.repository._pack_collection
1416
packs.ensure_loaded()
1417
name = packs.names()[0]
1418
pack_1 = packs.get_pack_by_name(name)
1419
# the pack should be correctly initialised
1420
sizes = packs._names[name]
1421
rev_index = GraphIndex(packs._index_transport, name + '.rix', sizes[0])
1422
inv_index = GraphIndex(packs._index_transport, name + '.iix', sizes[1])
1423
txt_index = GraphIndex(packs._index_transport, name + '.tix', sizes[2])
1424
sig_index = GraphIndex(packs._index_transport, name + '.six', sizes[3])
1425
self.assertEqual(pack_repo.ExistingPack(packs._pack_transport,
1426
name, rev_index, inv_index, txt_index, sig_index), pack_1)
1427
# and the same instance should be returned on successive calls.
1428
self.assertTrue(pack_1 is packs.get_pack_by_name(name))
1430
def test_reload_pack_names_new_entry(self):
1431
tree, r, packs, revs = self.make_packs_and_alt_repo()
1432
names = packs.names()
1433
# Add a new pack file into the repository
1434
rev4 = tree.commit('four')
1435
new_names = tree.branch.repository._pack_collection.names()
1436
new_name = set(new_names).difference(names)
1437
self.assertEqual(1, len(new_name))
1438
new_name = new_name.pop()
1439
# The old collection hasn't noticed yet
1440
self.assertEqual(names, packs.names())
1441
self.assertTrue(packs.reload_pack_names())
1442
self.assertEqual(new_names, packs.names())
1443
# And the repository can access the new revision
1444
self.assertEqual({rev4:(revs[-1],)}, r.get_parent_map([rev4]))
1445
self.assertFalse(packs.reload_pack_names())
1447
def test_reload_pack_names_added_and_removed(self):
1448
tree, r, packs, revs = self.make_packs_and_alt_repo()
1449
names = packs.names()
1450
# Now repack the whole thing
1451
tree.branch.repository.pack()
1452
new_names = tree.branch.repository._pack_collection.names()
1453
# The other collection hasn't noticed yet
1454
self.assertEqual(names, packs.names())
1455
self.assertTrue(packs.reload_pack_names())
1456
self.assertEqual(new_names, packs.names())
1457
self.assertEqual({revs[-1]:(revs[-2],)}, r.get_parent_map([revs[-1]]))
1458
self.assertFalse(packs.reload_pack_names())
1460
def test_reload_pack_names_preserves_pending(self):
1461
# TODO: Update this to also test for pending-deleted names
1462
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1463
# We will add one pack (via start_write_group + insert_record_stream),
1464
# and remove another pack (via _remove_pack_from_memory)
1465
orig_names = packs.names()
1466
orig_at_load = packs._packs_at_load
1467
to_remove_name = iter(orig_names).next()
1468
r.start_write_group()
1469
self.addCleanup(r.abort_write_group)
1470
r.texts.insert_record_stream([versionedfile.FulltextContentFactory(
1471
('text', 'rev'), (), None, 'content\n')])
1472
new_pack = packs._new_pack
1473
self.assertTrue(new_pack.data_inserted())
1475
packs.allocate(new_pack)
1476
packs._new_pack = None
1477
removed_pack = packs.get_pack_by_name(to_remove_name)
1478
packs._remove_pack_from_memory(removed_pack)
1479
names = packs.names()
1480
all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
1481
new_names = set([x[0][0] for x in new_nodes])
1482
self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1483
self.assertEqual(set(names) - set(orig_names), new_names)
1484
self.assertEqual(set([new_pack.name]), new_names)
1485
self.assertEqual([to_remove_name],
1486
sorted([x[0][0] for x in deleted_nodes]))
1487
packs.reload_pack_names()
1488
reloaded_names = packs.names()
1489
self.assertEqual(orig_at_load, packs._packs_at_load)
1490
self.assertEqual(names, reloaded_names)
1491
all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
1492
new_names = set([x[0][0] for x in new_nodes])
1493
self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1494
self.assertEqual(set(names) - set(orig_names), new_names)
1495
self.assertEqual(set([new_pack.name]), new_names)
1496
self.assertEqual([to_remove_name],
1497
sorted([x[0][0] for x in deleted_nodes]))
1499
def test_autopack_obsoletes_new_pack(self):
1500
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1501
packs._max_pack_count = lambda x: 1
1502
packs.pack_distribution = lambda x: [10]
1503
r.start_write_group()
1504
r.revisions.insert_record_stream([versionedfile.FulltextContentFactory(
1505
('bogus-rev',), (), None, 'bogus-content\n')])
1506
# This should trigger an autopack, which will combine everything into a
1508
new_names = r.commit_write_group()
1509
names = packs.names()
1510
self.assertEqual(1, len(names))
1511
self.assertEqual([names[0] + '.pack'],
1512
packs._pack_transport.list_dir('.'))
1514
def test_autopack_reloads_and_stops(self):
1515
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1516
# After we have determined what needs to be autopacked, trigger a
1517
# full-pack via the other repo which will cause us to re-evaluate and
1518
# decide we don't need to do anything
1519
orig_execute = packs._execute_pack_operations
1520
def _munged_execute_pack_ops(*args, **kwargs):
1521
tree.branch.repository.pack()
1522
return orig_execute(*args, **kwargs)
1523
packs._execute_pack_operations = _munged_execute_pack_ops
1524
packs._max_pack_count = lambda x: 1
1525
packs.pack_distribution = lambda x: [10]
1526
self.assertFalse(packs.autopack())
1527
self.assertEqual(1, len(packs.names()))
1528
self.assertEqual(tree.branch.repository._pack_collection.names(),
1531
def test__save_pack_names(self):
1532
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1533
names = packs.names()
1534
pack = packs.get_pack_by_name(names[0])
1535
packs._remove_pack_from_memory(pack)
1536
packs._save_pack_names(obsolete_packs=[pack])
1537
cur_packs = packs._pack_transport.list_dir('.')
1538
self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1539
# obsolete_packs will also have stuff like .rix and .iix present.
1540
obsolete_packs = packs.transport.list_dir('obsolete_packs')
1541
obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
1542
self.assertEqual([pack.name], sorted(obsolete_names))
1544
def test__save_pack_names_already_obsoleted(self):
1545
tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1546
names = packs.names()
1547
pack = packs.get_pack_by_name(names[0])
1548
packs._remove_pack_from_memory(pack)
1549
# We are going to simulate a concurrent autopack by manually obsoleting
1550
# the pack directly.
1551
packs._obsolete_packs([pack])
1552
packs._save_pack_names(clear_obsolete_packs=True,
1553
obsolete_packs=[pack])
1554
cur_packs = packs._pack_transport.list_dir('.')
1555
self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1556
# Note that while we set clear_obsolete_packs=True, it should not
1557
# delete a pack file that we have also scheduled for obsoletion.
1558
obsolete_packs = packs.transport.list_dir('obsolete_packs')
1559
obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
1560
self.assertEqual([pack.name], sorted(obsolete_names))
1564
class TestPack(TestCaseWithTransport):
1565
"""Tests for the Pack object."""
1567
def assertCurrentlyEqual(self, left, right):
1568
self.assertTrue(left == right)
1569
self.assertTrue(right == left)
1570
self.assertFalse(left != right)
1571
self.assertFalse(right != left)
1573
def assertCurrentlyNotEqual(self, left, right):
1574
self.assertFalse(left == right)
1575
self.assertFalse(right == left)
1576
self.assertTrue(left != right)
1577
self.assertTrue(right != left)
1579
def test___eq____ne__(self):
1580
left = pack_repo.ExistingPack('', '', '', '', '', '')
1581
right = pack_repo.ExistingPack('', '', '', '', '', '')
1582
self.assertCurrentlyEqual(left, right)
1583
# change all attributes and ensure equality changes as we do.
1584
left.revision_index = 'a'
1585
self.assertCurrentlyNotEqual(left, right)
1586
right.revision_index = 'a'
1587
self.assertCurrentlyEqual(left, right)
1588
left.inventory_index = 'a'
1589
self.assertCurrentlyNotEqual(left, right)
1590
right.inventory_index = 'a'
1591
self.assertCurrentlyEqual(left, right)
1592
left.text_index = 'a'
1593
self.assertCurrentlyNotEqual(left, right)
1594
right.text_index = 'a'
1595
self.assertCurrentlyEqual(left, right)
1596
left.signature_index = 'a'
1597
self.assertCurrentlyNotEqual(left, right)
1598
right.signature_index = 'a'
1599
self.assertCurrentlyEqual(left, right)
1601
self.assertCurrentlyNotEqual(left, right)
1603
self.assertCurrentlyEqual(left, right)
1604
left.transport = 'a'
1605
self.assertCurrentlyNotEqual(left, right)
1606
right.transport = 'a'
1607
self.assertCurrentlyEqual(left, right)
1609
def test_file_name(self):
1610
pack = pack_repo.ExistingPack('', 'a_name', '', '', '', '')
1611
self.assertEqual('a_name.pack', pack.file_name())
1614
class TestNewPack(TestCaseWithTransport):
1615
"""Tests for pack_repo.NewPack."""
1617
def test_new_instance_attributes(self):
1618
upload_transport = self.get_transport('upload')
1619
pack_transport = self.get_transport('pack')
1620
index_transport = self.get_transport('index')
1621
upload_transport.mkdir('.')
1622
collection = pack_repo.RepositoryPackCollection(
1624
transport=self.get_transport('.'),
1625
index_transport=index_transport,
1626
upload_transport=upload_transport,
1627
pack_transport=pack_transport,
1628
index_builder_class=BTreeBuilder,
1629
index_class=BTreeGraphIndex,
1630
use_chk_index=False)
1631
pack = pack_repo.NewPack(collection)
1632
self.addCleanup(pack.abort) # Make sure the write stream gets closed
1633
self.assertIsInstance(pack.revision_index, BTreeBuilder)
1634
self.assertIsInstance(pack.inventory_index, BTreeBuilder)
1635
self.assertIsInstance(pack._hash, type(osutils.md5()))
1636
self.assertTrue(pack.upload_transport is upload_transport)
1637
self.assertTrue(pack.index_transport is index_transport)
1638
self.assertTrue(pack.pack_transport is pack_transport)
1639
self.assertEqual(None, pack.index_sizes)
1640
self.assertEqual(20, len(pack.random_name))
1641
self.assertIsInstance(pack.random_name, str)
1642
self.assertIsInstance(pack.start_time, float)
1645
class TestPacker(TestCaseWithTransport):
1646
"""Tests for the packs repository Packer class."""
1648
def test_pack_optimizes_pack_order(self):
1649
builder = self.make_branch_builder('.', format="1.9")
1650
builder.start_series()
1651
builder.build_snapshot('A', None, [
1652
('add', ('', 'root-id', 'directory', None)),
1653
('add', ('f', 'f-id', 'file', 'content\n'))])
1654
builder.build_snapshot('B', ['A'],
1655
[('modify', ('f-id', 'new-content\n'))])
1656
builder.build_snapshot('C', ['B'],
1657
[('modify', ('f-id', 'third-content\n'))])
1658
builder.build_snapshot('D', ['C'],
1659
[('modify', ('f-id', 'fourth-content\n'))])
1660
b = builder.get_branch()
1662
builder.finish_series()
1663
self.addCleanup(b.unlock)
1664
# At this point, we should have 4 pack files available
1665
# Because of how they were built, they correspond to
1666
# ['D', 'C', 'B', 'A']
1667
packs = b.repository._pack_collection.packs
1668
packer = pack_repo.Packer(b.repository._pack_collection,
1670
revision_ids=['B', 'C'])
1671
# Now, when we are copying the B & C revisions, their pack files should
1672
# be moved to the front of the stack
1673
# The new ordering moves B & C to the front of the .packs attribute,
1674
# and leaves the others in the original order.
1675
new_packs = [packs[1], packs[2], packs[0], packs[3]]
1676
new_pack = packer.pack()
1677
self.assertEqual(new_packs, packer.packs)
1680
class TestOptimisingPacker(TestCaseWithTransport):
1681
"""Tests for the OptimisingPacker class."""
1683
def get_pack_collection(self):
1684
repo = self.make_repository('.')
1685
return repo._pack_collection
1687
def test_open_pack_will_optimise(self):
1688
packer = pack_repo.OptimisingPacker(self.get_pack_collection(),
1690
new_pack = packer.open_pack()
1691
self.addCleanup(new_pack.abort) # ensure cleanup
1692
self.assertIsInstance(new_pack, pack_repo.NewPack)
1693
self.assertTrue(new_pack.revision_index._optimize_for_size)
1694
self.assertTrue(new_pack.inventory_index._optimize_for_size)
1695
self.assertTrue(new_pack.text_index._optimize_for_size)
1696
self.assertTrue(new_pack.signature_index._optimize_for_size)
1699
class TestCrossFormatPacks(TestCaseWithTransport):
1701
def log_pack(self, hint=None):
1702
self.calls.append(('pack', hint))
1703
self.orig_pack(hint=hint)
1704
if self.expect_hint:
1705
self.assertTrue(hint)
1707
def run_stream(self, src_fmt, target_fmt, expect_pack_called):
1708
self.expect_hint = expect_pack_called
1710
source_tree = self.make_branch_and_tree('src', format=src_fmt)
1711
source_tree.lock_write()
1712
self.addCleanup(source_tree.unlock)
1713
tip = source_tree.commit('foo')
1714
target = self.make_repository('target', format=target_fmt)
1716
self.addCleanup(target.unlock)
1717
source = source_tree.branch.repository._get_source(target._format)
1718
self.orig_pack = target.pack
1719
target.pack = self.log_pack
1720
search = target.search_missing_revision_ids(
1721
source_tree.branch.repository, revision_ids=[tip])
1722
stream = source.get_stream(search)
1723
from_format = source_tree.branch.repository._format
1724
sink = target._get_sink()
1725
sink.insert_stream(stream, from_format, [])
1726
if expect_pack_called:
1727
self.assertLength(1, self.calls)
1729
self.assertLength(0, self.calls)
1731
def run_fetch(self, src_fmt, target_fmt, expect_pack_called):
1732
self.expect_hint = expect_pack_called
1734
source_tree = self.make_branch_and_tree('src', format=src_fmt)
1735
source_tree.lock_write()
1736
self.addCleanup(source_tree.unlock)
1737
tip = source_tree.commit('foo')
1738
target = self.make_repository('target', format=target_fmt)
1740
self.addCleanup(target.unlock)
1741
source = source_tree.branch.repository
1742
self.orig_pack = target.pack
1743
target.pack = self.log_pack
1744
target.fetch(source)
1745
if expect_pack_called:
1746
self.assertLength(1, self.calls)
1748
self.assertLength(0, self.calls)
1750
def test_sink_format_hint_no(self):
1751
# When the target format says packing makes no difference, pack is not
1753
self.run_stream('1.9', 'rich-root-pack', False)
1755
def test_sink_format_hint_yes(self):
1756
# When the target format says packing makes a difference, pack is
1758
self.run_stream('1.9', '2a', True)
1760
def test_sink_format_same_no(self):
1761
# When the formats are the same, pack is not called.
1762
self.run_stream('2a', '2a', False)
1764
def test_IDS_format_hint_no(self):
1765
# When the target format says packing makes no difference, pack is not
1767
self.run_fetch('1.9', 'rich-root-pack', False)
1769
def test_IDS_format_hint_yes(self):
1770
# When the target format says packing makes a difference, pack is
1772
self.run_fetch('1.9', '2a', True)
1774
def test_IDS_format_same_no(self):
1775
# When the formats are the same, pack is not called.
1776
self.run_fetch('2a', '2a', False)