/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4597.1.6 by John Arbash Meinel
Add a test that inventory texts are preserved during pack.
1
# Copyright (C) 2008, 2009 Canonical Ltd
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
2
#
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.
7
#
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.
12
#
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
16
17
"""Tests for pack repositories.
18
19
These tests are repeated for all pack-based repository formats.
20
"""
21
3582.3.4 by Martin Pool
Use cStringIO rather than StringIO
22
from cStringIO import StringIO
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
23
from stat import S_ISDIR
24
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
25
from bzrlib.btree_index import BTreeGraphIndex
26
from bzrlib.index import GraphIndex
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
27
from bzrlib import (
28
    bzrdir,
29
    errors,
30
    inventory,
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
31
    osutils,
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
32
    progress,
33
    repository,
34
    revision as _mod_revision,
35
    symbol_versioning,
36
    tests,
37
    ui,
38
    upgrade,
39
    workingtree,
40
    )
4360.4.6 by John Arbash Meinel
Change how 'missing.*parent_prevents_commit' determines what to skip.
41
from bzrlib.repofmt import (
42
    pack_repo,
43
    groupcompress_repo,
44
    )
4597.1.10 by John Arbash Meinel
Fix some tests that were failing because we checked against RepositoryFormatCHK1
45
from bzrlib.repofmt.groupcompress_repo import RepositoryFormat2a
3801.1.18 by Andrew Bennetts
Add a test that ensures that the autopack RPC is actually used for all pack formats.
46
from bzrlib.smart import (
47
    client,
48
    server,
49
    )
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
50
from bzrlib.tests import (
51
    TestCase,
52
    TestCaseWithTransport,
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
53
    TestNotApplicable,
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
54
    TestSkipped,
55
    )
56
from bzrlib.transport import (
57
    fakenfs,
3825.4.2 by Andrew Bennetts
Run the abort_write_group tests against a memory transport to avoid platform-specific limits on changing files that may be in use.
58
    memory,
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
59
    get_transport,
60
    )
3825.4.2 by Andrew Bennetts
Run the abort_write_group tests against a memory transport to avoid platform-specific limits on changing files that may be in use.
61
from bzrlib.tests.per_repository import TestCaseWithRepository
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
62
63
64
class TestPackRepository(TestCaseWithTransport):
65
    """Tests to be repeated across all pack-based formats.
66
67
    The following are populated from the test scenario:
68
69
    :ivar format_name: Registered name fo the format to test.
70
    :ivar format_string: On-disk format marker.
71
    :ivar format_supports_external_lookups: Boolean.
72
    """
73
74
    def get_format(self):
75
        return bzrdir.format_registry.make_bzrdir(self.format_name)
76
77
    def test_attribute__fetch_order(self):
3606.7.3 by John Arbash Meinel
We don't have to fetch in topological order, as long as we fix all of the delta logic pieces.
78
        """Packs do not need ordered data retrieval."""
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
79
        format = self.get_format()
80
        repo = self.make_repository('.', format=format)
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
81
        self.assertEqual('unordered', repo._format._fetch_order)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
82
83
    def test_attribute__fetch_uses_deltas(self):
84
        """Packs reuse deltas."""
85
        format = self.get_format()
86
        repo = self.make_repository('.', format=format)
4597.1.10 by John Arbash Meinel
Fix some tests that were failing because we checked against RepositoryFormatCHK1
87
        if isinstance(format.repository_format, RepositoryFormat2a):
4265.1.4 by John Arbash Meinel
Special case the CHK1 format to allow it to not fetch using deltas.
88
            # TODO: This is currently a workaround. CHK format repositories
89
            #       ignore the 'deltas' flag, but during conversions, we can't
90
            #       do unordered delta fetches. Remove this clause once we
91
            #       improve the inter-format fetching.
92
            self.assertEqual(False, repo._format._fetch_uses_deltas)
93
        else:
94
            self.assertEqual(True, repo._format._fetch_uses_deltas)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
95
96
    def test_disk_layout(self):
97
        format = self.get_format()
98
        repo = self.make_repository('.', format=format)
99
        # in case of side effects of locking.
100
        repo.lock_write()
101
        repo.unlock()
102
        t = repo.bzrdir.get_repository_transport(None)
103
        self.check_format(t)
104
        # XXX: no locks left when unlocked at the moment
105
        # self.assertEqualDiff('', t.get('lock').read())
106
        self.check_databases(t)
107
108
    def check_format(self, t):
109
        self.assertEqualDiff(
110
            self.format_string, # from scenario
111
            t.get('format').read())
112
113
    def assertHasNoKndx(self, t, knit_name):
114
        """Assert that knit_name has no index on t."""
115
        self.assertFalse(t.has(knit_name + '.kndx'))
116
117
    def assertHasNoKnit(self, t, knit_name):
118
        """Assert that knit_name exists on t."""
119
        # no default content
120
        self.assertFalse(t.has(knit_name + '.knit'))
121
122
    def check_databases(self, t):
123
        """check knit content for a repository."""
124
        # check conversion worked
125
        self.assertHasNoKndx(t, 'inventory')
126
        self.assertHasNoKnit(t, 'inventory')
127
        self.assertHasNoKndx(t, 'revisions')
128
        self.assertHasNoKnit(t, 'revisions')
129
        self.assertHasNoKndx(t, 'signatures')
130
        self.assertHasNoKnit(t, 'signatures')
131
        self.assertFalse(t.has('knits'))
132
        # revision-indexes file-container directory
133
        self.assertEqual([],
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
134
            list(self.index_class(t, 'pack-names', None).iter_all_entries()))
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
135
        self.assertTrue(S_ISDIR(t.stat('packs').st_mode))
136
        self.assertTrue(S_ISDIR(t.stat('upload').st_mode))
137
        self.assertTrue(S_ISDIR(t.stat('indices').st_mode))
138
        self.assertTrue(S_ISDIR(t.stat('obsolete_packs').st_mode))
139
140
    def test_shared_disk_layout(self):
141
        format = self.get_format()
142
        repo = self.make_repository('.', shared=True, format=format)
143
        # we want:
144
        t = repo.bzrdir.get_repository_transport(None)
145
        self.check_format(t)
146
        # XXX: no locks left when unlocked at the moment
147
        # self.assertEqualDiff('', t.get('lock').read())
148
        # We should have a 'shared-storage' marker file.
149
        self.assertEqualDiff('', t.get('shared-storage').read())
150
        self.check_databases(t)
151
152
    def test_shared_no_tree_disk_layout(self):
153
        format = self.get_format()
154
        repo = self.make_repository('.', shared=True, format=format)
155
        repo.set_make_working_trees(False)
156
        # we want:
157
        t = repo.bzrdir.get_repository_transport(None)
158
        self.check_format(t)
159
        # XXX: no locks left when unlocked at the moment
160
        # self.assertEqualDiff('', t.get('lock').read())
161
        # We should have a 'shared-storage' marker file.
162
        self.assertEqualDiff('', t.get('shared-storage').read())
163
        # We should have a marker for the no-working-trees flag.
164
        self.assertEqualDiff('', t.get('no-working-trees').read())
165
        # The marker should go when we toggle the setting.
166
        repo.set_make_working_trees(True)
167
        self.assertFalse(t.has('no-working-trees'))
168
        self.check_databases(t)
169
170
    def test_adding_revision_creates_pack_indices(self):
171
        format = self.get_format()
