/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
5675.2.5 by Jelmer Vernooij
add tests for repository attributes.
91
    def test_format_is_deprecated(self):
92
        repo = self.make_repository('repo')
5675.2.6 by Jelmer Vernooij
Fix some tests.
93
        self.assertSubset([repo._format.is_deprecated()], (True, False))
5675.2.5 by Jelmer Vernooij
add tests for repository attributes.
94
95
    def test_format_is_supported(self):
96
        repo = self.make_repository('repo')
5675.2.6 by Jelmer Vernooij
Fix some tests.
97
        self.assertSubset([repo._format.is_supported()], (True, False))
5675.2.5 by Jelmer Vernooij
add tests for repository attributes.
98
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.
99
    def test_attribute_inventories_store(self):
100
        """Test the existence of the inventories attribute."""
101
        tree = self.make_branch_and_tree('tree')
102
        repo = tree.branch.repository
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
103
        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.
104
105
    def test_attribute_inventories_basics(self):
106
        """Test basic aspects of the inventories attribute."""
107
        tree = self.make_branch_and_tree('tree')
108
        repo = tree.branch.repository
109
        rev_id = (tree.commit('a'),)
110
        tree.lock_read()
111
        self.addCleanup(tree.unlock)
112
        self.assertEqual(set([rev_id]), set(repo.inventories.keys()))
113
114
    def test_attribute_revision_store(self):
115
        """Test the existence of the revisions attribute."""
116
        tree = self.make_branch_and_tree('tree')
117
        repo = tree.branch.repository
