/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_bzrdir.py

  • Committer: Aaron Bentley
  • Date: 2009-03-11 03:07:31 UTC
  • mto: This revision was merged to the branch mainline in revision 4112.
  • Revision ID: aaron@aaronbentley.com-20090311030731-b9bnnv0qzbxqjk4d
Add tests for update_entry with tree references

Show diffs side-by-side

added added

removed removed

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