172
        tree = self.make_branch_and_tree('.', format=format)
173
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
174
        self.assertEqual([],
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
175
            list(self.index_class(trans, 'pack-names', None).iter_all_entries()))
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
176
        tree.commit('foobarbaz')
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
177
        index = self.index_class(trans, 'pack-names', None)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
178
        index_nodes = list(index.iter_all_entries())
179
        self.assertEqual(1, len(index_nodes))
180
        node = index_nodes[0]
181
        name = node[1][0]
182
        # the pack sizes should be listed in the index
183
        pack_value = node[2]
184
        sizes = [int(digits) for digits in pack_value.split(' ')]
185
        for size, suffix in zip(sizes, ['.rix', '.iix', '.tix', '.six']):
186
            stat = trans.stat('indices/%s%s' % (name, suffix))
187
            self.assertEqual(size, stat.st_size)
188
189
    def test_pulling_nothing_leads_to_no_new_names(self):
190
        format = self.get_format()
191
        tree1 = self.make_branch_and_tree('1', format=format)
192
        tree2 = self.make_branch_and_tree('2', format=format)
193
        tree1.branch.repository.fetch(tree2.branch.repository)
194
        trans = tree1.branch.repository.bzrdir.get_repository_transport(None)
195
        self.assertEqual([],
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
196
            list(self.index_class(trans, 'pack-names', None).iter_all_entries()))
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
197
198
    def test_commit_across_pack_shape_boundary_autopacks(self):
199
        format = self.get_format()
200
        tree = self.make_branch_and_tree('.', format=format)
201
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
202
        # This test could be a little cheaper by replacing the packs
203
        # attribute on the repository to allow a different pack distribution
204
        # and max packs policy - so we are checking the policy is honoured
205
        # in the test. But for now 11 commits is not a big deal in a single
206
        # test.
207
        for x in range(9):
208
            tree.commit('commit %s' % x)
209
        # there should be 9 packs:
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
210
        index = self.index_class(trans, 'pack-names', None)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
211
        self.assertEqual(9, len(list(index.iter_all_entries())))
212
        # insert some files in obsolete_packs which should be removed by pack.
213
        trans.put_bytes('obsolete_packs/foo', '123')
214
        trans.put_bytes('obsolete_packs/bar', '321')
215
        # committing one more should coalesce to 1 of 10.
216
        tree.commit('commit triggering pack')
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
217
        index = self.index_class(trans, 'pack-names', None)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
218
        self.assertEqual(1, len(list(index.iter_all_entries())))
219
        # packing should not damage data
220
        tree = tree.bzrdir.open_workingtree()
221
        check_result = tree.branch.repository.check(
222
            [tree.branch.last_revision()])
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
223
        nb_files = 5 # .pack, .rix, .iix, .tix, .six
224
        if tree.branch.repository._format.supports_chks:
225
            nb_files += 1 # .cix
226
        # We should have 10 x nb_files files in the obsolete_packs directory.
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
227
        obsolete_files = list(trans.list_dir('obsolete_packs'))
228
        self.assertFalse('foo' in obsolete_files)
229
        self.assertFalse('bar' in obsolete_files)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
230
        self.assertEqual(10 * nb_files, len(obsolete_files))
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
231
        # XXX: Todo check packs obsoleted correctly - old packs and indices
232
        # in the obsolete_packs directory.
233
        large_pack_name = list(index.iter_all_entries())[0][1][0]
234
        # finally, committing again should not touch the large pack.
235
        tree.commit('commit not triggering pack')
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
236
        index = self.index_class(trans, 'pack-names', None)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
237
        self.assertEqual(2, len(list(index.iter_all_entries())))
238
        pack_names = [node[1][0] for node in index.iter_all_entries()]
239
        self.assertTrue(large_pack_name in pack_names)
240
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
241
    def test_commit_write_group_returns_new_pack_names(self):
