~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_bzrdir.py

  • Committer: Alexander Belchenko
  • Date: 2007-10-04 05:35:10 UTC
  • mfrom: (2804.4.6 selftest.win32)
  • mto: This revision was merged to the branch mainline in revision 2884.
  • Revision ID: bialix@ukr.net-20071004053510-1zdsm5ywq7pq41et
changes after Martin's review

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.path
 
23
from StringIO import StringIO
 
24
 
 
25
from bzrlib import (
 
26
    bzrdir,
 
27
    errors,
 
28
    help_topics,
 
29
    repository,
 
30
    symbol_versioning,
 
31
    urlutils,
 
32
    workingtree,
 
33
    )
 
34
import bzrlib.branch
 
35
from bzrlib.errors import (NotBranchError,
 
36
                           UnknownFormatError,
 
37
                           UnsupportedFormatError,
 
38
                           )
 
39
from bzrlib.symbol_versioning import (
 
40
    zero_ninetyone,
 
41
    )
 
42
from bzrlib.tests import (
 
43
    TestCase,
 
44
    TestCaseWithTransport,
 
45
    test_sftp_transport
 
46
    )
 
47
from bzrlib.tests.HttpServer import HttpServer
 
48
from bzrlib.tests.HTTPTestUtil import (
 
49
    TestCaseWithTwoWebservers,
 
50
    HTTPServerRedirecting,
 
51
    )
 
52
from bzrlib.tests.test_http import TestWithTransport_pycurl
 
53
from bzrlib.transport import get_transport
 
54
from bzrlib.transport.http._urllib import HttpTransport_urllib
 
55
from bzrlib.transport.memory import MemoryServer
 
56
from bzrlib.repofmt import knitrepo, weaverepo
 
57
 
 
58
 
 
59
class TestDefaultFormat(TestCase):
 
60
 
 
61
    def test_get_set_default_format(self):
 
62
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
63
        # default is BzrDirFormat6
 
64
        self.failUnless(isinstance(old_format, bzrdir.BzrDirMetaFormat1))
 
65
        self.applyDeprecated(symbol_versioning.zero_fourteen, 
 
66
                             bzrdir.BzrDirFormat.set_default_format, 
 
67
                             SampleBzrDirFormat())
 
68
        # creating a bzr dir should now create an instrumented dir.
 
69
        try:
 
70
            result = bzrdir.BzrDir.create('memory:///')
 
71
            self.failUnless(isinstance(result, SampleBzrDir))
 
72
        finally:
 
73
            self.applyDeprecated(symbol_versioning.zero_fourteen,
 
74
                bzrdir.BzrDirFormat.set_default_format, old_format)
 
75
        self.assertEqual(old_format, bzrdir.BzrDirFormat.get_default_format())
 
76
 
 
77
 
 
78
class TestFormatRegistry(TestCase):
 
79
 
 
80
    def make_format_registry(self):
 
81
        my_format_registry = bzrdir.BzrDirFormatRegistry()
 
82
        my_format_registry.register('weave', bzrdir.BzrDirFormat6,
 
83
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
84
            ' repositories', deprecated=True)
 
85
        my_format_registry.register_lazy('lazy', 'bzrlib.bzrdir', 
 
86
            'BzrDirFormat6', 'Format registered lazily', deprecated=True)
 
87
        my_format_registry.register_metadir('knit',
 
88
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
 
89
            'Format using knits',
 
90
            )
 
91
        my_format_registry.set_default('knit')
 
92
        my_format_registry.register_metadir(
 
93
            'branch6',
 
94
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
 
95
            'Experimental successor to knit.  Use at your own risk.',
 
96
            branch_format='bzrlib.branch.BzrBranchFormat6')
 
97
        my_format_registry.register_metadir(
 
98
            'hidden format',
 
99
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
 
100
            'Experimental successor to knit.  Use at your own risk.',
 
101
            branch_format='bzrlib.branch.BzrBranchFormat6', hidden=True)
 
102
        my_format_registry.register('hiddenweave', bzrdir.BzrDirFormat6,
 
103
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
104
            ' repositories', hidden=True)
 
105
        my_format_registry.register_lazy('hiddenlazy', 'bzrlib.bzrdir',
 
106
            'BzrDirFormat6', 'Format registered lazily', deprecated=True,
 
107
            hidden=True)
 
108
        return my_format_registry
 
109
 
 
110
    def test_format_registry(self):
 
111
        my_format_registry = self.make_format_registry()
 
112
        my_bzrdir = my_format_registry.make_bzrdir('lazy')
 
113
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
 
114
        my_bzrdir = my_format_registry.make_bzrdir('weave')
 
115
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
 
116
        my_bzrdir = my_format_registry.make_bzrdir('default')
 
117
        self.assertIsInstance(my_bzrdir.repository_format, 
 
118
            knitrepo.RepositoryFormatKnit1)
 
119
        my_bzrdir = my_format_registry.make_bzrdir('knit')
 
120
        self.assertIsInstance(my_bzrdir.repository_format, 
 
121
            knitrepo.RepositoryFormatKnit1)
 
122
        my_bzrdir = my_format_registry.make_bzrdir('branch6')
 
