~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_bzrdir.py

  • Committer: Robert Collins
  • Date: 2007-07-04 01:39:50 UTC
  • mto: This revision was merged to the branch mainline in revision 2581.
  • Revision ID: robertc@robertcollins.net-20070704013950-7pp23plwyqjvgkxg
Review feedback.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
2
 
#
 
1
    # Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for the BzrDir facility and any format specific tests.
18
18
 
19
 
For interface contract tests, see tests/per_bzr_dir.
 
19
For interface contract tests, see tests/bzr_dir_implementations.
20
20
"""
21
21
 
22
 
import os
23
 
import subprocess
24
 
import sys
 
22
import os.path
 
23
from StringIO import StringIO
25
24
 
26
25
from bzrlib import (
27
 
    branch,
28
26
    bzrdir,
29
 
    config,
30
 
    controldir,
31
27
    errors,
32
28
    help_topics,
33
 
    lock,
34
29
    repository,
35
 
    revision as _mod_revision,
36
 
    osutils,
37
 
    remote,
38
30
    symbol_versioning,
39
 
    transport as _mod_transport,
40
31
    urlutils,
41
 
    win32utils,
42
 
    workingtree_3,
43
 
    workingtree_4,
 
32
    workingtree,
44
33
    )
45
34
import bzrlib.branch
46
 
from bzrlib.errors import (
47
 
    NotBranchError,
48
 
    NoColocatedBranchSupport,
49
 
    UnknownFormatError,
50
 
    UnsupportedFormatError,
51
 
    )
 
35
from bzrlib.errors import (NotBranchError,
 
36
                           UnknownFormatError,
 
37
                           UnsupportedFormatError,
 
38
                           )
52
39
from bzrlib.tests import (
53
40
    TestCase,
54
 
    TestCaseWithMemoryTransport,
55
41
    TestCaseWithTransport,
56
 
    TestSkipped,
 
42
    test_sftp_transport
57
43
    )
58
 
from bzrlib.tests import(
59
 
    http_server,
60
 
    http_utils,
 
44
from bzrlib.tests.HttpServer import HttpServer
 
45
from bzrlib.tests.HTTPTestUtil import (
 
46
    TestCaseWithTwoWebservers,
 
47
    HTTPServerRedirecting,
61
48
    )
62
49
from bzrlib.tests.test_http import TestWithTransport_pycurl
63
 
from bzrlib.transport import (
64
 
    memory,
65
 
    pathfilter,
66
 
    )
 
50
from bzrlib.transport import get_transport
67
51
from bzrlib.transport.http._urllib import HttpTransport_urllib
68
 
from bzrlib.transport.nosmart import NoSmartTransportDecorator
69
 
from bzrlib.transport.readonly import ReadonlyTransportDecorator
70
 
from bzrlib.repofmt import knitrepo, knitpack_repo
 
52
from bzrlib.transport.memory import MemoryServer
 
53
from bzrlib.repofmt import knitrepo, weaverepo
71
54
 
72
55
 
73
56
class TestDefaultFormat(TestCase):
74
57
 
75
58
    def test_get_set_default_format(self):
76
59
        old_format = bzrdir.BzrDirFormat.get_default_format()
77
 
        # default is BzrDirMetaFormat1
78
 
        self.assertIsInstance(old_format, bzrdir.BzrDirMetaFormat1)
79
 
        controldir.ControlDirFormat._set_default_format(SampleBzrDirFormat())
 
60
        # default is BzrDirFormat6
 
61
        self.failUnless(isinstance(old_format, bzrdir.BzrDirMetaFormat1))
 
62
        self.applyDeprecated(symbol_versioning.zero_fourteen, 
 
63
                             bzrdir.BzrDirFormat.set_default_format, 
 
64
                             SampleBzrDirFormat())
80
65
        # creating a bzr dir should now create an instrumented dir.
81
66
        try:
82
67
            result = bzrdir.BzrDir.create('memory:///')
83
 
            self.assertIsInstance(result, SampleBzrDir)
 
68
            self.failUnless(isinstance(result, SampleBzrDir))
84
69
        finally:
85
 
            controldir.ControlDirFormat._set_default_format(old_format)
 
70
            self.applyDeprecated(symbol_versioning.zero_fourteen,
 
71
                bzrdir.BzrDirFormat.set_default_format, old_format)
86
72
        self.assertEqual(old_format, bzrdir.BzrDirFormat.get_default_format())
87
73
 
88
74
 
89
 
class DeprecatedBzrDirFormat(bzrdir.BzrDirFormat):
90
 
    """A deprecated bzr dir format."""
91
 
 
92
 
 
93
75
class TestFormatRegistry(TestCase):
94
76
 
95
77
    def make_format_registry(self):
96
 
        my_format_registry = controldir.ControlDirFormatRegistry()
97
 
        my_format_registry.register('deprecated', DeprecatedBzrDirFormat,
98
 
            'Some format.  Slower and unawesome and deprecated.',
99
 
            deprecated=True)
100
 
        my_format_registry.register_lazy('lazy', 'bzrlib.tests.test_bzrdir',
101
 
            'DeprecatedBzrDirFormat', 'Format registered lazily',
102
 
            deprecated=True)
103
 
        bzrdir.register_metadir(my_format_registry, 'knit',
 
78
        my_format_registry = bzrdir.BzrDirFormatRegistry()
 
79
        my_format_registry.register('weave', bzrdir.BzrDirFormat6,
 
80
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
81
            ' repositories', deprecated=True)
 
82
        my_format_registry.register_lazy('lazy', 'bzrlib.bzrdir', 
 
83
            'BzrDirFormat6', 'Format registered lazily', deprecated=True)
 
84
        my_format_registry.register_metadir('knit',
104
85
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
105
86
            'Format using knits',
106
87
            )
107
88
        my_format_registry.set_default('knit')
108
 
        bzrdir.register_metadir(my_format_registry,
 
89
        my_format_registry.register_metadir(
109
90
            'branch6',
110
91
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
111
92
            'Experimental successor to knit.  Use at your own risk.',
112
 
            branch_format='bzrlib.branch.BzrBranchFormat6',
113
 
            experimental=True)
114
 
        bzrdir.register_metadir(my_format_registry,
 
93
            branch_format='bzrlib.branch.BzrBranchFormat6')
 
94
        my_format_registry.register_metadir(
115
95
            'hidden format',
116
96
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
117
97
            'Experimental successor to knit.  Use at your own risk.',
118
98
            branch_format='bzrlib.branch.BzrBranchFormat6', hidden=True)
119
 
        my_format_registry.register('hiddendeprecated', DeprecatedBzrDirFormat,
120
 
            'Old format.  Slower and does not support things. ', hidden=True)
121
 
        my_format_registry.register_lazy('hiddenlazy', 'bzrlib.tests.test_bzrdir',
122
 
            'DeprecatedBzrDirFormat', 'Format registered lazily',
123
 
            deprecated=True, hidden=True)
 
99
        my_format_registry.register('hiddenweave', bzrdir.BzrDirFormat6,
 
100
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
101
            ' repositories', hidden=True)
 
102
        my_format_registry.register_lazy('hiddenlazy', 'bzrlib.bzrdir',
 
103
            'BzrDirFormat6', 'Format registered lazily', deprecated=True,
 
104
            hidden=True)
124
105
        return my_format_registry
125
106
 
126
107
    def test_format_registry(self):
127
108
        my_format_registry = self.make_format_registry()
128
109
        my_bzrdir = my_format_registry.make_bzrdir('lazy')
129
 
        self.assertIsInstance(my_bzrdir, DeprecatedBzrDirFormat)
130
 
        my_bzrdir = my_format_registry.make_bzrdir('deprecated')
131
 
        self.assertIsInstance(my_bzrdir, DeprecatedBzrDirFormat)
 
110
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
 
111
        my_bzrdir = my_format_registry.make_bzrdir('weave')
 
112
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
132
113
        my_bzrdir = my_format_registry.make_bzrdir('default')
133
 
        self.assertIsInstance(my_bzrdir.repository_format,
 
114
        self.assertIsInstance(my_bzrdir.repository_format, 
134
115
            knitrepo.RepositoryFormatKnit1)
135
116
        my_bzrdir = my_format_registry.make_bzrdir('knit')
136
 
        self.assertIsInstance(my_bzrdir.repository_format,
 
117
        self.assertIsInstance(my_bzrdir.repository_format, 
137
118
            knitrepo.RepositoryFormatKnit1)
138
119
        my_bzrdir = my_format_registry.make_bzrdir('branch6')
139
120
        self.assertIsInstance(my_bzrdir.get_branch_format(),
143
124
        my_format_registry = self.make_format_registry()
144
125
        self.assertEqual('Format registered lazily',
145
126
                         my_format_registry.get_help('lazy'))
146
 
        self.assertEqual('Format using knits',
 
127
        self.assertEqual('Format using knits', 
147
128
                         my_format_registry.get_help('knit'))
148
 
        self.assertEqual('Format using knits',
 
129
        self.assertEqual('Format using knits', 
149
130
                         my_format_registry.get_help('default'))
150
 
        self.assertEqual('Some format.  Slower and unawesome and deprecated.',
151
 
                         my_format_registry.get_help('deprecated'))
152
 
 
 
131
        self.assertEqual('Pre-0.8 format.  Slower and does not support'
 
132
                         ' checkouts or shared repositories', 
 
133
                         my_format_registry.get_help('weave'))
 
134
        
153
135
    def test_help_topic(self):
154
136
        topics = help_topics.HelpTopicRegistry()
155
 
        registry = self.make_format_registry()
156
 
        topics.register('current-formats', registry.help_topic,
157
 
                        'Current formats')
158
 
        topics.register('other-formats', registry.help_topic,
159
 
                        'Other formats')
160
 
        new = topics.get_detail('current-formats')
161
 
        rest = topics.get_detail('other-formats')
162
 
        experimental, deprecated = rest.split('Deprecated formats')
163
 
        self.assertContainsRe(new, 'formats-help')
164
 
        self.assertContainsRe(new,
165
 
                ':knit:\n    \(native\) \(default\) Format using knits\n')
166
 
        self.assertContainsRe(experimental,
167
 
                ':branch6:\n    \(native\) Experimental successor to knit')
168
 
        self.assertContainsRe(deprecated,
169
 
                ':lazy:\n    \(native\) Format registered lazily\n')
 
137
        topics.register('formats', self.make_format_registry().help_topic, 
 
138
                        'Directory formats')
 
139
        topic = topics.get_detail('formats')
 
140
        new, deprecated = topic.split('Deprecated formats')
 
141
        self.assertContainsRe(new, 'Bazaar directory formats')
 
142
        self.assertContainsRe(new, 
 
143
            '  knit/default:\n    \(native\) Format using knits\n')
 
144
        self.assertContainsRe(deprecated, 
 
145
            '  lazy:\n    \(native\) Format registered lazily\n')
170
146
        self.assertNotContainsRe(new, 'hidden')
171
147
 
172
148
    def test_set_default_repository(self):
178
154
            self.assertIs(bzrdir.format_registry.get('dirstate-with-subtree'),
179
155
                          bzrdir.format_registry.get('default'))
180
156
            self.assertIs(
181
 
                repository.format_registry.get_default().__class__,
 
157
                repository.RepositoryFormat.get_default_format().__class__,
182
158
                knitrepo.RepositoryFormatKnit3)
183
159
        finally:
184
160
            bzrdir.format_registry.set_default_repository(old_default)
185
161
 
186
 
    def test_aliases(self):
187
 
        a_registry = controldir.ControlDirFormatRegistry()
188
 
        a_registry.register('deprecated', DeprecatedBzrDirFormat,
189
 
            'Old format.  Slower and does not support stuff',
190
 
            deprecated=True)
191
 
        a_registry.register('deprecatedalias', DeprecatedBzrDirFormat,
192
 
            'Old format.  Slower and does not support stuff',
193
 
            deprecated=True, alias=True)
194
 
        self.assertEqual(frozenset(['deprecatedalias']), a_registry.aliases())
195
 
 
196
162
 
197
163
class SampleBranch(bzrlib.branch.Branch):
198
164
    """A dummy branch for guess what, dummy use."""
201
167
        self.bzrdir = dir
202
168
 
203
169
 
204
 
class SampleRepository(bzrlib.repository.Repository):
205
 
    """A dummy repo."""
206
 
 
207
 
    def __init__(self, dir):
208
 
        self.bzrdir = dir
209
 
 
210
 
 
211
170
class SampleBzrDir(bzrdir.BzrDir):
212
171
    """A sample BzrDir implementation to allow testing static methods."""
213
172
 
217
176
 
218
177
    def open_repository(self):
219
178
        """See BzrDir.open_repository."""
220
 
        return SampleRepository(self)
 
179
        return "A repository"
221
180
 
222
 
    def create_branch(self, name=None):
 
181
    def create_branch(self):
223
182
        """See BzrDir.create_branch."""
224
 
        if name is not None:
225
 
            raise NoColocatedBranchSupport(self)
226
183
        return SampleBranch(self)
227
184
 
228
185
    def create_workingtree(self):
233
190
class SampleBzrDirFormat(bzrdir.BzrDirFormat):
234
191
    """A sample format
