/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.15 by John Arbash Meinel
Merge bzr.dev 5597 to resolve NEWS, aka bzr-2.3.txt
1
# Copyright (C) 2006-2011 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
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
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
16
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
17
"""Tests for repository implementations - tests a repository format."""
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
18
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
19
from cStringIO import StringIO
1666.1.6 by Robert Collins
Make knit the default format.
20
import re
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
21
1752.2.87 by Andrew Bennetts
Make tests pass.
22
from bzrlib import (
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
23
    branch as _mod_branch,
1752.2.87 by Andrew Bennetts
Make tests pass.
24
    bzrdir,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
25
    delta as _mod_delta,
1752.2.87 by Andrew Bennetts
Make tests pass.
26
    errors,
3735.2.100 by Vincent Ladeuil
Fix 3 failing tests due to an amazing typo.
27
    gpg,
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
28
    info,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
29
    inventory,
1752.2.87 by Andrew Bennetts
Make tests pass.
30
    remote,
31
    repository,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
32
    revision as _mod_revision,
33
    tests,
34
    transport,
35
    upgrade,
36
    versionedfile,
37
    workingtree,
1752.2.87 by Andrew Bennetts
Make tests pass.
38
    )
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
39
from bzrlib.repofmt import (
40
    pack_repo,
41
    weaverepo,
42
    )
5017.3.42 by Vincent Ladeuil
-s bt.per_repository.test_repo passing
43
from bzrlib.tests import (
44
    per_repository,
45
    test_server,
46
    )
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
47
from bzrlib.tests.matchers import *
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
48
49
50
class TestRepositoryMakeBranchAndTree(per_repository.TestCaseWithRepository):
2018.5.66 by Wouter van Heyst
Fix repository test parameterization for RemoteRepository.
51
52
    def test_repository_format(self):
2018.5.119 by Robert Collins
Unbreak TestRepositoryMakeBranchAndTree.
53
        # make sure the repository on tree.branch is of the desired format,
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
54
        # because developers use this api to setup the tree, branch and
2018.5.119 by Robert Collins
Unbreak TestRepositoryMakeBranchAndTree.
55
        # repository for their tests: having it now give the right repository
56
        # type would invalidate the tests.
2018.5.66 by Wouter van Heyst
Fix repository test parameterization for RemoteRepository.
57
        tree = self.make_branch_and_tree('repo')
58
        self.assertIsInstance(tree.branch.repository._format,
59
            self.repository_format.__class__)
2381.1.1 by Robert Collins
Split out hpss test fixes which dont depend on new or altered API's.
60
61
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
62
class TestRepository(per_repository.TestCaseWithRepository):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
63
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
64
    def assertFormatAttribute(self, attribute, allowed_values):
65
        """Assert that the format has an attribute 'attribute'."""
66
        repo = self.make_repository('repo')
67
        self.assertSubset([getattr(repo._format, attribute)], allowed_values)
68
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
69
    def test_attribute__fetch_order(self):
4775.1.1 by Martin Pool
Remove several 'the the' typos
70
        """Test the _fetch_order attribute."""
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
71
        self.assertFormatAttribute('_fetch_order', ('topological', 'unordered'))
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
72
73
    def test_attribute__fetch_uses_deltas(self):
4775.1.1 by Martin Pool
Remove several 'the the' typos
74
        """Test the _fetch_uses_deltas attribute."""
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
75
        self.assertFormatAttribute('_fetch_uses_deltas', (True, False))
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
76
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
77
    def test_attribute_fast_deltas(self):
78
        """Test the format.fast_deltas attribute."""
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
79
        self.assertFormatAttribute('fast_deltas', (True, False))
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
80
3565.3.4 by Robert Collins
Defer decision to reconcile to the repository being fetched into.
81
    def test_attribute__fetch_reconcile(self):
4775.1.1 by Martin Pool
Remove several 'the the' typos
82
        """Test the _fetch_reconcile attribute."""
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
83
        self.assertFormatAttribute('_fetch_reconcile', (True, False))
84
4988.9.1 by Jelmer Vernooij
Add experimental flag to RepositoryFormat.
85
    def test_attribute_format_experimental(self):
86
        self.assertFormatAttribute('experimental', (True, False))
87
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
88
    def test_attribute_format_pack_compresses(self):
89
        self.assertFormatAttribute('pack_compresses', (True, False))
3565.3.4 by Robert Collins
Defer decision to reconcile to the repository being fetched into.
90
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
91
    def test_attribute_inventories_store(self):
92
        """Test the existence of the inventories attribute."""
93
        tree = self.make_branch_and_tree('tree')
94
        repo = tree.branch.repository
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
95
        self.assertIsInstance(repo.inventories, versionedfile.VersionedFiles)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
96
97
    def test_attribute_inventories_basics(self):
98
        """Test basic aspects of the inventories attribute."""
99
        tree = self.make_branch_and_tree('tree')
100
        repo = tree.branch.repository
101
        rev_id = (tree.commit('a'),)
102
        tree.lock_read()
103
        self.addCleanup(tree.unlock)
104
        self.assertEqual(set([rev_id]), set(repo.inventories.keys()))
105
106
    def test_attribute_revision_store(self):
107
        """Test the existence of the revisions attribute."""
108
        tree = self.make_branch_and_tree('tree')
109
        repo = tree.branch.repository
110
        self.assertIsInstance(repo.revisions,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
111
            versionedfile.VersionedFiles)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
112
113
    def test_attribute_revision_store_basics(self):
114
        """Test the basic behaviour of the revisions attribute."""
115
        tree = self.make_branch_and_tree('tree')
116
        repo = tree.branch.repository
117
        repo.lock_write()
118
        try:
119
            self.assertEqual(set(), set(repo.revisions.keys()))
120
            revid = (tree.commit("foo"),)
121
            self.assertEqual(set([revid]), set(repo.revisions.keys()))
122
            self.assertEqual({revid:()},
123
                repo.revisions.get_parent_map([revid]))
124
        finally:
125
            repo.unlock()
126
        tree2 = self.make_branch_and_tree('tree2')
127
        tree2.pull(tree.branch)
128
        left_id = (tree2.commit('left'),)
129
        right_id = (tree.commit('right'),)
130
        tree.merge_from_branch(tree2.branch)
131
        merge_id = (tree.commit('merged'),)
132
        repo.lock_read()
133
        self.addCleanup(repo.unlock)
134
        self.assertEqual(set([revid, left_id, right_id, merge_id]),
135
            set(repo.revisions.keys()))
136
        self.assertEqual({revid:(), left_id:(revid,), right_id:(revid,),
137
             merge_id:(right_id, left_id)},
138
            repo.revisions.get_parent_map(repo.revisions.keys()))
139
140
    def test_attribute_signature_store(self):
141
        """Test the existence of the signatures attribute."""
142
        tree = self.make_branch_and_tree('tree')
143
        repo = tree.branch.repository
144
        self.assertIsInstance(repo.signatures,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
145
            versionedfile.VersionedFiles)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
146
147
    def test_attribute_text_store_basics(self):
148
        """Test the basic behaviour of the text store."""
149
        tree = self.make_branch_and_tree('tree')
150
        repo = tree.branch.repository
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
151
        file_id = "Foo:Bar"
152
        file_key = (file_id,)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
153
        tree.lock_write()
154
        try:
155
            self.assertEqual(set(), set(repo.texts.keys()))
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
156
            tree.add(['foo'], [file_id], ['file'])
157
            tree.put_file_bytes_non_atomic(file_id, 'content\n')
158
            try:
159
                rev_key = (tree.commit("foo"),)
160
            except errors.IllegalPath:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
161
                raise tests.TestNotApplicable(
162
                    'file_id %r cannot be stored on this'
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
163
                    ' platform for this repo format' % (file_id,))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
164
            if repo._format.rich_root_data:
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
165
                root_commit = (tree.get_root_id(),) + rev_key
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
166
                keys = set([root_commit])
167
                parents = {root_commit:()}
168
            else:
169
                keys = set()
170
                parents = {}
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
171
            keys.add(file_key + rev_key)
172
            parents[file_key + rev_key] = ()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
173
            self.assertEqual(keys, set(repo.texts.keys()))
174
            self.assertEqual(parents,
175
                repo.texts.get_parent_map(repo.texts.keys()))
176
        finally:
177
            tree.unlock()
178
        tree2 = self.make_branch_and_tree('tree2')
179
        tree2.pull(tree.branch)
180
        tree2.put_file_bytes_non_atomic('Foo:Bar', 'right\n')
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
181
        right_key = (tree2.commit('right'),)
182
        keys.add(file_key + right_key)
183
        parents[file_key + right_key] = (file_key + rev_key,)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
184
        tree.put_file_bytes_non_atomic('Foo:Bar', 'left\n')
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
185
        left_key = (tree.commit('left'),)
186
        keys.add(file_key + left_key)
187
        parents[file_key + left_key] = (file_key + rev_key,)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
188
        tree.merge_from_branch(tree2.branch)
189
        tree.put_file_bytes_non_atomic('Foo:Bar', 'merged\n')
190
        try:
191
            tree.auto_resolve()
192
        except errors.UnsupportedOperation:
193
            pass
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
194
        merge_key = (tree.commit('merged'),)
195
        keys.add(file_key + merge_key)
196
        parents[file_key + merge_key] = (file_key + left_key,
197
                                         file_key + right_key)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
198
        repo.lock_read()
199
        self.addCleanup(repo.unlock)