123
        self.assertIsInstance(my_bzrdir.get_branch_format(),
 
124
                              bzrlib.branch.BzrBranchFormat6)
 
125
 
 
126
    def test_get_help(self):
 
127
        my_format_registry = self.make_format_registry()
 
128
        self.assertEqual('Format registered lazily',
 
129
                         my_format_registry.get_help('lazy'))
 
130
        self.assertEqual('Format using knits', 
 
131
                         my_format_registry.get_help('knit'))
 
132
        self.assertEqual('Format using knits', 
 
133
                         my_format_registry.get_help('default'))
 
134
        self.assertEqual('Pre-0.8 format.  Slower and does not support'
 
135
                         ' checkouts or shared repositories', 
 
136
                         my_format_registry.get_help('weave'))
 
137
        
 
138
    def test_help_topic(self):
 
139
        topics = help_topics.HelpTopicRegistry()
 
140
        topics.register('formats', self.make_format_registry().help_topic, 
 
141
                        'Directory formats')
 
142
        topic = topics.get_detail('formats')
 
143
        new, deprecated = topic.split('Deprecated formats')
 
144
        self.assertContainsRe(new, 'These formats can be used')
 
145
        self.assertContainsRe(new, 
 
146
                ':knit:\n    \(native\) \(default\) Format using knits\n')
 
147
        self.assertContainsRe(deprecated, 
 
148
                ':lazy:\n    \(native\) Format registered lazily\n')
 
149
        self.assertNotContainsRe(new, 'hidden')
 
150
 
 
151
    def test_set_default_repository(self):
 
152
        default_factory = bzrdir.format_registry.get('default')
 
153
        old_default = [k for k, v in bzrdir.format_registry.iteritems()
 
154
                       if v == default_factory and k != 'default'][0]
 
155
        bzrdir.format_registry.set_default_repository('dirstate-with-subtree')
 
156
        try:
 
157
            self.assertIs(bzrdir.format_registry.get('dirstate-with-subtree'),
 
158
                          bzrdir.format_registry.get('default'))
 
159
            self.assertIs(
 
160
                repository.RepositoryFormat.get_default_format().__class__,
 
161
                knitrepo.RepositoryFormatKnit3)
 
162
        finally:
 
163
            bzrdir.format_registry.set_default_repository(old_default)
 
164
 
 
165
 
 
166
class SampleBranch(bzrlib.branch.Branch):
 
167
    """A dummy branch for guess what, dummy use."""
 
168
 
 
169
    def __init__(self, dir):
 
170
        self.bzrdir = dir
 
171
 
 
172
 
 
173
class SampleBzrDir(bzrdir.BzrDir):
 
174
    """A sample BzrDir implementation to allow testing static methods."""
 
175
 
 
176
    def create_repository(self, shared=False):
 
177
        """See BzrDir.create_repository."""
 
178
        return "A repository"
 
179
 
 
180
    def open_repository(self):
 
181
        """See BzrDir.open_repository."""
 
182
        return "A repository"
 
183
 
 
184
    def create_branch(self):
 
185
        """See BzrDir.create_branch."""
 
186
        return SampleBranch(self)
 
187
 
 
188
    def create_workingtree(self):
 
189
        """See BzrDir.create_workingtree."""
 
190
        return "A tree"
 
191
 
 
192
 
 
193
class SampleBzrDirFormat(bzrdir.BzrDirFormat):
 
194
    """A sample format
 
195
 
 
196
    this format is initializable, unsupported to aid in testing the 
 
197
    open and open_downlevel routines.
 
198
    """
 
199
 
 
200
    def get_format_string(self):
 
201
        """See BzrDirFormat.get_format_string()."""
 
202
        return "Sample .bzr dir format."
 
203
 
 
204
    def initialize(self, url, possible_transports=None):
 
205
        """Create a bzr dir."""
 
206
        t = get_transport(url, possible_transports)
 
207
        t.mkdir('.bzr')
 
208
        t.put_bytes('.bzr/branch-format', self.get_format_string())
 
209
        return SampleBzrDir(t, self)
 
210
 
 
211
    def is_supported(self):
 
212
        return False
 
213
 
 
214
    def open(self, transport, _found=None):
 
215
        return "opened branch."
 
216
 
 
217
 
 
218
class TestBzrDirFormat(TestCaseWithTransport):
 
219
    """Tests for the BzrDirFormat facility."""
 
220
 
 
221
    def test_find_format(self):
 
222
        # is the right format object found for a branch?
 
223
        # create a branch with a few known format objects.
 
224
        # this is not quite the same as 
 
225
        t = get_transport(self.get_url())
 
226
        self.build_tree(["foo/", "bar/"], transport=t)
 
227
        def check_format(format, url):
 
228
            format.initialize(url)
 
229
            t = get_transport(url)
 
230
            found_format = bzrdir.BzrDirFormat.find_format(t)
 
231
            self.failUnless(isinstance(found_format, format.__class__))
 
232
        check_format(bzrdir.BzrDirFormat5(), "foo")
 
233
        check_format(bzrdir.BzrDirFormat6(), "bar")
 
234
        
 
235
    def test_find_format_nothing_there(self):
 