235
192
 
236
 
    this format is initializable, unsupported to aid in testing the
 
193
    this format is initializable, unsupported to aid in testing the 
237
194
    open and open_downlevel routines.
238
195
    """
239
196
 
241
198
        """See BzrDirFormat.get_format_string()."""
242
199
        return "Sample .bzr dir format."
243
200
 
244
 
    def initialize_on_transport(self, t):
 
201
    def initialize(self, url):
245
202
        """Create a bzr dir."""
 
203
        t = get_transport(url)
246
204
        t.mkdir('.bzr')
247
205
        t.put_bytes('.bzr/branch-format', self.get_format_string())
248
206
        return SampleBzrDir(t, self)
254
212
        return "opened branch."
255
213
 
256
214
 
257
 
class BzrDirFormatTest1(bzrdir.BzrDirMetaFormat1):
258
 
 
259
 
    @staticmethod
260
 
    def get_format_string():
261
 
        return "Test format 1"
262
 
 
263
 
 
264
 
class BzrDirFormatTest2(bzrdir.BzrDirMetaFormat1):
265
 
 
266
 
    @staticmethod
267
 
    def get_format_string():
268
 
        return "Test format 2"
269
 
 
270
 
 
271
215
class TestBzrDirFormat(TestCaseWithTransport):
272
216
    """Tests for the BzrDirFormat facility."""
273
217
 
274
218
    def test_find_format(self):
275
219
        # is the right format object found for a branch?
276
220
        # create a branch with a few known format objects.
277
 
        bzrdir.BzrProber.formats.register(BzrDirFormatTest1.get_format_string(),
278
 
            BzrDirFormatTest1())
279
 
        self.addCleanup(bzrdir.BzrProber.formats.remove,
280
 
            BzrDirFormatTest1.get_format_string())
281
 
        bzrdir.BzrProber.formats.register(BzrDirFormatTest2.get_format_string(),
282
 
            BzrDirFormatTest2())
283
 
        self.addCleanup(bzrdir.BzrProber.formats.remove,
284
 
            BzrDirFormatTest2.get_format_string())
285
 
        t = self.get_transport()
 
221
        # this is not quite the same as 
 
222
        t = get_transport(self.get_url())
286
223
        self.build_tree(["foo/", "bar/"], transport=t)
287
224
        def check_format(format, url):
288
225
            format.initialize(url)
289
 
            t = _mod_transport.get_transport_from_path(url)
 
226
            t = get_transport(url)
290
227
            found_format = bzrdir.BzrDirFormat.find_format(t)
291
 
            self.assertIsInstance(found_format, format.__class__)
292
 
        check_format(BzrDirFormatTest1(), "foo")
293
 
        check_format(BzrDirFormatTest2(), "bar")
294
 
 
 
228
            self.failUnless(isinstance(found_format, format.__class__))
 
229
        check_format(bzrdir.BzrDirFormat5(), "foo")
 
230
        check_format(bzrdir.BzrDirFormat6(), "bar")
 
231
        
295
232
    def test_find_format_nothing_there(self):
296
233
        self.assertRaises(NotBranchError,
297
234
                          bzrdir.BzrDirFormat.find_format,
298
 
                          _mod_transport.get_transport_from_path('.'))
 
235
                          get_transport('.'))
299
236
 
300
237
    def test_find_format_unknown_format(self):
301
 
        t = self.get_transport()
 
238
        t = get_transport(self.get_url())
302
239
        t.mkdir('.bzr')
303
240
        t.put_bytes('.bzr/branch-format', '')
304
241
        self.assertRaises(UnknownFormatError,
305
242
                          bzrdir.BzrDirFormat.find_format,
306
 
                          _mod_transport.get_transport_from_path('.'))
 
243
                          get_transport('.'))
307
244
 
308
245
    def test_register_unregister_format(self):
309
246
        format = SampleBzrDirFormat()
311
248
        # make a bzrdir
312
249
        format.initialize(url)
313
250
        # register a format for it.
314
 
        bzrdir.BzrProber.formats.register(format.get_format_string(), format)
 
251
        bzrdir.BzrDirFormat.register_format(format)
315
252
        # which bzrdir.Open will refuse (not supported)
316
253
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open, url)
317
254
        # which bzrdir.open_containing will refuse (not supported)
318
255
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open_containing, url)
319
256
        # but open_downlevel will work
320
 
        t = _mod_transport.get_transport_from_url(url)
 
257
        t = get_transport(url)
321
258
        self.assertEqual(format.open(t), bzrdir.BzrDir.open_unsupported(url))
322
259
        # unregister the format
323
 
        bzrdir.BzrProber.formats.remove(format.get_format_string())
 
260
        bzrdir.BzrDirFormat.unregister_format(format)
324
261
        # now open_downlevel should fail too.
325
262
        self.assertRaises(UnknownFormatError, bzrdir.BzrDir.open_unsupported, url)
326
263
 
 
264
    def test_create_repository(self):
 
265
        format = SampleBzrDirFormat()
 
266
        repo = bzrdir.BzrDir.create_repository(self.get_url(), format=format)
 
267
        self.assertEqual('A repository', repo)
 
268
 
 
269
    def test_create_repository_shared(self):
 
270
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
271
        repo = bzrdir.BzrDir.create_repository('.', shared=True)
 
272
        self.assertTrue(repo.is_shared())
 
273
 
 
274
    def test_create_repository_nonshared(self):
 
275
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
276
        repo = bzrdir.BzrDir.create_repository('.')
 
277
        self.assertFalse(repo.is_shared())
 
278
 
 
279
    def test_create_repository_under_shared(self):
 
280
        # an explicit create_repository always does so.
 
281
        # we trust the format is right from the 'create_repository test'
 
282
        format = bzrdir.format_registry.make_bzrdir('knit')
 
283
        self.make_repository('.', shared=True, format=format)
 
284
        repo = bzrdir.BzrDir.create_repository(self.get_url('child'),
 
285
                                               format=format)
 
286
        self.assertTrue(isinstance(repo, repository.Repository))
 
287
        self.assertTrue(repo.bzrdir.root_transport.base.endswith('child/'))
 
288
 
327
289
    def test_create_branch_and_repo_uses_default(self):
328
290
        format = SampleBzrDirFormat()
329
 
        branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url(),
 
291
        branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url(), 
330
292
                                                      format=format)
331
293
        self.assertTrue(isinstance(branch, SampleBranch))
332
294
 
341
303
                          branch.bzrdir.open_repository)
342
304
 
343
305
    def test_create_branch_and_repo_under_shared_force_new(self):
344
 
        # creating a branch and repo in a shared repo can be forced to
 
306
        # creating a branch and repo in a shared repo can be forced to 
345
307
        # make a new repo
346
308
        format = bzrdir.format_registry.make_bzrdir('knit')
347
309
        self.make_repository('.', shared=True, format=format)
352
314
 
353
315
    def test_create_standalone_working_tree(self):
354
316
        format = SampleBzrDirFormat()
355
 
        # note this is deliberately readonly, as this failure should
 
317
        # note this is deliberately readonly, as this failure should 
356
318
        # occur before any writes.
357
319
        self.assertRaises(errors.NotLocalUrl,
358
320
                          bzrdir.BzrDir.create_standalone_workingtree,
359
321
                          self.get_readonly_url(), format=format)
360
 
        tree = bzrdir.BzrDir.create_standalone_workingtree('.',
 
322
        tree = bzrdir.BzrDir.create_standalone_workingtree('.', 
361
323
                                                           format=format)
362
324
        self.assertEqual('A tree', tree)
363
325
 
365
327
        # create standalone working tree always makes a repo.
366
328
        format = bzrdir.format_registry.make_bzrdir('knit')
367
329
        self.make_repository('.', shared=True, format=format)
368
 
        # note this is deliberately readonly, as this failure should
 
330
        # note this is deliberately readonly, as this failure should 
369
331
        # occur before any writes.
370
332
        self.assertRaises(errors.NotLocalUrl,
371
333
                          bzrdir.BzrDir.create_standalone_workingtree,
372
334
                          self.get_readonly_url('child'), format=format)
373
 
        tree = bzrdir.BzrDir.create_standalone_workingtree('child',
 
335
        tree = bzrdir.BzrDir.create_standalone_workingtree('child', 
374
336
            format=format)
375
337
        tree.bzrdir.open_repository()
376
338
 
381
343
        branch.bzrdir.open_workingtree()
382
344
        branch.bzrdir.open_repository()
383
345
 
384
 
    def test_create_branch_convenience_possible_transports(self):
385
 
        """Check that the optional 'possible_transports' is recognized"""
386
 
        format = bzrdir.format_registry.make_bzrdir('knit')
387
 
        t = self.get_transport()
388
 
        branch = bzrdir.BzrDir.create_branch_convenience(
389
 
            '.', format=format, possible_transports=[t])
390
 
        branch.bzrdir.open_workingtree()
391
 
        branch.bzrdir.open_repository()
392
 
 
393
346
    def test_create_branch_convenience_root(self):
394
347
        """Creating a branch at the root of a fs should work."""
395
 
        self.vfs_transport_factory = memory.MemoryServer
 
348
        self.vfs_transport_factory = MemoryServer
396
349
        # outside a repo the default convenience output is a repo+branch_tree
397
350
        format = bzrdir.format_registry.make_bzrdir('knit')
398
 
        branch = bzrdir.BzrDir.create_branch_convenience(self.get_url(),
 
351
        branch = bzrdir.BzrDir.create_branch_convenience(self.get_url(), 
399
352
                                                         format=format)
400
353
        self.assertRaises(errors.NoWorkingTree,
401
354
                          branch.bzrdir.open_workingtree)
411
364
        branch.bzrdir.open_workingtree()
412
365
        self.assertRaises(errors.NoRepositoryPresent,
413
366
                          branch.bzrdir.open_repository)
414
 
 
 
367
            
415
368
    def test_create_branch_convenience_under_shared_repo_force_no_tree(self):
416
369
        # inside a repo the default convenience output is a branch+ follow the
417
370
        # repo tree policy but we can override that
423
376
                          branch.bzrdir.open_workingtree)
424
377
        self.assertRaises(errors.NoRepositoryPresent,
425
378
                          branch.bzrdir.open_repository)
426
 
 
 
379
            
427
380
    def test_create_branch_convenience_under_shared_repo_no_tree_policy(self):
428
381
        # inside a repo the default convenience output is a branch+ follow the
429
382
        # repo tree policy
430
383
        format = bzrdir.format_registry.make_bzrdir('knit')
431
384
        repo = self.make_repository('.', shared=True, format=format)
432
385
        repo.set_make_working_trees(False)
433
 
        branch = bzrdir.BzrDir.create_branch_convenience('child',
 
386
        branch = bzrdir.BzrDir.create_branch_convenience('child', 
434
387
                                                         format=format)
435
388
        self.assertRaises(errors.NoWorkingTree,
436
389
                          branch.bzrdir.open_workingtree)
460
413
        branch.bzrdir.open_workingtree()
461
414
 
462
415
 
463
 
class TestRepositoryAcquisitionPolicy(TestCaseWithTransport):
464
 
 
465
 
    def test_acquire_repository_standalone(self):
466
 
        """The default acquisition policy should create a standalone branch."""
467
 
        my_bzrdir = self.make_bzrdir('.')
468
 
        repo_policy = my_bzrdir.determine_repository_policy()
469
 
        repo, is_new = repo_policy.acquire_repository()
470
 
        self.assertEqual(repo.bzrdir.root_transport.base,
471
 
                         my_bzrdir.root_transport.base)
472
 
        self.assertFalse(repo.is_shared())
473
 
 
474
 
    def test_determine_stacking_policy(self):
475
 
        parent_bzrdir = self.make_bzrdir('.')
476
 
        child_bzrdir = self.make_bzrdir('child')
477
 
        parent_bzrdir.get_config().set_default_stack_on('http://example.org')
478
 
        repo_policy = child_bzrdir.determine_repository_policy()
479
 
        self.assertEqual('http://example.org', repo_policy._stack_on)
480
 
 
481
 
    def test_determine_stacking_policy_relative(self):
482
 
        parent_bzrdir = self.make_bzrdir('.')
483
 
        child_bzrdir = self.make_bzrdir('child')
484
 
        parent_bzrdir.get_config().set_default_stack_on('child2')
485
 
        repo_policy = child_bzrdir.determine_repository_policy()
486
 
        self.assertEqual('child2', repo_policy._stack_on)
487
 
        self.assertEqual(parent_bzrdir.root_transport.base,
488
 
                         repo_policy._stack_on_pwd)
489
 
 
490
 
    def prepare_default_stacking(self, child_format='1.6'):
491
 
        parent_bzrdir = self.make_bzrdir('.')
492
 
        child_branch = self.make_branch('child', format=child_format)
493
 
        parent_bzrdir.get_config().set_default_stack_on(child_branch.base)
494
 
        new_child_transport = parent_bzrdir.transport.clone('child2')
495
 
        return child_branch, new_child_transport
496
 
 
497
 
    def test_clone_on_transport_obeys_stacking_policy(self):
498
 
        child_branch, new_child_transport = self.prepare_default_stacking()
499
 
        new_child = child_branch.bzrdir.clone_on_transport(new_child_transport)
500
 
        self.assertEqual(child_branch.base,
501
 
                         new_child.open_branch().get_stacked_on_url())
502
 
 
503
 
    def test_default_stacking_with_stackable_branch_unstackable_repo(self):
504
 
        # Make stackable source branch with an unstackable repo format.
505
 
        source_bzrdir = self.make_bzrdir('source')
506
 
        knitpack_repo.RepositoryFormatKnitPack1().initialize(source_bzrdir)
507
 
        source_branch = bzrlib.branch.BzrBranchFormat7().initialize(
508
 
            source_bzrdir)
509
 
        # Make a directory with a default stacking policy
510
 
        parent_bzrdir = self.make_bzrdir('parent')
511
 
        stacked_on = self.make_branch('parent/stacked-on', format='pack-0.92')
512
 
        parent_bzrdir.get_config().set_default_stack_on(stacked_on.base)
513
 
        # Clone source into directory
514
 
        target = source_bzrdir.clone(self.get_url('parent/target'))
515
 
 
516
 
    def test_sprout_obeys_stacking_policy(self):
517
 
        child_branch, new_child_transport = self.prepare_default_stacking()
518
 
        new_child = child_branch.bzrdir.sprout(new_child_transport.base)
519
 
        self.assertEqual(child_branch.base,
520
 
                         new_child.open_branch().get_stacked_on_url())
521
 
 
522
 
    def test_clone_ignores_policy_for_unsupported_formats(self):
523
 
        child_branch, new_child_transport = self.prepare_default_stacking(
524
 
            child_format='pack-0.92')
525
 
        new_child = child_branch.bzrdir.clone_on_transport(new_child_transport)
526
 
        self.assertRaises(errors.UnstackableBranchFormat,
527
 
                          new_child.open_branch().get_stacked_on_url)
528
 
 
529
 
    def test_sprout_ignores_policy_for_unsupported_formats(self):
530
 
        child_branch, new_child_transport = self.prepare_default_stacking(
531
 
            child_format='pack-0.92')
532
 
        new_child = child_branch.bzrdir.sprout(new_child_transport.base)
533
 
        self.assertRaises(errors.UnstackableBranchFormat,
534
 
                          new_child.open_branch().get_stacked_on_url)
535
 
 
536
 
    def test_sprout_upgrades_format_if_stacked_specified(self):
537
 
        child_branch, new_child_transport = self.prepare_default_stacking(
538
 
            child_format='pack-0.92')
539
 
        new_child = child_branch.bzrdir.sprout(new_child_transport.base,
540
 
                                               stacked=True)
541
 
        self.assertEqual(child_branch.bzrdir.root_transport.base,
542
 
                         new_child.open_branch().get_stacked_on_url())
543
 
        repo = new_child.open_repository()
544
 
        self.assertTrue(repo._format.supports_external_lookups)
545
 
        self.assertFalse(repo.supports_rich_root())
546
 
 
547
 
    def test_clone_on_transport_upgrades_format_if_stacked_on_specified(self):
548
 
        child_branch, new_child_transport = self.prepare_default_stacking(
549
 
            child_format='pack-0.92')
550
 
        new_child = child_branch.bzrdir.clone_on_transport(new_child_transport,
551
 
            stacked_on=child_branch.bzrdir.root_transport.base)
552
 
        self.assertEqual(child_branch.bzrdir.root_transport.base,
553
 
                         new_child.open_branch().get_stacked_on_url())
554
 
        repo = new_child.open_repository()
555
 
        self.assertTrue(repo._format.supports_external_lookups)
556
 
        self.assertFalse(repo.supports_rich_root())
557
 
 
558
 
    def test_sprout_upgrades_to_rich_root_format_if_needed(self):
559
 
        child_branch, new_child_transport = self.prepare_default_stacking(
560
 
            child_format='rich-root-pack')
561
 
        new_child = child_branch.bzrdir.sprout(new_child_transport.base,
562
 
                                               stacked=True)
563
 
        repo = new_child.open_repository()
564
 
        self.assertTrue(repo._format.supports_external_lookups)
565
 
        self.assertTrue(repo.supports_rich_root())
566
 
 
567
 
    def test_add_fallback_repo_handles_absolute_urls(self):
568
 
        stack_on = self.make_branch('stack_on', format='1.6')
569
 
        repo = self.make_repository('repo', format='1.6')
570
 
        policy = bzrdir.UseExistingRepository(repo, stack_on.base)
571
 
        policy._add_fallback(repo)
572
 
 
573
 
    def test_add_fallback_repo_handles_relative_urls(self):
574
 
        stack_on = self.make_branch('stack_on', format='1.6')
575
 
        repo = self.make_repository('repo', format='1.6')
576
 
        policy = bzrdir.UseExistingRepository(repo, '.', stack_on.base)
577
 
        policy._add_fallback(repo)
578
 
 
579
 
    def test_configure_relative_branch_stacking_url(self):
580
 
        stack_on = self.make_branch('stack_on', format='1.6')
581
 
        stacked = self.make_branch('stack_on/stacked', format='1.6')
582
 
        policy = bzrdir.UseExistingRepository(stacked.repository,
583
 
            '.', stack_on.base)
584
 
        policy.configure_branch(stacked)
585
 
        self.assertEqual('..', stacked.get_stacked_on_url())
586
 
 
587
 
    def test_relative_branch_stacking_to_absolute(self):
588
 
        stack_on = self.make_branch('stack_on', format='1.6')
589
 
        stacked = self.make_branch('stack_on/stacked', format='1.6')
590
 
        policy = bzrdir.UseExistingRepository(stacked.repository,
591
 
            '.', self.get_readonly_url('stack_on'))
592
 
        policy.configure_branch(stacked)
593
 
        self.assertEqual(self.get_readonly_url('stack_on'),
594
 
                         stacked.get_stacked_on_url())
595
 
 
596
 
 
597
416
class ChrootedTests(TestCaseWithTransport):
598
417
    """A support class that provides readonly urls outside the local namespace.
