1
# Copyright (C) 2006, 2007, 2008 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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
26
from StringIO import StringIO
29
from bzrlib.errors import (NotBranchError,
32
UnsupportedFormatError,
34
from bzrlib import graph
35
from bzrlib.btree_index import BTreeBuilder, BTreeGraphIndex
36
from bzrlib.index import GraphIndex, InMemoryGraphIndex
37
from bzrlib.repository import RepositoryFormat
38
from bzrlib.smart import server
39
from bzrlib.tests import (
41
TestCaseWithTransport,
45
from bzrlib.transport import (
49
from bzrlib.transport.memory import MemoryServer
50
from bzrlib.util import bencode
58
revision as _mod_revision,
63
from bzrlib.repofmt import knitrepo, weaverepo, pack_repo
66
class TestDefaultFormat(TestCase):
68
def test_get_set_default_format(self):
69
old_default = bzrdir.format_registry.get('default')
70
private_default = old_default().repository_format.__class__
71
old_format = repository.RepositoryFormat.get_default_format()
72
self.assertTrue(isinstance(old_format, private_default))
73
def make_sample_bzrdir():
74
my_bzrdir = bzrdir.BzrDirMetaFormat1()
75
my_bzrdir.repository_format = SampleRepositoryFormat()
77
bzrdir.format_registry.remove('default')
78
bzrdir.format_registry.register('sample', make_sample_bzrdir, '')
79
bzrdir.format_registry.set_default('sample')
80
# creating a repository should now create an instrumented dir.
82
# the default branch format is used by the meta dir format
83
# which is not the default bzrdir format at this point
84
dir = bzrdir.BzrDirMetaFormat1().initialize('memory:///')
85
result = dir.create_repository()
86
self.assertEqual(result, 'A bzr repository dir')
88
bzrdir.format_registry.remove('default')
89
bzrdir.format_registry.remove('sample')
90
bzrdir.format_registry.register('default', old_default, '')
91
self.assertIsInstance(repository.RepositoryFormat.get_default_format(),
95
class SampleRepositoryFormat(repository.RepositoryFormat):
98
this format is initializable, unsupported to aid in testing the
99
open and open(unsupported=True) routines.
102
def get_format_string(self):
103
"""See RepositoryFormat.get_format_string()."""
104
return "Sample .bzr repository format."
106
def initialize(self, a_bzrdir, shared=False):
107
"""Initialize a repository in a BzrDir"""
108
t = a_bzrdir.get_repository_transport(self)
109
t.put_bytes('format', self.get_format_string())
110
return 'A bzr repository dir'
112
def is_supported(self):
115
def open(self, a_bzrdir, _found=False):
116
return "opened repository."
119
class TestRepositoryFormat(TestCaseWithTransport):
120
"""Tests for the Repository format detection used by the bzr meta dir facility.BzrBranchFormat facility."""
122
def test_find_format(self):
123
# is the right format object found for a repository?
124
# create a branch with a few known format objects.
125
# this is not quite the same as
126
self.build_tree(["foo/", "bar/"])
127
def check_format(format, url):
128
dir = format._matchingbzrdir.initialize(url)
129
format.initialize(dir)
130
t = get_transport(url)
131
found_format = repository.RepositoryFormat.find_format(dir)
132
self.failUnless(isinstance(found_format, format.__class__))
133
check_format(weaverepo.RepositoryFormat7(), "bar")
135
def test_find_format_no_repository(self):
136
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
137
self.assertRaises(errors.NoRepositoryPresent,
138
repository.RepositoryFormat.find_format,
141
def test_find_format_unknown_format(self):
142
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
143
SampleRepositoryFormat().initialize(dir)
144
self.assertRaises(UnknownFormatError,
145
repository.RepositoryFormat.find_format,
148
def test_register_unregister_format(self):
149
format = SampleRepositoryFormat()
151
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
153
format.initialize(dir)
154
# register a format for it.
155
repository.RepositoryFormat.register_format(format)
156
# which repository.Open will refuse (not supported)
157
self.assertRaises(UnsupportedFormatError, repository.Repository.open, self.get_url())
158
# but open(unsupported) will work
159
self.assertEqual(format.open(dir), "opened repository.")
160
# unregister the format
161
repository.RepositoryFormat.unregister_format(format)
164
class TestFormat6(TestCaseWithTransport):
166
def test_attribute__fetch_order(self):
167
"""Weaves need topological data insertion."""
168
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
169
repo = weaverepo.RepositoryFormat6().initialize(control)
170
self.assertEqual('topological', repo._fetch_order)
172
def test_attribute__fetch_uses_deltas(self):
173
"""Weaves do not reuse deltas."""
174
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
175
repo = weaverepo.RepositoryFormat6().initialize(control)
176
self.assertEqual(False, repo._fetch_uses_deltas)
178
def test_attribute__fetch_reconcile(self):
179
"""Weave repositories need a reconcile after fetch."""
180
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
181
repo = weaverepo.RepositoryFormat6().initialize(control)
182
self.assertEqual(True, repo._fetch_reconcile)
184
def test_no_ancestry_weave(self):
185
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
186
repo = weaverepo.RepositoryFormat6().initialize(control)
187
# We no longer need to create the ancestry.weave file
188
# since it is *never* used.
189
self.assertRaises(NoSuchFile,
190
control.transport.get,
193
def test_supports_external_lookups(self):
194
control = bzrdir.BzrDirFormat6().initialize(self.get_url())
195
repo = weaverepo.RepositoryFormat6().initialize(control)
196
self.assertFalse(repo._format.supports_external_lookups)
199
class TestFormat7(TestCaseWithTransport):
201
def test_attribute__fetch_order(self):
202
"""Weaves need topological data insertion."""
203
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
204
repo = weaverepo.RepositoryFormat7().initialize(control)
205
self.assertEqual('topological', repo._fetch_order)
207
def test_attribute__fetch_uses_deltas(self):
208
"""Weaves do not reuse deltas."""
209
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
210
repo = weaverepo.RepositoryFormat7().initialize(control)
211
self.assertEqual(False, repo._fetch_uses_deltas)
213
def test_attribute__fetch_reconcile(self):
214
"""Weave repositories need a reconcile after fetch."""
215
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
216
repo = weaverepo.RepositoryFormat7().initialize(control)
217
self.assertEqual(True, repo._fetch_reconcile)
219
def test_disk_layout(self):
220
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
221
repo = weaverepo.RepositoryFormat7().initialize(control)
222
# in case of side effects of locking.
226
# format 'Bazaar-NG Repository format 7'
228
# inventory.weave == empty_weave
229
# empty revision-store directory
230
# empty weaves directory
231
t = control.get_repository_transport(None)
232
self.assertEqualDiff('Bazaar-NG Repository format 7',
233
t.get('format').read())
234
self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
235
self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
236
self.assertEqualDiff('# bzr weave file v5\n'
239
t.get('inventory.weave').read())
240
# Creating a file with id Foo:Bar results in a non-escaped file name on
242
control.create_branch()
243
tree = control.create_workingtree()
244
tree.add(['foo'], ['Foo:Bar'], ['file'])
245
tree.put_file_bytes_non_atomic('Foo:Bar', 'content\n')
246
tree.commit('first post', rev_id='first')
247
self.assertEqualDiff(
248
'# bzr weave file v5\n'
250
'1 7fe70820e08a1aac0ef224d9c66ab66831cc4ab1\n'
258
t.get('weaves/74/Foo%3ABar.weave').read())
260
def test_shared_disk_layout(self):
261
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
262
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
264
# format 'Bazaar-NG Repository format 7'
265
# inventory.weave == empty_weave
266
# empty revision-store directory
267
# empty weaves directory
268
# a 'shared-storage' marker file.
269
# lock is not present when unlocked
270
t = control.get_repository_transport(None)
271
self.assertEqualDiff('Bazaar-NG Repository format 7',
272
t.get('format').read())
273
self.assertEqualDiff('', t.get('shared-storage').read())
274
self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
275
self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
276
self.assertEqualDiff('# bzr weave file v5\n'
279
t.get('inventory.weave').read())
280
self.assertFalse(t.has('branch-lock'))
282
def test_creates_lockdir(self):
283
"""Make sure it appears to be controlled by a LockDir existence"""
284
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
285
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
286
t = control.get_repository_transport(None)
287
# TODO: Should check there is a 'lock' toplevel directory,
288
# regardless of contents
289
self.assertFalse(t.has('lock/held/info'))
292
self.assertTrue(t.has('lock/held/info'))
294
# unlock so we don't get a warning about failing to do so
297
def test_uses_lockdir(self):
298
"""repo format 7 actually locks on lockdir"""
299
base_url = self.get_url()
300
control = bzrdir.BzrDirMetaFormat1().initialize(base_url)
301
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
302
t = control.get_repository_transport(None)
306
# make sure the same lock is created by opening it
307
repo = repository.Repository.open(base_url)
309
self.assertTrue(t.has('lock/held/info'))
311
self.assertFalse(t.has('lock/held/info'))
313
def test_shared_no_tree_disk_layout(self):
314
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
315
repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
316
repo.set_make_working_trees(False)
318
# 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
t = control.get_repository_transport(None)
325
self.assertEqualDiff('Bazaar-NG Repository format 7',
326
t.get('format').read())
327
## self.assertEqualDiff('', t.get('lock').read())
328
self.assertEqualDiff('', t.get('shared-storage').read())
329
self.assertEqualDiff('', t.get('no-working-trees').read())
330
repo.set_make_working_trees(True)
331
self.assertFalse(t.has('no-working-trees'))
332
self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
333
self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
334
self.assertEqualDiff('# bzr weave file v5\n'
337
t.get('inventory.weave').read())
339
def test_supports_external_lookups(self):
340
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
341
repo = weaverepo.RepositoryFormat7().initialize(control)
342
self.assertFalse(repo._format.supports_external_lookups)
345
class TestFormatKnit1(TestCaseWithTransport):
347
def test_attribute__fetch_order(self):
348
"""Knits need topological data insertion."""
349
repo = self.make_repository('.',
350
format=bzrdir.format_registry.get('knit')())
351
self.assertEqual('topological', repo._fetch_order)
353
def test_attribute__fetch_uses_deltas(self):
354
"""Knits reuse deltas."""
355
repo = self.make_repository('.',
356
format=bzrdir.format_registry.get('knit')())
357
self.assertEqual(True, repo._fetch_uses_deltas)
359
def test_disk_layout(self):
360
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
361
repo = knitrepo.RepositoryFormatKnit1().initialize(control)
362
# in case of side effects of locking.
366
# format 'Bazaar-NG Knit Repository Format 1'
367
# lock: is a directory
368
# inventory.weave == empty_weave
369
# empty revision-store directory
370
# empty weaves directory
371
t = control.get_repository_transport(None)
372
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
373
t.get('format').read())
374
# XXX: no locks left when unlocked at the moment
375
# self.assertEqualDiff('', t.get('lock').read())
376
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
378
# Check per-file knits.
379
branch = control.create_branch()
380
tree = control.create_workingtree()
381
tree.add(['foo'], ['Nasty-IdC:'], ['file'])
382
tree.put_file_bytes_non_atomic('Nasty-IdC:', '')
383
tree.commit('1st post', rev_id='foo')
384
self.assertHasKnit(t, 'knits/e8/%254easty-%2549d%2543%253a',
385
'\nfoo fulltext 0 81 :')
387
def assertHasKnit(self, t, knit_name, extra_content=''):
388
"""Assert that knit_name exists on t."""
389
self.assertEqualDiff('# bzr knit index 8\n' + extra_content,
390
t.get(knit_name + '.kndx').read())
392
def check_knits(self, t):
393
"""check knit content for a repository."""
394
self.assertHasKnit(t, 'inventory')
395
self.assertHasKnit(t, 'revisions')
396
self.assertHasKnit(t, 'signatures')
398
def test_shared_disk_layout(self):
399
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
400
repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
402
# format 'Bazaar-NG Knit Repository Format 1'
403
# lock: is a directory
404
# inventory.weave == empty_weave
405
# empty revision-store directory
406
# empty weaves directory
407
# a 'shared-storage' marker file.
408
t = control.get_repository_transport(None)
409
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
410
t.get('format').read())
411
# XXX: no locks left when unlocked at the moment
412
# self.assertEqualDiff('', t.get('lock').read())
413
self.assertEqualDiff('', t.get('shared-storage').read())
414
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
417
def test_shared_no_tree_disk_layout(self):
418
control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
419
repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
420
repo.set_make_working_trees(False)
422
# format 'Bazaar-NG Knit Repository Format 1'
424
# inventory.weave == empty_weave
425
# empty revision-store directory
426
# empty weaves directory
427
# a 'shared-storage' marker file.
428
t = control.get_repository_transport(None)
429
self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
430
t.get('format').read())
431
# XXX: no locks left when unlocked at the moment
432
# self.assertEqualDiff('', t.get('lock').read())
433
self.assertEqualDiff('', t.get('shared-storage').read())
434
self.assertEqualDiff('', t.get('no-working-trees').read())
435
repo.set_make_working_trees(True)
436
self.assertFalse(t.has('no-working-trees'))
437
self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
440
def test_deserialise_sets_root_revision(self):
441
"""We must have a inventory.root.revision
443
Old versions of the XML5 serializer did not set the revision_id for
444
the whole inventory. So we grab the one from the expected text. Which
445
is valid when the api is not being abused.
447
repo = self.make_repository('.',
448
format=bzrdir.format_registry.get('knit')())
449
inv_xml = '<inventory format="5">\n</inventory>\n'
450
inv = repo.deserialise_inventory('test-rev-id', inv_xml)
451
self.assertEqual('test-rev-id', inv.root.revision)
453
def test_deserialise_uses_global_revision_id(self):
454
"""If it is set, then we re-use the global revision id"""
455
repo = self.make_repository('.',
456
format=bzrdir.format_registry.get('knit')())
457
inv_xml = ('<inventory format="5" revision_id="other-rev-id">\n'
459
# Arguably, the deserialise_inventory should detect a mismatch, and
460
# raise an error, rather than silently using one revision_id over the
462
self.assertRaises(AssertionError, repo.deserialise_inventory,
463
'test-rev-id', inv_xml)
464
inv = repo.deserialise_inventory('other-rev-id', inv_xml)
465
self.assertEqual('other-rev-id', inv.root.revision)
467
def test_supports_external_lookups(self):
468
repo = self.make_repository('.',
469
format=bzrdir.format_registry.get('knit')())
470
self.assertFalse(repo._format.supports_external_lookups)
473
class DummyRepository(object):
474
"""A dummy repository for testing."""
479
def supports_rich_root(self):
483
raise NotImplementedError
485
def get_parent_map(self, revision_ids):
486
raise NotImplementedError
489
class InterDummy(repository.InterRepository):
490
"""An inter-repository optimised code path for DummyRepository.
492
This is for use during testing where we use DummyRepository as repositories
493
so that none of the default regsitered inter-repository classes will
498
def is_compatible(repo_source, repo_target):
499
"""InterDummy is compatible with DummyRepository."""
500
return (isinstance(repo_source, DummyRepository) and
501
isinstance(repo_target, DummyRepository))
504
class TestInterRepository(TestCaseWithTransport):
506
def test_get_default_inter_repository(self):
507
# test that the InterRepository.get(repo_a, repo_b) probes
508
# for a inter_repo class where is_compatible(repo_a, repo_b) returns
509
# true and returns a default inter_repo otherwise.
510
# This also tests that the default registered optimised interrepository
511
# classes do not barf inappropriately when a surprising repository type
513
dummy_a = DummyRepository()
514
dummy_b = DummyRepository()
515
self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
517
def assertGetsDefaultInterRepository(self, repo_a, repo_b):
518
"""Asserts that InterRepository.get(repo_a, repo_b) -> the default.
520
The effective default is now InterSameDataRepository because there is
521
no actual sane default in the presence of incompatible data models.
523
inter_repo = repository.InterRepository.get(repo_a, repo_b)
524
self.assertEqual(repository.InterSameDataRepository,
525
inter_repo.__class__)
526
self.assertEqual(repo_a, inter_repo.source)
527
self.assertEqual(repo_b, inter_repo.target)
529
def test_register_inter_repository_class(self):
530
# test that a optimised code path provider - a
531
# InterRepository subclass can be registered and unregistered
532
# and that it is correctly selected when given a repository
533
# pair that it returns true on for the is_compatible static method
535
dummy_a = DummyRepository()
536
dummy_b = DummyRepository()
537
repo = self.make_repository('.')
538
# hack dummies to look like repo somewhat.
539
dummy_a._serializer = repo._serializer
540
dummy_b._serializer = repo._serializer
541
repository.InterRepository.register_optimiser(InterDummy)
543
# we should get the default for something InterDummy returns False
545
self.assertFalse(InterDummy.is_compatible(dummy_a, repo))
546
self.assertGetsDefaultInterRepository(dummy_a, repo)
547
# and we should get an InterDummy for a pair it 'likes'
548
self.assertTrue(InterDummy.is_compatible(dummy_a, dummy_b))
549
inter_repo = repository.InterRepository.get(dummy_a, dummy_b)
550
self.assertEqual(InterDummy, inter_repo.__class__)
551
self.assertEqual(dummy_a, inter_repo.source)
552
self.assertEqual(dummy_b, inter_repo.target)
554
repository.InterRepository.unregister_optimiser(InterDummy)
555
# now we should get the default InterRepository object again.
556
self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
559
class TestInterWeaveRepo(TestCaseWithTransport):
561
def test_is_compatible_and_registered(self):
562
# InterWeaveRepo is compatible when either side
563
# is a format 5/6/7 branch
564
from bzrlib.repofmt import knitrepo, weaverepo
565
formats = [weaverepo.RepositoryFormat5(),
566
weaverepo.RepositoryFormat6(),
567
weaverepo.RepositoryFormat7()]
568
incompatible_formats = [weaverepo.RepositoryFormat4(),
569
knitrepo.RepositoryFormatKnit1(),
571
repo_a = self.make_repository('a')
572
repo_b = self.make_repository('b')
573
is_compatible = repository.InterWeaveRepo.is_compatible
574
for source in incompatible_formats:
575
# force incompatible left then right
576
repo_a._format = source
577
repo_b._format = formats[0]
578
self.assertFalse(is_compatible(repo_a, repo_b))
579
self.assertFalse(is_compatible(repo_b, repo_a))
580
for source in formats:
581
repo_a._format = source
582
for target in formats:
583
repo_b._format = target
584
self.assertTrue(is_compatible(repo_a, repo_b))
585
self.assertEqual(repository.InterWeaveRepo,
586
repository.InterRepository.get(repo_a,
590
class TestRepositoryConverter(TestCaseWithTransport):
592
def test_convert_empty(self):
593
t = get_transport(self.get_url('.'))
594
t.mkdir('repository')
595
repo_dir = bzrdir.BzrDirMetaFormat1().initialize('repository')
596
repo = weaverepo.RepositoryFormat7().initialize(repo_dir)
597
target_format = knitrepo.RepositoryFormatKnit1()
598
converter = repository.CopyConverter(target_format)
599
pb = bzrlib.ui.ui_factory.nested_progress_bar()
601
converter.convert(repo, pb)
604
repo = repo_dir.open_repository()
605
self.assertTrue(isinstance(target_format, repo._format.__class__))
608
class TestMisc(TestCase):
610
def test_unescape_xml(self):
611
"""We get some kind of error when malformed entities are passed"""
612
self.assertRaises(KeyError, repository._unescape_xml, 'foo&bar;')
615
class TestRepositoryFormatKnit3(TestCaseWithTransport):
617
def test_attribute__fetch_order(self):
618
"""Knits need topological data insertion."""
619
format = bzrdir.BzrDirMetaFormat1()
620
format.repository_format = knitrepo.RepositoryFormatKnit3()
621
repo = self.make_repository('.', format=format)
622
self.assertEqual('topological', repo._fetch_order)
624
def test_attribute__fetch_uses_deltas(self):
625
"""Knits reuse deltas."""
626
format = bzrdir.BzrDirMetaFormat1()
627
format.repository_format = knitrepo.RepositoryFormatKnit3()
628
repo = self.make_repository('.', format=format)
629
self.assertEqual(True, repo._fetch_uses_deltas)
631
def test_convert(self):
632
"""Ensure the upgrade adds weaves for roots"""
633
format = bzrdir.BzrDirMetaFormat1()
634
format.repository_format = knitrepo.RepositoryFormatKnit1()
635
tree = self.make_branch_and_tree('.', format)
636
tree.commit("Dull commit", rev_id="dull")
637
revision_tree = tree.branch.repository.revision_tree('dull')
638
revision_tree.lock_read()
640
self.assertRaises(errors.NoSuchFile, revision_tree.get_file_lines,
641
revision_tree.inventory.root.file_id)
643
revision_tree.unlock()
644
format = bzrdir.BzrDirMetaFormat1()
645
format.repository_format = knitrepo.RepositoryFormatKnit3()
646
upgrade.Convert('.', format)
647
tree = workingtree.WorkingTree.open('.')
648
revision_tree = tree.branch.repository.revision_tree('dull')
649
revision_tree.lock_read()
651
revision_tree.get_file_lines(revision_tree.inventory.root.file_id)
653
revision_tree.unlock()
654
tree.commit("Another dull commit", rev_id='dull2')
655
revision_tree = tree.branch.repository.revision_tree('dull2')
656
revision_tree.lock_read()
657
self.addCleanup(revision_tree.unlock)
658
self.assertEqual('dull', revision_tree.inventory.root.revision)
660
def test_supports_external_lookups(self):
661
format = bzrdir.BzrDirMetaFormat1()
662
format.repository_format = knitrepo.RepositoryFormatKnit3()
663
repo = self.make_repository('.', format=format)
664
self.assertFalse(repo._format.supports_external_lookups)
667
class TestWithBrokenRepo(TestCaseWithTransport):
668
"""These tests seem to be more appropriate as interface tests?"""
670
def make_broken_repository(self):
671
# XXX: This function is borrowed from Aaron's "Reconcile can fix bad
672
# parent references" branch which is due to land in bzr.dev soon. Once
673
# it does, this duplication should be removed.
674
repo = self.make_repository('broken-repo')
678
cleanups.append(repo.unlock)
679
repo.start_write_group()
680
cleanups.append(repo.commit_write_group)
681
# make rev1a: A well-formed revision, containing 'file1'
682
inv = inventory.Inventory(revision_id='rev1a')
683
inv.root.revision = 'rev1a'
684
self.add_file(repo, inv, 'file1', 'rev1a', [])
685
repo.add_inventory('rev1a', inv, [])
686
revision = _mod_revision.Revision('rev1a',
687
committer='jrandom@example.com', timestamp=0,
688
inventory_sha1='', timezone=0, message='foo', parent_ids=[])
689
repo.add_revision('rev1a',revision, inv)
691
# make rev1b, which has no Revision, but has an Inventory, and
693
inv = inventory.Inventory(revision_id='rev1b')
694
inv.root.revision = 'rev1b'
695
self.add_file(repo, inv, 'file1', 'rev1b', [])
696
repo.add_inventory('rev1b', inv, [])
698
# make rev2, with file1 and file2
700
# file1 has 'rev1b' as an ancestor, even though this is not
701
# mentioned by 'rev1a', making it an unreferenced ancestor
702
inv = inventory.Inventory()
703
self.add_file(repo, inv, 'file1', 'rev2', ['rev1a', 'rev1b'])
704
self.add_file(repo, inv, 'file2', 'rev2', [])
705
self.add_revision(repo, 'rev2', inv, ['rev1a'])
707
# make ghost revision rev1c
708
inv = inventory.Inventory()
709
self.add_file(repo, inv, 'file2', 'rev1c', [])
711
# make rev3 with file2
712
# file2 refers to 'rev1c', which is a ghost in this repository, so
713
# file2 cannot have rev1c as its ancestor.
714
inv = inventory.Inventory()
715
self.add_file(repo, inv, 'file2', 'rev3', ['rev1c'])
716
self.add_revision(repo, 'rev3', inv, ['rev1c'])
719
for cleanup in reversed(cleanups):
722
def add_revision(self, repo, revision_id, inv, parent_ids):
723
inv.revision_id = revision_id
724
inv.root.revision = revision_id
725
repo.add_inventory(revision_id, inv, parent_ids)
726
revision = _mod_revision.Revision(revision_id,
727
committer='jrandom@example.com', timestamp=0, inventory_sha1='',
728
timezone=0, message='foo', parent_ids=parent_ids)
729
repo.add_revision(revision_id,revision, inv)
731
def add_file(self, repo, inv, filename, revision, parents):
732
file_id = filename + '-id'
733
entry = inventory.InventoryFile(file_id, filename, 'TREE_ROOT')
734
entry.revision = revision
737
text_key = (file_id, revision)
738
parent_keys = [(file_id, parent) for parent in parents]
739
repo.texts.add_lines(text_key, parent_keys, ['line\n'])
741
def test_insert_from_broken_repo(self):
742
"""Inserting a data stream from a broken repository won't silently
743
corrupt the target repository.
745
broken_repo = self.make_broken_repository()
746
empty_repo = self.make_repository('empty-repo')
747
self.assertRaises(errors.RevisionNotPresent, empty_repo.fetch, broken_repo)
750
class TestRepositoryPackCollection(TestCaseWithTransport):
752
def get_format(self):
753
return bzrdir.format_registry.make_bzrdir('pack-0.92')
756
format = self.get_format()
757
repo = self.make_repository('.', format=format)
758
return repo._pack_collection
760
def test__max_pack_count(self):
761
"""The maximum pack count is a function of the number of revisions."""
762
# no revisions - one pack, so that we can have a revision free repo
763
# without it blowing up
764
packs = self.get_packs()
765
self.assertEqual(1, packs._max_pack_count(0))
766
# after that the sum of the digits, - check the first 1-9
767
self.assertEqual(1, packs._max_pack_count(1))
768
self.assertEqual(2, packs._max_pack_count(2))
769
self.assertEqual(3, packs._max_pack_count(3))
770
self.assertEqual(4, packs._max_pack_count(4))
771
self.assertEqual(5, packs._max_pack_count(5))
772
self.assertEqual(6, packs._max_pack_count(6))
773
self.assertEqual(7, packs._max_pack_count(7))
774
self.assertEqual(8, packs._max_pack_count(8))
775
self.assertEqual(9, packs._max_pack_count(9))
776
# check the boundary cases with two digits for the next decade
777
self.assertEqual(1, packs._max_pack_count(10))
778
self.assertEqual(2, packs._max_pack_count(11))
779
self.assertEqual(10, packs._max_pack_count(19))
780
self.assertEqual(2, packs._max_pack_count(20))
781
self.assertEqual(3, packs._max_pack_count(21))
782
# check some arbitrary big numbers
783
self.assertEqual(25, packs._max_pack_count(112894))
785
def test_pack_distribution_zero(self):
786
packs = self.get_packs()
787
self.assertEqual([0], packs.pack_distribution(0))
789
def test_ensure_loaded_unlocked(self):
790
packs = self.get_packs()
791
self.assertRaises(errors.ObjectNotLocked,
794
def test_pack_distribution_one_to_nine(self):
795
packs = self.get_packs()
796
self.assertEqual([1],
797
packs.pack_distribution(1))
798
self.assertEqual([1, 1],
799
packs.pack_distribution(2))
800
self.assertEqual([1, 1, 1],
801
packs.pack_distribution(3))
802
self.assertEqual([1, 1, 1, 1],
803
packs.pack_distribution(4))
804
self.assertEqual([1, 1, 1, 1, 1],
805
packs.pack_distribution(5))
806
self.assertEqual([1, 1, 1, 1, 1, 1],
807
packs.pack_distribution(6))
808
self.assertEqual([1, 1, 1, 1, 1, 1, 1],
809
packs.pack_distribution(7))
810
self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1],
811
packs.pack_distribution(8))
812
self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1, 1],
813
packs.pack_distribution(9))
815
def test_pack_distribution_stable_at_boundaries(self):
816
"""When there are multi-rev packs the counts are stable."""
817
packs = self.get_packs()
819
self.assertEqual([10], packs.pack_distribution(10))
820
self.assertEqual([10, 1], packs.pack_distribution(11))
821
self.assertEqual([10, 10], packs.pack_distribution(20))
822
self.assertEqual([10, 10, 1], packs.pack_distribution(21))
824
self.assertEqual([100], packs.pack_distribution(100))
825
self.assertEqual([100, 1], packs.pack_distribution(101))
826
self.assertEqual([100, 10, 1], packs.pack_distribution(111))
827
self.assertEqual([100, 100], packs.pack_distribution(200))
828
self.assertEqual([100, 100, 1], packs.pack_distribution(201))
829
self.assertEqual([100, 100, 10, 1], packs.pack_distribution(211))
831
def test_plan_pack_operations_2009_revisions_skip_all_packs(self):
832
packs = self.get_packs()
833
existing_packs = [(2000, "big"), (9, "medium")]
834
# rev count - 2009 -> 2x1000 + 9x1
835
pack_operations = packs.plan_autopack_combinations(
836
existing_packs, [1000, 1000, 1, 1, 1, 1, 1, 1, 1, 1, 1])
837
self.assertEqual([], pack_operations)
839
def test_plan_pack_operations_2010_revisions_skip_all_packs(self):
840
packs = self.get_packs()
841
existing_packs = [(2000, "big"), (9, "medium"), (1, "single")]
842
# rev count - 2010 -> 2x1000 + 1x10
843
pack_operations = packs.plan_autopack_combinations(
844
existing_packs, [1000, 1000, 10])
845
self.assertEqual([], pack_operations)
847
def test_plan_pack_operations_2010_combines_smallest_two(self):
848
packs = self.get_packs()
849
existing_packs = [(1999, "big"), (9, "medium"), (1, "single2"),
851
# rev count - 2010 -> 2x1000 + 1x10 (3)
852
pack_operations = packs.plan_autopack_combinations(
853
existing_packs, [1000, 1000, 10])
854
self.assertEqual([[2, ["single2", "single1"]]], pack_operations)
856
def test_plan_pack_operations_creates_a_single_op(self):
857
packs = self.get_packs()
858
existing_packs = [(50, 'a'), (40, 'b'), (30, 'c'), (10, 'd'),
859
(10, 'e'), (6, 'f'), (4, 'g')]
860
# rev count 150 -> 1x100 and 5x10
861
# The two size 10 packs do not need to be touched. The 50, 40, 30 would
862
# be combined into a single 120 size pack, and the 6 & 4 would
863
# becombined into a size 10 pack. However, if we have to rewrite them,
864
# we save a pack file with no increased I/O by putting them into the
866
distribution = packs.pack_distribution(150)
867
pack_operations = packs.plan_autopack_combinations(existing_packs,
869
self.assertEqual([[130, ['a', 'b', 'c', 'f', 'g']]], pack_operations)
871
def test_all_packs_none(self):
872
format = self.get_format()
873
tree = self.make_branch_and_tree('.', format=format)
875
self.addCleanup(tree.unlock)
876
packs = tree.branch.repository._pack_collection
877
packs.ensure_loaded()
878
self.assertEqual([], packs.all_packs())
880
def test_all_packs_one(self):
881
format = self.get_format()
882
tree = self.make_branch_and_tree('.', format=format)
885
self.addCleanup(tree.unlock)
886
packs = tree.branch.repository._pack_collection
887
packs.ensure_loaded()
889
packs.get_pack_by_name(packs.names()[0])],
892
def test_all_packs_two(self):
893
format = self.get_format()
894
tree = self.make_branch_and_tree('.', format=format)
896
tree.commit('continue')
898
self.addCleanup(tree.unlock)
899
packs = tree.branch.repository._pack_collection
900
packs.ensure_loaded()
902
packs.get_pack_by_name(packs.names()[0]),
903
packs.get_pack_by_name(packs.names()[1]),
904
], packs.all_packs())
906
def test_get_pack_by_name(self):
907
format = self.get_format()
908
tree = self.make_branch_and_tree('.', format=format)
911
self.addCleanup(tree.unlock)
912
packs = tree.branch.repository._pack_collection
913
packs.ensure_loaded()
914
name = packs.names()[0]
915
pack_1 = packs.get_pack_by_name(name)
916
# the pack should be correctly initialised
917
sizes = packs._names[name]
918
rev_index = GraphIndex(packs._index_transport, name + '.rix', sizes[0])
919
inv_index = GraphIndex(packs._index_transport, name + '.iix', sizes[1])
920
txt_index = GraphIndex(packs._index_transport, name + '.tix', sizes[2])
921
sig_index = GraphIndex(packs._index_transport, name + '.six', sizes[3])
922
self.assertEqual(pack_repo.ExistingPack(packs._pack_transport,
923
name, rev_index, inv_index, txt_index, sig_index), pack_1)
924
# and the same instance should be returned on successive calls.
925
self.assertTrue(pack_1 is packs.get_pack_by_name(name))
927
def test_reload_pack_names_new_entry(self):
928
tree = self.make_branch_and_tree('.')
930
self.addCleanup(tree.unlock)
931
rev1 = tree.commit('one')
932
rev2 = tree.commit('two')
933
r = repository.Repository.open('.')
935
self.addCleanup(r.unlock)
936
packs = r._pack_collection
937
packs.ensure_loaded()
938
names = packs.names()
939
# Add a new pack file into the repository
940
rev3 = tree.commit('three')
941
new_names = tree.branch.repository._pack_collection.names()
942
new_name = set(new_names).difference(names)
943
self.assertEqual(1, len(new_name))
944
new_name = new_name.pop()
945
# The old collection hasn't noticed yet
946
self.assertEqual(names, packs.names())
947
self.assertTrue(packs.reload_pack_names())
948
self.assertEqual(new_names, packs.names())
949
# And the repository can access the new revision
950
self.assertEqual({rev3:(rev2,)}, r.get_parent_map([rev3]))
951
self.assertFalse(packs.reload_pack_names())
953
def test_reload_pack_names_added_and_removed(self):
954
tree = self.make_branch_and_tree('.')
956
self.addCleanup(tree.unlock)
957
rev1 = tree.commit('one')
958
rev2 = tree.commit('two')
959
r = repository.Repository.open('.')
961
self.addCleanup(r.unlock)
962
packs = r._pack_collection
963
packs.ensure_loaded()
964
names = packs.names()
965
# Now repack the whole thing
966
tree.branch.repository.pack()
967
new_names = tree.branch.repository._pack_collection.names()
968
# The other collection hasn't noticed yet
969
self.assertEqual(names, packs.names())
970
self.assertTrue(packs.reload_pack_names())
971
self.assertEqual(new_names, packs.names())
972
self.assertEqual({rev2:(rev1,)}, r.get_parent_map([rev2]))
973
self.assertFalse(packs.reload_pack_names())
976
class TestPack(TestCaseWithTransport):
977
"""Tests for the Pack object."""
979
def assertCurrentlyEqual(self, left, right):
980
self.assertTrue(left == right)
981
self.assertTrue(right == left)
982
self.assertFalse(left != right)
983
self.assertFalse(right != left)
985
def assertCurrentlyNotEqual(self, left, right):
986
self.assertFalse(left == right)
987
self.assertFalse(right == left)
988
self.assertTrue(left != right)
989
self.assertTrue(right != left)
991
def test___eq____ne__(self):
992
left = pack_repo.ExistingPack('', '', '', '', '', '')
993
right = pack_repo.ExistingPack('', '', '', '', '', '')
994
self.assertCurrentlyEqual(left, right)
995
# change all attributes and ensure equality changes as we do.
996
left.revision_index = 'a'
997
self.assertCurrentlyNotEqual(left, right)
998
right.revision_index = 'a'
999
self.assertCurrentlyEqual(left, right)
1000
left.inventory_index = 'a'
1001
self.assertCurrentlyNotEqual(left, right)
1002
right.inventory_index = 'a'
1003
self.assertCurrentlyEqual(left, right)
1004
left.text_index = 'a'
1005
self.assertCurrentlyNotEqual(left, right)
1006
right.text_index = 'a'
1007
self.assertCurrentlyEqual(left, right)
1008
left.signature_index = 'a'
1009
self.assertCurrentlyNotEqual(left, right)
1010
right.signature_index = 'a'
1011
self.assertCurrentlyEqual(left, right)
1013
self.assertCurrentlyNotEqual(left, right)
1015
self.assertCurrentlyEqual(left, right)
1016
left.transport = 'a'
1017
self.assertCurrentlyNotEqual(left, right)
1018
right.transport = 'a'
1019
self.assertCurrentlyEqual(left, right)
1021
def test_file_name(self):
1022
pack = pack_repo.ExistingPack('', 'a_name', '', '', '', '')
1023
self.assertEqual('a_name.pack', pack.file_name())
1026
class TestNewPack(TestCaseWithTransport):
1027
"""Tests for pack_repo.NewPack."""
1029
def test_new_instance_attributes(self):
1030
upload_transport = self.get_transport('upload')
1031
pack_transport = self.get_transport('pack')
1032
index_transport = self.get_transport('index')
1033
upload_transport.mkdir('.')
1034
pack = pack_repo.NewPack(upload_transport, index_transport,
1035
pack_transport, index_builder_class=BTreeBuilder,
1036
index_class=BTreeGraphIndex)
1037
self.assertIsInstance(pack.revision_index, BTreeBuilder)
1038
self.assertIsInstance(pack.inventory_index, BTreeBuilder)
1039
self.assertIsInstance(pack._hash, type(osutils.md5()))
1040
self.assertTrue(pack.upload_transport is upload_transport)
1041
self.assertTrue(pack.index_transport is index_transport)
1042
self.assertTrue(pack.pack_transport is pack_transport)
1043
self.assertEqual(None, pack.index_sizes)
1044
self.assertEqual(20, len(pack.random_name))
1045
self.assertIsInstance(pack.random_name, str)
1046
self.assertIsInstance(pack.start_time, float)
1049
class TestPacker(TestCaseWithTransport):
1050
"""Tests for the packs repository Packer class."""
1052
# To date, this class has been factored out and nothing new added to it;
1053
# thus there are not yet any tests.
1056
class TestOptimisingPacker(TestCaseWithTransport):
1057
"""Tests for the OptimisingPacker class."""
1059
def get_pack_collection(self):
1060
repo = self.make_repository('.')
1061
return repo._pack_collection
1063
def test_open_pack_will_optimise(self):
1064
packer = pack_repo.OptimisingPacker(self.get_pack_collection(),
1066
new_pack = packer.open_pack()
1067
self.assertIsInstance(new_pack, pack_repo.NewPack)
1068
self.assertTrue(new_pack.revision_index._optimize_for_size)
1069
self.assertTrue(new_pack.inventory_index._optimize_for_size)
1070
self.assertTrue(new_pack.text_index._optimize_for_size)
1071
self.assertTrue(new_pack.signature_index._optimize_for_size)
1074
class TestInterDifferingSerializer(TestCaseWithTransport):
1076
def test_progress_bar(self):
1077
tree = self.make_branch_and_tree('tree')
1078
tree.commit('rev1', rev_id='rev-1')
1079
tree.commit('rev2', rev_id='rev-2')
1080
tree.commit('rev3', rev_id='rev-3')
1081
repo = self.make_repository('repo')
1082
inter_repo = repository.InterDifferingSerializer(
1083
tree.branch.repository, repo)
1084
pb = progress.InstrumentedProgress(to_file=StringIO())
1085
pb.never_throttle = True
1086
inter_repo.fetch('rev-1', pb)
1087
self.assertEqual('Transferring revisions', pb.last_msg)
1088
self.assertEqual(1, pb.last_cnt)
1089
self.assertEqual(1, pb.last_total)
1090
inter_repo.fetch('rev-3', pb)
1091
self.assertEqual(2, pb.last_cnt)
1092
self.assertEqual(2, pb.last_total)