236
        self.assertRaises(NotBranchError,
 
237
                          bzrdir.BzrDirFormat.find_format,
 
238
                          get_transport('.'))
 
239
 
 
240
    def test_find_format_unknown_format(self):
 
241
        t = get_transport(self.get_url())
 
242
        t.mkdir('.bzr')
 
243
        t.put_bytes('.bzr/branch-format', '')
 
244
        self.assertRaises(UnknownFormatError,
 
245
                          bzrdir.BzrDirFormat.find_format,
 
246
                          get_transport('.'))
 
247
 
 
248
    def test_register_unregister_format(self):
 
249
        format = SampleBzrDirFormat()
 
250
        url = self.get_url()
 
251
        # make a bzrdir
 
252
        format.initialize(url)
 
253
        # register a format for it.
 
254
        bzrdir.BzrDirFormat.register_format(format)
 
255
        # which bzrdir.Open will refuse (not supported)
 
256
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open, url)
 
257
        # which bzrdir.open_containing will refuse (not supported)
 
258
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open_containing, url)
 
259
        # but open_downlevel will work
 
260
        t = get_transport(url)
 
261
        self.assertEqual(format.open(t), bzrdir.BzrDir.open_unsupported(url))
 
262
        # unregister the format
 
263
        bzrdir.BzrDirFormat.unregister_format(format)
 
264
        # now open_downlevel should fail too.
 
265
        self.assertRaises(UnknownFormatError, bzrdir.BzrDir.open_unsupported, url)
 
266
 
 
267
    def test_create_repository_deprecated(self):
 
268
        # new interface is to make the bzrdir, then a repository within that.
 
269
        format = SampleBzrDirFormat()
 
270
        repo = self.applyDeprecated(zero_ninetyone,
 
271
                bzrdir.BzrDir.create_repository,
 
272
                self.get_url(), format=format)
 
273
        self.assertEqual('A repository', repo)
 
274
 
 
275
    def test_create_repository_shared(self):
 
276
        # new interface is to make the bzrdir, then a repository within that.
 
277
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
278
        repo = self.applyDeprecated(zero_ninetyone,
 
279
                bzrdir.BzrDir.create_repository,
 
280
                '.', shared=True)
 
281
        self.assertTrue(repo.is_shared())
 
282
 
 
283
    def test_create_repository_nonshared(self):
 
284
        # new interface is to make the bzrdir, then a repository within that.
 
285
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
286
        repo = self.applyDeprecated(zero_ninetyone,
 
287
                bzrdir.BzrDir.create_repository,
 
288
                '.')
 
289
        self.assertFalse(repo.is_shared())
 
290
 
 
291
    def test_create_repository_under_shared(self):
 
292
        # an explicit create_repository always does so.
 
293
        # we trust the format is right from the 'create_repository test'
 
294
        # new interface is to make the bzrdir, then a repository within that.
 
295
        format = bzrdir.format_registry.make_bzrdir('knit')
 
296
        self.make_repository('.', shared=True, format=format)
 
297
        repo = self.applyDeprecated(zero_ninetyone,
 
298
                bzrdir.BzrDir.create_repository,
 
299
                self.get_url('child'),
 
300
                format=format)
 
301
        self.assertTrue(isinstance(repo, repository.Repository))
 
302
        self.assertTrue(repo.bzrdir.root_transport.base.endswith('child/'))
 
303
 
 
304
    def test_create_branch_and_repo_uses_default(self):
 
305
        format = SampleBzrDirFormat()
 
306
        branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url(),
 
307
                                                      format=format)
 
308
        self.assertTrue(isinstance(branch, SampleBranch))
 
309
 
 
310
    def test_create_branch_and_repo_under_shared(self):
 
311
        # creating a branch and repo in a shared repo uses the
 
312
        # shared repository
 
313
        format = bzrdir.format_registry.make_bzrdir('knit')
 
314
        self.make_repository('.', shared=True, format=format)
 
315
        branch = bzrdir.BzrDir.create_branch_and_repo(
 
316
            self.get_url('child'), format=format)
 
317
        self.assertRaises(errors.NoRepositoryPresent,
 
318
                          branch.bzrdir.open_repository)
 
319
 
 
320
    def test_create_branch_and_repo_under_shared_force_new(self):
 
321
        # creating a branch and repo in a shared repo can be forced to 
 
322
        # make a new repo
 
323
        format = bzrdir.format_registry.make_bzrdir('knit')
 
324
        self.make_repository('.', shared=True, format=format)
 
325
        branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url('child'),
 
326
                                                      force_new_repo=True,
 
327
                                                      format=format)
 
328
        branch.bzrdir.open_repository()
 
329
 
 
330
    def test_create_standalone_working_tree(self):
 
331
        format = SampleBzrDirFormat()
 
332
        # note this is deliberately readonly, as this failure should 
 
333
        # occur before any writes.
 
334
        self.assertRaises(errors.NotLocalUrl,
 
335
                          bzrdir.BzrDir.create_standalone_workingtree,
 
336
                          self.get_readonly_url(), format=format)
 
337
        tree = bzrdir.BzrDir.create_standalone_workingtree('.', 
 
338
                                                           format=format)
 
339
        self.assertEqual('A tree', tree)
 