599
418
 
604
423
 
605
424
    def setUp(self):
606
425
        super(ChrootedTests, self).setUp()
607
 
        if not self.vfs_transport_factory == memory.MemoryServer:
608
 
            self.transport_readonly_server = http_server.HttpServer
609
 
 
610
 
    def local_branch_path(self, branch):
611
 
         return os.path.realpath(urlutils.local_path_from_url(branch.base))
 
426
        if not self.vfs_transport_factory == MemoryServer:
 
427
            self.transport_readonly_server = HttpServer
612
428
 
613
429
    def test_open_containing(self):
614
430
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing,
621
437
        branch, relpath = bzrdir.BzrDir.open_containing(self.get_readonly_url('g/p/q'))
622
438
        self.assertEqual('g/p/q', relpath)
623
439
 
624
 
    def test_open_containing_tree_branch_or_repository_empty(self):
625
 
        self.assertRaises(errors.NotBranchError,
626
 
            bzrdir.BzrDir.open_containing_tree_branch_or_repository,
627
 
            self.get_readonly_url(''))
628
 
 
629
 
    def test_open_containing_tree_branch_or_repository_all(self):
630
 
        self.make_branch_and_tree('topdir')
631
 
        tree, branch, repo, relpath = \
632
 
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
633
 
                'topdir/foo')