200
        self.assertEqual(keys, set(repo.texts.keys()))
201
        self.assertEqual(parents, repo.texts.get_parent_map(repo.texts.keys()))
202
203
    def test_attribute_text_store(self):
204
        """Test the existence of the texts attribute."""
205
        tree = self.make_branch_and_tree('tree')
206
        repo = tree.branch.repository
207
        self.assertIsInstance(repo.texts,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
208
            versionedfile.VersionedFiles)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
209
210
    def test_exposed_versioned_files_are_marked_dirty(self):
211
        repo = self.make_repository('.')
212
        repo.lock_write()
213
        signatures = repo.signatures
214
        revisions = repo.revisions
215
        inventories = repo.inventories
216
        repo.unlock()
217
        self.assertRaises(errors.ObjectNotLocked,
218
            signatures.keys)
219
        self.assertRaises(errors.ObjectNotLocked,
220
            revisions.keys)
221
        self.assertRaises(errors.ObjectNotLocked,
222
            inventories.keys)
223
        self.assertRaises(errors.ObjectNotLocked,
224
            signatures.add_lines, ('foo',), [], [])
225
        self.assertRaises(errors.ObjectNotLocked,
226
            revisions.add_lines, ('foo',), [], [])
227
        self.assertRaises(errors.ObjectNotLocked,
228
            inventories.add_lines, ('foo',), [], [])
229
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
230
    def test_clone_to_default_format(self):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
231
        #TODO: Test that cloning a repository preserves all the information
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
232
        # such as signatures[not tested yet] etc etc.
233
        # when changing to the current default format.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
234
        tree_a = self.make_branch_and_tree('a')
2381.1.3 by Robert Collins
Review feedback.
235
        self.build_tree(['a/foo'])
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
236
        tree_a.add('foo', 'file1')
237
        tree_a.commit('rev1', rev_id='rev1')
238
        bzrdirb = self.make_bzrdir('b')
239
        repo_b = tree_a.branch.repository.clone(bzrdirb)
240
        tree_b = repo_b.revision_tree('rev1')
2592.3.214 by Robert Collins
Merge bzr.dev.
241
        tree_b.lock_read()
242
        self.addCleanup(tree_b.unlock)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
243
        tree_b.get_file_text('file1')
244
        rev1 = repo_b.get_revision('rev1')
245
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
246
    def test_iter_inventories_is_ordered(self):
247
        # just a smoke test
248
        tree = self.make_branch_and_tree('a')
249
        first_revision = tree.commit('')
250
        second_revision = tree.commit('')
251
        tree.lock_read()
252
        self.addCleanup(tree.unlock)
253
        revs = (first_revision, second_revision)
254
        invs = tree.branch.repository.iter_inventories(revs)
255
        for rev_id, inv in zip(revs, invs):
256
            self.assertEqual(rev_id, inv.revision_id)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
257
            self.assertIsInstance(inv, inventory.CommonInventory)
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
258
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
259
    def test_supports_rich_root(self):
260
        tree = self.make_branch_and_tree('a')
261
        tree.commit('')
262
        second_revision = tree.commit('')
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
263
        rev_tree = tree.branch.repository.revision_tree(second_revision)
264
        rev_tree.lock_read()
265
        self.addCleanup(rev_tree.unlock)
266
        inv = rev_tree.inventory
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
267
        rich_root = (inv.root.revision != second_revision)
2018.5.113 by Robert Collins
Test only fixes from the ported-to-bzr.dev test-correctness branch.
268
        self.assertEqual(rich_root,
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
269
                         tree.branch.repository.supports_rich_root())
270
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
271
    def test_clone_specific_format(self):
272
        """todo"""
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
273
274
    def test_format_initialize_find_open(self):
275
        # loopback test to check the current format initializes to itself.
276
        if not self.repository_format.is_supported():
277
            # unsupported formats are not loopback testable
278
            # because the default open will not open them and
279
            # they may not be initializable.
280
            return
281
        # supported formats must be able to init and open
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
282
        t = transport.get_transport(self.get_url())
283
        readonly_t = transport.get_transport(self.get_readonly_url())
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
284
        made_control = self.bzrdir_format.initialize(t.base)
285
        made_repo = self.repository_format.initialize(made_control)
286
        self.assertEqual(made_control, made_repo.bzrdir)
287
288
        # find it via bzrdir opening:
289
        opened_control = bzrdir.BzrDir.open(readonly_t.base)
290
        direct_opened_repo = opened_control.open_repository()
291
        self.assertEqual(direct_opened_repo.__class__, made_repo.__class__)
292
        self.assertEqual(opened_control, direct_opened_repo.bzrdir)
293
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
294
        self.assertIsInstance(direct_opened_repo._format,
295
                              self.repository_format.__class__)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
296
        # find it via Repository.open
297
        opened_repo = repository.Repository.open(readonly_t.base)
298
        self.failUnless(isinstance(opened_repo, made_repo.__class__))
299
        self.assertEqual(made_repo._format.__class__,
300
                         opened_repo._format.__class__)
301
        # if it has a unique id string, can we probe for it ?
302
        try:
303
            self.repository_format.get_format_string()
304
        except NotImplementedError:
305
            return
306
        self.assertEqual(self.repository_format,
307
                         repository.RepositoryFormat.find_format(opened_control))
308
3845.1.1 by John Arbash Meinel
Ensure that RepositoryFormat._matchingbzrdir.repository_format matches.
309
    def test_format_matchingbzrdir(self):
310
        self.assertEqual(self.repository_format,
311
            self.repository_format._matchingbzrdir.repository_format)
312
        self.assertEqual(self.repository_format,
313
            self.bzrdir_format.repository_format)
314
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
315
    def test_format_network_name(self):
316
        repo = self.make_repository('r')
317
        format = repo._format
318
        network_name = format.network_name()
319
        self.assertIsInstance(network_name, str)
320
        # We want to test that the network_name matches the actual format on
321
        # disk.  For local repositories, that means that using network_name as
322
        # a key in the registry gives back the same format.  For remote
323
        # repositories, that means that the network_name of the
324
        # RemoteRepositoryFormat we have locally matches the actual format
325
        # present on the remote side.
326
        if isinstance(format, remote.RemoteRepositoryFormat):
327
            repo._ensure_real()
328
            real_repo = repo._real_repository
329
            self.assertEqual(real_repo._format.network_name(), network_name)
330
        else:
331
            registry = repository.network_format_registry
332
            looked_up_format = registry.get(network_name)
333
            self.assertEqual(format.__class__, looked_up_format.__class__)
334
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
335
    def test_create_repository(self):
1534.6.1 by Robert Collins
allow API creation of shared repositories
336
        # bzrdir can construct a repository for itself.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
337
        if not self.bzrdir_format.is_supported():
338
            # unsupported formats are not loopback testable
339
            # because the default open will not open them and
340
            # they may not be initializable.
341
            return
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
342
        t = transport.get_transport(self.get_url())
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
343
        made_control = self.bzrdir_format.initialize(t.base)
344
        made_repo = made_control.create_repository()
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
345
        # Check that we have a repository object.
346
        made_repo.has_revision('foo')
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
347
        self.assertEqual(made_control, made_repo.bzrdir)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
348
1534.6.1 by Robert Collins
allow API creation of shared repositories
349
    def test_create_repository_shared(self):
350
        # bzrdir can construct a shared repository.
351
        if not self.bzrdir_format.is_supported():
352
            # unsupported formats are not loopback testable
353
            # because the default open will not open them and
354
            # they may not be initializable.
355
            return
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
356
        t = transport.get_transport(self.get_url())
1534.6.1 by Robert Collins
allow API creation of shared repositories
357
        made_control = self.bzrdir_format.initialize(t.base)
358
        try:
359
            made_repo = made_control.create_repository(shared=True)
360
        except errors.IncompatibleFormat:
361
            # not all repository formats understand being shared, or
362
            # may only be shared in some circumstances.
363
            return
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
364
        # Check that we have a repository object.
365
        made_repo.has_revision('foo')
1534.6.1 by Robert Collins
allow API creation of shared repositories
366
        self.assertEqual(made_control, made_repo.bzrdir)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
367
        self.assertTrue(made_repo.is_shared())
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
368
369
    def test_revision_tree(self):
370
        wt = self.make_branch_and_tree('.')
1731.1.33 by Aaron Bentley
Revert no-special-root changes
371
        wt.set_root_id('fixed-root')
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
372
        wt.commit('lala!', rev_id='revision-1', allow_pointless=True)
373
        tree = wt.branch.repository.revision_tree('revision-1')
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
374
        tree.lock_read()
375
        try:
376
            self.assertEqual('revision-1', tree.inventory.root.revision)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
377
            expected = inventory.InventoryDirectory('fixed-root', '', None)
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
378
            expected.revision = 'revision-1'
379
            self.assertEqual([('', 'V', 'directory', 'fixed-root', expected)],
380
                             list(tree.list_files(include_root=True)))
381
        finally:
382
            tree.unlock()
3668.5.3 by Jelmer Vernooij
Add test to make sure revision_tree(None) prints a deprecation warning.
383
        tree = self.callDeprecated(['NULL_REVISION should be used for the null'
384
            ' revision instead of None, as of bzr 0.91.'],
385
            wt.branch.repository.revision_tree, None)
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
386
        tree.lock_read()
387
        try:
388
            self.assertEqual([], list(tree.list_files(include_root=True)))
389
        finally:
390
            tree.unlock()
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
391
        tree = wt.branch.repository.revision_tree(_mod_revision.NULL_REVISION)
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
392
        tree.lock_read()