340
 
 
341
    def test_create_standalone_working_tree_under_shared_repo(self):
 
342
        # create standalone working tree always makes a repo.
 
343
        format = bzrdir.format_registry.make_bzrdir('knit')
 
344
        self.make_repository('.', shared=True, format=format)
 
345
        # note this is deliberately readonly, as this failure should 
 
346
        # occur before any writes.
 
347
        self.assertRaises(errors.NotLocalUrl,
 
348
                          bzrdir.BzrDir.create_standalone_workingtree,
 
349
                          self.get_readonly_url('child'), format=format)
 
350
        tree = bzrdir.BzrDir.create_standalone_workingtree('child', 
 
351
            format=format)
 
352
        tree.bzrdir.open_repository()
 
353
 
 
354
    def test_create_branch_convenience(self):
 
355
        # outside a repo the default convenience output is a repo+branch_tree
 
356
        format = bzrdir.format_registry.make_bzrdir('knit')
 
357
        branch = bzrdir.BzrDir.create_branch_convenience('.', format=format)
 
358
        branch.bzrdir.open_workingtree()
 
359
        branch.bzrdir.open_repository()
 
360
 
 
361
    def test_create_branch_convenience_possible_transports(self):
 
362
        """Check that the optional 'possible_transports' is recognized"""
 
363
        format = bzrdir.format_registry.make_bzrdir('knit')
 
364
        t = self.get_transport()
 
365
        branch = bzrdir.BzrDir.create_branch_convenience(
 
366
            '.', format=format, possible_transports=[t])
 
367
        branch.bzrdir.open_workingtree()
 
368
        branch.bzrdir.open_repository()
 
369
 
 
370
    def test_create_branch_convenience_root(self):
 
371
        """Creating a branch at the root of a fs should work."""
 
372
        self.vfs_transport_factory = MemoryServer
 
373
        # outside a repo the default convenience output is a repo+branch_tree
 
374
        format = bzrdir.format_registry.make_bzrdir('knit')
 
375
        branch = bzrdir.BzrDir.create_branch_convenience(self.get_url(), 
 
376
                                                         format=format)
 
377
        self.assertRaises(errors.NoWorkingTree,
 
378
                          branch.bzrdir.open_workingtree)
 
379
        branch.bzrdir.open_repository()
 
380
 
 
381
    def test_create_branch_convenience_under_shared_repo(self):
 
382
        # inside a repo the default convenience output is a branch+ follow the
 
383
        # repo tree policy
 
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
            format=format)
 
388
        branch.bzrdir.open_workingtree()
 
389
        self.assertRaises(errors.NoRepositoryPresent,
 
390
                          branch.bzrdir.open_repository)
 
391
            
 
392
    def test_create_branch_convenience_under_shared_repo_force_no_tree(self):
 
393
        # inside a repo the default convenience output is a branch+ follow the
 
394
        # repo tree policy but we can override that
 
395
        format = bzrdir.format_registry.make_bzrdir('knit')
 
396
        self.make_repository('.', shared=True, format=format)
 
397
        branch = bzrdir.BzrDir.create_branch_convenience('child',
 
398
            force_new_tree=False, format=format)
 
399
        self.assertRaises(errors.NoWorkingTree,
 
400
                          branch.bzrdir.open_workingtree)
 
401
        self.assertRaises(errors.NoRepositoryPresent,
 
402
                          branch.bzrdir.open_repository)
 
403
            
 
404
    def test_create_branch_convenience_under_shared_repo_no_tree_policy(self):
 
405
        # inside a repo the default convenience output is a branch+ follow the
 
406
        # repo tree policy
 
407
        format = bzrdir.format_registry.make_bzrdir('knit')
 
408
        repo = self.make_repository('.', shared=True, format=format)
 
409
        repo.set_make_working_trees(False)
 
410
        branch = bzrdir.BzrDir.create_branch_convenience('child', 
 
411
                                                         format=format)
 
412
        self.assertRaises(errors.NoWorkingTree,
 
413
                          branch.bzrdir.open_workingtree)
 
414
        self.assertRaises(errors.NoRepositoryPresent,
 
415
                          branch.bzrdir.open_repository)
 
416
 
 
417
    def test_create_branch_convenience_under_shared_repo_no_tree_policy_force_tree(self):
 
418
        # inside a repo the default convenience output is a branch+ follow the
 
419
        # repo tree policy but we can override that
 
420
        format = bzrdir.format_registry.make_bzrdir('knit')
 
421
        repo = self.make_repository('.', shared=True, format=format)
 
422
        repo.set_make_working_trees(False)
 
423
        branch = bzrdir.BzrDir.create_branch_convenience('child',
 
424
            force_new_tree=True, format=format)
 
425
        branch.bzrdir.open_workingtree()
 
426
        self.assertRaises(errors.NoRepositoryPresent,
 
427
                          branch.bzrdir.open_repository)
 
428
 
 
429
    def test_create_branch_convenience_under_shared_repo_force_new_repo(self):
 
430
        # inside a repo the default convenience output is overridable to give
 
431
        # repo+branch+tree
 
432
        format = bzrdir.format_registry.make_bzrdir('knit')
 