634
 
        self.assertEqual(os.path.realpath('topdir'),
635
 
                         os.path.realpath(tree.basedir))
636
 
        self.assertEqual(os.path.realpath('topdir'),
637
 
                         self.local_branch_path(branch))
638
 
        self.assertEqual(
639
 
            osutils.realpath(os.path.join('topdir', '.bzr', 'repository')),
640
 
            repo.bzrdir.transport.local_abspath('repository'))
641
 
        self.assertEqual(relpath, 'foo')
642
 
 
643
 
    def test_open_containing_tree_branch_or_repository_no_tree(self):
644
 
        self.make_branch('branch')
645
 
        tree, branch, repo, relpath = \
646
 
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
647
 
                'branch/foo')
648
 
        self.assertEqual(tree, None)
649
 
        self.assertEqual(os.path.realpath('branch'),
650
 
                         self.local_branch_path(branch))
651
 
        self.assertEqual(
652
 
            osutils.realpath(os.path.join('branch', '.bzr', 'repository')),
653
 
            repo.bzrdir.transport.local_abspath('repository'))
654
 
        self.assertEqual(relpath, 'foo')
655
 
 
656
 
    def test_open_containing_tree_branch_or_repository_repo(self):
657
 
        self.make_repository('repo')
658
 
        tree, branch, repo, relpath = \
659
 
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
660
 
                'repo')
661
 
        self.assertEqual(tree, None)
662
 
        self.assertEqual(branch, None)
663
 
        self.assertEqual(
664
 
            osutils.realpath(os.path.join('repo', '.bzr', 'repository')),
665
 
            repo.bzrdir.transport.local_abspath('repository'))
666
 
        self.assertEqual(relpath, '')
667
 
 
668
 
    def test_open_containing_tree_branch_or_repository_shared_repo(self):
669
 
        self.make_repository('shared', shared=True)
670
 
        bzrdir.BzrDir.create_branch_convenience('shared/branch',
671
 
                                                force_new_tree=False)
672
 
        tree, branch, repo, relpath = \
673
 
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
674
 
                'shared/branch')
675
 
        self.assertEqual(tree, None)
676
 
        self.assertEqual(os.path.realpath('shared/branch'),
677
 
                         self.local_branch_path(branch))
678
 
        self.assertEqual(
679
 
            osutils.realpath(os.path.join('shared', '.bzr', 'repository')),
680
 
            repo.bzrdir.transport.local_abspath('repository'))
681
 
        self.assertEqual(relpath, '')
682
 
 
683
 
    def test_open_containing_tree_branch_or_repository_branch_subdir(self):
684
 
        self.make_branch_and_tree('foo')
685
 
        self.build_tree(['foo/bar/'])
686
 
        tree, branch, repo, relpath = \
687
 
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
688
 
                'foo/bar')
689
 
        self.assertEqual(os.path.realpath('foo'),
690
 
                         os.path.realpath(tree.basedir))
691
 
        self.assertEqual(os.path.realpath('foo'),
692
 
                         self.local_branch_path(branch))
693
 
        self.assertEqual(
694
 
            osutils.realpath(os.path.join('foo', '.bzr', 'repository')),
695
 
            repo.bzrdir.transport.local_abspath('repository'))
696
 
        self.assertEqual(relpath, 'bar')
697
 
 
698
 
    def test_open_containing_tree_branch_or_repository_repo_subdir(self):
699
 
        self.make_repository('bar')
700
 
        self.build_tree(['bar/baz/'])
701
 
        tree, branch, repo, relpath = \
702
 
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
703
 
                'bar/baz')
704
 
        self.assertEqual(tree, None)
705
 
        self.assertEqual(branch, None)
706
 
        self.assertEqual(
707
 
            osutils.realpath(os.path.join('bar', '.bzr', 'repository')),
708
 
            repo.bzrdir.transport.local_abspath('repository'))
709
 
        self.assertEqual(relpath, 'baz')
710
 
 
711
440
    def test_open_containing_from_transport(self):
712
 
        self.assertRaises(NotBranchError,
713
 
            bzrdir.BzrDir.open_containing_from_transport,
714
 
            _mod_transport.get_transport_from_url(self.get_readonly_url('')))
715
 
        self.assertRaises(NotBranchError,
716
 
            bzrdir.BzrDir.open_containing_from_transport,
717
 
            _mod_transport.get_transport_from_url(
718
 
                self.get_readonly_url('g/p/q')))
 
441
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
 
442
                          get_transport(self.get_readonly_url('')))
 
443
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
 
444
                          get_transport(self.get_readonly_url('g/p/q')))
719
445
        control = bzrdir.BzrDir.create(self.get_url())
720
446
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
721
 
            _mod_transport.get_transport_from_url(
722
 
                self.get_readonly_url('')))
 
447
            get_transport(self.get_readonly_url('')))
723
448
        self.assertEqual('', relpath)
724
449
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
725
 
            _mod_transport.get_transport_from_url(
726
 
                self.get_readonly_url('g/p/q')))
 
450
            get_transport(self.get_readonly_url('g/p/q')))
727
451
        self.assertEqual('g/p/q', relpath)