118
        self.assertIsInstance(repo.revisions,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
119
            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.
120
121
    def test_attribute_revision_store_basics(self):
122
        """Test the basic behaviour of the revisions attribute."""
123
        tree = self.make_branch_and_tree('tree')
124
        repo = tree.branch.repository
125
        repo.lock_write()
126
        try:
127
            self.assertEqual(set(), set(repo.revisions.keys()))
128
            revid = (tree.commit("foo"),)
129
            self.assertEqual(set([revid]), set(repo.revisions.keys()))
130
            self.assertEqual({revid:()},
131
                repo.revisions.get_parent_map([revid]))
132
        finally:
133
            repo.unlock()
134
        tree2 = self.make_branch_and_tree('tree2')
135
        tree2.pull(tree.branch)
136
        left_id = (tree2.commit('left'),)
137
        right_id = (tree.commit('right'),)
138
        tree.merge_from_branch(tree2.branch)
139
        merge_id = (tree.commit('merged'),)
140
        repo.lock_read()
141
        self.addCleanup(repo.unlock)
142
        self.assertEqual(set([revid, left_id, right_id, merge_id]),
143
            set(repo.revisions.keys()))
144
        self.assertEqual({revid:(), left_id:(revid,), right_id:(revid,),
145
             merge_id:(right_id, left_id)},
146
            repo.revisions.get_parent_map(repo.revisions.keys()))
147
148
    def test_attribute_signature_store(self):
149
        """Test the existence of the signatures attribute."""
150
        tree = self.make_branch_and_tree('tree')
151
        repo = tree.branch.repository
152
        self.assertIsInstance(repo.signatures,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
153
            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.
154
155
    def test_attribute_text_store_basics(self):
156
        """Test the basic behaviour of the text store."""
157
        tree = self.make_branch_and_tree('tree')
158
        repo = tree.branch.repository
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
159
        file_id = "Foo:Bar"
160
        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.
161
        tree.lock_write()
162
        try:
163
            self.assertEqual(set(), set(repo.texts.keys()))
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
164
            tree.add(['foo'], [file_id], ['file'])
165
            tree.put_file_bytes_non_atomic(file_id, 'content\n')
166
            try:
167
                rev_key = (tree.commit("foo"),)
168
            except errors.IllegalPath:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
169
                raise tests.TestNotApplicable(
170
                    'file_id %r cannot be stored on this'
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
171
                    ' 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.
172
            if repo._format.rich_root_data:
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
173
                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.
174
                keys = set([root_commit])
175
                parents = {root_commit:()}
176
            else:
177
                keys = set()
178
                parents = {}
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
179
            keys.add(file_key + rev_key)
180
            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.
181
            self.assertEqual(keys, set(repo.texts.keys()))
182
            self.assertEqual(parents,
183
                repo.texts.get_parent_map(repo.texts.keys()))
184
        finally:
185
            tree.unlock()
186
        tree2 = self.make_branch_and_tree('tree2')
187
        tree2.pull(tree.branch)
188
        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.
189
        right_key = (tree2.commit('right'),)
190
        keys.add(file_key + right_key)
191
        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.
192
        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.
193
        left_key = (tree.commit('left'),)
194
        keys.add(file_key + left_key)
195
        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.
196
        tree.merge_from_branch(tree2.branch)
197
        tree.put_file_bytes_non_atomic('Foo:Bar', 'merged\n')
198
        try:
199
            tree.auto_resolve()
200
        except errors.UnsupportedOperation:
201
            pass
4398.7.1 by John Arbash Meinel
Fix some failing tests for repositories and win32.
202
        merge_key = (tree.commit('merged'),)
203
        keys.add(file_key + merge_key)
204
        parents[file_key + merge_key] = (file_key + left_key,
205
                                         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.
206
        repo.lock_read()
207
        self.addCleanup(repo.unlock)
208
        self.assertEqual(keys, set(repo.texts.keys()))
209
        self.assertEqual(parents, repo.texts.get_parent_map(repo.texts.keys()))
210
211
    def test_attribute_text_store(self):
212
        """Test the existence of the texts attribute."""
213
        tree = self.make_branch_and_tree('tree')
214
        repo = tree.branch.repository
215
        self.assertIsInstance(repo.texts,
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
216
            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.
217
218
    def test_exposed_versioned_files_are_marked_dirty(self):
219
        repo = self.make_repository('.')
220
        repo.lock_write()
221
        signatures = repo.signatures
222
        revisions = repo.revisions
223
        inventories = repo.inventories
224
        repo.unlock()
225
        self.assertRaises(errors.ObjectNotLocked,
226
            signatures.keys)
227
        self.assertRaises(errors.ObjectNotLocked,
228
            revisions.keys)
229
        self.assertRaises(errors.ObjectNotLocked,
230
            inventories.keys)
231
        self.assertRaises(errors.ObjectNotLocked,
232
            signatures.add_lines, ('foo',), [], [])
233
        self.assertRaises(errors.ObjectNotLocked,
234
            revisions.add_lines, ('foo',), [], [])
235
        self.assertRaises(errors.ObjectNotLocked,
236
            inventories.add_lines, ('foo',), [], [])
237
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.
238
    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.
239
        #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.
240
        # such as signatures[not tested yet] etc etc.
241
        # when changing to the current default format.
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
242
        tree_a = self.make_branch_and_tree('a')
2381.1.3 by Robert Collins
Review feedback.
243
        self.build_tree(['a/foo'])
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
244
        tree_a.add('foo', 'file1')
245
        tree_a.commit('rev1', rev_id='rev1')
246
        bzrdirb = self.make_bzrdir('b')
247
        repo_b = tree_a.branch.repository.clone(bzrdirb)
248
        tree_b = repo_b.revision_tree('rev1')
2592.3.214 by Robert Collins
Merge bzr.dev.
249
        tree_b.lock_read()
250
        self.addCleanup(tree_b.unlock)
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
251
        tree_b.get_file_text('file1')
252
        rev1 = repo_b.get_revision('rev1')
253
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
254
    def test_iter_inventories_is_ordered(self):
255
        # just a smoke test
256
        tree = self.make_branch_and_tree('a')
257
        first_revision = tree.commit('')
258
        second_revision = tree.commit('')
259
        tree.lock_read()
260
        self.addCleanup(tree.unlock)
261
        revs = (first_revision, second_revision)
262
        invs = tree.branch.repository.iter_inventories(revs)
263
        for rev_id, inv in zip(revs, invs):
264
            self.assertEqual(rev_id, inv.revision_id)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
265
            self.assertIsInstance(inv, inventory.CommonInventory)
3169.2.1 by Robert Collins
New method ``iter_inventories`` on Repository for access to many
266
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
267
    def test_supports_rich_root(self):
268
        tree = self.make_branch_and_tree('a')
269
        tree.commit('')
270
        second_revision = tree.commit('')
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
271
        rev_tree = tree.branch.repository.revision_tree(second_revision)
272
        rev_tree.lock_read()
273
        self.addCleanup(rev_tree.unlock)
274
        inv = rev_tree.inventory
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
275
        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.
276
        self.assertEqual(rich_root,
1910.2.63 by Aaron Bentley
Add supports_rich_root member to repository
277
                         tree.branch.repository.supports_rich_root())
278
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
279
    def test_clone_specific_format(self):
280
        """todo"""
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
281
282
    def test_format_initialize_find_open(self):
283
        # loopback test to check the current format initializes to itself.
284
        if not self.repository_format.is_supported():
285
            # unsupported formats are not loopback testable
286
            # because the default open will not open them and
287
            # they may not be initializable.
288
            return
289
        # supported formats must be able to init and open
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
290
        t = self.get_transport()
291
        readonly_t = self.get_readonly_transport()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
292
        made_control = self.bzrdir_format.initialize(t.base)
293
        made_repo = self.repository_format.initialize(made_control)
294
        self.assertEqual(made_control, made_repo.bzrdir)
295
296
        # find it via bzrdir opening:
297
        opened_control = bzrdir.BzrDir.open(readonly_t.base)
298
        direct_opened_repo = opened_control.open_repository()
299
        self.assertEqual(direct_opened_repo.__class__, made_repo.__class__)
300
        self.assertEqual(opened_control, direct_opened_repo.bzrdir)
301
1752.2.52 by Andrew Bennetts
Flesh out more Remote* methods needed to open and initialise remote branches/trees/repositories.
302
        self.assertIsInstance(direct_opened_repo._format,
303
                              self.repository_format.__class__)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
304
        # find it via Repository.open
305
        opened_repo = repository.Repository.open(readonly_t.base)
306
        self.failUnless(isinstance(opened_repo, made_repo.__class__))
307
        self.assertEqual(made_repo._format.__class__,
308
                         opened_repo._format.__class__)
309
        # if it has a unique id string, can we probe for it ?
310
        try:
311
            self.repository_format.get_format_string()
312
        except NotImplementedError:
313
            return
314
        self.assertEqual(self.repository_format,
315
                         repository.RepositoryFormat.find_format(opened_control))
316
3845.1.1 by John Arbash Meinel
Ensure that RepositoryFormat._matchingbzrdir.repository_format matches.
317
    def test_format_matchingbzrdir(self):
318
        self.assertEqual(self.repository_format,
319
            self.repository_format._matchingbzrdir.repository_format)
320
        self.assertEqual(self.repository_format,
321
            self.bzrdir_format.repository_format)
322
3990.5.1 by Andrew Bennetts
Add network_name() to RepositoryFormat.
323
    def test_format_network_name(self):
324
        repo = self.make_repository('r')
325
        format = repo._format
326
        network_name = format.network_name()
327
        self.assertIsInstance(network_name, str)
328
        # We want to test that the network_name matches the actual format on
329
        # disk.  For local repositories, that means that using network_name as
330
        # a key in the registry gives back the same format.  For remote
331
        # repositories, that means that the network_name of the
332
        # RemoteRepositoryFormat we have locally matches the actual format
333
        # present on the remote side.
334
        if isinstance(format, remote.RemoteRepositoryFormat):
335
            repo._ensure_real()
336
            real_repo = repo._real_repository
337
            self.assertEqual(real_repo._format.network_name(), network_name)
338
        else:
339
            registry = repository.network_format_registry
340
            looked_up_format = registry.get(network_name)
341
            self.assertEqual(format.__class__, looked_up_format.__class__)
342
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
343
    def test_create_repository(self):
1534.6.1 by Robert Collins
allow API creation of shared repositories
344
        # 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.
345
        if not self.bzrdir_format.is_supported():
346
            # unsupported formats are not loopback testable
347
            # because the default open will not open them and
348
            # they may not be initializable.
349
            return
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
350
        t = self.get_transport()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
351
        made_control = self.bzrdir_format.initialize(t.base)
352
        made_repo = made_control.create_repository()
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
353
        # Check that we have a repository object.
354
        made_repo.has_revision('foo')
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
355
        self.assertEqual(made_control, made_repo.bzrdir)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
356
1534.6.1 by Robert Collins
allow API creation of shared repositories
357
    def test_create_repository_shared(self):
358
        # bzrdir can construct a shared repository.
359
        if not self.bzrdir_format.is_supported():
360
            # unsupported formats are not loopback testable
361
            # because the default open will not open them and
362
            # they may not be initializable.
363
            return
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
364
        t = self.get_transport()
1534.6.1 by Robert Collins
allow API creation of shared repositories
365
        made_control = self.bzrdir_format.initialize(t.base)
366
        try:
367
            made_repo = made_control.create_repository(shared=True)
368
        except errors.IncompatibleFormat:
369
            # not all repository formats understand being shared, or
370
            # may only be shared in some circumstances.
371
            return
1752.2.50 by Andrew Bennetts
Implement RemoteBzrDir.create_{branch,workingtree}
372
        # Check that we have a repository object.
373
        made_repo.has_revision('foo')
1534.6.1 by Robert Collins
allow API creation of shared repositories
374
        self.assertEqual(made_control, made_repo.bzrdir)
1534.6.3 by Robert Collins
find_repository sufficiently robust.
375
        self.assertTrue(made_repo.is_shared())
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
376
377
    def test_revision_tree(self):
378
        wt = self.make_branch_and_tree('.')
1731.1.33 by Aaron Bentley
Revert no-special-root changes
379
        wt.set_root_id('fixed-root')
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
380
        wt.commit('lala!', rev_id='revision-1', allow_pointless=True)
381
        tree = wt.branch.repository.revision_tree('revision-1')
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
382
        tree.lock_read()
383
        try:
384
            self.assertEqual('revision-1', tree.inventory.root.revision)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
385
            expected = inventory.InventoryDirectory('fixed-root', '', None)
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
386
            expected.revision = 'revision-1'
387
            self.assertEqual([('', 'V', 'directory', 'fixed-root', expected)],
388
                             list(tree.list_files(include_root=True)))
389
        finally:
390
            tree.unlock()
3668.5.3 by Jelmer Vernooij
Add test to make sure revision_tree(None) prints a deprecation warning.
391
        tree = self.callDeprecated(['NULL_REVISION should be used for the null'
392
            ' revision instead of None, as of bzr 0.91.'],
393
            wt.branch.repository.revision_tree, None)
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
394
        tree.lock_read()
395
        try:
396
            self.assertEqual([], list(tree.list_files(include_root=True)))
397
        finally:
398
            tree.unlock()
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
399
        tree = wt.branch.repository.revision_tree(_mod_revision.NULL_REVISION)
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
400
        tree.lock_read()
401
        try:
402
            self.assertEqual([], list(tree.list_files(include_root=True)))
403
        finally:
404
            tree.unlock()
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
405
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
406
    def test_get_revision_delta(self):
407
        tree_a = self.make_branch_and_tree('a')
2381.1.3 by Robert Collins
Review feedback.
408
        self.build_tree(['a/foo'])
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
409
        tree_a.add('foo', 'file1')
410
        tree_a.commit('rev1', rev_id='rev1')
2381.1.3 by Robert Collins
Review feedback.
411
        self.build_tree(['a/vla'])
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
412
        tree_a.add('vla', 'file2')
413
        tree_a.commit('rev2', rev_id='rev2')
414
415
        delta = tree_a.branch.repository.get_revision_delta('rev1')
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
416
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
417
        self.assertEqual([('foo', 'file1', 'file')], delta.added)
418
        delta = tree_a.branch.repository.get_revision_delta('rev2')
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
419
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
1770.3.3 by Jelmer Vernooij
Add tests for Branch.get_revision_delta() and Repository.get_revision_delta().
420
        self.assertEqual([('vla', 'file2', 'file')], delta.added)
421
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
422
    def test_get_revision_delta_filtered(self):
423
        tree_a = self.make_branch_and_tree('a')
424
        self.build_tree(['a/foo', 'a/bar/', 'a/bar/b1', 'a/bar/b2', 'a/baz'])
425
        tree_a.add(['foo', 'bar', 'bar/b1', 'bar/b2', 'baz'],
426
                   ['foo-id', 'bar-id', 'b1-id', 'b2-id', 'baz-id'])
427
        tree_a.commit('rev1', rev_id='rev1')
428
        self.build_tree(['a/bar/b3'])
429
        tree_a.add('bar/b3', 'b3-id')
430
        tree_a.commit('rev2', rev_id='rev2')
431
432
        # Test multiple files
433
        delta = tree_a.branch.repository.get_revision_delta('rev1',
434
            specific_fileids=['foo-id', 'baz-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
            ('baz', 'baz-id', 'file'),
438
            ('foo', 'foo-id', 'file'),
439
            ], delta.added)
440
        # Test a directory
441
        delta = tree_a.branch.repository.get_revision_delta('rev1',
442
            specific_fileids=['bar-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
443
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
444
        self.assertEqual([
445
            ('bar', 'bar-id', 'directory'),
446
            ('bar/b1', 'b1-id', 'file'),
447
            ('bar/b2', 'b2-id', 'file'),
448
            ], delta.added)
449
        # Test a file in a directory
450
        delta = tree_a.branch.repository.get_revision_delta('rev1',
451
            specific_fileids=['b2-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/b2', 'b2-id', 'file'),
456
            ], delta.added)
457
        # Try another revision
458
        delta = tree_a.branch.repository.get_revision_delta('rev2',
459
                specific_fileids=['b3-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
460
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
461
        self.assertEqual([
462
            ('bar', 'bar-id', 'directory'),
463
            ('bar/b3', 'b3-id', 'file'),
464
            ], delta.added)
465
        delta = tree_a.branch.repository.get_revision_delta('rev2',
466
                specific_fileids=['foo-id'])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
467
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
4137.3.2 by Ian Clatworthy
Repository.get_deltas_for_revisions() now supports file-id filtering
468
        self.assertEqual([], delta.added)
469
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.
470
    def test_clone_bzrdir_repository_revision(self):
471
        # make a repository with some revisions,
472
        # and clone it, this should not have unreferenced revisions.
473
        # 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.
474
        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.
475
476
    def test_clone_repository_basis_revision(self):
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
477
        raise tests.TestSkipped(
478
            '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.
479
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
480
    def test_clone_shared_no_tree(self):
481
        # cloning a shared repository keeps it shared
482
        # and preserves the make_working_tree setting.
483
        made_control = self.make_bzrdir('source')
484
        try:
485
            made_repo = made_control.create_repository(shared=True)
486
        except errors.IncompatibleFormat:
487
            # not all repository formats understand being shared, or
488
            # may only be shared in some circumstances.
489
            return
2018.14.2 by Andrew Bennetts
All but one repository_implementation tests for RemoteRepository passing.
490
        try:
491
            made_repo.set_make_working_trees(False)
492
        except NotImplementedError:
2018.5.120 by Robert Collins
The Repository API ``make_working_trees`` is now permitted to return
493
            # the repository does not support having its tree-making flag
494
            # toggled.
495
            return
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
496
        result = made_control.clone(self.get_url('target'))
1752.2.55 by Andrew Bennetts
Replace another isinstance(made_repo, Repository) check.
497
        # Check that we have a repository object.
498
        made_repo.has_revision('foo')
499
1534.6.5 by Robert Collins
Cloning of repos preserves shared and make-working-tree attributes.
500
        self.assertEqual(made_control, made_repo.bzrdir)
501
        self.assertTrue(result.open_repository().is_shared())
502
        self.assertFalse(result.open_repository().make_working_trees())
503
2018.5.90 by Andrew Bennetts
Fix test_upgrade_preserves_signatures; it incorrectly assumed that upgrade(wt, ...) would necessarily affect the repository.
504
    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.
505
        wt = self.make_branch_and_tree('source')
506
        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.
507
        repo = wt.branch.repository
2592.3.39 by Robert Collins
Fugly version to remove signatures.kndx
508
        repo.lock_write()
509
        repo.start_write_group()
3735.2.100 by Vincent Ladeuil
Fix 3 failing tests due to an amazing typo.
510
        repo.sign_revision('A', gpg.LoopbackGPGStrategy(None))
2592.3.39 by Robert Collins
Fugly version to remove signatures.kndx
511
        repo.commit_write_group()
512
        repo.unlock()
2018.5.90 by Andrew Bennetts
Fix test_upgrade_preserves_signatures; it incorrectly assumed that upgrade(wt, ...) would necessarily affect the repository.
513
        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.
514
        try:
515
            old_format = bzrdir.BzrDirFormat.get_default_format()
516
            # This gives metadir branches something they can convert to.
517
            # it would be nice to have a 'latest' vs 'default' concept.
2255.2.208 by Robert Collins
Remove more references to 'experimental' formats.
518
            format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
519
            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.
520
        except errors.UpToDateFormat:
521
            # this is in the most current format already.
522
            return
1910.2.12 by Aaron Bentley
Implement knit repo format 2
523
        except errors.BadConversionTarget, e:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
524
            raise tests.TestSkipped(str(e))
525
        wt = workingtree.WorkingTree.open(wt.basedir)
1563.2.31 by Robert Collins
Convert Knit repositories to use knits.
526
        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.
527
        self.assertEqual(old_signature, new_signature)
528
1624.3.19 by Olaf Conradi
New call get_format_description to give a user-friendly description of a
529
    def test_format_description(self):
530
        repo = self.make_repository('.')
531
        text = repo._format.get_format_description()
532
        self.failUnless(len(text))
533
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
534
    def test_format_supports_external_lookups(self):
535
        repo = self.make_repository('.')
536
        self.assertSubset(
537
            [repo._format.supports_external_lookups], (True, False))
538
1666.1.6 by Robert Collins
Make knit the default format.
539
    def assertMessageRoundtrips(self, message):
540
        """Assert that message roundtrips to a repository and back intact."""
541
        tree = self.make_branch_and_tree('.')
542
        tree.commit(message, rev_id='a', allow_pointless=True)
543
        rev = tree.branch.repository.get_revision('a')
4416.5.1 by Jelmer Vernooij
Move squashing of XML-invalid characters to XMLSerializer.
544
        if tree.branch.repository._serializer.squashes_xml_invalid_characters:
545
            # we have to manually escape this as we dont try to
4443.1.2 by Jelmer Vernooij
Fix comment about XML escaping in tests.
546
            # roundtrip xml invalid characters in the xml-based serializers.
4416.5.1 by Jelmer Vernooij
Move squashing of XML-invalid characters to XMLSerializer.
547
            escaped_message, escape_count = re.subn(
548
                u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]+',
549
                lambda match: match.group(0).encode('unicode_escape'),
550
                message)
551
            self.assertEqual(rev.message, escaped_message)
552
        else:
553
            self.assertEqual(rev.message, message)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
554
        # insist the class is unicode no matter what came in for
1666.1.6 by Robert Collins
Make knit the default format.
555
        # consistency.
556
        self.assertIsInstance(rev.message, unicode)
557
558
    def test_commit_unicode_message(self):
559
        # a siple unicode message should be preserved
560
        self.assertMessageRoundtrips(u'foo bar gamm\xae plop')
561
562
    def test_commit_unicode_control_characters(self):
563
        # a unicode message with control characters should roundtrip too.
3831.1.4 by John Arbash Meinel
Update the per-repository unicode commit test.
564
        unichars = [unichr(x) for x in range(256)]
565
        # '\r' is not directly allowed anymore, as it used to be translated
566
        # into '\n' anyway
567
        unichars[ord('\r')] = u'\n'
1666.1.6 by Robert Collins
Make knit the default format.
568
        self.assertMessageRoundtrips(
3831.1.4 by John Arbash Meinel
Update the per-repository unicode commit test.
569
            u"All 8-bit chars: " +  ''.join(unichars))
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
570
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
571
    def test_check_repository(self):
572
        """Check a fairly simple repository's history"""
573
        tree = self.make_branch_and_tree('.')
574
        tree.commit('initial empty commit', rev_id='a-rev',
575
                    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.
576
        result = tree.branch.repository.check()
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
577
        # writes to log; should accept both verbose or non-verbose
578
        result.report_results(verbose=True)
579
        result.report_results(verbose=False)
580
1756.1.5 by Aaron Bentley
Test get_revisions with all repository types (and fix bug...)
581
    def test_get_revisions(self):
582
        tree = self.make_branch_and_tree('.')
583
        tree.commit('initial empty commit', rev_id='a-rev',
584
                    allow_pointless=True)
585
        tree.commit('second empty commit', rev_id='b-rev',
586
                    allow_pointless=True)
587
        tree.commit('third empty commit', rev_id='c-rev',
588
                    allow_pointless=True)
589
        repo = tree.branch.repository
590
        revision_ids = ['a-rev', 'b-rev', 'c-rev']
591
        revisions = repo.get_revisions(revision_ids)
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
592
        self.assertEqual(len(revisions), 3)
1756.1.5 by Aaron Bentley
Test get_revisions with all repository types (and fix bug...)
593
        zipped = zip(revisions, revision_ids)
594
        self.assertEqual(len(zipped), 3)
595
        for revision, revision_id in zipped:
596
            self.assertEqual(revision.revision_id, revision_id)
597
            self.assertEqual(revision, repo.get_revision(revision_id))
1732.2.4 by Martin Pool
Split check into Branch.check and Repository.check
598
1910.2.1 by Aaron Bentley
Ensure root entry always has a revision
599
    def test_root_entry_has_revision(self):
600
        tree = self.make_branch_and_tree('.')
601
        tree.commit('message', rev_id='rev_id')
2255.7.65 by Robert Collins
Split test_root_revision_entry into tree and repository portions.
602
        rev_tree = tree.branch.repository.revision_tree(tree.last_revision())
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
603
        rev_tree.lock_read()
604
        self.addCleanup(rev_tree.unlock)
1910.2.6 by Aaron Bentley
Update for merge review, handle deprecations
605
        self.assertEqual('rev_id', rev_tree.inventory.root.revision)
1910.2.1 by Aaron Bentley
Ensure root entry always has a revision
606
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
607
    def test_upgrade_from_format4(self):
608
        from bzrlib.tests.test_upgrade import _upgrade_dir_template
4792.1.2 by Andrew Bennetts
Fix test failure.
609
        if isinstance(self.repository_format, remote.RemoteRepositoryFormat):
610
            return # local conversion to/from RemoteObjects is irrelevant.
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
611
        if self.repository_format.get_format_description() \
612
            == "Repository format 4":
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
613
            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
614
        self.build_tree_contents(_upgrade_dir_template)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
615
        old_repodir = bzrdir.BzrDir.open_unsupported('.')
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
616
        old_repo_format = old_repodir.open_repository()._format
617
        format = self.repository_format._matchingbzrdir
618
        try:
619
            format.repository_format = self.repository_format
620
        except AttributeError:
621
            pass
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
622
        upgrade.upgrade('.', format)
1910.2.36 by Aaron Bentley
Get upgrade from format4 under test and fixed for all formats
623
1910.2.37 by Aaron Bentley
Handle empty commits, fix test
624
    def test_pointless_commit(self):
625
        tree = self.make_branch_and_tree('.')
626
        self.assertRaises(errors.PointlessCommit, tree.commit, 'pointless',
627
                          allow_pointless=False)
628
        tree.commit('pointless', allow_pointless=True)
629
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
630
    def test_format_attributes(self):
631
        """All repository formats should have some basic attributes."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
632
        # create a repository to get a real format instance, not the
3128.1.3 by Vincent Ladeuil
Since we are there s/parameteris.*/parameteriz&/.
633
        # template from the test suite parameterization.
2323.5.17 by Martin Pool
Add supports_tree_reference to all repo formats (robert)
634
        repo = self.make_repository('.')
635
        repo._format.rich_root_data
636
        repo._format.supports_tree_reference
637
2520.4.113 by Aaron Bentley
Avoid peeking at Repository._serializer
638
    def test_get_serializer_format(self):
639
        repo = self.make_repository('.')
640
        format = repo.get_serializer_format()
641
        self.assertEqual(repo._serializer.format_num, format)
642
2708.1.7 by Aaron Bentley
Rename extract_files_bytes to iter_files_bytes
643
    def test_iter_files_bytes(self):
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
644
        tree = self.make_branch_and_tree('tree')
645
        self.build_tree_contents([('tree/file1', 'foo'),
646
                                  ('tree/file2', 'bar')])
647
        tree.add(['file1', 'file2'], ['file1-id', 'file2-id'])
648
        tree.commit('rev1', rev_id='rev1')
649
        self.build_tree_contents([('tree/file1', 'baz')])
650
        tree.commit('rev2', rev_id='rev2')
2708.1.11 by Aaron Bentley
Test and tweak error handling
651
        repository = tree.branch.repository
2592.3.214 by Robert Collins
Merge bzr.dev.
652
        repository.lock_read()
653
        self.addCleanup(repository.unlock)
2708.1.6 by Aaron Bentley
Turn extract_files_bytes into an iterator
654
        extracted = dict((i, ''.join(b)) for i, b in
2708.1.11 by Aaron Bentley
Test and tweak error handling
655
                         repository.iter_files_bytes(
2708.1.6 by Aaron Bentley
Turn extract_files_bytes into an iterator
656
                         [('file1-id', 'rev1', 'file1-old'),
657
                          ('file1-id', 'rev2', 'file1-new'),
658
                          ('file2-id', 'rev1', 'file2'),
659
                         ]))
660
        self.assertEqual('foo', extracted['file1-old'])
661
        self.assertEqual('bar', extracted['file2'])
662
        self.assertEqual('baz', extracted['file1-new'])
2708.1.11 by Aaron Bentley
Test and tweak error handling
663
        self.assertRaises(errors.RevisionNotPresent, list,
664
                          repository.iter_files_bytes(
665
                          [('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.
666
        self.assertRaises((errors.RevisionNotPresent, errors.NoSuchId), list,
2708.1.11 by Aaron Bentley
Test and tweak error handling
667
                          repository.iter_files_bytes(
668
                          [('file3-id', 'rev3', 'file1-notpresent')]))
2708.1.3 by Aaron Bentley
Implement extract_files_bytes on Repository
669
2535.3.63 by Andrew Bennetts
Add repository implementations test for item_keys_introduced_by.
670
    def test_item_keys_introduced_by(self):
671
        # Make a repo with one revision and one versioned file.
672
        tree = self.make_branch_and_tree('t')
673
        self.build_tree(['t/foo'])
674
        tree.add('foo', 'file1')
675
        tree.commit('message', rev_id='rev_id')
676
        repo = tree.branch.repository
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
677
        repo.lock_write()
678
        repo.start_write_group()
3735.2.100 by Vincent Ladeuil
Fix 3 failing tests due to an amazing typo.
679
        repo.sign_revision('rev_id', gpg.LoopbackGPGStrategy(None))
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
680
        repo.commit_write_group()
681
        repo.unlock()
3381.1.3 by Aaron Bentley
Stop locking in get_data_stream_for_search
682
        repo.lock_read()
683
        self.addCleanup(repo.unlock)
2535.3.63 by Andrew Bennetts
Add repository implementations test for item_keys_introduced_by.
684
685
        # Item keys will be in this order, for maximum convenience for
686
        # generating data to insert into knit repository:
687
        #   * files
688
        #   * inventory
689
        #   * signatures
690
        #   * revisions
691
        expected_item_keys = [
692
            ('file', 'file1', ['rev_id']),
693
            ('inventory', None, ['rev_id']),
3825.5.2 by Andrew Bennetts
Ensure that item_keys_introduced_by returns the
694
            ('signatures', None, ['rev_id']),
2535.3.63 by Andrew Bennetts
Add repository implementations test for item_keys_introduced_by.
695
            ('revisions', None, ['rev_id'])]
696
        item_keys = list(repo.item_keys_introduced_by(['rev_id']))
697
        item_keys = [
698
            (kind, file_id, list(versions))
699
            for (kind, file_id, versions) in item_keys]
700
701
        if repo.supports_rich_root():
702
            # Check for the root versioned file in the item_keys, then remove
703
            # it from streamed_names so we can compare that with
704
            # expected_record_names.
705
            # Note that the file keys can be in any order, so this test is
706
            # written to allow that.
707
            inv = repo.get_inventory('rev_id')
708
            root_item_key = ('file', inv.root.file_id, ['rev_id'])
709
            self.assertTrue(root_item_key in item_keys)
710
            item_keys.remove(root_item_key)
711
712
        self.assertEqual(expected_item_keys, item_keys)
713
2850.4.1 by Andrew Bennetts
Add smoketest for repo.get_graph, and fix bug in RemoteRepository.get_graph that it reveals.
714
    def test_get_graph(self):
715
        """Bare-bones smoketest that all repositories implement get_graph."""
716
        repo = self.make_repository('repo')
2592.3.214 by Robert Collins
Merge bzr.dev.
717
        repo.lock_read()
718
        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.
719
        repo.get_graph()
720
3146.1.1 by Aaron Bentley
Fix bad ghost handling in KnitParentsProvider
721
    def test_graph_ghost_handling(self):
722
        tree = self.make_branch_and_tree('here')
723
        tree.lock_write()
724
        self.addCleanup(tree.unlock)
725
        tree.commit('initial commit', rev_id='rev1')
726
        tree.add_parent_tree_id('ghost')
727
        tree.commit('commit-with-ghost', rev_id='rev2')
728
        graph = tree.branch.repository.get_graph()
729
        parents = graph.get_parent_map(['ghost', 'rev2'])
730
        self.assertTrue('ghost' not in parents)
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
731
        self.assertEqual(parents['rev2'], ('rev1', 'ghost'))
732
4913.4.4 by Jelmer Vernooij
Add test for Repository.get_known_graph_ancestry().
733
    def test_get_known_graph_ancestry(self):
734
        tree = self.make_branch_and_tree('here')
735
        tree.lock_write()
736
        self.addCleanup(tree.unlock)
737
        # A
738
        # |\
739
        # | B
740
        # |/
741
        # C
742
        tree.commit('initial commit', rev_id='A')
743
        tree_other = tree.bzrdir.sprout('there').open_workingtree()
744
        tree_other.commit('another', rev_id='B')
745
        tree.merge_from_branch(tree_other.branch)
746
        tree.commit('another', rev_id='C')
747
        kg = tree.branch.repository.get_known_graph_ancestry(
748
            ['C'])
749
        self.assertEqual(['C'], list(kg.heads(['A', 'B', 'C'])))
750
        self.assertEqual(['A', 'B', 'C'], list(kg.topo_sort()))
751
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
752
    def test_parent_map_type(self):
753
        tree = self.make_branch_and_tree('here')
754
        tree.lock_write()
755
        self.addCleanup(tree.unlock)
756
        tree.commit('initial commit', rev_id='rev1')
757
        tree.commit('next commit', rev_id='rev2')
758
        graph = tree.branch.repository.get_graph()
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
759
        parents = graph.get_parent_map(
760
            [_mod_revision.NULL_REVISION, 'rev1', 'rev2'])
3146.1.2 by Aaron Bentley
ParentsProviders now provide tuples of parents, never lists
761
        for value in parents.values():
762
            self.assertIsInstance(value, tuple)
3146.1.1 by Aaron Bentley
Fix bad ghost handling in KnitParentsProvider
763
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
764
    def test_implements_revision_graph_can_have_wrong_parents(self):
765
        """All repositories should implement
766
        revision_graph_can_have_wrong_parents, so that check and reconcile can
767
        work correctly.
768
        """
769
        repo = self.make_repository('.')
770
        # This should work, not raise NotImplementedError:
2592.3.214 by Robert Collins
Merge bzr.dev.
771
        if not repo.revision_graph_can_have_wrong_parents():
772
            return
773
        repo.lock_read()
774
        self.addCleanup(repo.unlock)
775
        # This repo must also implement
776
        # _find_inconsistent_revision_parents and
777
        # _check_for_inconsistent_revision_parents.  So calling these
778
        # should not raise NotImplementedError.
779
        list(repo._find_inconsistent_revision_parents())
780
        repo._check_for_inconsistent_revision_parents()
2819.2.4 by Andrew Bennetts
Add a 'revision_graph_can_have_wrong_parents' method to repository.
781
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
782
    def test_add_signature_text(self):
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
783
        repo = self.make_repository('repo')
784
        repo.lock_write()
785
        self.addCleanup(repo.unlock)
786
        repo.start_write_group()
4634.35.16 by Andrew Bennetts
Fix more test fallout.
787
        self.addCleanup(repo.abort_write_group)
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
788
        inv = inventory.Inventory(revision_id='A')
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
789
        inv.root.revision = 'A'
790
        repo.add_inventory('A', inv, [])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
791
        repo.add_revision('A', _mod_revision.Revision(
792
                'A', committer='A', timestamp=0,
793
                inventory_sha1='', timezone=0, message='A'))
2996.2.4 by Aaron Bentley
Rename function to add_signature_text
794
        repo.add_signature_text('A', 'This might be a signature')
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
795
        self.assertEqual('This might be a signature',
796
                         repo.get_signature_text('A'))
797
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
798
    def test_add_revision_inventory_sha1(self):
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
799
        inv = inventory.Inventory(revision_id='A')
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
800
        inv.root.revision = 'A'
801
        inv.root.file_id = 'fixed-root'
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
802
        # Insert the inventory on its own to an identical repository, to get
803
        # its sha1.
804
        reference_repo = self.make_repository('reference_repo')
805
        reference_repo.lock_write()
806
        reference_repo.start_write_group()
807
        inv_sha1 = reference_repo.add_inventory('A', inv, [])
808
        reference_repo.abort_write_group()
809
        reference_repo.unlock()
810
        # Now insert a revision with this inventory, and it should get the same
811
        # sha1.
812
        repo = self.make_repository('repo')
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
813
        repo.lock_write()
814
        repo.start_write_group()
4634.35.16 by Andrew Bennetts
Fix more test fallout.
815
        root_id = inv.root.file_id
816
        repo.texts.add_lines(('fixed-root', 'A'), [], [])
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
817
        repo.add_revision('A', _mod_revision.Revision(
818
                'A', committer='B', timestamp=0,
819
                timezone=0, message='C'), inv=inv)
3305.1.1 by Jelmer Vernooij
Make sure that specifying the inv= argument to add_revision() sets the
820
        repo.commit_write_group()
821
        repo.unlock()
822
        repo.lock_read()
4253.3.1 by Robert Collins
per_repository/test_repository improvements (Robert Collins)
823
        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
824
        repo.unlock()
825
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
826
    def test_install_revisions(self):
827
        wt = self.make_branch_and_tree('source')
828
        wt.commit('A', allow_pointless=True, rev_id='A')
829
        repo = wt.branch.repository
830
        repo.lock_write()
831
        repo.start_write_group()
3735.2.100 by Vincent Ladeuil
Fix 3 failing tests due to an amazing typo.
832
        repo.sign_revision('A', gpg.LoopbackGPGStrategy(None))
2996.2.3 by Aaron Bentley
Add tests for install_revisions and add_signature
833
        repo.commit_write_group()
834
        repo.unlock()
835
        repo.lock_read()
836
        self.addCleanup(repo.unlock)
837
        repo2 = self.make_repository('repo2')
838
        revision = repo.get_revision('A')
839
        tree = repo.revision_tree('A')
840
        signature = repo.get_signature_text('A')
841
        repo2.lock_write()
842
        self.addCleanup(repo2.unlock)
843
        repository.install_revisions(repo2, [(revision, tree, signature)])
844
        self.assertEqual(revision, repo2.get_revision('A'))
845
        self.assertEqual(signature, repo2.get_signature_text('A'))
1852.9.6 by Robert Collins
Merge the change from Tree.compare to Tree.changes_from.
846
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
847
    # 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.
848
    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.
849
        """Make a RemoteRepository object backed by a real repository that will
850
        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.
851
        repo = self.make_repository(path, shared=shared)
5017.3.42 by Vincent Ladeuil
-s bt.per_repository.test_repo passing
852
        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,
853
        self.start_server(smart_server, self.get_server())
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
854
        remote_transport = transport.get_transport(
855
            smart_server.get_url()).clone(path)
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
856
        remote_bzrdir = bzrdir.BzrDir.open_from_transport(remote_transport)
857
        remote_repo = remote_bzrdir.open_repository()
858
        return remote_repo
859
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
860
    def test_sprout_from_hpss_preserves_format(self):
861
        """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.
862
        remote_repo = self.make_remote_repository('remote')
863
        local_bzrdir = self.make_bzrdir('local')
864
        try:
865
            local_repo = remote_repo.sprout(local_bzrdir)
866
        except errors.TransportNotPossible:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
867
            raise tests.TestNotApplicable(
3047.1.1 by Andrew Bennetts
Fix for bug 164626, add test that Repository.sprout preserves format.
868
                "Cannot lock_read old formats like AllInOne over HPSS.")
869
        remote_backing_repo = bzrdir.BzrDir.open(
870
            self.get_vfs_only_url('remote')).open_repository()
871
        self.assertEqual(remote_backing_repo._format, local_repo._format)
872
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
873
    def test_sprout_branch_from_hpss_preserves_repo_format(self):
874
        """branch.sprout from a smart server preserves the repository format.
875
        """
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
876
        if not self.repository_format.supports_leaving_lock:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
877
            raise tests.TestNotApplicable(
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
878
                "Format can not be used over HPSS")
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
879
        remote_repo = self.make_remote_repository('remote')
880
        remote_branch = remote_repo.bzrdir.create_branch()
881
        try:
882
            local_bzrdir = remote_branch.bzrdir.sprout('local')
883
        except errors.TransportNotPossible:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
884
            raise tests.TestNotApplicable(
3047.1.2 by Andrew Bennetts
Directly test that sprouting branches from a HPSS preserves the repository format.
885
                "Cannot lock_read old formats like AllInOne over HPSS.")
886
        local_repo = local_bzrdir.open_repository()
887
        remote_backing_repo = bzrdir.BzrDir.open(
888
            self.get_vfs_only_url('remote')).open_repository()
889
        self.assertEqual(remote_backing_repo._format, local_repo._format)
890
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
891
    def test_sprout_branch_from_hpss_preserves_shared_repo_format(self):
892
        """branch.sprout from a smart server preserves the repository format of
893
        a branch from a shared repository.
894
        """
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
895
        if not self.repository_format.supports_leaving_lock:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
896
            raise tests.TestNotApplicable(
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
897
                "Format can not be used over HPSS")
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
898
        # Make a shared repo
899
        remote_repo = self.make_remote_repository('remote', shared=True)
900
        remote_backing_repo = bzrdir.BzrDir.open(
901
            self.get_vfs_only_url('remote')).open_repository()
902
        # Make a branch in that repo in an old format that isn't the default
903
        # branch format for the repo.
904
        from bzrlib.branch import BzrBranchFormat5
905
        format = remote_backing_repo.bzrdir.cloning_metadir()
906
        format._branch_format = BzrBranchFormat5()
907
        remote_transport = remote_repo.bzrdir.root_transport.clone('branch')
908
        remote_backing_repo.bzrdir.create_branch_convenience(
909
            remote_transport.base, force_new_repo=False, format=format)
910
        remote_branch = bzrdir.BzrDir.open_from_transport(
911
            remote_transport).open_branch()
912
        try:
913
            local_bzrdir = remote_branch.bzrdir.sprout('local')
914
        except errors.TransportNotPossible:
5010.2.6 by Vincent Ladeuil
Fix per_repository/test_repository.py imports.
915
            raise tests.TestNotApplicable(
3697.6.2 by Andrew Bennetts
Add test for preserving shared repository format when sprouting from a smart server.
916
                "Cannot lock_read old formats like AllInOne over HPSS.")
917
        local_repo = local_bzrdir.open_repository()
918
        self.assertEqual(remote_backing_repo._format, local_repo._format)
919
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
920
    def test_clone_to_hpss(self):
5674.1.1 by Jelmer Vernooij
Add supports_leave_lock flag to BranchFormat and RepositoryFormat.
921
        if not self.repository_format.supports_leaving_lock:
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')
5673.1.3 by Jelmer Vernooij
Change flexible_components to fixed_components.
940
        if repo.bzrdir._format.fixed_components:
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
class TestRepositoryControlComponent(per_repository.TestCaseWithRepository):
1351
    """Repository implementations adequately implement ControlComponent."""
5673.1.1 by Jelmer Vernooij
Add flexible_components boolean to ControlDir if the
1352
5158.6.4 by Martin Pool
Repository implements ControlComponent too
1353
    def test_urls(self):
1354
        repo = self.make_repository('repo')
1355
        self.assertIsInstance(repo.user_url, str)
1356
        self.assertEqual(repo.user_url, repo.user_transport.base)
1357
        # for all current bzrdir implementations the user dir must be 
1358
        # above the control dir but we might need to relax that?
1359
        self.assertEqual(repo.control_url.find(repo.user_url), 0)
1360
        self.assertEqual(repo.control_url, repo.control_transport.base)