433
        self.make_repository('.', shared=True, format=format)
 
434
        branch = bzrdir.BzrDir.create_branch_convenience('child',
 
435
            force_new_repo=True, format=format)
 
436
        branch.bzrdir.open_repository()
 
437
        branch.bzrdir.open_workingtree()
 
438
 
 
439
 
 
440
class ChrootedTests(TestCaseWithTransport):
 
441
    """A support class that provides readonly urls outside the local namespace.
 
442
 
 
443
    This is done by checking if self.transport_server is a MemoryServer. if it
 
444
    is then we are chrooted already, if it is not then an HttpServer is used
 
445
    for readonly urls.
 
446
    """
 
447
 
 
448
    def setUp(self):
 
449
        super(ChrootedTests, self).setUp()
 
450
        if not self.vfs_transport_factory == MemoryServer:
 
451
            self.transport_readonly_server = HttpServer
 
452
 
 
453
    def test_open_containing(self):
 
454
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing,
 
455
                          self.get_readonly_url(''))
 
456
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing,
 
457
                          self.get_readonly_url('g/p/q'))
 
458
        control = bzrdir.BzrDir.create(self.get_url())
 
459
        branch, relpath = bzrdir.BzrDir.open_containing(self.get_readonly_url(''))
 
460
        self.assertEqual('', relpath)
 
461
        branch, relpath = bzrdir.BzrDir.open_containing(self.get_readonly_url('g/p/q'))
 
462
        self.assertEqual('g/p/q', relpath)
 
463
 
 
464
    def test_open_containing_from_transport(self):
 
465
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
 
466
                          get_transport(self.get_readonly_url('')))
 
467
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
 
468
                          get_transport(self.get_readonly_url('g/p/q')))
 
469
        control = bzrdir.BzrDir.create(self.get_url())
 
470
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
 
471
            get_transport(self.get_readonly_url('')))
 
472
        self.assertEqual('', relpath)
 
473
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
 
474
            get_transport(self.get_readonly_url('g/p/q')))
 
475
        self.assertEqual('g/p/q', relpath)
 
476
 
 
477
    def test_open_containing_tree_or_branch(self):
 
478
        def local_branch_path(branch):
 
479
             return os.path.realpath(
 
480
                urlutils.local_path_from_url(branch.base))
 
481
 
 
482
        self.make_branch_and_tree('topdir')
 
483
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
484
            'topdir/foo')
 
485
        self.assertEqual(os.path.realpath('topdir'),
 
486
                         os.path.realpath(tree.basedir))
 
487
        self.assertEqual(os.path.realpath('topdir'),
 
488
                         local_branch_path(branch))
 
489
        self.assertIs(tree.bzrdir, branch.bzrdir)
 
490
        self.assertEqual('foo', relpath)
 
491
        # opening from non-local should not return the tree
 
492
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
493
            self.get_readonly_url('topdir/foo'))
 
494
        self.assertEqual(None, tree)
 
495
        self.assertEqual('foo', relpath)
 
496
        # without a tree:
 
497
        self.make_branch('topdir/foo')
 
498
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
 
499
            'topdir/foo')
 
500
        self.assertIs(tree, None)
 
501
        self.assertEqual(os.path.realpath('topdir/foo'),
 
502
                         local_branch_path(branch))
 
503
        self.assertEqual('', relpath)
 
504
 
 
505
    def test_open_from_transport(self):
 
506
        # transport pointing at bzrdir should give a bzrdir with root transport
 
507
        # set to the given transport
 
508
        control = bzrdir.BzrDir.create(self.get_url())
 
509
        transport = get_transport(self.get_url())
 
510
        opened_bzrdir = bzrdir.BzrDir.open_from_transport(transport)
 
511
        self.assertEqual(transport.base, opened_bzrdir.root_transport.base)
 
512
        self.assertIsInstance(opened_bzrdir, bzrdir.BzrDir)
 
513
        
 
514
    def test_open_from_transport_no_bzrdir(self):
 
515
        transport = get_transport(self.get_url())
 
516
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
 
517
                          transport)
 
518
 
 
519
    def test_open_from_transport_bzrdir_in_parent(self):
 
520
        control = bzrdir.BzrDir.create(self.get_url())
 
521
        transport = get_transport(self.get_url())
 
522
        transport.mkdir('subdir')
 
523
        transport = transport.clone('subdir')
 
524
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
 
525
                          transport)
 
526
 
 
527
    def test_sprout_recursive(self):
 
528
        tree = self.make_branch_and_tree('tree1', format='dirstate-with-subtree')
 
529
        sub_tree = self.make_branch_and_tree('tree1/subtree',
 
530
            format='dirstate-with-subtree')
 
531
        tree.add_reference(sub_tree)
 
532
        self.build_tree(['tree1/subtree/file'])
 
533
        sub_tree.add('file')
 
534
        tree.commit('Initial commit')
 
535
        tree.bzrdir.sprout('tree2')
 
536
        self.failUnlessExists('tree2/subtree/file')
 
537
 
 
538
    def test_cloning_metadir(self):
 
539
        """Ensure that cloning metadir is suitable"""
 
540
        bzrdir = self.make_bzrdir('bzrdir')
 