728
452
 
729
453
    def test_open_containing_tree_or_branch(self):
 
454
        def local_branch_path(branch):
 
455
             return os.path.realpath(
 
456
                urlutils.local_path_from_url(branch.base))
 
457
 
730
458
        self.make_branch_and_tree('topdir')
731
459
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
732
460
            'topdir/foo')
733
461
        self.assertEqual(os.path.realpath('topdir'),
734
462
                         os.path.realpath(tree.basedir))
735
463
        self.assertEqual(os.path.realpath('topdir'),
736
 
                         self.local_branch_path(branch))
 
464
                         local_branch_path(branch))
737
465
        self.assertIs(tree.bzrdir, branch.bzrdir)
738
466
        self.assertEqual('foo', relpath)
739
467
        # opening from non-local should not return the tree
747
475
            'topdir/foo')
748
476
        self.assertIs(tree, None)
749
477
        self.assertEqual(os.path.realpath('topdir/foo'),
750
 
                         self.local_branch_path(branch))
 
478
                         local_branch_path(branch))
751
479
        self.assertEqual('', relpath)
752
480
 
753
 
    def test_open_tree_or_branch(self):
754
 
        self.make_branch_and_tree('topdir')
755
 
        tree, branch = bzrdir.BzrDir.open_tree_or_branch('topdir')
756
 
        self.assertEqual(os.path.realpath('topdir'),
757
 
                         os.path.realpath(tree.basedir))
758
 
        self.assertEqual(os.path.realpath('topdir'),
759
 
                         self.local_branch_path(branch))
760
 
        self.assertIs(tree.bzrdir, branch.bzrdir)
761
 
        # opening from non-local should not return the tree
762
 
        tree, branch = bzrdir.BzrDir.open_tree_or_branch(
763
 
            self.get_readonly_url('topdir'))
764
 
        self.assertEqual(None, tree)
765
 
        # without a tree:
766
 
        self.make_branch('topdir/foo')
767
 
        tree, branch = bzrdir.BzrDir.open_tree_or_branch('topdir/foo')
768
 
        self.assertIs(tree, None)
769
 
        self.assertEqual(os.path.realpath('topdir/foo'),
770
 
                         self.local_branch_path(branch))
771
 
 
772
481
    def test_open_from_transport(self):
773
482
        # transport pointing at bzrdir should give a bzrdir with root transport
774
483
        # set to the given transport
775
484
        control = bzrdir.BzrDir.create(self.get_url())
776
 
        t = self.get_transport()
777
 
        opened_bzrdir = bzrdir.BzrDir.open_from_transport(t)
778
 
        self.assertEqual(t.base, opened_bzrdir.root_transport.base)
 
485
        transport = get_transport(self.get_url())
 
486
        opened_bzrdir = bzrdir.BzrDir.open_from_transport(transport)
 
487
        self.assertEqual(transport.base, opened_bzrdir.root_transport.base)
779
488
        self.assertIsInstance(opened_bzrdir, bzrdir.BzrDir)
780
 
 
 
489
        
781
490
    def test_open_from_transport_no_bzrdir(self):
782
 
        t = self.get_transport()
783
 
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport, t)
 
491
        transport = get_transport(self.get_url())
 
492
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
 
493
                          transport)
784
494
 
785
495
    def test_open_from_transport_bzrdir_in_parent(self):
786
496
        control = bzrdir.BzrDir.create(self.get_url())
787
 
        t = self.get_transport()
788
 
        t.mkdir('subdir')
789
 
        t = t.clone('subdir')
790
 
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport, t)
 
497
        transport = get_transport(self.get_url())
 
498
        transport.mkdir('subdir')
 
499
        transport = transport.clone('subdir')
 
500
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
 
501
                          transport)
791
502
 
792
503
    def test_sprout_recursive(self):
793
 
        tree = self.make_branch_and_tree('tree1',
794
 
                                         format='dirstate-with-subtree')
 
504
        tree = self.make_branch_and_tree('tree1', format='dirstate-with-subtree')
795
505
        sub_tree = self.make_branch_and_tree('tree1/subtree',
796
506
            format='dirstate-with-subtree')
797
 
        sub_tree.set_root_id('subtree-root')
798
507
        tree.add_reference(sub_tree)
799
508
        self.build_tree(['tree1/subtree/file'])
800
509
        sub_tree.add('file')
801
510
        tree.commit('Initial commit')
802
 
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
803
 
        tree2.lock_read()
804
 
        self.addCleanup(tree2.unlock)
805
 
        self.assertPathExists('tree2/subtree/file')
806
 
        self.assertEqual('tree-reference', tree2.kind('subtree-root'))
 
511
        tree.bzrdir.sprout('tree2')
 
512
        self.failUnlessExists('tree2/subtree/file')
807
513
 
808
514
    def test_cloning_metadir(self):
809
515
        """Ensure that cloning metadir is suitable"""
812
518
        branch = self.make_branch('branch', format='knit')
813
519
        format = branch.bzrdir.cloning_metadir()
814
520
        self.assertIsInstance(format.workingtree_format,
815
 
            workingtree_4.WorkingTreeFormat6)
 
521
            workingtree.WorkingTreeFormat3)
816
522
 
817
523
    def test_sprout_recursive_treeless(self):
818
524
        tree = self.make_branch_and_tree('tree1',
823
529
        self.build_tree(['tree1/subtree/file'])
824
530
        sub_tree.add('file')
825
531
        tree.commit('Initial commit')
826
 
        # The following line force the orhaning to reveal bug #634470
827
 
        tree.branch.get_config().set_user_option(
828
 
            'bzr.transform.orphan_policy', 'move')
829
532
        tree.bzrdir.destroy_workingtree()
830
 
        # FIXME: subtree/.bzr is left here which allows the test to pass (or
831
 
        # fail :-( ) -- vila 20100909
832
533
        repo = self.make_repository('repo', shared=True,
833
534
            format='dirstate-with-subtree')
834
535
        repo.set_make_working_trees(False)
835
 
        # FIXME: we just deleted the workingtree and now we want to use it ????
836
 
        # At a minimum, we should use tree.branch below (but this fails too
837
 
        # currently) or stop calling this test 'treeless'. Specifically, I've
838
 
        # turn the line below into an assertRaises when 'subtree/.bzr' is
839
 
        # orphaned and sprout tries to access the branch there (which is left
840
 
        # by bzrdir.BzrDirMeta1.destroy_workingtree when it ignores the
841
 
        # [DeletingParent('Not deleting', u'subtree', None)] conflict). See bug
842
 
        # #634470.  -- vila 20100909
843
 
        self.assertRaises(errors.NotBranchError,
844
 
                          tree.bzrdir.sprout, 'repo/tree2')
845
 
#        self.assertPathExists('repo/tree2/subtree')
846
 
#        self.assertPathDoesNotExist('repo/tree2/subtree/file')
847
 
 
848
 
    def make_foo_bar_baz(self):
849
 
        foo = bzrdir.BzrDir.create_branch_convenience('foo').bzrdir
850
 
        bar = self.make_branch('foo/bar').bzrdir
851
 
        baz = self.make_branch('baz').bzrdir
852
 
        return foo, bar, baz
853
 
 
854
 
    def test_find_bzrdirs(self):
855
 
        foo, bar, baz = self.make_foo_bar_baz()
856
 
        t = self.get_transport()
857
 
        self.assertEqualBzrdirs([baz, foo, bar], bzrdir.BzrDir.find_bzrdirs(t))
858
 
 
859
 
    def make_fake_permission_denied_transport(self, transport, paths):
860
 
        """Create a transport that raises PermissionDenied for some paths."""
861
 
        def filter(path):
862
 
            if path in paths:
863
 
                raise errors.PermissionDenied(path)
864
 
            return path
865
 
        path_filter_server = pathfilter.PathFilteringServer(transport, filter)
866
 
        path_filter_server.start_server()
867
 
        self.addCleanup(path_filter_server.stop_server)
868
 
        path_filter_transport = pathfilter.PathFilteringTransport(
869
 
            path_filter_server, '.')
870
 
        return (path_filter_server, path_filter_transport)
871
 
 
872
 
    def assertBranchUrlsEndWith(self, expect_url_suffix, actual_bzrdirs):
873
 
        """Check that each branch url ends with the given suffix."""
874
 
        for actual_bzrdir in actual_bzrdirs:
875
 
            self.assertEndsWith(actual_bzrdir.user_url, expect_url_suffix)
876
 
 
877
 
    def test_find_bzrdirs_permission_denied(self):
878
 
        foo, bar, baz = self.make_foo_bar_baz()
879
 
        t = self.get_transport()
880
 
        path_filter_server, path_filter_transport = \
881
 
            self.make_fake_permission_denied_transport(t, ['foo'])
882
 
        # local transport
883
 
        self.assertBranchUrlsEndWith('/baz/',
884
 
            bzrdir.BzrDir.find_bzrdirs(path_filter_transport))
885
 
        # smart server
886
 
        smart_transport = self.make_smart_server('.',
887
 
            backing_server=path_filter_server)
888
 
        self.assertBranchUrlsEndWith('/baz/',
889
 
            bzrdir.BzrDir.find_bzrdirs(smart_transport))
890
 
 
891
 
    def test_find_bzrdirs_list_current(self):
892
 
        def list_current(transport):
893
 
            return [s for s in transport.list_dir('') if s != 'baz']
894
 
 
895
 
        foo, bar, baz = self.make_foo_bar_baz()
896
 
        t = self.get_transport()
897
 
        self.assertEqualBzrdirs(
898
 
            [foo, bar],
899
 
            bzrdir.BzrDir.find_bzrdirs(t, list_current=list_current))
900
 
 
901
 
    def test_find_bzrdirs_evaluate(self):
902
 
        def evaluate(bzrdir):
903
 
            try:
904
 
                repo = bzrdir.open_repository()
905
 
            except errors.NoRepositoryPresent:
906
 
                return True, bzrdir.root_transport.base
907
 
            else:
908
 
                return False, bzrdir.root_transport.base
909
 
 
910
 
        foo, bar, baz = self.make_foo_bar_baz()
911
 
        t = self.get_transport()
912
 
        self.assertEqual([baz.root_transport.base, foo.root_transport.base],
913
 
                         list(bzrdir.BzrDir.find_bzrdirs(t, evaluate=evaluate)))
914
 
 
915
 
    def assertEqualBzrdirs(self, first, second):
916
 
        first = list(first)
917
 
        second = list(second)
918
 
        self.assertEqual(len(first), len(second))
919
 
        for x, y in zip(first, second):
920
 
            self.assertEqual(x.root_transport.base, y.root_transport.base)
921
 
 
922
 
    def test_find_branches(self):
923
 
        root = self.make_repository('', shared=True)
924
 
        foo, bar, baz = self.make_foo_bar_baz()
925
 
        qux = self.make_bzrdir('foo/qux')
926
 
        t = self.get_transport()
927
 
        branches = bzrdir.BzrDir.find_branches(t)
928
 
        self.assertEqual(baz.root_transport.base, branches[0].base)
929
 
        self.assertEqual(foo.root_transport.base, branches[1].base)
930
 
        self.assertEqual(bar.root_transport.base, branches[2].base)
931
 
 
932
 
        # ensure this works without a top-level repo
933
 
        branches = bzrdir.BzrDir.find_branches(t.clone('foo'))
934
 
        self.assertEqual(foo.root_transport.base, branches[0].base)
935
 
        self.assertEqual(bar.root_transport.base, branches[1].base)
936
 
 
937
 
 
938
 
class TestMissingRepoBranchesSkipped(TestCaseWithMemoryTransport):
939
 
 
940
 
    def test_find_bzrdirs_missing_repo(self):
941
 
        t = self.get_transport()
942
 
        arepo = self.make_repository('arepo', shared=True)
943
 
        abranch_url = arepo.user_url + '/abranch'
944
 
        abranch = bzrdir.BzrDir.create(abranch_url).create_branch()
945
 
        t.delete_tree('arepo/.bzr')
946
 
        self.assertRaises(errors.NoRepositoryPresent,
947
 
            branch.Branch.open, abranch_url)
948
 
        self.make_branch('baz')
949
 
        for actual_bzrdir in bzrdir.BzrDir.find_branches(t):
950
 
            self.assertEndsWith(actual_bzrdir.user_url, '/baz/')
 
536
        tree.bzrdir.sprout('repo/tree2')
 
537
        self.failUnlessExists('repo/tree2/subtree')
 
538
        self.failIfExists('repo/tree2/subtree/file')
951
539
 
952
540
 
953
541
class TestMeta1DirFormat(TestCaseWithTransport):
962
550
                         dir.get_branch_transport(bzrlib.branch.BzrBranchFormat5()).base)