393
        try:
394
            self.assertEqual([], list(tree.list_files(include_root=True)))
395
        finally:
396
            tree.unlock()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
397
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
398
    def test_get_revision_delta(self):
399
        tree_a = self.make_branch_and_tree('a')
2381.1.3 by Robert Collins
Review feedback.
400
        self.build_tree(['a/foo'])
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
401
        tree_a.add('foo', 'file1')
402
        tree_a.commit('rev1', rev_id='rev1')
2381.1.3 by Robert Collins
Review feedback.
403
        self.build_tree(['a/vla'])
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
404
        tree_a.add('vla', 'file2')
405
        tree_a.commit('rev2', rev_id='rev2')
406
407
        delta = tree_a.branch.repository.get_revision_delta('rev1')
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
408
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
409
        self.assertEqual([('foo', 'file1', 'file')], delta.added)
410
        delta = tree_a.branch.repository.get_revision_delta('rev2')
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
411
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
412
        self.assertEqual([('vla', 'file2', 'file')], delta.added)
413
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
414
    def test_get_revision_delta_filtered(self):
415
        tree_a = self.make_branch_and_tree('a')
416
        self.build_tree(['a/foo', 'a/bar/', 'a/bar/b1', 'a/bar/b2', 'a/baz'])
417
        tree_a.add(['foo', 'bar', 'bar/b1', 'bar/b2', 'baz'],
418
                   ['foo-id', 'bar-id', 'b1-id', 'b2-id', 'baz-id'])
419
        tree_a.commit('rev1', rev_id='rev1')
420
        self.build_tree(['a/bar/b3'])
421
        tree_a.add('bar/b3', 'b3-id')
422
        tree_a.commit('rev2', rev_id='rev2')
423
424
        # Test multiple files