541
        bzrdir.cloning_metadir()
 
542
        branch = self.make_branch('branch', format='knit')
 
543
        format = branch.bzrdir.cloning_metadir()
 
544
        self.assertIsInstance(format.workingtree_format,
 
545
            workingtree.WorkingTreeFormat3)
 
546
 
 
547
    def test_sprout_recursive_treeless(self):
 
548
        tree = self.make_branch_and_tree('tree1',
 
549
            format='dirstate-with-subtree')
 
550
        sub_tree = self.make_branch_and_tree('tree1/subtree',
 
551
            format='dirstate-with-subtree')
 
552
        tree.add_reference(sub_tree)
 
553
        self.build_tree(['tree1/subtree/file'])
 
554
        sub_tree.add('file')
 
555
        tree.commit('Initial commit')
 
556
        tree.bzrdir.destroy_workingtree()
 
557
        repo = self.make_repository('repo', shared=True,
 
558
            format='dirstate-with-subtree')
 
559
        repo.set_make_working_trees(False)
 
560
        tree.bzrdir.sprout('repo/tree2')
 
561
        self.failUnlessExists('repo/tree2/subtree')
 
562
        self.failIfExists('repo/tree2/subtree/file')
 
563
 
 
564
 
 
565
class TestMeta1DirFormat(TestCaseWithTransport):
 
566
    """Tests specific to the meta1 dir format."""
 
567
 
 
568
    def test_right_base_dirs(self):
 
569
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
 
570
        t = dir.transport
 
571
        branch_base = t.clone('branch').base
 
572
        self.assertEqual(branch_base, dir.get_branch_transport(None).base)
 
573
        self.assertEqual(branch_base,
 
574
                         dir.get_branch_transport(bzrlib.branch.BzrBranchFormat5()).base)
 
575
        repository_base = t.clone('repository').base
 
576
        self.assertEqual(repository_base, dir.get_repository_transport(None).base)
 
577
        self.assertEqual(repository_base,
 
578
                         dir.get_repository_transport(weaverepo.RepositoryFormat7()).base)
 
579
        checkout_base = t.clone('checkout').base
 
580
        self.assertEqual(checkout_base, dir.get_workingtree_transport(None).base)
 
581
        self.assertEqual(checkout_base,
 
582
                         dir.get_workingtree_transport(workingtree.WorkingTreeFormat3()).base)
 
583
 
 
584
    def test_meta1dir_uses_lockdir(self):
 
585
        """Meta1 format uses a LockDir to guard the whole directory, not a file."""
 
586
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
 
587
        t = dir.transport
 
588
        self.assertIsDirectory('branch-lock', t)
 
589
 
 
590
    def test_comparison(self):
 
591
        """Equality and inequality behave properly.
 
592
 
 
593
        Metadirs should compare equal iff they have the same repo, branch and
 
594
        tree formats.
 
595
        """
 
596
        mydir = bzrdir.format_registry.make_bzrdir('knit')
 
597
        self.assertEqual(mydir, mydir)
 
598
        self.assertFalse(mydir != mydir)
 
599
        otherdir = bzrdir.format_registry.make_bzrdir('knit')
 
600
        self.assertEqual(otherdir, mydir)
 
601
        self.assertFalse(otherdir != mydir)
 
602
        otherdir2 = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
 
603
        self.assertNotEqual(otherdir2, mydir)
 
604
        self.assertFalse(otherdir2 == mydir)
 
605
 
 
606
    def test_needs_conversion_different_working_tree(self):
 
607
        # meta1dirs need an conversion if any element is not the default.
 
608
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
609
        # test with 
 
610
        new_default = bzrdir.format_registry.make_bzrdir('dirstate')
 
611
        bzrdir.BzrDirFormat._set_default_format(new_default)
 
612
        try:
 
613
            tree = self.make_branch_and_tree('tree', format='knit')
 
614
            self.assertTrue(tree.bzrdir.needs_format_conversion())
 
615
        finally:
 
616
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
617
 
 
618
 
 
619
class TestFormat5(TestCaseWithTransport):
 
620
    """Tests specific to the version 5 bzrdir format."""
 
621
 
 
622
    def test_same_lockfiles_between_tree_repo_branch(self):
 
623
        # this checks that only a single lockfiles instance is created 
 
624
        # for format 5 objects
 
625
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
626
        def check_dir_components_use_same_lock(dir):
 
627
            ctrl_1 = dir.open_repository().control_files
 
628
            ctrl_2 = dir.open_branch().control_files
 
629
            ctrl_3 = dir.open_workingtree()._control_files
 
630
            self.assertTrue(ctrl_1 is ctrl_2)
 
631
            self.assertTrue(ctrl_2 is ctrl_3)
 
632
        check_dir_components_use_same_lock(dir)
 
633
        # and if we open it normally.
 
634
        dir = bzrdir.BzrDir.open(self.get_url())
 
635
        check_dir_components_use_same_lock(dir)
 
636
    
 
637
    def test_can_convert(self):
 
638
        # format 5 dirs are convertable
 
639
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
640
        self.assertTrue(dir.can_convert_format())
 
641
    
 
642
    def test_needs_conversion(self):
 