963
551
        repository_base = t.clone('repository').base
964
552
        self.assertEqual(repository_base, dir.get_repository_transport(None).base)
965
 
        repository_format = repository.format_registry.get_default()
966
553
        self.assertEqual(repository_base,
967
 
                         dir.get_repository_transport(repository_format).base)
 
554
                         dir.get_repository_transport(weaverepo.RepositoryFormat7()).base)
968
555
        checkout_base = t.clone('checkout').base
969
556
        self.assertEqual(checkout_base, dir.get_workingtree_transport(None).base)
970
557
        self.assertEqual(checkout_base,
971
 
                         dir.get_workingtree_transport(workingtree_3.WorkingTreeFormat3()).base)
 
558
                         dir.get_workingtree_transport(workingtree.WorkingTreeFormat3()).base)
972
559
 
973
560
    def test_meta1dir_uses_lockdir(self):
974
561
        """Meta1 format uses a LockDir to guard the whole directory, not a file."""
994
581
 
995
582
    def test_needs_conversion_different_working_tree(self):
996
583
        # meta1dirs need an conversion if any element is not the default.
997
 
        new_format = bzrdir.format_registry.make_bzrdir('dirstate')
998
 
        tree = self.make_branch_and_tree('tree', format='knit')
999
 
        self.assertTrue(tree.bzrdir.needs_format_conversion(
1000
 
            new_format))
1001
 
 
1002
 
    def test_initialize_on_format_uses_smart_transport(self):
1003
 
        self.setup_smart_server_with_call_log()
1004
 
        new_format = bzrdir.format_registry.make_bzrdir('dirstate')
1005
 
        transport = self.get_transport('target')
1006
 
        transport.ensure_base()
1007
 
        self.reset_smart_call_log()
1008
 
        instance = new_format.initialize_on_transport(transport)
1009
 
        self.assertIsInstance(instance, remote.RemoteBzrDir)
1010
 
        rpc_count = len(self.hpss_calls)
1011
 
        # This figure represent the amount of work to perform this use case. It
1012
 
        # is entirely ok to reduce this number if a test fails due to rpc_count
1013
 
        # being too low. If rpc_count increases, more network roundtrips have
1014
 
        # become necessary for this use case. Please do not adjust this number
1015
 
        # upwards without agreement from bzr's network support maintainers.
1016
 
        self.assertEqual(2, rpc_count)
 
584
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
585
        # test with 
 
586
        new_default = bzrdir.format_registry.make_bzrdir('dirstate')
 
587
        bzrdir.BzrDirFormat._set_default_format(new_default)
 
588
        try:
 
589
            tree = self.make_branch_and_tree('tree', format='knit')
 
590
            self.assertTrue(tree.bzrdir.needs_format_conversion())
 
591
        finally:
 
592
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
593
 
 
594
 
 
595
class TestFormat5(TestCaseWithTransport):
 
596
    """Tests specific to the version 5 bzrdir format."""
 
597
 
 
598
    def test_same_lockfiles_between_tree_repo_branch(self):
 
599
        # this checks that only a single lockfiles instance is created 
 
600
        # for format 5 objects
 
601
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
602
        def check_dir_components_use_same_lock(dir):
 
603
            ctrl_1 = dir.open_repository().control_files
 
604
            ctrl_2 = dir.open_branch().control_files
 
605
            ctrl_3 = dir.open_workingtree()._control_files
 
606
            self.assertTrue(ctrl_1 is ctrl_2)
 
607
            self.assertTrue(ctrl_2 is ctrl_3)
 
608
        check_dir_components_use_same_lock(dir)
 
609
        # and if we open it normally.
 
610
        dir = bzrdir.BzrDir.open(self.get_url())
 
611
        check_dir_components_use_same_lock(dir)
 
612
    
 
613
    def test_can_convert(self):
 
614
        # format 5 dirs are convertable
 
615
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
616
        self.assertTrue(dir.can_convert_format())
 
617
    
 
618
    def test_needs_conversion(self):
 
619
        # format 5 dirs need a conversion if they are not the default.
 
620
        # and they start of not the default.
 
621
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
622
        bzrdir.BzrDirFormat._set_default_format(bzrdir.BzrDirFormat5())
 
623
        try:
 
624
            dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
625
            self.assertFalse(dir.needs_format_conversion())
 
626
        finally:
 
627
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
628
        self.assertTrue(dir.needs_format_conversion())
 
629
 
 
630
 
 
631
class TestFormat6(TestCaseWithTransport):
 
632
    """Tests specific to the version 6 bzrdir format."""
 
633
 
 
634
    def test_same_lockfiles_between_tree_repo_branch(self):
 
635
        # this checks that only a single lockfiles instance is created 
 
636
        # for format 6 objects
 
637
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
638
        def check_dir_components_use_same_lock(dir):
 
639
            ctrl_1 = dir.open_repository().control_files
 
640
            ctrl_2 = dir.open_branch().control_files
 
641
            ctrl_3 = dir.open_workingtree()._control_files
 
642
            self.assertTrue(ctrl_1 is ctrl_2)
 
643
            self.assertTrue(ctrl_2 is ctrl_3)
 
644
        check_dir_components_use_same_lock(dir)
 
645
        # and if we open it normally.
 
646
        dir = bzrdir.BzrDir.open(self.get_url())
 
647
        check_dir_components_use_same_lock(dir)
 
648
    
 
649
    def test_can_convert(self):
 
650
        # format 6 dirs are convertable
 
651
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
652
        self.assertTrue(dir.can_convert_format())
 
653
    
 
654
    def test_needs_conversion(self):
 
655
        # format 6 dirs need an conversion if they are not the default.
 
656
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
657
        bzrdir.BzrDirFormat._set_default_format(bzrdir.BzrDirMetaFormat1())
 
658
        try:
 
659
            dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
660
            self.assertTrue(dir.needs_format_conversion())
 
661
        finally:
 
662
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
663
 
 
664
 
 
665
class NotBzrDir(bzrlib.bzrdir.BzrDir):
 
666
    """A non .bzr based control directory."""
 
667
 
 
668
    def __init__(self, transport, format):
 
669
        self._format = format
 
670
        self.root_transport = transport
 
671
        self.transport = transport.clone('.not')
 
672
 
 
673
 
 
674
class NotBzrDirFormat(bzrlib.bzrdir.BzrDirFormat):
 
675
    """A test class representing any non-.bzr based disk format."""
 
676
 
 
677
    def initialize_on_transport(self, transport):
 
678
        """Initialize a new .not dir in the base directory of a Transport."""
 
679
        transport.mkdir('.not')
 
680
        return self.open(transport)
 
681
 
 
682
    def open(self, transport):
 
683
        """Open this directory."""
 