4634.30.1 by Robert Collins
Properly pack 2a repositories during conversion operations. (Robert Collins. #423818)
242
        # This test doesn't need real disk.
243
        self.vfs_transport_factory = tests.MemoryServer
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
244
        format = self.get_format()
4634.30.1 by Robert Collins
Properly pack 2a repositories during conversion operations. (Robert Collins. #423818)
245
        repo = self.make_repository('foo', format=format)
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
246
        repo.lock_write()
247
        try:
4634.30.1 by Robert Collins
Properly pack 2a repositories during conversion operations. (Robert Collins. #423818)
248
            # All current pack repository styles autopack at 10 revisions; and
249
            # autopack as well as regular commit write group needs to return
250
            # the new pack name. Looping is a little ugly, but we don't have a
251
            # clean way to test both the autopack logic and the normal code
252
            # path without doing this loop.
253
            for pos in range(10):
254
                revid = str(pos)
255
                repo.start_write_group()
256
                try:
257
                    inv = inventory.Inventory(revision_id=revid)
258
                    inv.root.revision = revid
259
                    repo.texts.add_lines((inv.root.file_id, revid), [], [])
260
                    rev = _mod_revision.Revision(timestamp=0, timezone=None,
261
                        committer="Foo Bar <foo@example.com>", message="Message",
262
                        revision_id=revid)
263
                    rev.parent_ids = ()
264
                    repo.add_revision(revid, rev, inv=inv)
265
                except:
266
                    repo.abort_write_group()
267
                    raise
268
                else:
269
                    old_names = repo._pack_collection._names.keys()
270
                    result = repo.commit_write_group()
271
                    cur_names = repo._pack_collection._names.keys()
272
                    new_names = list(set(cur_names) - set(old_names))
273
                    self.assertEqual(new_names, result)
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
274
        finally:
275
            repo.unlock()
276
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
277
    def test_fail_obsolete_deletion(self):
278
        # failing to delete obsolete packs is not fatal
279
        format = self.get_format()
280
        server = fakenfs.FakeNFSServer()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
281
        self.start_server(server)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
282
        transport = get_transport(server.get_url())
283
        bzrdir = self.get_format().initialize_on_transport(transport)
284
        repo = bzrdir.create_repository()
285
        repo_transport = bzrdir.get_repository_transport(None)
286
        self.assertTrue(repo_transport.has('obsolete_packs'))
287
        # these files are in use by another client and typically can't be deleted
288
        repo_transport.put_bytes('obsolete_packs/.nfsblahblah', 'contents')
289
        repo._pack_collection._clear_obsolete_packs()
290
        self.assertTrue(repo_transport.has('obsolete_packs/.nfsblahblah'))
291
292
    def test_pack_after_two_commits_packs_everything(self):
293
        format = self.get_format()
294
        tree = self.make_branch_and_tree('.', format=format)
295
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
296
        tree.commit('start')
297
        tree.commit('more work')
298
        tree.branch.repository.pack()
299
        # there should be 1 pack:
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
300
        index = self.index_class(trans, 'pack-names', None)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
301
        self.assertEqual(1, len(list(index.iter_all_entries())))
302
        self.assertEqual(2, len(tree.branch.repository.all_revision_ids()))
303
4597.1.6 by John Arbash Meinel
Add a test that inventory texts are preserved during pack.
304
    def test_pack_preserves_all_inventories(self):
305
        # This is related to bug:
306
        #   https://bugs.launchpad.net/bzr/+bug/412198
307
        # Stacked repositories need to keep the inventory for parents, even
308
        # after a pack operation. However, it is harder to test that, then just
309
        # test that all inventory texts are preserved.
310
        format = self.get_format()
311
        builder = self.make_branch_builder('source', format=format)
312
        builder.start_series()
313
        builder.build_snapshot('A-id', None, [
314
            ('add', ('', 'root-id', 'directory', None))])
315
        builder.build_snapshot('B-id', None, [
316
            ('add', ('file', 'file-id', 'file', 'B content\n'))])
317
        builder.build_snapshot('C-id', None, [
318
            ('modify', ('file-id', 'C content\n'))])
319
        builder.finish_series()
320
        b = builder.get_branch()
321
        b.lock_read()
322
        self.addCleanup(b.unlock)
323
        repo = self.make_repository('repo', shared=True, format=format)
324
        repo.lock_write()
325
        self.addCleanup(repo.unlock)
326
        repo.fetch(b.repository, revision_id='B-id')
327
        inv = b.repository.iter_inventories(['C-id']).next()
328
        repo.start_write_group()
329
        repo.add_inventory('C-id', inv, ['B-id'])
330
        repo.commit_write_group()
331
        self.assertEqual([('A-id',), ('B-id',), ('C-id',)],
332
                         sorted(repo.inventories.keys()))
333
        repo.pack()
334
        self.assertEqual([('A-id',), ('B-id',), ('C-id',)],
335
                         sorted(repo.inventories.keys()))
336
        # Content should be preserved as well
337
        self.assertEqual(inv, repo.iter_inventories(['C-id']).next())
338
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
339
    def test_pack_layout(self):
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
340
        # Test that the ordering of revisions in pack repositories is
341
        # tip->ancestor
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
342
        format = self.get_format()
343
        tree = self.make_branch_and_tree('.', format=format)
344
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
345
        tree.commit('start', rev_id='1')
346
        tree.commit('more work', rev_id='2')
347
        tree.branch.repository.pack()
348
        tree.lock_read()
349
        self.addCleanup(tree.unlock)
350
        pack = tree.branch.repository._pack_collection.get_pack_by_name(
351
            tree.branch.repository._pack_collection.names()[0])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
352
        # revision access tends to be tip->ancestor, so ordering that way on
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
353
        # disk is a good idea.
354
        for _1, key, val, refs in pack.revision_index.iter_all_entries():
4597.1.10 by John Arbash Meinel
Fix some tests that were failing because we checked against RepositoryFormatCHK1
355
            if type(format.repository_format) is RepositoryFormat2a:
4350.2.1 by John Arbash Meinel
Update a test to support CHK formats.
356
                # group_start, group_len, internal_start, internal_len
357
                pos = map(int, val.split())
358
            else:
359
                # eol_flag, start, len
360
                pos = int(val[1:].split()[0])
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
361
            if key == ('1',):
4350.2.1 by John Arbash Meinel
Update a test to support CHK formats.
362
                pos_1 = pos
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
363
            else:
4350.2.1 by John Arbash Meinel
Update a test to support CHK formats.
364
                pos_2 = pos
365
        self.assertTrue(pos_2 < pos_1, 'rev 1 came before rev 2 %s > %s'
366
                                       % (pos_1, pos_2))
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
367
368
    def test_pack_repositories_support_multiple_write_locks(self):
369
        format = self.get_format()
370
        self.make_repository('.', shared=True, format=format)
371
        r1 = repository.Repository.open('.')
372
        r2 = repository.Repository.open('.')
373
        r1.lock_write()
374
        self.addCleanup(r1.unlock)
375
        r2.lock_write()
376
        r2.unlock()
377
378
    def _add_text(self, repo, fileid):
379
        """Add a text to the repository within a write group."""
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
380
        repo.texts.add_lines((fileid, 'samplerev+'+fileid), [],
381
            ['smaplerev+'+fileid])
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
382
383
    def test_concurrent_writers_merge_new_packs(self):
384
        format = self.get_format()
385
        self.make_repository('.', shared=True, format=format)
386
        r1 = repository.Repository.open('.')
387
        r2 = repository.Repository.open('.')
388
        r1.lock_write()
389
        try:
390
            # access enough data to load the names list
391
            list(r1.all_revision_ids())
392
            r2.lock_write()
393
            try:
394
                # access enough data to load the names list
395
                list(r2.all_revision_ids())
396
                r1.start_write_group()
397
                try:
398
                    r2.start_write_group()
399
                    try:
400
                        self._add_text(r1, 'fileidr1')
401
                        self._add_text(r2, 'fileidr2')
402
                    except:
403
                        r2.abort_write_group()
404
                        raise
405
                except:
406
                    r1.abort_write_group()
407
                    raise
408
                # both r1 and r2 have open write groups with data in them
409
                # created while the other's write group was open.
410
                # Commit both which requires a merge to the pack-names.
411
                try:
412
                    r1.commit_write_group()
413
                except:
414
                    r1.abort_write_group()
415
                    r2.abort_write_group()
416
                    raise
417
                r2.commit_write_group()
418
                # tell r1 to reload from disk
419
                r1._pack_collection.reset()
420
                # Now both repositories should know about both names
421
                r1._pack_collection.ensure_loaded()
422
                r2._pack_collection.ensure_loaded()
423
                self.assertEqual(r1._pack_collection.names(), r2._pack_collection.names())
424
                self.assertEqual(2, len(r1._pack_collection.names()))
425
            finally:
426
                r2.unlock()
427
        finally:
428
            r1.unlock()
429
430
    def test_concurrent_writer_second_preserves_dropping_a_pack(self):
431
        format = self.get_format()
432
        self.make_repository('.', shared=True, format=format)
433
        r1 = repository.Repository.open('.')
434
        r2 = repository.Repository.open('.')
435
        # add a pack to drop
436
        r1.lock_write()
437
        try:
438
            r1.start_write_group()
439
            try:
440
                self._add_text(r1, 'fileidr1')
441
            except:
442
                r1.abort_write_group()
443
                raise
444
            else:
445
                r1.commit_write_group()
446
            r1._pack_collection.ensure_loaded()
447
            name_to_drop = r1._pack_collection.all_packs()[0].name
448
        finally:
449
            r1.unlock()
450
        r1.lock_write()
451
        try:
452
            # access enough data to load the names list
453
            list(r1.all_revision_ids())
454
            r2.lock_write()
455
            try:
456
                # access enough data to load the names list
457
                list(r2.all_revision_ids())
458
                r1._pack_collection.ensure_loaded()
459
                try:
460
                    r2.start_write_group()
461
                    try:
462
                        # in r1, drop the pack
463
                        r1._pack_collection._remove_pack_from_memory(
464
                            r1._pack_collection.get_pack_by_name(name_to_drop))
465
                        # in r2, add a pack
466
                        self._add_text(r2, 'fileidr2')
467
                    except:
468
                        r2.abort_write_group()
469
                        raise
470
                except:
471
                    r1._pack_collection.reset()
472
                    raise
473
                # r1 has a changed names list, and r2 an open write groups with
474
                # changes.
475
                # save r1, and then commit the r2 write group, which requires a
476
                # merge to the pack-names, which should not reinstate
477
                # name_to_drop
478
                try:
479
                    r1._pack_collection._save_pack_names()
480
                    r1._pack_collection.reset()
481
                except:
482
                    r2.abort_write_group()
483
                    raise
484
                try:
485
                    r2.commit_write_group()
486
                except:
487
                    r2.abort_write_group()
488
                    raise
489
                # Now both repositories should now about just one name.
490
                r1._pack_collection.ensure_loaded()
491
                r2._pack_collection.ensure_loaded()
492
                self.assertEqual(r1._pack_collection.names(), r2._pack_collection.names())
493
                self.assertEqual(1, len(r1._pack_collection.names()))
494
                self.assertFalse(name_to_drop in r1._pack_collection.names())
495
            finally:
496
                r2.unlock()
497
        finally:
498
            r1.unlock()
499
3789.1.1 by John Arbash Meinel
add the failing acceptance test for the first portion.
500
    def test_concurrent_pack_triggers_reload(self):
501
        # create 2 packs, which we will then collapse
502
        tree = self.make_branch_and_tree('tree')
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
503
        tree.lock_write()
3789.1.1 by John Arbash Meinel
add the failing acceptance test for the first portion.
504
        try:
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
505
            rev1 = tree.commit('one')
506
            rev2 = tree.commit('two')
507
            r2 = repository.Repository.open('tree')
3789.1.1 by John Arbash Meinel
add the failing acceptance test for the first portion.
508
            r2.lock_read()
509
            try:
510
                # Now r2 has read the pack-names file, but will need to reload
511
                # it after r1 has repacked
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
512
                tree.branch.repository.pack()
513
                self.assertEqual({rev2:(rev1,)}, r2.get_parent_map([rev2]))
3789.1.1 by John Arbash Meinel
add the failing acceptance test for the first portion.
514
            finally:
515
                r2.unlock()
516
        finally:
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
517
            tree.unlock()
3789.1.1 by John Arbash Meinel
add the failing acceptance test for the first portion.
518
3789.2.8 by John Arbash Meinel
Add a test that KnitPackRepository.get_record_stream retries when appropriate.
519
    def test_concurrent_pack_during_get_record_reloads(self):
520
        tree = self.make_branch_and_tree('tree')
521
        tree.lock_write()
522
        try:
523
            rev1 = tree.commit('one')
524
            rev2 = tree.commit('two')
3789.2.14 by John Arbash Meinel
Update AggregateIndex to pass the reload_func into _DirectPackAccess
525
            keys = [(rev1,), (rev2,)]
3789.2.8 by John Arbash Meinel
Add a test that KnitPackRepository.get_record_stream retries when appropriate.
526
            r2 = repository.Repository.open('tree')
527
            r2.lock_read()
528
            try:
529
                # At this point, we will start grabbing a record stream, and
530
                # trigger a repack mid-way
531
                packed = False
532
                result = {}
533
                record_stream = r2.revisions.get_record_stream(keys,
534
                                    'unordered', False)
535
                for record in record_stream:
536
                    result[record.key] = record
537
                    if not packed:
538
                        tree.branch.repository.pack()
539
                        packed = True
540
                # The first record will be found in the original location, but
541
                # after the pack, we have to reload to find the next record
3789.2.14 by John Arbash Meinel
Update AggregateIndex to pass the reload_func into _DirectPackAccess
542
                self.assertEqual(sorted(keys), sorted(result.keys()))
3789.2.8 by John Arbash Meinel
Add a test that KnitPackRepository.get_record_stream retries when appropriate.
543
            finally:
544
                r2.unlock()
545
        finally:
546
            tree.unlock()
547
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
548
    def test_lock_write_does_not_physically_lock(self):
549
        repo = self.make_repository('.', format=self.get_format())
550
        repo.lock_write()
551
        self.addCleanup(repo.unlock)
552
        self.assertFalse(repo.get_physical_lock_status())
553
554
    def prepare_for_break_lock(self):
555
        # Setup the global ui factory state so that a break-lock method call
556
        # will find usable input in the input stream.
557
        old_factory = ui.ui_factory
558
        def restoreFactory():
559
            ui.ui_factory = old_factory
560
        self.addCleanup(restoreFactory)
4449.3.27 by Martin Pool
More test updates to use CannedInputUIFactory
561
        ui.ui_factory = ui.CannedInputUIFactory([True])
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
562
563
    def test_break_lock_breaks_physical_lock(self):
564
        repo = self.make_repository('.', format=self.get_format())
565
        repo._pack_collection.lock_names()
3650.4.1 by Aaron Bentley
Fix test kipple in test_break_lock_breaks_physical_lock
566
        repo.control_files.leave_in_place()
567
        repo.unlock()
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
568
        repo2 = repository.Repository.open('.')
569
        self.assertTrue(repo.get_physical_lock_status())
570
        self.prepare_for_break_lock()
571
        repo2.break_lock()
572
        self.assertFalse(repo.get_physical_lock_status())
573
574
    def test_broken_physical_locks_error_on__unlock_names_lock(self):
575
        repo = self.make_repository('.', format=self.get_format())
576
        repo._pack_collection.lock_names()
577
        self.assertTrue(repo.get_physical_lock_status())
578
        repo2 = repository.Repository.open('.')
579
        self.prepare_for_break_lock()
580
        repo2.break_lock()
581
        self.assertRaises(errors.LockBroken, repo._pack_collection._unlock_names)
582
583
    def test_fetch_without_find_ghosts_ignores_ghosts(self):
584
        # we want two repositories at this point:
585
        # one with a revision that is a ghost in the other
586
        # repository.
587
        # 'ghost' is present in has_ghost, 'ghost' is absent in 'missing_ghost'.
588
        # 'references' is present in both repositories, and 'tip' is present
589
        # just in has_ghost.
590
        # has_ghost       missing_ghost
591
        #------------------------------
592
        # 'ghost'             -
593
        # 'references'    'references'
594
        # 'tip'               -
595
        # In this test we fetch 'tip' which should not fetch 'ghost'
596
        has_ghost = self.make_repository('has_ghost', format=self.get_format())
597
        missing_ghost = self.make_repository('missing_ghost',
598
            format=self.get_format())
599
600
        def add_commit(repo, revision_id, parent_ids):
601
            repo.lock_write()
602
            repo.start_write_group()
603
            inv = inventory.Inventory(revision_id=revision_id)
604
            inv.root.revision = revision_id
605
            root_id = inv.root.file_id
606
            sha1 = repo.add_inventory(revision_id, inv, [])
607
            repo.texts.add_lines((root_id, revision_id), [], [])
608
            rev = _mod_revision.Revision(timestamp=0,
609
                                         timezone=None,
610
                                         committer="Foo Bar <foo@example.com>",
611
                                         message="Message",
612
                                         inventory_sha1=sha1,
613
                                         revision_id=revision_id)
614
            rev.parent_ids = parent_ids
615
            repo.add_revision(revision_id, rev)
616
            repo.commit_write_group()
617
            repo.unlock()
618
        add_commit(has_ghost, 'ghost', [])
619
        add_commit(has_ghost, 'references', ['ghost'])
620
        add_commit(missing_ghost, 'references', ['ghost'])
621
        add_commit(has_ghost, 'tip', ['references'])
622
        missing_ghost.fetch(has_ghost, 'tip')
623
        # missing ghost now has tip and not ghost.
624
        rev = missing_ghost.get_revision('tip')
625
        inv = missing_ghost.get_inventory('tip')
626
        self.assertRaises(errors.NoSuchRevision,
627
            missing_ghost.get_revision, 'ghost')
628
        self.assertRaises(errors.NoSuchRevision,
629
            missing_ghost.get_inventory, 'ghost')
630
4011.5.6 by Andrew Bennetts
Make sure it's not possible to commit a pack write group when any versioned file has missing compression parents.
631
    def make_write_ready_repo(self):
4360.4.6 by John Arbash Meinel
Change how 'missing.*parent_prevents_commit' determines what to skip.
632
        format = self.get_format()
4597.1.10 by John Arbash Meinel
Fix some tests that were failing because we checked against RepositoryFormatCHK1
633
        if isinstance(format.repository_format, RepositoryFormat2a):
4360.4.6 by John Arbash Meinel
Change how 'missing.*parent_prevents_commit' determines what to skip.
634
            raise TestNotApplicable("No missing compression parents")
635
        repo = self.make_repository('.', format=format)
4011.5.6 by Andrew Bennetts
Make sure it's not possible to commit a pack write group when any versioned file has missing compression parents.
636
        repo.lock_write()
4360.4.6 by John Arbash Meinel
Change how 'missing.*parent_prevents_commit' determines what to skip.
637
        self.addCleanup(repo.unlock)
4011.5.6 by Andrew Bennetts
Make sure it's not possible to commit a pack write group when any versioned file has missing compression parents.
638
        repo.start_write_group()
4360.4.6 by John Arbash Meinel
Change how 'missing.*parent_prevents_commit' determines what to skip.
639
        self.addCleanup(repo.abort_write_group)
4011.5.6 by Andrew Bennetts
Make sure it's not possible to commit a pack write group when any versioned file has missing compression parents.
640
        return repo
641
642
    def test_missing_inventories_compression_parent_prevents_commit(self):
643
        repo = self.make_write_ready_repo()
644
        key = ('junk',)
645
        repo.inventories._index._missing_compression_parents.add(key)
646
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
647
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
648
649
    def test_missing_revisions_compression_parent_prevents_commit(self):
650
        repo = self.make_write_ready_repo()
651
        key = ('junk',)
652
        repo.revisions._index._missing_compression_parents.add(key)
653
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
654
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
655
656
    def test_missing_signatures_compression_parent_prevents_commit(self):
657
        repo = self.make_write_ready_repo()
658
        key = ('junk',)
659
        repo.signatures._index._missing_compression_parents.add(key)
660
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
661
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
662
663
    def test_missing_text_compression_parent_prevents_commit(self):
664
        repo = self.make_write_ready_repo()
665
        key = ('some', 'junk')
666
        repo.texts._index._missing_compression_parents.add(key)
667
        self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
668
        e = self.assertRaises(errors.BzrCheckError, repo.commit_write_group)
669
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
670
    def test_supports_external_lookups(self):
671
        repo = self.make_repository('.', format=self.get_format())
672
        self.assertEqual(self.format_supports_external_lookups,
673
            repo._format.supports_external_lookups)
674
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
675
    def test_abort_write_group_does_not_raise_when_suppressed(self):
676
        """Similar to per_repository.test_write_group's test of the same name.
677
678
        Also requires that the exception is logged.
679
        """
3825.4.2 by Andrew Bennetts
Run the abort_write_group tests against a memory transport to avoid platform-specific limits on changing files that may be in use.
680
        self.vfs_transport_factory = memory.MemoryServer
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
681
        repo = self.make_repository('repo', format=self.get_format())
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
682
        token = repo.lock_write()
683
        self.addCleanup(repo.unlock)
684
        repo.start_write_group()
685
        # Damage the repository on the filesystem
686
        self.get_transport('').rename('repo', 'foo')
687
        # abort_write_group will not raise an error
688
        self.assertEqual(None, repo.abort_write_group(suppress_errors=True))
689
        # But it does log an error
690
        log_file = self._get_log(keep_log_file=True)
691
        self.assertContainsRe(log_file, 'abort_write_group failed')
692
        self.assertContainsRe(log_file, r'INFO  bzr: ERROR \(ignored\):')
693
        if token is not None:
694
            repo.leave_lock_in_place()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
695
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
696
    def test_abort_write_group_does_raise_when_not_suppressed(self):
3825.4.2 by Andrew Bennetts
Run the abort_write_group tests against a memory transport to avoid platform-specific limits on changing files that may be in use.
697
        self.vfs_transport_factory = memory.MemoryServer
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
698
        repo = self.make_repository('repo', format=self.get_format())
3825.4.1 by Andrew Bennetts
Add suppress_errors to abort_write_group.
699
        token = repo.lock_write()
700
        self.addCleanup(repo.unlock)
701
        repo.start_write_group()
702
        # Damage the repository on the filesystem
703
        self.get_transport('').rename('repo', 'foo')
704
        # abort_write_group will not raise an error
705
        self.assertRaises(Exception, repo.abort_write_group)
706
        if token is not None:
707
            repo.leave_lock_in_place()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
708
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
709
    def test_suspend_write_group(self):
710
        self.vfs_transport_factory = memory.MemoryServer
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
711
        repo = self.make_repository('repo', format=self.get_format())
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
712
        token = repo.lock_write()
713
        self.addCleanup(repo.unlock)
714
        repo.start_write_group()
715
        repo.texts.add_lines(('file-id', 'revid'), (), ['lines'])
716
        wg_tokens = repo.suspend_write_group()
717
        expected_pack_name = wg_tokens[0] + '.pack'
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
718
        expected_names = [wg_tokens[0] + ext for ext in
719
                            ('.rix', '.iix', '.tix', '.six')]
720
        if repo.chk_bytes is not None:
721
            expected_names.append(wg_tokens[0] + '.cix')
722
        expected_names.append(expected_pack_name)
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
723
        upload_transport = repo._pack_collection._upload_transport
724
        limbo_files = upload_transport.list_dir('')
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
725
        self.assertEqual(sorted(expected_names), sorted(limbo_files))
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
726
        md5 = osutils.md5(upload_transport.get_bytes(expected_pack_name))
727
        self.assertEqual(wg_tokens[0], md5.hexdigest())
728
4343.3.8 by John Arbash Meinel
Some cleanup passes.
729
    def test_resume_chk_bytes(self):
730
        self.vfs_transport_factory = memory.MemoryServer
731
        repo = self.make_repository('repo', format=self.get_format())
732
        if repo.chk_bytes is None:
733
            raise TestNotApplicable('no chk_bytes for this repository')
734
        token = repo.lock_write()
735
        self.addCleanup(repo.unlock)
736
        repo.start_write_group()
737
        text = 'a bit of text\n'
738
        key = ('sha1:' + osutils.sha_string(text),)
739
        repo.chk_bytes.add_lines(key, (), [text])
740
        wg_tokens = repo.suspend_write_group()
741
        same_repo = repo.bzrdir.open_repository()
742
        same_repo.lock_write()
743
        self.addCleanup(same_repo.unlock)
744
        same_repo.resume_write_group(wg_tokens)
745
        self.assertEqual([key], list(same_repo.chk_bytes.keys()))
746
        self.assertEqual(
747
            text, same_repo.chk_bytes.get_record_stream([key],
748
                'unordered', True).next().get_bytes_as('fulltext'))
749
        same_repo.abort_write_group()
750
        self.assertEqual([], list(same_repo.chk_bytes.keys()))
751
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
752
    def test_resume_write_group_then_abort(self):
753
        # Create a repo, start a write group, insert some data, suspend.
754
        self.vfs_transport_factory = memory.MemoryServer
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
755
        repo = self.make_repository('repo', format=self.get_format())
4002.1.1 by Andrew Bennetts
Implement suspend_write_group/resume_write_group.
756
        token = repo.lock_write()
757
        self.addCleanup(repo.unlock)
758
        repo.start_write_group()
759
        text_key = ('file-id', 'revid')
760
        repo.texts.add_lines(text_key, (), ['lines'])
761
        wg_tokens = repo.suspend_write_group()
762
        # Get a fresh repository object for the repo on the filesystem.
763
        same_repo = repo.bzrdir.open_repository()
764
        # Resume
765
        same_repo.lock_write()
766
        self.addCleanup(same_repo.unlock)
767
        same_repo.resume_write_group(wg_tokens)
768
        same_repo.abort_write_group()
769
        self.assertEqual(
770
            [], same_repo._pack_collection._upload_transport.list_dir(''))
771
        self.assertEqual(
772
            [], same_repo._pack_collection._pack_transport.list_dir(''))
773
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
774
    def test_commit_resumed_write_group(self):
775
        self.vfs_transport_factory = memory.MemoryServer
776
        repo = self.make_repository('repo', format=self.get_format())
777
        token = repo.lock_write()
778
        self.addCleanup(repo.unlock)
779
        repo.start_write_group()
780
        text_key = ('file-id', 'revid')
781
        repo.texts.add_lines(text_key, (), ['lines'])
782
        wg_tokens = repo.suspend_write_group()
783
        # Get a fresh repository object for the repo on the filesystem.
784
        same_repo = repo.bzrdir.open_repository()
785
        # Resume
786
        same_repo.lock_write()
787
        self.addCleanup(same_repo.unlock)
788
        same_repo.resume_write_group(wg_tokens)
789
        same_repo.commit_write_group()
790
        expected_pack_name = wg_tokens[0] + '.pack'
791
        expected_names = [wg_tokens[0] + ext for ext in
792
                            ('.rix', '.iix', '.tix', '.six')]
793
        if repo.chk_bytes is not None:
794
            expected_names.append(wg_tokens[0] + '.cix')
795
        self.assertEqual(
796
            [], same_repo._pack_collection._upload_transport.list_dir(''))
797
        index_names = repo._pack_collection._index_transport.list_dir('')
798
        self.assertEqual(sorted(expected_names), sorted(index_names))
799
        pack_names = repo._pack_collection._pack_transport.list_dir('')
800
        self.assertEqual([expected_pack_name], pack_names)
801
4002.1.5 by Andrew Bennetts
Fix possible security issue with resuming write groups: make sure the token is well-formed so that it's not possible to steal a write group from another repo.
802
    def test_resume_malformed_token(self):
803
        self.vfs_transport_factory = memory.MemoryServer
804
        # Make a repository with a suspended write group
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
805
        repo = self.make_repository('repo', format=self.get_format())
4002.1.5 by Andrew Bennetts
Fix possible security issue with resuming write groups: make sure the token is well-formed so that it's not possible to steal a write group from another repo.
806
        token = repo.lock_write()
807
        self.addCleanup(repo.unlock)
808
        repo.start_write_group()
809
        text_key = ('file-id', 'revid')
810
        repo.texts.add_lines(text_key, (), ['lines'])
811
        wg_tokens = repo.suspend_write_group()
812
        # Make a new repository
4343.3.7 by John Arbash Meinel
Update the suspend/resume/commit/abort_write_group tests for CHK1.
813
        new_repo = self.make_repository('new_repo', format=self.get_format())
4002.1.5 by Andrew Bennetts
Fix possible security issue with resuming write groups: make sure the token is well-formed so that it's not possible to steal a write group from another repo.
814
        token = new_repo.lock_write()
815
        self.addCleanup(new_repo.unlock)
816
        hacked_wg_token = (
817
            '../../../../repo/.bzr/repository/upload/' + wg_tokens[0])
818
        self.assertRaises(
4002.1.7 by Andrew Bennetts
Rename UnresumableWriteGroups to UnresumableWriteGroup.
819
            errors.UnresumableWriteGroup,
4002.1.5 by Andrew Bennetts
Fix possible security issue with resuming write groups: make sure the token is well-formed so that it's not possible to steal a write group from another repo.
820
            new_repo.resume_write_group, [hacked_wg_token])
821
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
822
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
823
class TestPackRepositoryStacking(TestCaseWithTransport):
824
825
    """Tests for stacking pack repositories"""
826
827
    def setUp(self):
828
        if not self.format_supports_external_lookups:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
829
            raise TestNotApplicable("%r doesn't support stacking"
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
830
                % (self.format_name,))
831
        super(TestPackRepositoryStacking, self).setUp()
832
833
    def get_format(self):
834
        return bzrdir.format_registry.make_bzrdir(self.format_name)
835
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
836
    def test_stack_checks_rich_root_compatibility(self):
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
837
        # early versions of the packing code relied on pack internals to
838
        # stack, but the current version should be able to stack on any
839
        # format.
840
        #
841
        # TODO: Possibly this should be run per-repository-format and raise
842
        # TestNotApplicable on formats that don't support stacking. -- mbp
843
        # 20080729
844
        repo = self.make_repository('repo', format=self.get_format())
845
        if repo.supports_rich_root():
846
            # can only stack on repositories that have compatible internal
847
            # metadata
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
848
            if getattr(repo._format, 'supports_tree_reference', False):
4343.3.27 by John Arbash Meinel
Now that dev6 supports external references, the tests for
849
                matching_format_name = 'pack-0.92-subtree'
850
            else:
3735.2.9 by Robert Collins
Get a working chk_map using inventory implementation bootstrapped.
851
                if repo._format.supports_chks:
4597.1.6 by John Arbash Meinel
Add a test that inventory texts are preserved during pack.
852
                    matching_format_name = '2a'
3735.2.9 by Robert Collins
Get a working chk_map using inventory implementation bootstrapped.
853
                else:
4343.3.27 by John Arbash Meinel
Now that dev6 supports external references, the tests for
854
                    matching_format_name = 'rich-root-pack'
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
855
            mismatching_format_name = 'pack-0.92'
856
        else:
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
857
            # We don't have a non-rich-root CHK format.
3735.2.9 by Robert Collins
Get a working chk_map using inventory implementation bootstrapped.
858
            if repo._format.supports_chks:
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
859
                raise AssertionError("no non-rich-root CHK formats known")
3735.2.9 by Robert Collins
Get a working chk_map using inventory implementation bootstrapped.
860
            else:
861
                matching_format_name = 'pack-0.92'
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
862
            mismatching_format_name = 'pack-0.92-subtree'
863
        base = self.make_repository('base', format=matching_format_name)
864
        repo.add_fallback_repository(base)
865
        # you can't stack on something with incompatible data
866
        bad_repo = self.make_repository('mismatch',
867
            format=mismatching_format_name)
868
        e = self.assertRaises(errors.IncompatibleRepositories,
869
            repo.add_fallback_repository, bad_repo)
870
        self.assertContainsRe(str(e),
871
            r'(?m)KnitPackRepository.*/mismatch/.*\nis not compatible with\n'
3735.2.9 by Robert Collins
Get a working chk_map using inventory implementation bootstrapped.
872
            r'.*Repository.*/repo/.*\n'
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
873
            r'different rich-root support')
874
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
875
    def test_stack_checks_serializers_compatibility(self):
876
        repo = self.make_repository('repo', format=self.get_format())
877
        if getattr(repo._format, 'supports_tree_reference', False):
878
            # can only stack on repositories that have compatible internal
879
            # metadata
4343.3.27 by John Arbash Meinel
Now that dev6 supports external references, the tests for
880
            matching_format_name = 'pack-0.92-subtree'
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
881
            mismatching_format_name = 'rich-root-pack'
882
        else:
883
            if repo.supports_rich_root():
4343.3.27 by John Arbash Meinel
Now that dev6 supports external references, the tests for
884
                if repo._format.supports_chks:
4597.1.6 by John Arbash Meinel
Add a test that inventory texts are preserved during pack.
885
                    matching_format_name = '2a'
4343.3.27 by John Arbash Meinel
Now that dev6 supports external references, the tests for
886
                else:
887
                    matching_format_name = 'rich-root-pack'
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
888
                mismatching_format_name = 'pack-0.92-subtree'
889
            else:
890
                raise TestNotApplicable('No formats use non-v5 serializer'
891
                    ' without having rich-root also set')
892
        base = self.make_repository('base', format=matching_format_name)
893
        repo.add_fallback_repository(base)
894
        # you can't stack on something with incompatible data
895
        bad_repo = self.make_repository('mismatch',
896
            format=mismatching_format_name)
897
        e = self.assertRaises(errors.IncompatibleRepositories,
898
            repo.add_fallback_repository, bad_repo)
899
        self.assertContainsRe(str(e),
900
            r'(?m)KnitPackRepository.*/mismatch/.*\nis not compatible with\n'
3735.2.9 by Robert Collins
Get a working chk_map using inventory implementation bootstrapped.
901
            r'.*Repository.*/repo/.*\n'
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
902
            r'different serializers')
903
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
904
    def test_adding_pack_does_not_record_pack_names_from_other_repositories(self):
905
        base = self.make_branch_and_tree('base', format=self.get_format())
906
        base.commit('foo')
907
        referencing = self.make_branch_and_tree('repo', format=self.get_format())
908
        referencing.branch.repository.add_fallback_repository(base.branch.repository)
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
909
        local_tree = referencing.branch.create_checkout('local')
910
        local_tree.commit('bar')
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
911
        new_instance = referencing.bzrdir.open_repository()
912
        new_instance.lock_read()
913
        self.addCleanup(new_instance.unlock)
914
        new_instance._pack_collection.ensure_loaded()
915
        self.assertEqual(1, len(new_instance._pack_collection.all_packs()))
916
917
    def test_autopack_only_considers_main_repo_packs(self):
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
918
        format = self.get_format()
919
        base = self.make_branch_and_tree('base', format=format)
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
920
        base.commit('foo')
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
921
        tree = self.make_branch_and_tree('repo', format=format)
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
922
        tree.branch.repository.add_fallback_repository(base.branch.repository)
923
        trans = tree.branch.repository.bzrdir.get_repository_transport(None)
924
        # This test could be a little cheaper by replacing the packs
925
        # attribute on the repository to allow a different pack distribution
926
        # and max packs policy - so we are checking the policy is honoured
927
        # in the test. But for now 11 commits is not a big deal in a single
928
        # test.
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
929
        local_tree = tree.branch.create_checkout('local')
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
930
        for x in range(9):
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
931
            local_tree.commit('commit %s' % x)
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
932
        # there should be 9 packs:
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
933
        index = self.index_class(trans, 'pack-names', None)
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
934
        self.assertEqual(9, len(list(index.iter_all_entries())))
935
        # committing one more should coalesce to 1 of 10.
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
936
        local_tree.commit('commit triggering pack')
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
937
        index = self.index_class(trans, 'pack-names', None)
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
938
        self.assertEqual(1, len(list(index.iter_all_entries())))
939
        # packing should not damage data
940
        tree = tree.bzrdir.open_workingtree()
941
        check_result = tree.branch.repository.check(
942
            [tree.branch.last_revision()])
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
943
        nb_files = 5 # .pack, .rix, .iix, .tix, .six
944
        if tree.branch.repository._format.supports_chks:
945
            nb_files += 1 # .cix
946
        # We should have 10 x nb_files files in the obsolete_packs directory.
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
947
        obsolete_files = list(trans.list_dir('obsolete_packs'))
948
        self.assertFalse('foo' in obsolete_files)
949
        self.assertFalse('bar' in obsolete_files)
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
950
        self.assertEqual(10 * nb_files, len(obsolete_files))
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
951
        # XXX: Todo check packs obsoleted correctly - old packs and indices
952
        # in the obsolete_packs directory.
953
        large_pack_name = list(index.iter_all_entries())[0][1][0]
954
        # finally, committing again should not touch the large pack.
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
955
        local_tree.commit('commit not triggering pack')
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
956
        index = self.index_class(trans, 'pack-names', None)
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
957
        self.assertEqual(2, len(list(index.iter_all_entries())))
958
        pack_names = [node[1][0] for node in index.iter_all_entries()]
959
        self.assertTrue(large_pack_name in pack_names)
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
960
961
4343.3.33 by John Arbash Meinel
Clear KeyDependencies on abort/suspend/commit_write_group.
962
class TestKeyDependencies(TestCaseWithTransport):
963
964
    def get_format(self):
965
        return bzrdir.format_registry.make_bzrdir(self.format_name)
966
967
    def create_source_and_target(self):
968
        builder = self.make_branch_builder('source', format=self.get_format())
969
        builder.start_series()
970
        builder.build_snapshot('A-id', None, [
971
            ('add', ('', 'root-id', 'directory', None))])
972
        builder.build_snapshot('B-id', ['A-id', 'ghost-id'], [])
973
        builder.finish_series()
4634.29.16 by Andrew Bennetts
Fix buggy TestKeyDependencies test, tweak error string and comment.
974
        repo = self.make_repository('target', format=self.get_format())
4343.3.33 by John Arbash Meinel
Clear KeyDependencies on abort/suspend/commit_write_group.
975
        b = builder.get_branch()
976
        b.lock_read()
977
        self.addCleanup(b.unlock)
978
        repo.lock_write()
979
        self.addCleanup(repo.unlock)
980
        return b.repository, repo
981
982
    def test_key_dependencies_cleared_on_abort(self):
983
        source_repo, target_repo = self.create_source_and_target()
984
        target_repo.start_write_group()
985
        try:
986
            stream = source_repo.revisions.get_record_stream([('B-id',)],
987
                                                             'unordered', True)
988
            target_repo.revisions.insert_record_stream(stream)
989
            key_refs = target_repo.revisions._index._key_dependencies
990
            self.assertEqual([('B-id',)], sorted(key_refs.get_referrers()))
991
        finally:
992
            target_repo.abort_write_group()
993
        self.assertEqual([], sorted(key_refs.get_referrers()))
994
995
    def test_key_dependencies_cleared_on_suspend(self):
996
        source_repo, target_repo = self.create_source_and_target()
997
        target_repo.start_write_group()
998
        try:
999
            stream = source_repo.revisions.get_record_stream([('B-id',)],
1000
                                                             'unordered', True)
1001
            target_repo.revisions.insert_record_stream(stream)
1002
            key_refs = target_repo.revisions._index._key_dependencies
1003
            self.assertEqual([('B-id',)], sorted(key_refs.get_referrers()))
1004
        finally:
1005
            target_repo.suspend_write_group()
1006
        self.assertEqual([], sorted(key_refs.get_referrers()))
1007
1008
    def test_key_dependencies_cleared_on_commit(self):
1009
        source_repo, target_repo = self.create_source_and_target()
1010
        target_repo.start_write_group()
1011
        try:
4634.29.16 by Andrew Bennetts
Fix buggy TestKeyDependencies test, tweak error string and comment.
1012
            # Copy all texts, inventories, and chks so that nothing is missing
1013
            # for revision B-id.
1014
            for vf_name in ['texts', 'chk_bytes', 'inventories']:
1015
                source_vf = getattr(source_repo, vf_name, None)
1016
                if source_vf is None:
1017
                    continue
1018
                target_vf = getattr(target_repo, vf_name)
1019
                stream = source_vf.get_record_stream(
1020
                    source_vf.keys(), 'unordered', True)
1021
                target_vf.insert_record_stream(stream)
1022
            # Copy just revision B-id
1023
            stream = source_repo.revisions.get_record_stream(
1024
                [('B-id',)], 'unordered', True)
4343.3.33 by John Arbash Meinel
Clear KeyDependencies on abort/suspend/commit_write_group.
1025
            target_repo.revisions.insert_record_stream(stream)
1026
            key_refs = target_repo.revisions._index._key_dependencies
1027
            self.assertEqual([('B-id',)], sorted(key_refs.get_referrers()))
1028
        finally:
1029
            target_repo.commit_write_group()
1030
        self.assertEqual([], sorted(key_refs.get_referrers()))
1031
1032
3801.1.18 by Andrew Bennetts
Add a test that ensures that the autopack RPC is actually used for all pack formats.
1033
class TestSmartServerAutopack(TestCaseWithTransport):
1034
1035
    def setUp(self):
1036
        super(TestSmartServerAutopack, self).setUp()
1037
        # Create a smart server that publishes whatever the backing VFS server
1038
        # does.
1039
        self.smart_server = server.SmartTCPServer_for_testing()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
1040
        self.start_server(self.smart_server, self.get_server())
3801.1.18 by Andrew Bennetts
Add a test that ensures that the autopack RPC is actually used for all pack formats.
1041
        # Log all HPSS calls into self.hpss_calls.
1042
        client._SmartClient.hooks.install_named_hook(
1043
            'call', self.capture_hpss_call, None)
1044
        self.hpss_calls = []
1045
1046
    def capture_hpss_call(self, params):
1047
        self.hpss_calls.append(params.method)
1048
1049
    def get_format(self):
1050
        return bzrdir.format_registry.make_bzrdir(self.format_name)
1051
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1052
    def test_autopack_or_streaming_rpc_is_used_when_using_hpss(self):
3801.1.18 by Andrew Bennetts
Add a test that ensures that the autopack RPC is actually used for all pack formats.
1053
        # Make local and remote repos
3735.2.98 by John Arbash Meinel
Merge bzr.dev 4032. Resolve the new streaming fetch.
1054
        format = self.get_format()
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1055
        tree = self.make_branch_and_tree('local', format=format)
1056
        self.make_branch_and_tree('remote', format=format)
3801.1.18 by Andrew Bennetts
Add a test that ensures that the autopack RPC is actually used for all pack formats.
1057
        remote_branch_url = self.smart_server.get_url() + 'remote'
1058
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
1059
        # Make 9 local revisions, and push them one at a time to the remote
1060
        # repo to produce 9 pack files.
1061
        for x in range(9):
1062
            tree.commit('commit %s' % x)
1063
            tree.branch.push(remote_branch)
1064
        # Make one more push to trigger an autopack
1065
        self.hpss_calls = []
1066
        tree.commit('commit triggering pack')
1067
        tree.branch.push(remote_branch)
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1068
        autopack_calls = len([call for call in self.hpss_calls if call ==
1069
            'PackRepository.autopack'])
4476.3.66 by Andrew Bennetts
Fix trivial test failure by making the test recognise the new insert_stream_1.18 verb.
1070
        streaming_calls = len([call for call in self.hpss_calls if call in
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
1071
            ('Repository.insert_stream', 'Repository.insert_stream_1.19')])
4029.2.1 by Robert Collins
Support streaming push to stacked branches.
1072
        if autopack_calls:
1073
            # Non streaming server
1074
            self.assertEqual(1, autopack_calls)
1075
            self.assertEqual(0, streaming_calls)
1076
        else:
1077
            # Streaming was used, which autopacks on the remote end.
1078
            self.assertEqual(0, autopack_calls)
1079
            # NB: The 2 calls are because of the sanity check that the server
1080
            # supports the verb (see remote.py:RemoteSink.insert_stream for
1081
            # details).
1082
            self.assertEqual(2, streaming_calls)
3801.1.18 by Andrew Bennetts
Add a test that ensures that the autopack RPC is actually used for all pack formats.
1083
1084
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
1085
def load_tests(basic_tests, module, loader):
3582.3.3 by Martin Pool
Reenable tests for stacking pack repositories
1086
    # these give the bzrdir canned format name, and the repository on-disk
1087
    # format string
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
1088
    scenarios_params = [
1089
         dict(format_name='pack-0.92',
1090
              format_string="Bazaar pack repository format 1 (needs bzr 0.92)\n",
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1091
              format_supports_external_lookups=False,
1092
              index_class=GraphIndex),
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
1093
         dict(format_name='pack-0.92-subtree',
1094
              format_string="Bazaar pack repository format 1 "
1095
              "with subtree support (needs bzr 0.92)\n",
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1096
              format_supports_external_lookups=False,
1097
              index_class=GraphIndex),
3582.3.2 by Martin Pool
Add 1.6 formats to pack repository tests
1098
         dict(format_name='1.6',
1099
              format_string="Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n",
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1100
              format_supports_external_lookups=True,
1101
              index_class=GraphIndex),
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
1102
         dict(format_name='1.6.1-rich-root',
3582.3.2 by Martin Pool
Add 1.6 formats to pack repository tests
1103
              format_string="Bazaar RepositoryFormatKnitPack5RichRoot "
3606.10.5 by John Arbash Meinel
Switch out --1.6-rich-root for --1.6.1-rich-root.
1104
                  "(bzr 1.6.1)\n",
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1105
              format_supports_external_lookups=True,
1106
              index_class=GraphIndex),
3805.3.1 by John Arbash Meinel
Add repository 1.9 format, and update the documentation.
1107
         dict(format_name='1.9',
1108
              format_string="Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n",
1109
              format_supports_external_lookups=True,
1110
              index_class=BTreeGraphIndex),
1111
         dict(format_name='1.9-rich-root',
1112
              format_string="Bazaar RepositoryFormatKnitPack6RichRoot "
1113
                  "(bzr 1.9)\n",
1114
              format_supports_external_lookups=True,
1115
              index_class=BTreeGraphIndex),
4597.1.6 by John Arbash Meinel
Add a test that inventory texts are preserved during pack.
1116
         dict(format_name='2a',
1117
              format_string="Bazaar repository format 2a "
1118
                "(needs bzr 1.16 or later)\n",
4343.3.8 by John Arbash Meinel
Some cleanup passes.
1119
              format_supports_external_lookups=True,
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
1120
              index_class=BTreeGraphIndex),
3582.3.1 by Martin Pool
Split pack repository tests into their own file and use scenarios
1121
         ]
1122
    # name of the scenario is the format name
4084.5.1 by Robert Collins
Bulk update all test adaptation into a single approach, using multiply_tests rather than test adapters.
1123
    scenarios = [(s['format_name'], s) for s in scenarios_params]
1124
    return tests.multiply_tests(basic_tests, scenarios, loader.suiteClass())