643
        # format 5 dirs need a conversion if they are not the default.
 
644
        # and they start of not the default.
 
645
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
646
        bzrdir.BzrDirFormat._set_default_format(bzrdir.BzrDirFormat5())
 
647
        try:
 
648
            dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
649
            self.assertFalse(dir.needs_format_conversion())
 
650
        finally:
 
651
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
652
        self.assertTrue(dir.needs_format_conversion())
 
653
 
 
654
 
 
655
class TestFormat6(TestCaseWithTransport):
 
656
    """Tests specific to the version 6 bzrdir format."""
 
657
 
 
658
    def test_same_lockfiles_between_tree_repo_branch(self):
 
659
        # this checks that only a single lockfiles instance is created 
 
660
        # for format 6 objects
 
661
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
662
        def check_dir_components_use_same_lock(dir):
 
663
            ctrl_1 = dir.open_repository().control_files
 
664
            ctrl_2 = dir.open_branch().control_files
 
665
            ctrl_3 = dir.open_workingtree()._control_files
 
666
            self.assertTrue(ctrl_1 is ctrl_2)
 
667
            self.assertTrue(ctrl_2 is ctrl_3)
 
668
        check_dir_components_use_same_lock(dir)
 
669
        # and if we open it normally.
 
670
        dir = bzrdir.BzrDir.open(self.get_url())
 
671
        check_dir_components_use_same_lock(dir)
 
672
    
 
673
    def test_can_convert(self):
 
674
        # format 6 dirs are convertable
 
675
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
676
        self.assertTrue(dir.can_convert_format())
 
677
    
 
678
    def test_needs_conversion(self):
 
679
        # format 6 dirs need an conversion if they are not the default.
 
680
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
681
        bzrdir.BzrDirFormat._set_default_format(bzrdir.BzrDirMetaFormat1())
 
682
        try:
 
683
            dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
684
            self.assertTrue(dir.needs_format_conversion())
 
685
        finally:
 
686
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
687
 
 
688
 
 
689
class NotBzrDir(bzrlib.bzrdir.BzrDir):
 
690
    """A non .bzr based control directory."""
 
691
 
 
692
    def __init__(self, transport, format):
 
693
        self._format = format
 
694
        self.root_transport = transport
 
695
        self.transport = transport.clone('.not')
 
696
 
 
697
 
 
698
class NotBzrDirFormat(bzrlib.bzrdir.BzrDirFormat):
 
699
    """A test class representing any non-.bzr based disk format."""
 
700
 
 
701
    def initialize_on_transport(self, transport):
 
702
        """Initialize a new .not dir in the base directory of a Transport."""
 
703
        transport.mkdir('.not')
 
704
        return self.open(transport)
 
705
 
 
706
    def open(self, transport):
 
707
        """Open this directory."""
 
708
        return NotBzrDir(transport, self)
 
709
 
 
710
    @classmethod
 
711
    def _known_formats(self):
 
712
        return set([NotBzrDirFormat()])
 
713
 
 
714
    @classmethod
 
715
    def probe_transport(self, transport):
 
716
        """Our format is present if the transport ends in '.not/'."""
 
717
        if transport.has('.not'):
 
718
            return NotBzrDirFormat()
 
719
 
 
720
 
 
721
class TestNotBzrDir(TestCaseWithTransport):
 
722
    """Tests for using the bzrdir api with a non .bzr based disk format.
 
723
    
 
724
    If/when one of these is in the core, we can let the implementation tests
 
725
    verify this works.
 
726
    """
 
727
 
 
728
    def test_create_and_find_format(self):
 
729
        # create a .notbzr dir 
 
730
        format = NotBzrDirFormat()
 
731
        dir = format.initialize(self.get_url())
 
732
        self.assertIsInstance(dir, NotBzrDir)
 
733
        # now probe for it.
 
734
        bzrlib.bzrdir.BzrDirFormat.register_control_format(format)
 
735
        try:
 
736
            found = bzrlib.bzrdir.BzrDirFormat.find_format(
 
737
                get_transport(self.get_url()))
 
738
            self.assertIsInstance(found, NotBzrDirFormat)
 
739
        finally:
 
740
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(format)
 
741
 
 
742
    def test_included_in_known_formats(self):
 
743
        bzrlib.bzrdir.BzrDirFormat.register_control_format(NotBzrDirFormat)
 
744
        try:
 
745
            formats = bzrlib.bzrdir.BzrDirFormat.known_formats()
 
746
            for format in formats:
 
747
                if isinstance(format, NotBzrDirFormat):
 
748
                    return
 
749
            self.fail("No NotBzrDirFormat in %s" % formats)
 
750
        finally:
 
751
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(NotBzrDirFormat)
 
752
 
 
753
 
 
754
class NonLocalTests(TestCaseWithTransport):
 
755
    """Tests for bzrdir static behaviour on non local paths."""
 
756
 
 
757
    def setUp(self):
 
758
        super(NonLocalTests, self).setUp()
 
759
        self.vfs_transport_factory = MemoryServer
 
760
    
 
761
    def test_create_branch_convenience(self):
 
762
        # outside a repo the default convenience output is a repo+branch_tree
 