684
        return NotBzrDir(transport, self)
 
685
 
 
686
    @classmethod
 
687
    def _known_formats(self):
 
688
        return set([NotBzrDirFormat()])
 
689
 
 
690
    @classmethod
 
691
    def probe_transport(self, transport):
 
692
        """Our format is present if the transport ends in '.not/'."""
 
693
        if transport.has('.not'):
 
694
            return NotBzrDirFormat()
 
695
 
 
696
 
 
697
class TestNotBzrDir(TestCaseWithTransport):
 
698
    """Tests for using the bzrdir api with a non .bzr based disk format.
 
699
    
 
700
    If/when one of these is in the core, we can let the implementation tests
 
701
    verify this works.
 
702
    """
 
703
 
 
704
    def test_create_and_find_format(self):
 
705
        # create a .notbzr dir 
 
706
        format = NotBzrDirFormat()
 
707
        dir = format.initialize(self.get_url())
 
708
        self.assertIsInstance(dir, NotBzrDir)
 
709
        # now probe for it.
 
710
        bzrlib.bzrdir.BzrDirFormat.register_control_format(format)
 
711
        try:
 
712
            found = bzrlib.bzrdir.BzrDirFormat.find_format(
 
713
                get_transport(self.get_url()))
 
714
            self.assertIsInstance(found, NotBzrDirFormat)
 
715
        finally:
 
716
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(format)
 
717
 
 
718
    def test_included_in_known_formats(self):
 
719
        bzrlib.bzrdir.BzrDirFormat.register_control_format(NotBzrDirFormat)
 
720
        try:
 
721
            formats = bzrlib.bzrdir.BzrDirFormat.known_formats()
 
722
            for format in formats:
 
723
                if isinstance(format, NotBzrDirFormat):
 
724
                    return
 
725
            self.fail("No NotBzrDirFormat in %s" % formats)
 
726
        finally:
 
727
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(NotBzrDirFormat)
1017
728
 
1018
729
 
1019
730
class NonLocalTests(TestCaseWithTransport):
1021
732
 
1022
733
    def setUp(self):
1023
734
        super(NonLocalTests, self).setUp()
1024
 
        self.vfs_transport_factory = memory.MemoryServer
1025
 
 
 
735
        self.vfs_transport_factory = MemoryServer
 
736
    
1026
737
    def test_create_branch_convenience(self):
1027
738
        # outside a repo the default convenience output is a repo+branch_tree
1028
739
        format = bzrdir.format_registry.make_bzrdir('knit')
1040
751
            self.get_url('foo'),
1041
752
            force_new_tree=True,
1042
753
            format=format)
1043
 
        t = self.get_transport()
 
754
        t = get_transport(self.get_url('.'))
1044
755
        self.assertFalse(t.has('foo'))
1045
756
 
1046
757
    def test_clone(self):
1062
773
        my_bzrdir = bzrdir.BzrDir.open(self.get_url('branch-knit2'))
1063
774
        checkout_format = my_bzrdir.checkout_metadir()
1064
775
        self.assertIsInstance(checkout_format.workingtree_format,
1065
 
                              workingtree_4.WorkingTreeFormat4)
1066
 
 
1067
 
 
1068
 
class TestHTTPRedirections(object):
1069
 
    """Test redirection between two http servers.
 
776
                              workingtree.WorkingTreeFormat3)
 
777
 
 
778
 
 
779
class TestHTTPRedirectionLoop(object):
 
780
    """Test redirection loop between two http servers.
1070
781
 
1071
782
    This MUST be used by daughter classes that also inherit from
1072
783
    TestCaseWithTwoWebservers.
1073
784
 
1074
785
    We can't inherit directly from TestCaseWithTwoWebservers or the
1075
786
    test framework will try to create an instance which cannot
1076
 
    run, its implementation being incomplete.
 
787
    run, its implementation being incomplete. 
1077
788
    """
1078
789
 
 
790
    # Should be defined by daughter classes to ensure redirection
 
791
    # still use the same transport implementation (not currently
 
792
    # enforced as it's a bit tricky to get right (see the FIXME
 
793
    # in BzrDir.open_from_transport for the unique use case so
 
794
    # far)
 
795
    _qualifier = None
 
796
 
1079
797
    def create_transport_readonly_server(self):
1080
 
        # We don't set the http protocol version, relying on the default
1081
 
        return http_utils.HTTPServerRedirecting()
 
798
        return HTTPServerRedirecting()
1082
799
 
1083
800
    def create_transport_secondary_server(self):
1084
 
        # We don't set the http protocol version, relying on the default
1085
 
        return http_utils.HTTPServerRedirecting()
 
801
        return HTTPServerRedirecting()
1086
802
 
1087
803
    def setUp(self):
1088
 
        super(TestHTTPRedirections, self).setUp()
 
804
        # Both servers redirect to each server creating a loop
 
805
        super(TestHTTPRedirectionLoop, self).setUp()
1089
806
        # The redirections will point to the new server
1090
807
        self.new_server = self.get_readonly_server()
1091
808
        # The requests to the old server will be redirected
1092
809
        self.old_server = self.get_secondary_server()
1093
810
        # Configure the redirections
1094
811
        self.old_server.redirect_to(self.new_server.host, self.new_server.port)
 
812
        self.new_server.redirect_to(self.old_server.host, self.old_server.port)
 
813
 
 
814
    def _qualified_url(self, host, port):
 
815
        return 'http+%s://%s:%s' % (self._qualifier, host, port)
1095
816
 
1096
817
    def test_loop(self):
1097
 
        # Both servers redirect to each other creating a loop
1098
 
        self.new_server.redirect_to(self.old_server.host, self.old_server.port)
1099
818
        # Starting from either server should loop
1100
 
        old_url = self._qualified_url(self.old_server.host,
 
819
        old_url = self._qualified_url(self.old_server.host, 
1101
820
                                      self.old_server.port)
1102
821
        oldt = self._transport(old_url)
1103
822
        self.assertRaises(errors.NotBranchError,
1104
823
                          bzrdir.BzrDir.open_from_transport, oldt)
1105
 
        new_url = self._qualified_url(self.new_server.host,
 
824
        new_url = self._qualified_url(self.new_server.host, 
1106
825
                                      self.new_server.port)
1107
826
        newt = self._transport(new_url)
1108
827
        self.assertRaises(errors.NotBranchError,
1109
828
                          bzrdir.BzrDir.open_from_transport, newt)
1110
829
 
1111
 
    def test_qualifier_preserved(self):
1112
 
        wt = self.make_branch_and_tree('branch')
1113
 
        old_url = self._qualified_url(self.old_server.host,
1114
 
                                      self.old_server.port)
1115
 
        start = self._transport(old_url).clone('branch')
1116
 
        bdir = bzrdir.BzrDir.open_from_transport(start)
1117
 
        # Redirection should preserve the qualifier, hence the transport class
1118
 
        # itself.
1119
 
        self.assertIsInstance(bdir.root_transport, type(start))
1120
 
 
1121
 
 
1122
 
class TestHTTPRedirections_urllib(TestHTTPRedirections,
1123
 
                                  http_utils.TestCaseWithTwoWebservers):
 
830
 
 
831
class TestHTTPRedirections_urllib(TestHTTPRedirectionLoop,
 
832
                                  TestCaseWithTwoWebservers):
1124
833
    """Tests redirections for urllib implementation"""
1125
834
 
 
835
    _qualifier = 'urllib'
1126
836
    _transport = HttpTransport_urllib
1127
837
 
1128
 
    def _qualified_url(self, host, port):
1129
 
        result = 'http+urllib://%s:%s' % (host, port)
1130
 
        self.permit_url(result)
1131
 
        return result
1132
 
 
1133
838
 
1134
839
 
1135
840
class TestHTTPRedirections_pycurl(TestWithTransport_pycurl,
1136
 
                                  TestHTTPRedirections,
1137
 
                                  http_utils.TestCaseWithTwoWebservers):
 
841
                                  TestHTTPRedirectionLoop,
 
842
                                  TestCaseWithTwoWebservers):
1138
843
    """Tests redirections for pycurl implementation"""
1139
844
 
1140
 
    def _qualified_url(self, host, port):
1141
 
        result = 'http+pycurl://%s:%s' % (host, port)
1142
 
        self.permit_url(result)
1143
 
        return result
1144
 
 
1145
 
 
1146
 
class TestHTTPRedirections_nosmart(TestHTTPRedirections,
1147
 
                                  http_utils.TestCaseWithTwoWebservers):
1148
 
    """Tests redirections for the nosmart decorator"""
1149
 
 
1150
 
    _transport = NoSmartTransportDecorator
1151
 
 
1152
 
    def _qualified_url(self, host, port):
1153
 
        result = 'nosmart+http://%s:%s' % (host, port)
1154
 
        self.permit_url(result)
1155
 
        return result
1156
 
 
1157
 
 
1158
 
class TestHTTPRedirections_readonly(TestHTTPRedirections,
1159
 
                                    http_utils.TestCaseWithTwoWebservers):
1160
 
    """Tests redirections for readonly decoratror"""
1161
 
 
1162
 
    _transport = ReadonlyTransportDecorator
1163
 
 
1164
 
    def _qualified_url(self, host, port):
1165
 
        result = 'readonly+http://%s:%s' % (host, port)
1166
 
        self.permit_url(result)
1167
 
        return result
1168
 
 
1169
 
 
1170
 
class TestDotBzrHidden(TestCaseWithTransport):
1171
 
 
1172
 
    ls = ['ls']
1173
 
    if sys.platform == 'win32':
1174
 
        ls = [os.environ['COMSPEC'], '/C', 'dir', '/B']
1175
 
 
1176
 
    def get_ls(self):
1177
 
        f = subprocess.Popen(self.ls, stdout=subprocess.PIPE,
1178
 
            stderr=subprocess.PIPE)
1179
 
        out, err = f.communicate()
1180
 
        self.assertEqual(0, f.returncode, 'Calling %s failed: %s'
1181
 
                         % (self.ls, err))
1182
 
        return out.splitlines()
1183
 
 
1184
 
    def test_dot_bzr_hidden(self):
1185
 
        if sys.platform == 'win32' and not win32utils.has_win32file:
1186
 
            raise TestSkipped('unable to make file hidden without pywin32 library')
1187
 
        b = bzrdir.BzrDir.create('.')
1188
 
        self.build_tree(['a'])
1189
 
        self.assertEquals(['a'], self.get_ls())
1190
 
 
1191
 
    def test_dot_bzr_hidden_with_url(self):
1192
 
        if sys.platform == 'win32' and not win32utils.has_win32file:
1193
 
            raise TestSkipped('unable to make file hidden without pywin32 library')
1194
 
        b = bzrdir.BzrDir.create(urlutils.local_path_to_url('.'))
1195
 
        self.build_tree(['a'])
1196
 
        self.assertEquals(['a'], self.get_ls())
1197
 
 
1198
 
 
1199
 
class _TestBzrDirFormat(bzrdir.BzrDirMetaFormat1):
1200
 
    """Test BzrDirFormat implementation for TestBzrDirSprout."""
1201
 
 
1202
 
    def _open(self, transport):
1203
 
        return _TestBzrDir(transport, self)
1204
 
 
1205
 
 
1206
 
class _TestBzrDir(bzrdir.BzrDirMeta1):
1207
 
    """Test BzrDir implementation for TestBzrDirSprout.