425
        delta = tree_a.branch.repository.get_revision_delta('rev1',
426
            specific_fileids=['foo-id', 'baz-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
427
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
428
        self.assertEqual([
429
            ('baz', 'baz-id', 'file'),
430
            ('foo', 'foo-id', 'file'),
431
            ], delta.added)
432
        # Test a directory
433
        delta = tree_a.branch.repository.get_revision_delta('rev1',
434
            specific_fileids=['bar-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
435
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
436
        self.assertEqual([
437
            ('bar', 'bar-id', 'directory'),
438
            ('bar/b1', 'b1-id', 'file'),
439
            ('bar/b2', 'b2-id', 'file'),
440
            ], delta.added)
441
        # Test a file in a directory
442
        delta = tree_a.branch.repository.get_revision_delta('rev1',
443
            specific_fileids=['b2-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
444
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
445
        self.assertEqual([
446
            ('bar', 'bar-id', 'directory'),
447
            ('bar/b2', 'b2-id', 'file'),
448
            ], delta.added)
449
        # Try another revision
450
        delta = tree_a.branch.repository.get_revision_delta('rev2',
451
                specific_fileids=['b3-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
452
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
453
        self.assertEqual([
454
            ('bar', 'bar-id', 'directory'),
455
            ('bar/b3', 'b3-id', 'file'),
456
            ], delta.added)
457
        delta = tree_a.branch.repository.get_revision_delta('rev2',
458
                specific_fileids=['foo-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
459
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
460
        self.assertEqual([], delta.added)
461
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
462
    def test_clone_bzrdir_repository_revision(self):
463
        # make a repository with some revisions,
464
        # and clone it, this should not have unreferenced revisions.
465
        # also: test cloning with a revision id of NULL_REVISION -> empty repo.
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
466
        raise tests.TestSkipped('revision limiting is not implemented yet.')
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
467
468
    def test_clone_repository_basis_revision(self):
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
469
        raise tests.TestSkipped(
470
            'the use of a basis should not add noise data to the result.')
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
471
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
472
    def test_clone_shared_no_tree(self):
473
        # cloning a shared repository keeps it shared
474
        # and preserves the make_working_tree setting.
475
        made_control = self.make_bzrdir('source')
476
        try:
477
            made_repo = made_control.create_repository(shared=True)
478
        except errors.IncompatibleFormat:
479
            # not all repository formats understand being shared, or
480
            # may only be shared in some circumstances.
481
            return
2018.14.2 by Andrew Bennetts
All but one repository_implementation tests for RemoteRepository passing.
482
        try:
483
            made_repo.set_make_working_trees(False)
484
        except NotImplementedError:
2018.5.120 by Robert Collins
The Repository API ``make_working_trees`` is now permitted to return
485
            # the repository does not support having its tree-making flag
486
            # toggled.
487
            return
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
488
        result = made_control.clone(self.get_url('target'))
1752.2.55 by Andrew Bennetts
Replace another isinstance(made_repo, Repository) check.
489
        # Check that we have a repository object.
490
        made_repo.has_revision('foo')
491
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
492
        self.assertEqual(made_control, made_repo.bzrdir)
493
        self.assertTrue(result.open_repository().is_shared())
494
        self.assertFalse(result.open_repository().make_working_trees())
495
2018.5.90 by Andrew Bennetts
Fix test_upgrade_preserves_signatures; it incorrectly assumed that upgrade(wt, ...) would necessarily affect the repository.
496
    def test_upgrade_preserves_signatures(self):
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
497
        wt = self.make_branch_and_tree('source')
498
        wt.commit('A', allow_pointless=True, rev_id='A')
2018.5.90 by Andrew Bennetts
Fix test_upgrade_preserves_signatures; it incorrectly assumed that upgrade(wt, ...) would necessarily affect the repository.
499
        repo = wt.branch.repository
2592.3.39 by Robert Collins
Fugly version to remove signatures.kndx
500
        repo.lock_write()
501
        repo.start_write_group()
3735.2.100 by Vincent Ladeuil
Fix 3 failing tests due to an amazing typo.
502
        repo.sign_revision('A', gpg.LoopbackGPGStrategy(None))
2592.3.39 by Robert Collins
Fugly version to remove signatures.kndx
503
        repo.commit_write_group()
504
        repo.unlock()
2018.5.90 by Andrew Bennetts
Fix test_upgrade_preserves_signatures; it incorrectly assumed that upgrade(wt, ...) would necessarily affect the repository.
505
        old_signature = repo.get_signature_text('A')
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
506
        try:
507
            old_format = bzrdir.BzrDirFormat.get_default_format()
508
            # This gives metadir branches something they can convert to.
509
            # it would be nice to have a 'latest' vs 'default' concept.
2255.2.208 by Robert Collins
Remove more references to 'experimental' formats.
510
            format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
511
            upgrade.upgrade(repo.bzrdir.root_transport.base, format=format)
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
512
        except errors.UpToDateFormat:
513
            # this is in the most current format already.
514
            return
1910.2.12 by Aaron Bentley
Implement knit repo format 2
515
        except errors.BadConversionTarget, e:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
516
            raise tests.TestSkipped(str(e))
517
        wt = workingtree.WorkingTree.open(wt.basedir)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
518
        new_signature = wt.branch.repository.get_signature_text('A')
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
519
        self.assertEqual(old_signature, new_signature)
520
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
521
    def test_format_description(self):
522
        repo = self.make_repository('.')
523
        text = repo._format.get_format_description()
524
        self.failUnless(len(text))
525
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
526
    def test_format_supports_external_lookups(self):
527
        repo = self.make_repository('.')
528
        self.assertSubset(
529
            [repo._format.supports_external_lookups], (True, False))
530
1666.1.6 by Robert Collins
Make knit the default format.
531
    def assertMessageRoundtrips(self, message):
532
        """Assert that message roundtrips to a repository and back intact."""
533
        tree = self.make_branch_and_tree('.')
534
        tree.commit(message, rev_id='a', allow_pointless=True)
535
        rev = tree.branch.repository.get_revision('a')
4416.5.1 by Jelmer Vernooij
Move squashing of XML-invalid characters to XMLSerializer.
536
        if tree.branch.repository._serializer.squashes_xml_invalid_characters:
537
            # we have to manually escape this as we dont try to
4443.1.2 by Jelmer Vernooij
Fix comment about XML escaping in tests.
538
            # roundtrip xml invalid characters in the xml-based serializers.
4416.5.1 by Jelmer Vernooij
Move squashing of XML-invalid characters to XMLSerializer.
539
            escaped_message, escape_count = re.subn(
540
                u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]+',
541
                lambda match: match.group(0).encode('unicode_escape'),
542
                message)
543
            self.assertEqual(rev.message, escaped_message)
544
        else:
545
            self.assertEqual(rev.message, message)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
546
        # insist the class is unicode no matter what came in for
1666.1.6 by Robert Collins
Make knit the default format.
547
        # consistency.
548
        self.assertIsInstance(rev.message, unicode)
549
550
    def test_commit_unicode_message(self):
551
        # a siple unicode message should be preserved
552
        self.assertMessageRoundtrips(u'foo bar gamm\xae plop')
553
554
    def test_commit_unicode_control_characters(self):
555
        # a unicode message with control characters should roundtrip too.
3831.1.4 by John Arbash Meinel
Update the per-repository unicode commit test.
556
        unichars = [unichr(x) for x in range(256)]
557
        # '\r' is not directly allowed anymore, as it used to be translated
558
        # into '\n' anyway
559
        unichars[ord('\r')] = u'\n'
1666.1.6 by Robert Collins
Make knit the default format.
560
        self.assertMessageRoundtrips(
3831.1.4 by John Arbash Meinel
Update the per-repository unicode commit test.
561
            u"All 8-bit chars: " +  ''.join(unichars))
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
562
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
563
    def test_check_repository(self):
564
        """Check a fairly simple repository's history"""
565
        tree = self.make_branch_and_tree('.')
566
        tree.commit('initial empty commit', rev_id='a-rev',
567
                    allow_pointless=True)
2745.6.39 by Andrew Bennetts
Use scenario in test_check too, and make check actually report inconsistent parents to the end user.
568
        result = tree.branch.repository.check()
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
569
        # writes to log; should accept both verbose or non-verbose
570
        result.report_results(verbose=True)
571
        result.report_results(verbose=False)
572
1756.1.5 by Aaron Bentley
Test get_revisions with all repository types (and fix bug...)
573
    def test_get_revisions(self):
574
        tree = self.make_branch_and_tree('.')
575
        tree.commit('initial empty commit', rev_id='a-rev',
576
                    allow_pointless=True)
577
        tree.commit('second empty commit', rev_id='b-rev',
578
                    allow_pointless=True)
579
        tree.commit('third empty commit', rev_id='c-rev',
580
                    allow_pointless=True)
581
        repo = tree.branch.repository
582
        revision_ids = ['a-rev', 'b-rev', 'c-rev']
583
        revisions = repo.get_revisions(revision_ids)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
584
        self.assertEqual(len(revisions), 3)
1756.1.5 by Aaron Bentley
Test get_revisions with all repository types (and fix bug...)
585
        zipped = zip(revisions, revision_ids)
586
        self.assertEqual(len(zipped), 3)
587
        for revision, revision_id in zipped:
588
            self.assertEqual(revision.revision_id, revision_id)
589
            self.assertEqual(revision, repo.get_revision(revision_id))
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
590
1910.2.1 by Aaron Bentley
Ensure root entry always has a revision
591
    def test_root_entry_has_revision(self):
592
        tree = self.make_branch_and_tree('.')
593
        tree.commit('message', rev_id='rev_id')
2255.7.65 by Robert Collins
Split test_root_revision_entry into tree and repository portions.
594
        rev_tree = tree.branch.repository.revision_tree(tree.last_revision())
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
595
        rev_tree.lock_read()
596
        self.addCleanup(rev_tree.unlock)
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
597
        self.assertEqual('rev_id', rev_tree.inventory.root.revision)
1910.2.1 by Aaron Bentley
Ensure root entry always has a revision
598
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
599
    def test_upgrade_from_format4(self):
600
        from bzrlib.tests.test_upgrade import _upgrade_dir_template
4792.1.2 by Andrew Bennetts
Fix test failure.
601
        if isinstance(self.repository_format, remote.RemoteRepositoryFormat):
602
            return # local conversion to/from RemoteObjects is irrelevant.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
603
        if self.repository_format.get_format_description() \
604
            == "Repository format 4":
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
605
            raise tests.TestSkipped('Cannot convert format-4 to itself')
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
606
        self.build_tree_contents(_upgrade_dir_template)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
607
        old_repodir = bzrdir.BzrDir.open_unsupported('.')
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
608
        old_repo_format = old_repodir.open_repository()._format
609
        format = self.repository_format._matchingbzrdir
610
        try:
611
            format.repository_format = self.repository_format
612
        except AttributeError:
613
            pass
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
614
        upgrade.upgrade('.', format)
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
615
1910.2.37 by Aaron Bentley
Handle empty commits, fix test
616
    def test_pointless_commit(self):
617
        tree = self.make_branch_and_tree('.')
618
        self.assertRaises(errors.PointlessCommit, tree.commit, 'pointless',
619
                          allow_pointless=False)
620
        tree.commit('pointless', allow_pointless=True)
621
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
622
    def test_format_attributes(self):
623
        """All repository formats should have some basic attributes."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
624
        # create a repository to get a real format instance, not the
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
625
        # template from the test suite parameterization.
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
626
        repo = self.make_repository('.')
627
        repo._format.rich_root_data
628
        repo._format.supports_tree_reference
629
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
630
    def test_get_serializer_format(self):
631
        repo = self.make_repository('.')
632
        format = repo.get_serializer_format()
633
        self.assertEqual(repo._serializer.format_num, format)
634
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
635
    def test_iter_files_bytes(self):
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
636
        tree = self.make_branch_and_tree('tree')
637
        self.build_tree_contents([('tree/file1', 'foo'),
638
                                  ('tree/file2', 'bar')])
639
        tree.add(['file1', 'file2'], ['file1-id', 'file2-id'])
640
        tree.commit('rev1', rev_id='rev1')
641
        self.build_tree_contents([('tree/file1', 'baz')])
642
        tree.commit('rev2', rev_id='rev2')
2708.1.11 by Aaron Bentley
Test and tweak error handling
643
        repository = tree.branch.repository
2592.3.214 by Robert Collins
Merge bzr.dev.
644
        repository.lock_read()
645
        self.addCleanup(repository.unlock)
2708.1.6 by Aaron Bentley
Turn extract_files_bytes into an iterator
646
        extracted = dict((i, ''.join(b)) for i, b in
2708.1.11 by Aaron Bentley
Test and tweak error handling
647
                         repository.iter_files_bytes(
2708.1.6 by Aaron Bentley
Turn extract_files_bytes into an iterator
648
                         [('file1-id', 'rev1', 'file1-old'),
649
                          ('file1-id', 'rev2', 'file1-new'),
650
                          ('file2-id', 'rev1', 'file2'),
651
                         ]))
652
        self.assertEqual('foo', extracted['file1-old'])
653
        self.assertEqual('bar', extracted['file2'])
654
        self.assertEqual('baz', extracted['file1-new'])
2708.1.11 by Aaron Bentley
Test and tweak error handling
655
        self.assertRaises(errors.RevisionNotPresent, list,
656
                          repository.iter_files_bytes(
657
                          [('file1-id', 'rev3', 'file1-notpresent')]))
2592.3.102 by Robert Collins
Change the iter_files_bytes error to allow either RevisionNotPresent or NoSuchId when requesting a file that was not in the repository at all.
658
        self.assertRaises((errors.RevisionNotPresent, errors.NoSuchId), list,
2708.1.11 by Aaron Bentley
Test and tweak error handling
659
                          repository.iter_files_bytes(
660
                          [('file3-id', 'rev3', 'file1-notpresent')]))
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
661
2535.3.63 by Andrew Bennetts
Add repository implementations test for item_keys_introduced_by.
662
    def test_item_keys_introduced_by(self):
663
        # Make a repo with one revision and one versioned file.
664
        tree = self.make_branch_and_tree('t')
665
        self.build_tree(['t/foo'])
666
        tree.add('foo', 'file1')
667
        tree.commit('message', rev_id='rev_id')
668
        repo = tree.branch.repository
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
669
        repo.lock_write()
670
        repo.start_write_group()
3735.2.100 by Vincent Ladeuil
Fix 3 failing tests due to an amazing typo.
671
        repo.sign_revision('rev_id', gpg.LoopbackGPGStrategy(None))
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
672
        repo.commit_write_group()
673
        repo.unlock()
3381.1.3 by Aaron Bentley
Stop locking in get_data_stream_for_search
674
        repo.lock_read()
675
        self.addCleanup(repo.unlock)
2535.3.63 by Andrew Bennetts
Add repository implementations test for item_keys_introduced_by.
676
677
        # Item keys will be in this order, for maximum convenience for
678
        # generating data to insert into knit repository:
679
        #   * files
680
        #   * inventory
681
        #   * signatures
682
        #   * revisions
683
        expected_item_keys = [
684
            ('file', 'file1', ['rev_id']),
685
            ('inventory', None, ['rev_id']),
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
686
            ('signatures', None, ['rev_id']),
2535.3.63 by Andrew Bennetts
Add repository implementations test for item_keys_introduced_by.
687
            ('revisions', None, ['rev_id'])]
688
        item_keys = list(repo.item_keys_introduced_by(['rev_id']))
689
        item_keys = [
690
            (kind, file_id, list(versions))
691
            for (kind, file_id, versions) in item_keys]
692
693
        if repo.supports_rich_root():
694
            # Check for the root versioned file in the item_keys, then remove
695
            # it from streamed_names so we can compare that with
696
            # expected_record_names.
697
            # Note that the file keys can be in any order, so this test is
698
            # written to allow that.
699
            inv = repo.get_inventory('rev_id')
700
            root_item_key = ('file', inv.root.file_id, ['rev_id'])
701
            self.assertTrue(root_item_key in item_keys)
702
            item_keys.remove(root_item_key)
703
704
        self.assertEqual(expected_item_keys, item_keys)
705
2850.4.1 by Andrew Bennetts
Add smoketest for repo.get_graph, and fix bug in RemoteRepository.get_graph that it reveals.
706
    def test_get_graph(self):
707
        """Bare-bones smoketest that all repositories implement get_graph."""
708
        repo = self.make_repository('repo')
2592.3.214 by Robert Collins
Merge bzr.dev.
709
        repo.lock_read()
710
        self.addCleanup(repo.unlock)
2850.4.1 by Andrew Bennetts
Add smoketest for repo.get_graph, and fix bug in RemoteRepository.get_graph that it reveals.
711
        repo.get_graph()
712
3146.1.1 by Aaron Bentley
Fix bad ghost handling in KnitParentsProvider
713
    def test_graph_ghost_handling(self):
714
        tree = self.make_branch_and_tree('here')
715
        tree.lock_write()
716
        self.addCleanup(tree.unlock)
717
        tree.commit('initial commit', rev_id='rev1')
718
        tree.add_parent_tree_id('ghost')
719
        tree.commit('commit-with-ghost', rev_id='rev2')
720
        graph = tree.branch.repository.get_graph()
721
        parents = graph.get_parent_map(['ghost', 'rev2'])
722
        self.assertTrue('ghost' not in parents)
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
723
        self.assertEqual(parents['rev2'], ('rev1', 'ghost'))
724
4913.4.4 by Jelmer Vernooij
Add test for Repository.get_known_graph_ancestry().
725
    def test_get_known_graph_ancestry(self):
726
        tree = self.make_branch_and_tree('here')
727
        tree.lock_write()
728
        self.addCleanup(tree.unlock)
729
        # A
730
        # |\
731
        # | B
732
        # |/
733
        # C
734
        tree.commit('initial commit', rev_id='A')
735
        tree_other = tree.bzrdir.sprout('there').open_workingtree()
736
        tree_other.commit('another', rev_id='B')
737
        tree.merge_from_branch(tree_other.branch)
738
        tree.commit('another', rev_id='C')
739
        kg = tree.branch.repository.get_known_graph_ancestry(
740
            ['C'])
741
        self.assertEqual(['C'], list(kg.heads(['A', 'B', 'C'])))
742
        self.assertEqual(['A', 'B', 'C'], list(kg.topo_sort()))
743
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
744
    def test_parent_map_type(self):
745
        tree = self.make_branch_and_tree('here')
746
        tree.lock_write()
747
        self.addCleanup(tree.unlock)
748
        tree.commit('initial commit', rev_id='rev1')
749
        tree.commit('next commit', rev_id='rev2')
750
        graph = tree.branch.repository.get_graph()
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
751
        parents = graph.get_parent_map(
752
            [_mod_revision.NULL_REVISION, 'rev1', 'rev2'])
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
753
        for value in parents.values():
754
            self.assertIsInstance(value, tuple)
3146.1.1 by Aaron Bentley
Fix bad ghost handling in KnitParentsProvider
755
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
756
    def test_implements_revision_graph_can_have_wrong_parents(self):
757
        """All repositories should implement
758
        revision_graph_can_have_wrong_parents, so that check and reconcile can
759
        work correctly.
760
        """
761
        repo = self.make_repository('.')
762
        # This should work, not raise NotImplementedError:
2592.3.214 by Robert Collins
Merge bzr.dev.
763
        if not repo.revision_graph_can_have_wrong_parents():
764
            return
765
        repo.lock_read()
766
        self.addCleanup(repo.unlock)
767
        # This repo must also implement
768
        # _find_inconsistent_revision_parents and
769
        # _check_for_inconsistent_revision_parents.  So calling these
770
        # should not raise NotImplementedError.
771
        list(repo._find_inconsistent_revision_parents())
772
        repo._check_for_inconsistent_revision_parents()
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
773
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
774
    def test_add_signature_text(self):
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
775
        repo = self.make_repository('repo')
776
        repo.lock_write()
777
        self.addCleanup(repo.unlock)
778
        repo.start_write_group()
4634.35.16 by Andrew Bennetts
Fix more test fallout.
779
        self.addCleanup(repo.abort_write_group)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
780
        inv = inventory.Inventory(revision_id='A')
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
781
        inv.root.revision = 'A'
782
        repo.add_inventory('A', inv, [])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
783
        repo.add_revision('A', _mod_revision.Revision(
784
                'A', committer='A', timestamp=0,
785
                inventory_sha1='', timezone=0, message='A'))
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
786
        repo.add_signature_text('A', 'This might be a signature')
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
787
        self.assertEqual('This might be a signature',
788
                         repo.get_signature_text('A'))
789
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
790
    def test_add_revision_inventory_sha1(self):
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
791
        inv = inventory.Inventory(revision_id='A')
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
792
        inv.root.revision = 'A'
793
        inv.root.file_id = 'fixed-root'
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
794
        # Insert the inventory on its own to an identical repository, to get
795
        # its sha1.
796
        reference_repo = self.make_repository('reference_repo')
797
        reference_repo.lock_write()
798
        reference_repo.start_write_group()
799
        inv_sha1 = reference_repo.add_inventory('A', inv, [])
800
        reference_repo.abort_write_group()
801
        reference_repo.unlock()
802
        # Now insert a revision with this inventory, and it should get the same
803
        # sha1.
804
        repo = self.make_repository('repo')
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
805
        repo.lock_write()
806
        repo.start_write_group()
4634.35.16 by Andrew Bennetts
Fix more test fallout.
807
        root_id = inv.root.file_id
808
        repo.texts.add_lines(('fixed-root', 'A'), [], [])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
809
        repo.add_revision('A', _mod_revision.Revision(
810
                'A', committer='B', timestamp=0,
811
                timezone=0, message='C'), inv=inv)
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
812
        repo.commit_write_group()
813
        repo.unlock()
814
        repo.lock_read()
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
815
        self.assertEquals(inv_sha1, repo.get_revision('A').inventory_sha1)
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
816
        repo.unlock()
817
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
818
    def test_install_revisions(self):
819
        wt = self.make_branch_and_tree('source')
820
        wt.commit('A', allow_pointless=True, rev_id='A')
821
        repo = wt.branch.repository
822
        repo.lock_write()
823
        repo.start_write_group()
3735.2.100 by Vincent Ladeuil
Fix 3 failing tests due to an amazing typo.
824
        repo.sign_revision('A', gpg.LoopbackGPGStrategy(None))
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
825
        repo.commit_write_group()
826
        repo.unlock()
827
        repo.lock_read()
828
        self.addCleanup(repo.unlock)
829
        repo2 = self.make_repository('repo2')
830
        revision = repo.get_revision('A')
831
        tree = repo.revision_tree('A')
832
        signature = repo.get_signature_text('A')
833
        repo2.lock_write()
834
        self.addCleanup(repo2.unlock)
835
        repository.install_revisions(repo2, [(revision, tree, signature)])
836
        self.assertEqual(revision, repo2.get_revision('A'))
837
        self.assertEqual(signature, repo2.get_signature_text('A'))
1852.9.6 by Robert Collins
Merge the change from Tree.compare to Tree.changes_from.
838
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
839
    # XXX: this helper duplicated from tests.test_repository
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
840
    def make_remote_repository(self, path, shared=False):
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
841
        """Make a RemoteRepository object backed by a real repository that will
842
        be created at the given path."""
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
843
        repo = self.make_repository(path, shared=shared)
5017.3.42 by Vincent Ladeuil
-s bt.per_repository.test_repo passing
844
        smart_server = test_server.SmartTCPServer_for_testing()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
845
        self.start_server(smart_server, self.get_server())
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
846
        remote_transport = transport.get_transport(
847
            smart_server.get_url()).clone(path)
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
848
        remote_bzrdir = bzrdir.BzrDir.open_from_transport(remote_transport)
849
        remote_repo = remote_bzrdir.open_repository()
850
        return remote_repo
851
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
852
    def test_sprout_from_hpss_preserves_format(self):
853
        """repo.sprout from a smart server preserves the repository format."""
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
854
        remote_repo = self.make_remote_repository('remote')
855
        local_bzrdir = self.make_bzrdir('local')
856
        try:
857
            local_repo = remote_repo.sprout(local_bzrdir)
858
        except errors.TransportNotPossible:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
859
            raise tests.TestNotApplicable(
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
860
                "Cannot lock_read old formats like AllInOne over HPSS.")
861
        remote_backing_repo = bzrdir.BzrDir.open(
862
            self.get_vfs_only_url('remote')).open_repository()
863
        self.assertEqual(remote_backing_repo._format, local_repo._format)
864
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
865
    def test_sprout_branch_from_hpss_preserves_repo_format(self):
866
        """branch.sprout from a smart server preserves the repository format.
867
        """
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
868
        weave_formats = [weaverepo.RepositoryFormat5(),
869
                         weaverepo.RepositoryFormat6(),
870
                         weaverepo.RepositoryFormat7()]
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
871
        if self.repository_format in weave_formats:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
872
            raise tests.TestNotApplicable(
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
873
                "Cannot fetch weaves over smart protocol.")
874
        remote_repo = self.make_remote_repository('remote')
875
        remote_branch = remote_repo.bzrdir.create_branch()
876
        try:
877
            local_bzrdir = remote_branch.bzrdir.sprout('local')
878
        except errors.TransportNotPossible:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
879
            raise tests.TestNotApplicable(
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
880
                "Cannot lock_read old formats like AllInOne over HPSS.")
881
        local_repo = local_bzrdir.open_repository()
882
        remote_backing_repo = bzrdir.BzrDir.open(
883
            self.get_vfs_only_url('remote')).open_repository()
884
        self.assertEqual(remote_backing_repo._format, local_repo._format)
885
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
886
    def test_sprout_branch_from_hpss_preserves_shared_repo_format(self):
887
        """branch.sprout from a smart server preserves the repository format of
888
        a branch from a shared repository.
889
        """
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
890
        weave_formats = [weaverepo.RepositoryFormat5(),
891
                         weaverepo.RepositoryFormat6(),
892
                         weaverepo.RepositoryFormat7()]
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
893
        if self.repository_format in weave_formats:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
894
            raise tests.TestNotApplicable(
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
895
                "Cannot fetch weaves over smart protocol.")
896
        # Make a shared repo
897
        remote_repo = self.make_remote_repository('remote', shared=True)
898
        remote_backing_repo = bzrdir.BzrDir.open(
899
            self.get_vfs_only_url('remote')).open_repository()
900
        # Make a branch in that repo in an old format that isn't the default
901
        # branch format for the repo.
902
        from bzrlib.branch import BzrBranchFormat5
903
        format = remote_backing_repo.bzrdir.cloning_metadir()
904
        format._branch_format = BzrBranchFormat5()
905
        remote_transport = remote_repo.bzrdir.root_transport.clone('branch')
906
        remote_backing_repo.bzrdir.create_branch_convenience(
907
            remote_transport.base, force_new_repo=False, format=format)
908
        remote_branch = bzrdir.BzrDir.open_from_transport(
909
            remote_transport).open_branch()
910
        try:
911
            local_bzrdir = remote_branch.bzrdir.sprout('local')
912
        except errors.TransportNotPossible:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
913
            raise tests.TestNotApplicable(
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
914
                "Cannot lock_read old formats like AllInOne over HPSS.")
915
        local_repo = local_bzrdir.open_repository()
916
        self.assertEqual(remote_backing_repo._format, local_repo._format)
917
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
918
    def test_clone_to_hpss(self):
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
919
        pre_metadir_formats = [weaverepo.RepositoryFormat5(),
920
                               weaverepo.RepositoryFormat6()]
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
921
        if self.repository_format in pre_metadir_formats:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
922
            raise tests.TestNotApplicable(
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
923
                "Cannot lock pre_metadir_formats remotely.")
924
        remote_transport = self.make_smart_server('remote')
925
        local_branch = self.make_branch('local')
926
        remote_branch = local_branch.create_clone_on_transport(remote_transport)
927
        self.assertEqual(
928
            local_branch.repository._format.supports_external_lookups,
929
            remote_branch.repository._format.supports_external_lookups)
930
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
931
    def test_clone_stacking_policy_upgrades(self):
932
        """Cloning an unstackable branch format to somewhere with a default
933
        stack-on branch upgrades branch and repo to match the target and honour
934
        the policy.
3904.3.8 by Andrew Bennetts
Add test requested by John, and fix whitespace nit.
935
        """
936
        try:
937
            repo = self.make_repository('repo', shared=True)
938
        except errors.IncompatibleFormat:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
939
            raise tests.TestNotApplicable('Cannot make a shared repository')
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
940
        if isinstance(repo.bzrdir, bzrdir.BzrDirPreSplitOut):
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
941
            raise tests.KnownFailure(
942
                "pre metadir branches do not upgrade on push "
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
943
                "with stacking policy")
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
944
        if isinstance(repo._format,
945
                      pack_repo.RepositoryFormatKnitPack5RichRootBroken):
946
            raise tests.TestNotApplicable("unsupported format")
3904.3.8 by Andrew Bennetts
Add test requested by John, and fix whitespace nit.
947
        # Make a source branch in 'repo' in an unstackable branch format
948
        bzrdir_format = self.repository_format._matchingbzrdir
949
        transport = self.get_transport('repo/branch')
950
        transport.mkdir('.')
951
        target_bzrdir = bzrdir_format.initialize_on_transport(transport)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
952
        branch = _mod_branch.BzrBranchFormat6().initialize(target_bzrdir)
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
953
        # Ensure that stack_on will be stackable and match the serializer of
954
        # repo.
955
        if isinstance(repo, remote.RemoteRepository):
956
            repo._ensure_real()
957
            info_repo = repo._real_repository
4599.4.40 by Robert Collins
Fix formats for per_repository upgrade-to-stacking test.
958
        else:
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
959
            info_repo = repo
960
        format_description = info.describe_format(info_repo.bzrdir,
961
            info_repo, None, None)
962
        formats = format_description.split(' or ')
963
        stack_on_format = formats[0]
964
        if stack_on_format in ["pack-0.92", "dirstate", "metaweave"]:
965
            stack_on_format = "1.9"
966
        elif stack_on_format in ["dirstate-with-subtree", "rich-root",
967
            "rich-root-pack", "pack-0.92-subtree"]:
968
            stack_on_format = "1.9-rich-root"
969
        # formats not tested for above are already stackable, so we can use the
970
        # format as-is.
971
        stack_on = self.make_branch('stack-on-me', format=stack_on_format)
3904.3.8 by Andrew Bennetts
Add test requested by John, and fix whitespace nit.
972
        self.make_bzrdir('.').get_config().set_default_stack_on('stack-on-me')
973
        target = branch.bzrdir.clone(self.get_url('target'))
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
974
        # The target branch supports stacking.
975
        self.assertTrue(target.open_branch()._format.supports_stacking())
3904.3.8 by Andrew Bennetts
Add test requested by John, and fix whitespace nit.
976
        if isinstance(repo, remote.RemoteRepository):
977
            repo._ensure_real()
978
            repo = repo._real_repository
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
979
        target_repo = target.open_repository()
980
        if isinstance(target_repo, remote.RemoteRepository):
981
            target_repo._ensure_real()
982
            target_repo = target_repo._real_repository
4599.4.45 by Robert Collins
Fix a final failure in stacking upgrade of branch/repository tests.
983
        # The repository format is unchanged if it could already stack, or the
984
        # same as the stack on.
985
        if repo._format.supports_external_lookups:
986
            self.assertEqual(repo._format, target_repo._format)
987
        else:
988
            self.assertEqual(stack_on.repository._format, target_repo._format)
3904.3.8 by Andrew Bennetts
Add test requested by John, and fix whitespace nit.
989
4022.1.1 by Robert Collins
Refactoring of fetch to have a sender and sink component enabling splitting the logic over a network stream. (Robert Collins, Andrew Bennetts)
990
    def test__get_sink(self):
991
        repo = self.make_repository('repo')
992
        sink = repo._get_sink()
993
        self.assertIsInstance(sink, repository.StreamSink)
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
994
3089.2.1 by Andrew Bennetts
Implement RemoteRepository._make_parents_provider.
995
    def test__make_parents_provider(self):
996
        """Repositories must have a _make_parents_provider method that returns
3099.3.5 by John Arbash Meinel
Update the last couple of places that referred to Provider.get_parents() directly.
997
        an object with a get_parent_map method.
3089.2.1 by Andrew Bennetts
Implement RemoteRepository._make_parents_provider.
998
        """
999
        repo = self.make_repository('repo')
3099.3.5 by John Arbash Meinel
Update the last couple of places that referred to Provider.get_parents() directly.
1000
        repo._make_parents_provider().get_parent_map
3089.2.1 by Andrew Bennetts
Implement RemoteRepository._make_parents_provider.
1001
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1002
    def make_repository_and_foo_bar(self, shared):
1003
        made_control = self.make_bzrdir('repository')
1004
        repo = made_control.create_repository(shared=shared)
1005
        bzrdir.BzrDir.create_branch_convenience(self.get_url('repository/foo'),
1006
                                                force_new_repo=False)
1007
        bzrdir.BzrDir.create_branch_convenience(self.get_url('repository/bar'),
1008
                                                force_new_repo=True)
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
1009
        baz = self.make_bzrdir('repository/baz')
1010
        qux = self.make_branch('repository/baz/qux')
3140.1.6 by Aaron Bentley
Add test that nested branches are returned
1011
        quxx = self.make_branch('repository/baz/qux/quxx')
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1012
        return repo
1013
1014
    def test_find_branches(self):
1015
        repo = self.make_repository_and_foo_bar(shared=False)
1016
        branches = repo.find_branches()
1017
        self.assertContainsRe(branches[-1].base, 'repository/foo/$')
3140.1.6 by Aaron Bentley
Add test that nested branches are returned
1018
        self.assertContainsRe(branches[-3].base, 'repository/baz/qux/$')
1019
        self.assertContainsRe(branches[-2].base, 'repository/baz/qux/quxx/$')
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1020
        # in some formats, creating a repo creates a branch
3140.1.6 by Aaron Bentley
Add test that nested branches are returned
1021
        if len(branches) == 6:
1022
            self.assertContainsRe(branches[-4].base, 'repository/baz/$')
1023
            self.assertContainsRe(branches[-5].base, 'repository/bar/$')
1024
            self.assertContainsRe(branches[-6].base, 'repository/$')
1025
        else:
1026
            self.assertEqual(4, len(branches))
3140.1.3 by Aaron Bentley
Add support for finding branches to BzrDir
1027
            self.assertContainsRe(branches[-4].base, 'repository/bar/$')
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1028
1029
    def test_find_branches_using(self):
1030
        try:
1031
            repo = self.make_repository_and_foo_bar(shared=True)
1032
        except errors.IncompatibleFormat:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1033
            raise tests.TestNotApplicable
3140.1.2 by Aaron Bentley
Add ability to find branches inside repositories
1034
        branches = repo.find_branches(using=True)
1035
        self.assertContainsRe(branches[-1].base, 'repository/foo/$')
1036
        # in some formats, creating a repo creates a branch
1037
        if len(branches) == 2:
1038
            self.assertContainsRe(branches[-2].base, 'repository/$')
1039
        else:
1040
            self.assertEqual(1, len(branches))
1041
3140.1.9 by Aaron Bentley
Optimize find_branches for standalone repositories
1042
    def test_find_branches_using_standalone(self):
1043
        branch = self.make_branch('branch')
1044
        contained = self.make_branch('branch/contained')
1045
        branches = branch.repository.find_branches(using=True)
1046
        self.assertEqual([branch.base], [b.base for b in branches])
1047
        branches = branch.repository.find_branches(using=False)
1048
        self.assertEqual([branch.base, contained.base],
1049
                         [b.base for b in branches])
1050
1051
    def test_find_branches_using_empty_standalone_repo(self):
1052
        repo = self.make_repository('repo')
1053
        self.assertFalse(repo.is_shared())
1054
        try:
1055
            repo.bzrdir.open_branch()
1056
        except errors.NotBranchError:
1057
            self.assertEqual([], repo.find_branches(using=True))
1058
        else:
1059
            self.assertEqual([repo.bzrdir.root_transport.base],
1060
                             [b.base for b in repo.find_branches(using=True)])
1061
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
1062
    def test_set_get_make_working_trees_true(self):
1063
        repo = self.make_repository('repo')
3349.1.2 by Aaron Bentley
Change ValueError to RepositoryUpgradeRequired
1064
        try:
1065
            repo.set_make_working_trees(True)
1066
        except errors.RepositoryUpgradeRequired, e:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1067
            raise tests.TestNotApplicable('Format does not support this flag.')
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
1068
        self.assertTrue(repo.make_working_trees())
1069
1070
    def test_set_get_make_working_trees_false(self):
1071
        repo = self.make_repository('repo')
1072
        try:
1073
            repo.set_make_working_trees(False)
3349.1.2 by Aaron Bentley
Change ValueError to RepositoryUpgradeRequired
1074
        except errors.RepositoryUpgradeRequired, e:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1075
            raise tests.TestNotApplicable('Format does not support this flag.')
3349.1.2 by Aaron Bentley
Change ValueError to RepositoryUpgradeRequired
1076
        self.assertFalse(repo.make_working_trees())
3349.1.1 by Aaron Bentley
Enable setting and getting make_working_trees for all repositories
1077
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
1078
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1079
class TestRepositoryLocking(per_repository.TestCaseWithRepository):
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1080
1081
    def test_leave_lock_in_place(self):
1082
        repo = self.make_repository('r')
1083
        # Lock the repository, then use leave_lock_in_place so that when we
1084
        # unlock the repository the lock is still held on disk.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1085
        token = repo.lock_write().repository_token
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1086
        try:
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
1087
            if token is None:
1088
                # This test does not apply, because this repository refuses lock
1089
                # tokens.
1090
                self.assertRaises(NotImplementedError, repo.leave_lock_in_place)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1091
                return
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
1092
            repo.leave_lock_in_place()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1093
        finally:
1094
            repo.unlock()
1095
        # We should be unable to relock the repo.
1096
        self.assertRaises(errors.LockContention, repo.lock_write)
4327.1.8 by Vincent Ladeuil
Fix 4 more lock-related test failures.
1097
        # Cleanup
1098
        repo.lock_write(token)
1099
        repo.dont_leave_lock_in_place()
1100
        repo.unlock()
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1101
1102
    def test_dont_leave_lock_in_place(self):
1103
        repo = self.make_repository('r')
1104
        # Create a lock on disk.
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1105
        token = repo.lock_write().repository_token
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1106
        try:
1107
            if token is None:
1108
                # This test does not apply, because this repository refuses lock
1109
                # tokens.
2018.5.76 by Andrew Bennetts
Testing that repository.{dont_,}leave_lock_in_place raises NotImplementedError if lock_write returns None.
1110
                self.assertRaises(NotImplementedError,
1111
                                  repo.dont_leave_lock_in_place)
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1112
                return
1113
            try:
1114
                repo.leave_lock_in_place()
1115
            except NotImplementedError:
1116
                # This repository doesn't support this API.
1117
                return
1118
        finally:
1119
            repo.unlock()
1120
        # Reacquire the lock (with a different repository object) by using the
1121
        # token.
1122
        new_repo = repo.bzrdir.open_repository()
1123
        new_repo.lock_write(token=token)
1124
        # Call dont_leave_lock_in_place, so that the lock will be released by
1125
        # this instance, even though the lock wasn't originally acquired by it.
1126
        new_repo.dont_leave_lock_in_place()
1127
        new_repo.unlock()
1128
        # Now the repository is unlocked.  Test this by locking it (without a
1129
        # token).
1130
        repo.lock_write()
1131
        repo.unlock()
1132
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1133
    def test_lock_read_then_unlock(self):
1134
        # Calling lock_read then unlocking should work without errors.
1135
        repo = self.make_repository('r')
1136
        repo.lock_read()
1137
        repo.unlock()
1138
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1139
    def test_lock_read_returns_unlockable(self):
1140
        repo = self.make_repository('r')
1141
        self.assertThat(repo.lock_read, ReturnsUnlockable(repo))
1142
1143
    def test_lock_write_returns_unlockable(self):
1144
        repo = self.make_repository('r')
1145
        self.assertThat(repo.lock_write, ReturnsUnlockable(repo))
1146
2018.5.75 by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place.
1147
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1148
class TestCaseWithComplexRepository(per_repository.TestCaseWithRepository):
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1149
1150
    def setUp(self):
1151
        super(TestCaseWithComplexRepository, self).setUp()
1152
        tree_a = self.make_branch_and_tree('a')
1153
        self.bzrdir = tree_a.branch.bzrdir
1154
        # add a corrupt inventory 'orphan'
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1155
        # this may need some generalising for knits.
2592.3.74 by Robert Collins
Test setup fix to use get_inventory_weave rather than control_store.get_weave.
1156
        tree_a.lock_write()
1157
        try:
1158
            tree_a.branch.repository.start_write_group()
1159
            try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1160
                inv_file = tree_a.branch.repository.inventories
1161
                inv_file.add_lines(('orphan',), [], [])
2592.3.74 by Robert Collins
Test setup fix to use get_inventory_weave rather than control_store.get_weave.
1162
            except:
1163
                tree_a.branch.repository.commit_write_group()
1164
                raise
1165
            else:
1166
                tree_a.branch.repository.abort_write_group()
1167
        finally:
1168
            tree_a.unlock()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1169
        # add a real revision 'rev1'
1170
        tree_a.commit('rev1', rev_id='rev1', allow_pointless=True)
1171
        # add a real revision 'rev2' based on rev1
1172
        tree_a.commit('rev2', rev_id='rev2', allow_pointless=True)
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1173
        # add a reference to a ghost
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
1174
        tree_a.add_parent_tree_id('ghost1')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1175
        try:
1176
            tree_a.commit('rev3', rev_id='rev3', allow_pointless=True)
1177
        except errors.RevisionNotPresent:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1178
            raise tests.TestNotApplicable(
1179
                "Cannot test with ghosts for this format.")
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1180
        # add another reference to a ghost, and a second ghost.
1908.6.7 by Robert Collins
Remove all users of set_pending_merges and add_pending_merge except tests that they work correctly.
1181
        tree_a.add_parent_tree_id('ghost1')
1182
        tree_a.add_parent_tree_id('ghost2')
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1183
        tree_a.commit('rev4', rev_id='rev4', allow_pointless=True)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1184
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1185
    def test_revision_trees(self):
1186
        revision_ids = ['rev1', 'rev2', 'rev3', 'rev4']
1187
        repository = self.bzrdir.open_repository()
2592.3.214 by Robert Collins
Merge bzr.dev.
1188
        repository.lock_read()
1189
        self.addCleanup(repository.unlock)
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1190
        trees1 = list(repository.revision_trees(revision_ids))
1191
        trees2 = [repository.revision_tree(t) for t in revision_ids]
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1192
        self.assertEqual(len(trees1), len(trees2))
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1193
        for tree1, tree2 in zip(trees1, trees2):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1194
            self.assertFalse(tree2.changes_from(tree1).has_changed())
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1195
1756.3.22 by Aaron Bentley
Tweaks from review
1196
    def test_get_deltas_for_revisions(self):
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1197
        repository = self.bzrdir.open_repository()
2592.3.214 by Robert Collins
Merge bzr.dev.
1198
        repository.lock_read()
1199
        self.addCleanup(repository.unlock)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1200
        revisions = [repository.get_revision(r) for r in
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1201
                     ['rev1', 'rev2', 'rev3', 'rev4']]
1756.3.22 by Aaron Bentley
Tweaks from review
1202
        deltas1 = list(repository.get_deltas_for_revisions(revisions))
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1203
        deltas2 = [repository.get_revision_delta(r.revision_id) for r in
1204
                   revisions]
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1205
        self.assertEqual(deltas1, deltas2)
1756.3.20 by Aaron Bentley
Tests for get_revision_deltas and revisions_trees
1206
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1207
    def test_all_revision_ids(self):
1208
        # all_revision_ids -> all revisions
3221.12.1 by Robert Collins
Backport development1 format (stackable packs) to before-shallow-branches.
1209
        self.assertEqual(set(['rev1', 'rev2', 'rev3', 'rev4']),
1210
            set(self.bzrdir.open_repository().all_revision_ids()))
1534.4.50 by Robert Collins
Got the bzrdir api straightened out, plenty of refactoring to use it pending, but the api is up and running.
1211
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1212
    def test_get_ancestry_missing_revision(self):
1534.1.34 by Robert Collins
Move missing_revision_ids from Repository to InterRepository, and eliminate the now unused Repository._compatible_formats method.
1213
        # get_ancestry(revision that is in some data but not fully installed
1214
        # -> NoSuchRevision
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
1215
        self.assertRaises(errors.NoSuchRevision,
1216
                          self.bzrdir.open_repository().get_ancestry, 'orphan')
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1217
3606.7.8 by John Arbash Meinel
Switch names to 'unordered' that I missed before.
1218
    def test_get_unordered_ancestry(self):
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
1219
        repo = self.bzrdir.open_repository()
1220
        self.assertEqual(set(repo.get_ancestry('rev3')),
1221
                         set(repo.get_ancestry('rev3', topo_sorted=False)))
1222
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
1223
    def test_reserved_id(self):
1224
        repo = self.make_repository('repository')
2592.3.61 by Robert Collins
Remove inventory.kndx.
1225
        repo.lock_write()
1226
        repo.start_write_group()
1227
        try:
1228
            self.assertRaises(errors.ReservedId, repo.add_inventory, 'reserved:',
1229
                              None, None)
3879.2.12 by John Arbash Meinel
Missed an add_inventory_delta => add_inventory_by_delta.
1230
            self.assertRaises(errors.ReservedId, repo.add_inventory_by_delta,
3775.2.1 by Robert Collins
Create bzrlib.repository.Repository.add_inventory_delta for adding inventories via deltas.
1231
                "foo", [], 'reserved:', None)
2592.3.61 by Robert Collins
Remove inventory.kndx.
1232
            self.assertRaises(errors.ReservedId, repo.add_revision, 'reserved:',
1233
                              None)
1234
        finally:
1235
            repo.abort_write_group()
1236
            repo.unlock()
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
1237
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1238
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1239
class TestCaseWithCorruptRepository(per_repository.TestCaseWithRepository):
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1240
1241
    def setUp(self):
1242
        super(TestCaseWithCorruptRepository, self).setUp()
1243
        # a inventory with no parents and the revision has parents..
1244
        # i.e. a ghost.
1245
        repo = self.make_repository('inventory_with_unnecessary_ghost')
2592.3.38 by Robert Collins
All experimental format tests passing again.
1246
        repo.lock_write()
1247
        repo.start_write_group()
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1248
        inv = inventory.Inventory(revision_id = 'ghost')
1910.2.23 by Aaron Bentley
Fix up test cases that manually construct inventories
1249
        inv.root.revision = 'ghost'
4634.35.16 by Andrew Bennetts
Fix more test fallout.
1250
        if repo.supports_rich_root():
1251
            root_id = inv.root.file_id
1252
            repo.texts.add_lines((root_id, 'ghost'), [], [])
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
1253
        sha1 = repo.add_inventory('ghost', inv, [])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1254
        rev = _mod_revision.Revision(
1255
            timestamp=0, timezone=None, committer="Foo Bar <foo@example.com>",
1256
            message="Message", inventory_sha1=sha1, revision_id='ghost')
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1257
        rev.parent_ids = ['the_ghost']
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1258
        try:
1259
            repo.add_revision('ghost', rev)
1260
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1261
            raise tests.TestNotApplicable(
1262
                "Cannot test with ghosts for this format.")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1263
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1264
        inv = inventory.Inventory(revision_id = 'the_ghost')
1910.2.23 by Aaron Bentley
Fix up test cases that manually construct inventories
1265
        inv.root.revision = 'the_ghost'
4634.35.16 by Andrew Bennetts
Fix more test fallout.
1266
        if repo.supports_rich_root():
1267
            root_id = inv.root.file_id
1268
            repo.texts.add_lines((root_id, 'the_ghost'), [], [])
1907.1.1 by Aaron Bentley
Unshelved all changes except those related to removing RootEntry
1269
        sha1 = repo.add_inventory('the_ghost', inv, [])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1270
        rev = _mod_revision.Revision(
1271
            timestamp=0, timezone=None, committer="Foo Bar <foo@example.com>",
1272
            message="Message", inventory_sha1=sha1, revision_id='the_ghost')
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1273
        rev.parent_ids = []
1274
        repo.add_revision('the_ghost', rev)
1275
        # check its setup usefully
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1276
        inv_weave = repo.inventories
1277
        possible_parents = (None, (('ghost',),))
1278
        self.assertSubset(inv_weave.get_parent_map([('ghost',)])[('ghost',)],
1279
            possible_parents)
2592.3.38 by Robert Collins
All experimental format tests passing again.
1280
        repo.commit_write_group()
1281
        repo.unlock()
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1282
1594.2.10 by Robert Collins
Teach knit fetching and branching to only duplicate relevant data avoiding unnecessary reconciles.
1283
    def test_corrupt_revision_access_asserts_if_reported_wrong(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1284
        repo_url = self.get_url('inventory_with_unnecessary_ghost')
1285
        repo = repository.Repository.open(repo_url)
1594.2.10 by Robert Collins
Teach knit fetching and branching to only duplicate relevant data avoiding unnecessary reconciles.
1286
        reported_wrong = False
1287
        try:
1288
            if repo.get_ancestry('ghost') != [None, 'the_ghost', 'ghost']:
1289
                reported_wrong = True
1290
        except errors.CorruptRepository:
1291
            # caught the bad data:
1292
            return
1293
        if not reported_wrong:
1294
            return
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1295
        self.assertRaises(errors.CorruptRepository, repo.get_revision, 'ghost')
1296
1594.2.3 by Robert Collins
bugfix revision.MultipleRevisionSources.get_revision_graph to integrate ghosts between sources. [slow on weaves, fast on knits.
1297
    def test_corrupt_revision_get_revision_reconcile(self):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1298
        repo_url = self.get_url('inventory_with_unnecessary_ghost')
1299
        repo = repository.Repository.open(repo_url)
1570.1.13 by Robert Collins
Check for incorrect revision parentage in the weave during revision access.
1300
        repo.get_revision_reconcile('ghost')
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1301
1302
2018.5.29 by Robert Collins
Dont run the vfat repository test on RemoteRepositories as there is no point.
1303
# FIXME: document why this is a TestCaseWithTransport rather than a
1304
#        TestCaseWithRepository
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1305
class TestEscaping(tests.TestCaseWithTransport):
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1306
    """Test that repositories can be stored correctly on VFAT transports.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1307
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1308
    Makes sure we have proper escaping of invalid characters, etc.
1309
1310
    It'd be better to test all operations on the FakeVFATTransportDecorator,
1311
    but working trees go straight to the os not through the Transport layer.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1312
    Therefore we build some history first in the regular way and then
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1313
    check it's safe to access for vfat.
1314
    """
1315
1316
    def test_on_vfat(self):
2018.5.29 by Robert Collins
Dont run the vfat repository test on RemoteRepositories as there is no point.
1317
        # dont bother with remote repository testing, because this test is
1318
        # about local disk layout/support.
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1319
        if isinstance(self.repository_format, remote.RemoteRepositoryFormat):
2018.5.29 by Robert Collins
Dont run the vfat repository test on RemoteRepositories as there is no point.
1320
            return
5017.3.42 by Vincent Ladeuil
-s bt.per_repository.test_repo passing
1321
        self.transport_server = test_server.FakeVFATServer
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1322
        FOO_ID = 'foo<:>ID'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1323
        REV_ID = 'revid-1'
1324
        # this makes a default format repository always, which is wrong:
1325
        # it should be a TestCaseWithRepository in order to get the
2018.5.29 by Robert Collins
Dont run the vfat repository test on RemoteRepositories as there is no point.
1326
        # default format.
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1327
        wt = self.make_branch_and_tree('repo')
2052.2.1 by Alexander Belchenko
test_on_vfat win32 fix: use binary line-endings
1328
        self.build_tree(["repo/foo"], line_endings='binary')
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1329
        # add file with id containing wierd characters
1330
        wt.add(['foo'], [FOO_ID])
1331
        wt.commit('this is my new commit', rev_id=REV_ID)
1332
        # now access over vfat; should be safe
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
1333
        branch = bzrdir.BzrDir.open(self.get_url('repo')).open_branch()
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1334
        revtree = branch.repository.revision_tree(REV_ID)
3015.2.13 by Robert Collins
More lock correctness for the use of get_file_text in repository_implementations.
1335
        revtree.lock_read()
1336
        self.addCleanup(revtree.unlock)
1986.1.1 by Robert Collins
Move test_branch_on_vfat into a repository implementation test, to ensure that all repository formats are safe on vfat.
1337
        contents = revtree.get_file_text(FOO_ID)
1338
        self.assertEqual(contents, 'contents of repo/foo\n')
2520.4.54 by Aaron Bentley
Hang a create_bundle method off repository
1339
1340
    def test_create_bundle(self):
1341
        wt = self.make_branch_and_tree('repo')
1342
        self.build_tree(['repo/file1'])
1343
        wt.add('file1')
1344
        wt.commit('file1', rev_id='rev1')
1345
        fileobj = StringIO()
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
1346
        wt.branch.repository.create_bundle(
1347
            'rev1', _mod_revision.NULL_REVISION, fileobj)
5158.6.4 by Martin Pool
Repository implements ControlComponent too
1348
1349
1350
1351
1352
class TestRepositoryControlComponent(per_repository.TestCaseWithRepository):
1353
    """Repository implementations adequately implement ControlComponent."""
1354
    
1355
    def test_urls(self):
1356
        repo = self.make_repository('repo')
1357
        self.assertIsInstance(repo.user_url, str)
1358
        self.assertEqual(repo.user_url, repo.user_transport.base)
1359
        # for all current bzrdir implementations the user dir must be 
1360
        # above the control dir but we might need to relax that?
1361
        self.assertEqual(repo.control_url.find(repo.user_url), 0)
1362
        self.assertEqual(repo.control_url, repo.control_transport.base)