763
        format = bzrdir.format_registry.make_bzrdir('knit')
 
764
        branch = bzrdir.BzrDir.create_branch_convenience(
 
765
            self.get_url('foo'), format=format)
 
766
        self.assertRaises(errors.NoWorkingTree,
 
767
                          branch.bzrdir.open_workingtree)
 
768
        branch.bzrdir.open_repository()
 
769
 
 
770
    def test_create_branch_convenience_force_tree_not_local_fails(self):
 
771
        # outside a repo the default convenience output is a repo+branch_tree
 
772
        format = bzrdir.format_registry.make_bzrdir('knit')
 
773
        self.assertRaises(errors.NotLocalUrl,
 
774
            bzrdir.BzrDir.create_branch_convenience,
 
775
            self.get_url('foo'),
 
776
            force_new_tree=True,
 
777
            format=format)
 
778
        t = get_transport(self.get_url('.'))
 
779
        self.assertFalse(t.has('foo'))
 
780
 
 
781
    def test_clone(self):
 
782
        # clone into a nonlocal path works
 
783
        format = bzrdir.format_registry.make_bzrdir('knit')
 
784
        branch = bzrdir.BzrDir.create_branch_convenience('local',
 
785
                                                         format=format)
 
786
        branch.bzrdir.open_workingtree()
 
787
        result = branch.bzrdir.clone(self.get_url('remote'))
 
788
        self.assertRaises(errors.NoWorkingTree,
 
789
                          result.open_workingtree)
 
790
        result.open_branch()
 
791
        result.open_repository()
 
792
 
 
793
    def test_checkout_metadir(self):
 
794
        # checkout_metadir has reasonable working tree format even when no
 
795
        # working tree is present
 
796
        self.make_branch('branch-knit2', format='dirstate-with-subtree')
 
797
        my_bzrdir = bzrdir.BzrDir.open(self.get_url('branch-knit2'))
 
798
        checkout_format = my_bzrdir.checkout_metadir()
 
799
        self.assertIsInstance(checkout_format.workingtree_format,
 
800
                              workingtree.WorkingTreeFormat3)
 
801
 
 
802
 
 
803
class TestHTTPRedirectionLoop(object):
 
804
    """Test redirection loop between two http servers.
 
805
 
 
806
    This MUST be used by daughter classes that also inherit from
 
807
    TestCaseWithTwoWebservers.
 
808
 
 
809
    We can't inherit directly from TestCaseWithTwoWebservers or the
 
810
    test framework will try to create an instance which cannot
 
811
    run, its implementation being incomplete. 
 
812
    """
 
813
 
 
814
    # Should be defined by daughter classes to ensure redirection
 
815
    # still use the same transport implementation (not currently
 
816
    # enforced as it's a bit tricky to get right (see the FIXME
 
817
    # in BzrDir.open_from_transport for the unique use case so
 
818
    # far)
 
819
    _qualifier = None
 
820
 
 
821
    def create_transport_readonly_server(self):
 
822
        return HTTPServerRedirecting()
 
823
 
 
824
    def create_transport_secondary_server(self):
 
825
        return HTTPServerRedirecting()
 
826
 
 
827
    def setUp(self):
 
828
        # Both servers redirect to each server creating a loop
 
829
        super(TestHTTPRedirectionLoop, self).setUp()
 
830
        # The redirections will point to the new server
 
831
        self.new_server = self.get_readonly_server()
 
832
        # The requests to the old server will be redirected
 
833
        self.old_server = self.get_secondary_server()
 
834
        # Configure the redirections
 
835
        self.old_server.redirect_to(self.new_server.host, self.new_server.port)
 
836
        self.new_server.redirect_to(self.old_server.host, self.old_server.port)
 
837
 
 
838
    def _qualified_url(self, host, port):
 
839
        return 'http+%s://%s:%s' % (self._qualifier, host, port)
 
840
 
 
841
    def test_loop(self):
 
842
        # Starting from either server should loop
 
843
        old_url = self._qualified_url(self.old_server.host, 
 
844
                                      self.old_server.port)
 
845
        oldt = self._transport(old_url)
 
846
        self.assertRaises(errors.NotBranchError,
 
847
                          bzrdir.BzrDir.open_from_transport, oldt)
 
848
        new_url = self._qualified_url(self.new_server.host, 
 
849
                                      self.new_server.port)
 
850
        newt = self._transport(new_url)
 
851
        self.assertRaises(errors.NotBranchError,
 
852
                          bzrdir.BzrDir.open_from_transport, newt)
 
853
 
 
854
 
 
855
class TestHTTPRedirections_urllib(TestHTTPRedirectionLoop,
 
856
                                  TestCaseWithTwoWebservers):
 
857
    """Tests redirections for urllib implementation"""
 
858
 
 
859
    _qualifier = 'urllib'
 
860
    _transport = HttpTransport_urllib
 
861
 
 
862
 
 
863
 
 
864
class TestHTTPRedirections_pycurl(TestWithTransport_pycurl,
 
865
                                  TestHTTPRedirectionLoop,
 
866
                                  TestCaseWithTwoWebservers):
 
867
    """Tests redirections for pycurl implementation"""
 
868
 
 
869
    _qualifier = 'pycurl'