1208
 
 
1209
 
    When created a _TestBzrDir already has repository and a branch.  The branch
1210
 
    is a test double as well.
1211
 
    """
1212
 
 
1213
 
    def __init__(self, *args, **kwargs):
1214
 
        super(_TestBzrDir, self).__init__(*args, **kwargs)
1215
 
        self.test_branch = _TestBranch(self.transport)
1216
 
        self.test_branch.repository = self.create_repository()
1217
 
 
1218
 
    def open_branch(self, unsupported=False):
1219
 
        return self.test_branch
1220
 
 
1221
 
    def cloning_metadir(self, require_stacking=False):
1222
 
        return _TestBzrDirFormat()
1223
 
 
1224
 
 
1225
 
class _TestBranchFormat(bzrlib.branch.BranchFormat):
1226
 
    """Test Branch format for TestBzrDirSprout."""
1227
 
 
1228
 
 
1229
 
class _TestBranch(bzrlib.branch.Branch):
1230
 
    """Test Branch implementation for TestBzrDirSprout."""
1231
 
 
1232
 
    def __init__(self, transport, *args, **kwargs):
1233
 
        self._format = _TestBranchFormat()
1234
 
        self._transport = transport
1235
 
        self.base = transport.base
1236
 
        super(_TestBranch, self).__init__(*args, **kwargs)
1237
 
        self.calls = []
1238
 
        self._parent = None
1239
 
 
1240
 
    def sprout(self, *args, **kwargs):
1241
 
        self.calls.append('sprout')
1242
 
        return _TestBranch(self._transport)
1243
 
 
1244
 
    def copy_content_into(self, destination, revision_id=None):
1245
 
        self.calls.append('copy_content_into')
1246
 
 
1247
 
    def last_revision(self):
1248
 
        return _mod_revision.NULL_REVISION
1249
 
 
1250
 
    def get_parent(self):
1251
 
        return self._parent
1252
 
 
1253
 
    def _get_config(self):
1254
 
        return config.TransportConfig(self._transport, 'branch.conf')
1255
 
 
1256
 
    def set_parent(self, parent):
1257
 
        self._parent = parent
1258
 
 
1259
 
    def lock_read(self):
1260
 
        return lock.LogicalLockResult(self.unlock)
1261
 
 
1262
 
    def unlock(self):
1263
 
        return
1264
 
 
1265
 
 
1266
 
class TestBzrDirSprout(TestCaseWithMemoryTransport):
1267
 
 
1268
 
    def test_sprout_uses_branch_sprout(self):
1269
 
        """BzrDir.sprout calls Branch.sprout.
1270
 
 
1271
 
        Usually, BzrDir.sprout should delegate to the branch's sprout method
1272
 
        for part of the work.  This allows the source branch to control the
1273
 
        choice of format for the new branch.
1274
 
 
1275
 
        There are exceptions, but this tests avoids them:
1276
 
          - if there's no branch in the source bzrdir,
1277
 
          - or if the stacking has been requested and the format needs to be
1278
 
            overridden to satisfy that.
1279
 
        """
1280
 
        # Make an instrumented bzrdir.
1281
 
        t = self.get_transport('source')
1282
 
        t.ensure_base()
1283
 
        source_bzrdir = _TestBzrDirFormat().initialize_on_transport(t)
1284
 
        # The instrumented bzrdir has a test_branch attribute that logs calls
1285
 
        # made to the branch contained in that bzrdir.  Initially the test
1286
 
        # branch exists but no calls have been made to it.
1287
 
        self.assertEqual([], source_bzrdir.test_branch.calls)
1288
 
 
1289
 
        # Sprout the bzrdir
1290
 
        target_url = self.get_url('target')
1291
 
        result = source_bzrdir.sprout(target_url, recurse='no')
1292
 
 
1293
 
        # The bzrdir called the branch's sprout method.
1294
 
        self.assertSubset(['sprout'], source_bzrdir.test_branch.calls)
1295
 
 
1296
 
    def test_sprout_parent(self):
1297
 
        grandparent_tree = self.make_branch('grandparent')
1298
 
        parent = grandparent_tree.bzrdir.sprout('parent').open_branch()
1299
 
        branch_tree = parent.bzrdir.sprout('branch').open_branch()
1300
 
        self.assertContainsRe(branch_tree.get_parent(), '/parent/$')
1301
 
 
1302
 
 
1303
 
class TestBzrDirHooks(TestCaseWithMemoryTransport):
1304
 
 
1305
 
    def test_pre_open_called(self):
1306
 
        calls = []
1307
 
        bzrdir.BzrDir.hooks.install_named_hook('pre_open', calls.append, None)
1308
 
        transport = self.get_transport('foo')
1309
 
        url = transport.base
1310
 
        self.assertRaises(errors.NotBranchError, bzrdir.BzrDir.open, url)
1311
 
        self.assertEqual([transport.base], [t.base for t in calls])
1312
 
 
1313
 
    def test_pre_open_actual_exceptions_raised(self):
1314
 
        count = [0]
1315
 
        def fail_once(transport):
1316
 
            count[0] += 1
1317
 
            if count[0] == 1:
1318
 
                raise errors.BzrError("fail")
1319
 
        bzrdir.BzrDir.hooks.install_named_hook('pre_open', fail_once, None)
1320
 
        transport = self.get_transport('foo')
1321
 
        url = transport.base
1322
 
        err = self.assertRaises(errors.BzrError, bzrdir.BzrDir.open, url)
1323
 
        self.assertEqual('fail', err._preformatted_string)
1324
 
 
1325
 
    def test_post_repo_init(self):
1326
 
        from bzrlib.bzrdir import RepoInitHookParams
1327
 
        calls = []
1328
 
        bzrdir.BzrDir.hooks.install_named_hook('post_repo_init',
1329
 
            calls.append, None)
1330
 
        self.make_repository('foo')
1331
 
        self.assertLength(1, calls)
1332
 
        params = calls[0]
1333
 
        self.assertIsInstance(params, RepoInitHookParams)
1334
 
        self.assertTrue(hasattr(params, 'bzrdir'))
1335
 
        self.assertTrue(hasattr(params, 'repository'))
1336
 
 
1337
 
    def test_post_repo_init_hook_repr(self):
1338
 
        param_reprs = []
1339
 
        bzrdir.BzrDir.hooks.install_named_hook('post_repo_init',
1340
 
            lambda params: param_reprs.append(repr(params)), None)
1341
 
        self.make_repository('foo')
1342
 
        self.assertLength(1, param_reprs)
1343
 
        param_repr = param_reprs[0]
1344
 
        self.assertStartsWith(param_repr, '<RepoInitHookParams for ')
1345
 
 
1346
 
 
1347
 
class TestGenerateBackupName(TestCaseWithMemoryTransport):
1348
 
    # FIXME: This may need to be unified with test_osutils.TestBackupNames or
1349
 
    # moved to per_bzrdir or per_transport for better coverage ?
1350
 
    # -- vila 20100909
1351
 
 
1352
 
    def setUp(self):
1353
 
        super(TestGenerateBackupName, self).setUp()
1354
 
        self._transport = self.get_transport()
1355
 
        bzrdir.BzrDir.create(self.get_url(),
1356
 
            possible_transports=[self._transport])
1357
 
        self._bzrdir = bzrdir.BzrDir.open_from_transport(self._transport)
1358
 
 
1359
 
    def test_deprecated_generate_backup_name(self):
1360
 
        res = self.applyDeprecated(
1361
 
                symbol_versioning.deprecated_in((2, 3, 0)),
1362
 
                self._bzrdir.generate_backup_name, 'whatever')
1363
 
 
1364
 
    def test_new(self):
1365
 
        self.assertEqual("a.~1~", self._bzrdir._available_backup_name("a"))
1366
 
 
1367
 
    def test_exiting(self):
1368
 
        self._transport.put_bytes("a.~1~", "some content")
1369
 
        self.assertEqual("a.~2~", self._bzrdir._available_backup_name("a"))
1370
 
 
 
845
    _qualifier = 'pycurl'