~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_bzrdir.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-09-01 06:53:18 UTC
  • mfrom: (3668.1.1 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20080901065318-3r92nk175nbu54dw
(vila, verterok) Fix some OSX failing tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2013, 2016 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for the BzrDir facility and any format specific tests.
18
18
 
19
 
For interface contract tests, see tests/per_bzr_dir.
 
19
For interface contract tests, see tests/bzr_dir_implementations.
20
20
"""
21
21
 
22
22
import os
 
23
import os.path
 
24
from StringIO import StringIO
23
25
import subprocess
24
26
import sys
25
27
 
26
28
from bzrlib import (
27
 
    branch,
28
29
    bzrdir,
29
 
    config,
30
 
    controldir,
31
30
    errors,
32
31
    help_topics,
33
 
    lock,
34
32
    repository,
35
 
    revision as _mod_revision,
36
33
    osutils,
37
 
    remote,
38
 
    transport as _mod_transport,
 
34
    symbol_versioning,
39
35
    urlutils,
40
36
    win32utils,
41
 
    workingtree_3,
42
 
    workingtree_4,
 
37
    workingtree,
43
38
    )
44
39
import bzrlib.branch
45
 
from bzrlib.branchfmt.fullhistory import BzrBranchFormat5
46
 
from bzrlib.errors import (
47
 
    NotBranchError,
48
 
    NoColocatedBranchSupport,
49
 
    UnknownFormatError,
50
 
    UnsupportedFormatError,
51
 
    )
 
40
from bzrlib.errors import (NotBranchError,
 
41
                           UnknownFormatError,
 
42
                           UnsupportedFormatError,
 
43
                           )
52
44
from bzrlib.tests import (
53
45
    TestCase,
54
46
    TestCaseWithMemoryTransport,
55
47
    TestCaseWithTransport,
56
48
    TestSkipped,
 
49
    test_sftp_transport
57
50
    )
58
 
from bzrlib.tests import(
59
 
    http_server,
60
 
    http_utils,
 
51
from bzrlib.tests.http_server import HttpServer
 
52
from bzrlib.tests.http_utils import (
 
53
    TestCaseWithTwoWebservers,
 
54
    HTTPServerRedirecting,
61
55
    )
62
56
from bzrlib.tests.test_http import TestWithTransport_pycurl
63
 
from bzrlib.transport import (
64
 
    memory,
65
 
    pathfilter,
66
 
    )
 
57
from bzrlib.transport import get_transport
67
58
from bzrlib.transport.http._urllib import HttpTransport_urllib
68
 
from bzrlib.transport.nosmart import NoSmartTransportDecorator
69
 
from bzrlib.transport.readonly import ReadonlyTransportDecorator
70
 
from bzrlib.repofmt import knitrepo, knitpack_repo
 
59
from bzrlib.transport.memory import MemoryServer
 
60
from bzrlib.repofmt import knitrepo, weaverepo
71
61
 
72
62
 
73
63
class TestDefaultFormat(TestCase):
74
64
 
75
65
    def test_get_set_default_format(self):
76
66
        old_format = bzrdir.BzrDirFormat.get_default_format()
77
 
        # default is BzrDirMetaFormat1
78
 
        self.assertIsInstance(old_format, bzrdir.BzrDirMetaFormat1)
79
 
        controldir.ControlDirFormat._set_default_format(SampleBzrDirFormat())
 
67
        # default is BzrDirFormat6
 
68
        self.failUnless(isinstance(old_format, bzrdir.BzrDirMetaFormat1))
 
69
        bzrdir.BzrDirFormat._set_default_format(SampleBzrDirFormat())
80
70
        # creating a bzr dir should now create an instrumented dir.
81
71
        try:
82
72
            result = bzrdir.BzrDir.create('memory:///')
83
 
            self.assertIsInstance(result, SampleBzrDir)
 
73
            self.failUnless(isinstance(result, SampleBzrDir))
84
74
        finally:
85
 
            controldir.ControlDirFormat._set_default_format(old_format)
 
75
            bzrdir.BzrDirFormat._set_default_format(old_format)
86
76
        self.assertEqual(old_format, bzrdir.BzrDirFormat.get_default_format())
87
77
 
88
78
 
89
 
class DeprecatedBzrDirFormat(bzrdir.BzrDirFormat):
90
 
    """A deprecated bzr dir format."""
91
 
 
92
 
 
93
79
class TestFormatRegistry(TestCase):
94
80
 
95
81
    def make_format_registry(self):
96
 
        my_format_registry = controldir.ControlDirFormatRegistry()
97
 
        my_format_registry.register('deprecated', DeprecatedBzrDirFormat,
98
 
            'Some format.  Slower and unawesome and deprecated.',
99
 
            deprecated=True)
100
 
        my_format_registry.register_lazy('lazy', 'bzrlib.tests.test_bzrdir',
101
 
            'DeprecatedBzrDirFormat', 'Format registered lazily',
102
 
            deprecated=True)
103
 
        bzrdir.register_metadir(my_format_registry, 'knit',
 
82
        my_format_registry = bzrdir.BzrDirFormatRegistry()
 
83
        my_format_registry.register('weave', bzrdir.BzrDirFormat6,
 
84
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
85
            ' repositories', deprecated=True)
 
86
        my_format_registry.register_lazy('lazy', 'bzrlib.bzrdir', 
 
87
            'BzrDirFormat6', 'Format registered lazily', deprecated=True)
 
88
        my_format_registry.register_metadir('knit',
104
89
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
105
90
            'Format using knits',
106
91
            )
107
92
        my_format_registry.set_default('knit')
108
 
        bzrdir.register_metadir(my_format_registry,
 
93
        my_format_registry.register_metadir(
109
94
            'branch6',
110
95
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
111
96
            'Experimental successor to knit.  Use at your own risk.',
112
97
            branch_format='bzrlib.branch.BzrBranchFormat6',
113
98
            experimental=True)
114
 
        bzrdir.register_metadir(my_format_registry,
 
99
        my_format_registry.register_metadir(
115
100
            'hidden format',
116
101
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
117
102
            'Experimental successor to knit.  Use at your own risk.',
118
103
            branch_format='bzrlib.branch.BzrBranchFormat6', hidden=True)
119
 
        my_format_registry.register('hiddendeprecated', DeprecatedBzrDirFormat,
120
 
            'Old format.  Slower and does not support things. ', hidden=True)
121
 
        my_format_registry.register_lazy('hiddenlazy', 'bzrlib.tests.test_bzrdir',
122
 
            'DeprecatedBzrDirFormat', 'Format registered lazily',
123
 
            deprecated=True, hidden=True)
 
104
        my_format_registry.register('hiddenweave', bzrdir.BzrDirFormat6,
 
105
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
106
            ' repositories', hidden=True)
 
107
        my_format_registry.register_lazy('hiddenlazy', 'bzrlib.bzrdir',
 
108
            'BzrDirFormat6', 'Format registered lazily', deprecated=True,
 
109
            hidden=True)
124
110
        return my_format_registry
125
111
 
126
112
    def test_format_registry(self):
127
113
        my_format_registry = self.make_format_registry()
128
114
        my_bzrdir = my_format_registry.make_bzrdir('lazy')
129
 
        self.assertIsInstance(my_bzrdir, DeprecatedBzrDirFormat)
130
 
        my_bzrdir = my_format_registry.make_bzrdir('deprecated')
131
 
        self.assertIsInstance(my_bzrdir, DeprecatedBzrDirFormat)
 
115
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
 
116
        my_bzrdir = my_format_registry.make_bzrdir('weave')
 
117
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
132
118
        my_bzrdir = my_format_registry.make_bzrdir('default')
133
 
        self.assertIsInstance(my_bzrdir.repository_format,
 
119
        self.assertIsInstance(my_bzrdir.repository_format, 
134
120
            knitrepo.RepositoryFormatKnit1)
135
121
        my_bzrdir = my_format_registry.make_bzrdir('knit')
136
 
        self.assertIsInstance(my_bzrdir.repository_format,
 
122
        self.assertIsInstance(my_bzrdir.repository_format, 
137
123
            knitrepo.RepositoryFormatKnit1)
138
124
        my_bzrdir = my_format_registry.make_bzrdir('branch6')
139
125
        self.assertIsInstance(my_bzrdir.get_branch_format(),
143
129
        my_format_registry = self.make_format_registry()
144
130
        self.assertEqual('Format registered lazily',
145
131
                         my_format_registry.get_help('lazy'))
146
 
        self.assertEqual('Format using knits',
 
132
        self.assertEqual('Format using knits', 
147
133
                         my_format_registry.get_help('knit'))
148
 
        self.assertEqual('Format using knits',
 
134
        self.assertEqual('Format using knits', 
149
135
                         my_format_registry.get_help('default'))
150
 
        self.assertEqual('Some format.  Slower and unawesome and deprecated.',
151
 
                         my_format_registry.get_help('deprecated'))
152
 
 
 
136
        self.assertEqual('Pre-0.8 format.  Slower and does not support'
 
137
                         ' checkouts or shared repositories', 
 
138
                         my_format_registry.get_help('weave'))
 
139
        
153
140
    def test_help_topic(self):
154
141
        topics = help_topics.HelpTopicRegistry()
155
 
        registry = self.make_format_registry()
156
 
        topics.register('current-formats', registry.help_topic,
157
 
                        'Current formats')
158
 
        topics.register('other-formats', registry.help_topic,
159
 
                        'Other formats')
160
 
        new = topics.get_detail('current-formats')
161
 
        rest = topics.get_detail('other-formats')
 
142
        topics.register('formats', self.make_format_registry().help_topic, 
 
143
                        'Directory formats')
 
144
        topic = topics.get_detail('formats')
 
145
        new, rest = topic.split('Experimental formats')
162
146
        experimental, deprecated = rest.split('Deprecated formats')
163
 
        self.assertContainsRe(new, 'formats-help')
164
 
        self.assertContainsRe(new,
 
147
        self.assertContainsRe(new, 'These formats can be used')
 
148
        self.assertContainsRe(new, 
165
149
                ':knit:\n    \(native\) \(default\) Format using knits\n')
166
 
        self.assertContainsRe(experimental,
 
150
        self.assertContainsRe(experimental, 
167
151
                ':branch6:\n    \(native\) Experimental successor to knit')
168
 
        self.assertContainsRe(deprecated,
 
152
        self.assertContainsRe(deprecated, 
169
153
                ':lazy:\n    \(native\) Format registered lazily\n')
170
154
        self.assertNotContainsRe(new, 'hidden')
171
155
 
172
156
    def test_set_default_repository(self):
173
 
        default_factory = controldir.format_registry.get('default')
174
 
        old_default = [k for k, v in controldir.format_registry.iteritems()
 
157
        default_factory = bzrdir.format_registry.get('default')
 
158
        old_default = [k for k, v in bzrdir.format_registry.iteritems()
175
159
                       if v == default_factory and k != 'default'][0]
176
 
        controldir.format_registry.set_default_repository('dirstate-with-subtree')
 
160
        bzrdir.format_registry.set_default_repository('dirstate-with-subtree')
177
161
        try:
178
 
            self.assertIs(controldir.format_registry.get('dirstate-with-subtree'),
179
 
                          controldir.format_registry.get('default'))
 
162
            self.assertIs(bzrdir.format_registry.get('dirstate-with-subtree'),
 
163
                          bzrdir.format_registry.get('default'))
180
164
            self.assertIs(
181
 
                repository.format_registry.get_default().__class__,
 
165
                repository.RepositoryFormat.get_default_format().__class__,
182
166
                knitrepo.RepositoryFormatKnit3)
183
167
        finally:
184
 
            controldir.format_registry.set_default_repository(old_default)
 
168
            bzrdir.format_registry.set_default_repository(old_default)
185
169
 
186
170
    def test_aliases(self):
187
 
        a_registry = controldir.ControlDirFormatRegistry()
188
 
        a_registry.register('deprecated', DeprecatedBzrDirFormat,
189
 
            'Old format.  Slower and does not support stuff',
190
 
            deprecated=True)
191
 
        a_registry.register('deprecatedalias', DeprecatedBzrDirFormat,
192
 
            'Old format.  Slower and does not support stuff',
193
 
            deprecated=True, alias=True)
194
 
        self.assertEqual(frozenset(['deprecatedalias']), a_registry.aliases())
195
 
 
 
171
        a_registry = bzrdir.BzrDirFormatRegistry()
 
172
        a_registry.register('weave', bzrdir.BzrDirFormat6,
 
173
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
174
            ' repositories', deprecated=True)
 
175
        a_registry.register('weavealias', bzrdir.BzrDirFormat6,
 
176
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
 
177
            ' repositories', deprecated=True, alias=True)
 
178
        self.assertEqual(frozenset(['weavealias']), a_registry.aliases())
 
179
    
196
180
 
197
181
class SampleBranch(bzrlib.branch.Branch):
198
182
    """A dummy branch for guess what, dummy use."""
201
185
        self.bzrdir = dir
202
186
 
203
187
 
204
 
class SampleRepository(bzrlib.repository.Repository):
205
 
    """A dummy repo."""
206
 
 
207
 
    def __init__(self, dir):
208
 
        self.bzrdir = dir
209
 
 
210
 
 
211
188
class SampleBzrDir(bzrdir.BzrDir):
212
189
    """A sample BzrDir implementation to allow testing static methods."""
213
190
 
214
191
    def create_repository(self, shared=False):
215
 
        """See ControlDir.create_repository."""
 
192
        """See BzrDir.create_repository."""
216
193
        return "A repository"
217
194
 
218
195
    def open_repository(self):
219
 
        """See ControlDir.open_repository."""
220
 
        return SampleRepository(self)
 
196
        """See BzrDir.open_repository."""
 
197
        return "A repository"
221
198
 
222
 
    def create_branch(self, name=None):
223
 
        """See ControlDir.create_branch."""
224
 
        if name is not None:
225
 
            raise NoColocatedBranchSupport(self)
 
199
    def create_branch(self):
 
200
        """See BzrDir.create_branch."""
226
201
        return SampleBranch(self)
227
202
 
228
203
    def create_workingtree(self):
229
 
        """See ControlDir.create_workingtree."""
 
204
        """See BzrDir.create_workingtree."""
230
205
        return "A tree"
231
206
 
232
207
 
233
208
class SampleBzrDirFormat(bzrdir.BzrDirFormat):
234
209
    """A sample format
235
210
 
236
 
    this format is initializable, unsupported to aid in testing the
 
211
    this format is initializable, unsupported to aid in testing the 
237
212
    open and open_downlevel routines.
238
213
    """
239
214
 
253
228
    def open(self, transport, _found=None):
254
229
        return "opened branch."
255
230
 
256
 
    @classmethod
257
 
    def from_string(cls, format_string):
258
 
        return cls()
259
 
 
260
 
 
261
 
class BzrDirFormatTest1(bzrdir.BzrDirMetaFormat1):
262
 
 
263
 
    @staticmethod
264
 
    def get_format_string():
265
 
        return "Test format 1"
266
 
 
267
 
 
268
 
class BzrDirFormatTest2(bzrdir.BzrDirMetaFormat1):
269
 
 
270
 
    @staticmethod
271
 
    def get_format_string():
272
 
        return "Test format 2"
273
 
 
274
231
 
275
232
class TestBzrDirFormat(TestCaseWithTransport):
276
233
    """Tests for the BzrDirFormat facility."""
278
235
    def test_find_format(self):
279
236
        # is the right format object found for a branch?
280
237
        # create a branch with a few known format objects.
281
 
        bzrdir.BzrProber.formats.register(BzrDirFormatTest1.get_format_string(),
282
 
            BzrDirFormatTest1())
283
 
        self.addCleanup(bzrdir.BzrProber.formats.remove,
284
 
            BzrDirFormatTest1.get_format_string())
285
 
        bzrdir.BzrProber.formats.register(BzrDirFormatTest2.get_format_string(),
286
 
            BzrDirFormatTest2())
287
 
        self.addCleanup(bzrdir.BzrProber.formats.remove,
288
 
            BzrDirFormatTest2.get_format_string())
289
 
        t = self.get_transport()
 
238
        # this is not quite the same as 
 
239
        t = get_transport(self.get_url())
290
240
        self.build_tree(["foo/", "bar/"], transport=t)
291
241
        def check_format(format, url):
292
242
            format.initialize(url)
293
 
            t = _mod_transport.get_transport_from_path(url)
 
243
            t = get_transport(url)
294
244
            found_format = bzrdir.BzrDirFormat.find_format(t)
295
 
            self.assertIsInstance(found_format, format.__class__)
296
 
        check_format(BzrDirFormatTest1(), "foo")
297
 
        check_format(BzrDirFormatTest2(), "bar")
298
 
 
 
245
            self.failUnless(isinstance(found_format, format.__class__))
 
246
        check_format(bzrdir.BzrDirFormat5(), "foo")
 
247
        check_format(bzrdir.BzrDirFormat6(), "bar")
 
248
        
299
249
    def test_find_format_nothing_there(self):
300
250
        self.assertRaises(NotBranchError,
301
251
                          bzrdir.BzrDirFormat.find_format,
302
 
                          _mod_transport.get_transport_from_path('.'))
 
252
                          get_transport('.'))
303
253
 
304
254
    def test_find_format_unknown_format(self):
305
 
        t = self.get_transport()
 
255
        t = get_transport(self.get_url())
306
256
        t.mkdir('.bzr')
307
257
        t.put_bytes('.bzr/branch-format', '')
308
258
        self.assertRaises(UnknownFormatError,
309
259
                          bzrdir.BzrDirFormat.find_format,
310
 
                          _mod_transport.get_transport_from_path('.'))
 
260
                          get_transport('.'))
311
261
 
312
262
    def test_register_unregister_format(self):
313
263
        format = SampleBzrDirFormat()
315
265
        # make a bzrdir
316
266
        format.initialize(url)
317
267
        # register a format for it.
318
 
        bzrdir.BzrProber.formats.register(format.get_format_string(), format)
 
268
        bzrdir.BzrDirFormat.register_format(format)
319
269
        # which bzrdir.Open will refuse (not supported)
320
270
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open, url)
321
271
        # which bzrdir.open_containing will refuse (not supported)
322
272
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open_containing, url)
323
273
        # but open_downlevel will work
324
 
        t = _mod_transport.get_transport_from_url(url)
 
274
        t = get_transport(url)
325
275
        self.assertEqual(format.open(t), bzrdir.BzrDir.open_unsupported(url))
326
276
        # unregister the format
327
 
        bzrdir.BzrProber.formats.remove(format.get_format_string())
 
277
        bzrdir.BzrDirFormat.unregister_format(format)
328
278
        # now open_downlevel should fail too.
329
279
        self.assertRaises(UnknownFormatError, bzrdir.BzrDir.open_unsupported, url)
330
280
 
337
287
    def test_create_branch_and_repo_under_shared(self):
338
288
        # creating a branch and repo in a shared repo uses the
339
289
        # shared repository
340
 
        format = controldir.format_registry.make_bzrdir('knit')
 
290
        format = bzrdir.format_registry.make_bzrdir('knit')
341
291
        self.make_repository('.', shared=True, format=format)
342
292
        branch = bzrdir.BzrDir.create_branch_and_repo(
343
293
            self.get_url('child'), format=format)
345
295
                          branch.bzrdir.open_repository)
346
296
 
347
297
    def test_create_branch_and_repo_under_shared_force_new(self):
348
 
        # creating a branch and repo in a shared repo can be forced to
 
298
        # creating a branch and repo in a shared repo can be forced to 
349
299
        # make a new repo
350
 
        format = controldir.format_registry.make_bzrdir('knit')
 
300
        format = bzrdir.format_registry.make_bzrdir('knit')
351
301
        self.make_repository('.', shared=True, format=format)
352
302
        branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url('child'),
353
303
                                                      force_new_repo=True,
356
306
 
357
307
    def test_create_standalone_working_tree(self):
358
308
        format = SampleBzrDirFormat()
359
 
        # note this is deliberately readonly, as this failure should
 
309
        # note this is deliberately readonly, as this failure should 
360
310
        # occur before any writes.
361
311
        self.assertRaises(errors.NotLocalUrl,
362
312
                          bzrdir.BzrDir.create_standalone_workingtree,
363
313
                          self.get_readonly_url(), format=format)
364
 
        tree = bzrdir.BzrDir.create_standalone_workingtree('.',
 
314
        tree = bzrdir.BzrDir.create_standalone_workingtree('.', 
365
315
                                                           format=format)
366
316
        self.assertEqual('A tree', tree)
367
317
 
368
318
    def test_create_standalone_working_tree_under_shared_repo(self):
369
319
        # create standalone working tree always makes a repo.
370
 
        format = controldir.format_registry.make_bzrdir('knit')
 
320
        format = bzrdir.format_registry.make_bzrdir('knit')
371
321
        self.make_repository('.', shared=True, format=format)
372
 
        # note this is deliberately readonly, as this failure should
 
322
        # note this is deliberately readonly, as this failure should 
373
323
        # occur before any writes.
374
324
        self.assertRaises(errors.NotLocalUrl,
375
325
                          bzrdir.BzrDir.create_standalone_workingtree,
376
326
                          self.get_readonly_url('child'), format=format)
377
 
        tree = bzrdir.BzrDir.create_standalone_workingtree('child',
 
327
        tree = bzrdir.BzrDir.create_standalone_workingtree('child', 
378
328
            format=format)
379
329
        tree.bzrdir.open_repository()
380
330
 
381
331
    def test_create_branch_convenience(self):
382
332
        # outside a repo the default convenience output is a repo+branch_tree
383
 
        format = controldir.format_registry.make_bzrdir('knit')
 
333
        format = bzrdir.format_registry.make_bzrdir('knit')
384
334
        branch = bzrdir.BzrDir.create_branch_convenience('.', format=format)
385
335
        branch.bzrdir.open_workingtree()
386
336
        branch.bzrdir.open_repository()
387
337
 
388
338
    def test_create_branch_convenience_possible_transports(self):
389
339
        """Check that the optional 'possible_transports' is recognized"""
390
 
        format = controldir.format_registry.make_bzrdir('knit')
 
340
        format = bzrdir.format_registry.make_bzrdir('knit')
391
341
        t = self.get_transport()
392
342
        branch = bzrdir.BzrDir.create_branch_convenience(
393
343
            '.', format=format, possible_transports=[t])
396
346
 
397
347
    def test_create_branch_convenience_root(self):
398
348
        """Creating a branch at the root of a fs should work."""
399
 
        self.vfs_transport_factory = memory.MemoryServer
 
349
        self.vfs_transport_factory = MemoryServer
400
350
        # outside a repo the default convenience output is a repo+branch_tree
401
 
        format = controldir.format_registry.make_bzrdir('knit')
402
 
        branch = bzrdir.BzrDir.create_branch_convenience(self.get_url(),
 
351
        format = bzrdir.format_registry.make_bzrdir('knit')
 
352
        branch = bzrdir.BzrDir.create_branch_convenience(self.get_url(), 
403
353
                                                         format=format)
404
354
        self.assertRaises(errors.NoWorkingTree,
405
355
                          branch.bzrdir.open_workingtree)
408
358
    def test_create_branch_convenience_under_shared_repo(self):
409
359
        # inside a repo the default convenience output is a branch+ follow the
410
360
        # repo tree policy
411
 
        format = controldir.format_registry.make_bzrdir('knit')
 
361
        format = bzrdir.format_registry.make_bzrdir('knit')
412
362
        self.make_repository('.', shared=True, format=format)
413
363
        branch = bzrdir.BzrDir.create_branch_convenience('child',
414
364
            format=format)
415
365
        branch.bzrdir.open_workingtree()
416
366
        self.assertRaises(errors.NoRepositoryPresent,
417
367
                          branch.bzrdir.open_repository)
418
 
 
 
368
            
419
369
    def test_create_branch_convenience_under_shared_repo_force_no_tree(self):
420
370
        # inside a repo the default convenience output is a branch+ follow the
421
371
        # repo tree policy but we can override that
422
 
        format = controldir.format_registry.make_bzrdir('knit')
 
372
        format = bzrdir.format_registry.make_bzrdir('knit')
423
373
        self.make_repository('.', shared=True, format=format)
424
374
        branch = bzrdir.BzrDir.create_branch_convenience('child',
425
375
            force_new_tree=False, format=format)
427
377
                          branch.bzrdir.open_workingtree)
428
378
        self.assertRaises(errors.NoRepositoryPresent,
429
379
                          branch.bzrdir.open_repository)
430
 
 
 
380
            
431
381
    def test_create_branch_convenience_under_shared_repo_no_tree_policy(self):
432
382
        # inside a repo the default convenience output is a branch+ follow the
433
383
        # repo tree policy
434
 
        format = controldir.format_registry.make_bzrdir('knit')
 
384
        format = bzrdir.format_registry.make_bzrdir('knit')
435
385
        repo = self.make_repository('.', shared=True, format=format)
436
386
        repo.set_make_working_trees(False)
437
 
        branch = bzrdir.BzrDir.create_branch_convenience('child',
 
387
        branch = bzrdir.BzrDir.create_branch_convenience('child', 
438
388
                                                         format=format)
439
389
        self.assertRaises(errors.NoWorkingTree,
440
390
                          branch.bzrdir.open_workingtree)
444
394
    def test_create_branch_convenience_under_shared_repo_no_tree_policy_force_tree(self):
445
395
        # inside a repo the default convenience output is a branch+ follow the
446
396
        # repo tree policy but we can override that
447
 
        format = controldir.format_registry.make_bzrdir('knit')
 
397
        format = bzrdir.format_registry.make_bzrdir('knit')
448
398
        repo = self.make_repository('.', shared=True, format=format)
449
399
        repo.set_make_working_trees(False)
450
400
        branch = bzrdir.BzrDir.create_branch_convenience('child',
456
406
    def test_create_branch_convenience_under_shared_repo_force_new_repo(self):
457
407
        # inside a repo the default convenience output is overridable to give
458
408
        # repo+branch+tree
459
 
        format = controldir.format_registry.make_bzrdir('knit')
 
409
        format = bzrdir.format_registry.make_bzrdir('knit')
460
410
        self.make_repository('.', shared=True, format=format)
461
411
        branch = bzrdir.BzrDir.create_branch_convenience('child',
462
412
            force_new_repo=True, format=format)
470
420
        """The default acquisition policy should create a standalone branch."""
471
421
        my_bzrdir = self.make_bzrdir('.')
472
422
        repo_policy = my_bzrdir.determine_repository_policy()
473
 
        repo, is_new = repo_policy.acquire_repository()
 
423
        repo = repo_policy.acquire_repository()
474
424
        self.assertEqual(repo.bzrdir.root_transport.base,
475
425
                         my_bzrdir.root_transport.base)
476
426
        self.assertFalse(repo.is_shared())
477
427
 
 
428
 
478
429
    def test_determine_stacking_policy(self):
479
430
        parent_bzrdir = self.make_bzrdir('.')
480
431
        child_bzrdir = self.make_bzrdir('child')
491
442
        self.assertEqual(parent_bzrdir.root_transport.base,
492
443
                         repo_policy._stack_on_pwd)
493
444
 
494
 
    def prepare_default_stacking(self, child_format='1.6'):
 
445
    def prepare_default_stacking(self, child_format='development1'):
495
446
        parent_bzrdir = self.make_bzrdir('.')
496
447
        child_branch = self.make_branch('child', format=child_format)
497
448
        parent_bzrdir.get_config().set_default_stack_on(child_branch.base)
504
455
        self.assertEqual(child_branch.base,
505
456
                         new_child.open_branch().get_stacked_on_url())
506
457
 
507
 
    def test_default_stacking_with_stackable_branch_unstackable_repo(self):
508
 
        # Make stackable source branch with an unstackable repo format.
509
 
        source_bzrdir = self.make_bzrdir('source')
510
 
        knitpack_repo.RepositoryFormatKnitPack1().initialize(source_bzrdir)
511
 
        source_branch = bzrlib.branch.BzrBranchFormat7().initialize(
512
 
            source_bzrdir)
513
 
        # Make a directory with a default stacking policy
514
 
        parent_bzrdir = self.make_bzrdir('parent')
515
 
        stacked_on = self.make_branch('parent/stacked-on', format='pack-0.92')
516
 
        parent_bzrdir.get_config().set_default_stack_on(stacked_on.base)
517
 
        # Clone source into directory
518
 
        target = source_bzrdir.clone(self.get_url('parent/target'))
519
 
 
520
 
    def test_format_initialize_on_transport_ex_stacked_on(self):
521
 
        # trunk is a stackable format.  Note that its in the same server area
522
 
        # which is what launchpad does, but not sufficient to exercise the
523
 
        # general case.
524
 
        trunk = self.make_branch('trunk', format='1.9')
525
 
        t = self.get_transport('stacked')
526
 
        old_fmt = controldir.format_registry.make_bzrdir('pack-0.92')
527
 
        repo_name = old_fmt.repository_format.network_name()
528
 
        # Should end up with a 1.9 format (stackable)
529
 
        repo, control, require_stacking, repo_policy = \
530
 
            old_fmt.initialize_on_transport_ex(t,
531
 
                    repo_format_name=repo_name, stacked_on='../trunk',
532
 
                    stack_on_pwd=t.base)
533
 
        if repo is not None:
534
 
            # Repositories are open write-locked
535
 
            self.assertTrue(repo.is_write_locked())
536
 
            self.addCleanup(repo.unlock)
537
 
        else:
538
 
            repo = control.open_repository()
539
 
        self.assertIsInstance(control, bzrdir.BzrDir)
540
 
        opened = bzrdir.BzrDir.open(t.base)
541
 
        if not isinstance(old_fmt, remote.RemoteBzrDirFormat):
542
 
            self.assertEqual(control._format.network_name(),
543
 
                old_fmt.network_name())
544
 
            self.assertEqual(control._format.network_name(),
545
 
                opened._format.network_name())
546
 
        self.assertEqual(control.__class__, opened.__class__)
547
 
        self.assertLength(1, repo._fallback_repositories)
548
 
 
549
458
    def test_sprout_obeys_stacking_policy(self):
550
459
        child_branch, new_child_transport = self.prepare_default_stacking()
551
460
        new_child = child_branch.bzrdir.sprout(new_child_transport.base)
577
486
        self.assertTrue(repo._format.supports_external_lookups)
578
487
        self.assertFalse(repo.supports_rich_root())
579
488
 
580
 
    def test_clone_on_transport_upgrades_format_if_stacked_on_specified(self):
581
 
        child_branch, new_child_transport = self.prepare_default_stacking(
582
 
            child_format='pack-0.92')
583
 
        new_child = child_branch.bzrdir.clone_on_transport(new_child_transport,
584
 
            stacked_on=child_branch.bzrdir.root_transport.base)
585
 
        self.assertEqual(child_branch.bzrdir.root_transport.base,
586
 
                         new_child.open_branch().get_stacked_on_url())
587
 
        repo = new_child.open_repository()
588
 
        self.assertTrue(repo._format.supports_external_lookups)
589
 
        self.assertFalse(repo.supports_rich_root())
590
 
 
591
489
    def test_sprout_upgrades_to_rich_root_format_if_needed(self):
592
490
        child_branch, new_child_transport = self.prepare_default_stacking(
593
491
            child_format='rich-root-pack')
598
496
        self.assertTrue(repo.supports_rich_root())
599
497
 
600
498
    def test_add_fallback_repo_handles_absolute_urls(self):
601
 
        stack_on = self.make_branch('stack_on', format='1.6')
602
 
        repo = self.make_repository('repo', format='1.6')
 
499
        stack_on = self.make_branch('stack_on', format='development1')
 
500
        repo = self.make_repository('repo', format='development1')
603
501
        policy = bzrdir.UseExistingRepository(repo, stack_on.base)
604
502
        policy._add_fallback(repo)
605
503
 
606
504
    def test_add_fallback_repo_handles_relative_urls(self):
607
 
        stack_on = self.make_branch('stack_on', format='1.6')
608
 
        repo = self.make_repository('repo', format='1.6')
 
505
        stack_on = self.make_branch('stack_on', format='development1')
 
506
        repo = self.make_repository('repo', format='development1')
609
507
        policy = bzrdir.UseExistingRepository(repo, '.', stack_on.base)
610
508
        policy._add_fallback(repo)
611
509
 
612
510
    def test_configure_relative_branch_stacking_url(self):
613
 
        stack_on = self.make_branch('stack_on', format='1.6')
614
 
        stacked = self.make_branch('stack_on/stacked', format='1.6')
 
511
        stack_on = self.make_branch('stack_on', format='development1')
 
512
        stacked = self.make_branch('stack_on/stacked', format='development1')
615
513
        policy = bzrdir.UseExistingRepository(stacked.repository,
616
514
            '.', stack_on.base)
617
515
        policy.configure_branch(stacked)
618
516
        self.assertEqual('..', stacked.get_stacked_on_url())
619
517
 
620
518
    def test_relative_branch_stacking_to_absolute(self):
621
 
        stack_on = self.make_branch('stack_on', format='1.6')
622
 
        stacked = self.make_branch('stack_on/stacked', format='1.6')
 
519
        stack_on = self.make_branch('stack_on', format='development1')
 
520
        stacked = self.make_branch('stack_on/stacked', format='development1')
623
521
        policy = bzrdir.UseExistingRepository(stacked.repository,
624
522
            '.', self.get_readonly_url('stack_on'))
625
523
        policy.configure_branch(stacked)
637
535
 
638
536
    def setUp(self):
639
537
        super(ChrootedTests, self).setUp()
640
 
        if not self.vfs_transport_factory == memory.MemoryServer:
641
 
            self.transport_readonly_server = http_server.HttpServer
 
538
        if not self.vfs_transport_factory == MemoryServer:
 
539
            self.transport_readonly_server = HttpServer
642
540
 
643
541
    def local_branch_path(self, branch):
644
542
         return os.path.realpath(urlutils.local_path_from_url(branch.base))
742
640
        self.assertEqual(relpath, 'baz')
743
641
 
744
642
    def test_open_containing_from_transport(self):
745
 
        self.assertRaises(NotBranchError,
746
 
            bzrdir.BzrDir.open_containing_from_transport,
747
 
            _mod_transport.get_transport_from_url(self.get_readonly_url('')))
748
 
        self.assertRaises(NotBranchError,
749
 
            bzrdir.BzrDir.open_containing_from_transport,
750
 
            _mod_transport.get_transport_from_url(
751
 
                self.get_readonly_url('g/p/q')))
 
643
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
 
644
                          get_transport(self.get_readonly_url('')))
 
645
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
 
646
                          get_transport(self.get_readonly_url('g/p/q')))
752
647
        control = bzrdir.BzrDir.create(self.get_url())
753
648
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
754
 
            _mod_transport.get_transport_from_url(
755
 
                self.get_readonly_url('')))
 
649
            get_transport(self.get_readonly_url('')))
756
650
        self.assertEqual('', relpath)
757
651
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
758
 
            _mod_transport.get_transport_from_url(
759
 
                self.get_readonly_url('g/p/q')))
 
652
            get_transport(self.get_readonly_url('g/p/q')))
760
653
        self.assertEqual('g/p/q', relpath)
761
654
 
762
655
    def test_open_containing_tree_or_branch(self):
806
699
        # transport pointing at bzrdir should give a bzrdir with root transport
807
700
        # set to the given transport
808
701
        control = bzrdir.BzrDir.create(self.get_url())
809
 
        t = self.get_transport()
810
 
        opened_bzrdir = bzrdir.BzrDir.open_from_transport(t)
811
 
        self.assertEqual(t.base, opened_bzrdir.root_transport.base)
 
702
        transport = get_transport(self.get_url())
 
703
        opened_bzrdir = bzrdir.BzrDir.open_from_transport(transport)
 
704
        self.assertEqual(transport.base, opened_bzrdir.root_transport.base)
812
705
        self.assertIsInstance(opened_bzrdir, bzrdir.BzrDir)
813
 
 
 
706
        
814
707
    def test_open_from_transport_no_bzrdir(self):
815
 
        t = self.get_transport()
816
 
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport, t)
 
708
        transport = get_transport(self.get_url())
 
709
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
 
710
                          transport)
817
711
 
818
712
    def test_open_from_transport_bzrdir_in_parent(self):
819
713
        control = bzrdir.BzrDir.create(self.get_url())
820
 
        t = self.get_transport()
821
 
        t.mkdir('subdir')
822
 
        t = t.clone('subdir')
823
 
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport, t)
 
714
        transport = get_transport(self.get_url())
 
715
        transport.mkdir('subdir')
 
716
        transport = transport.clone('subdir')
 
717
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
 
718
                          transport)
824
719
 
825
720
    def test_sprout_recursive(self):
826
 
        tree = self.make_branch_and_tree('tree1',
827
 
                                         format='development-subtree')
 
721
        tree = self.make_branch_and_tree('tree1', format='dirstate-with-subtree')
828
722
        sub_tree = self.make_branch_and_tree('tree1/subtree',
829
 
            format='development-subtree')
830
 
        sub_tree.set_root_id('subtree-root')
 
723
            format='dirstate-with-subtree')
831
724
        tree.add_reference(sub_tree)
832
725
        self.build_tree(['tree1/subtree/file'])
833
726
        sub_tree.add('file')
834
727
        tree.commit('Initial commit')
835
 
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
836
 
        tree2.lock_read()
837
 
        self.addCleanup(tree2.unlock)
838
 
        self.assertPathExists('tree2/subtree/file')
839
 
        self.assertEqual('tree-reference', tree2.kind('subtree-root'))
 
728
        tree.bzrdir.sprout('tree2')
 
729
        self.failUnlessExists('tree2/subtree/file')
840
730
 
841
731
    def test_cloning_metadir(self):
842
732
        """Ensure that cloning metadir is suitable"""
845
735
        branch = self.make_branch('branch', format='knit')
846
736
        format = branch.bzrdir.cloning_metadir()
847
737
        self.assertIsInstance(format.workingtree_format,
848
 
            workingtree_4.WorkingTreeFormat6)
 
738
            workingtree.WorkingTreeFormat3)
849
739
 
850
740
    def test_sprout_recursive_treeless(self):
851
741
        tree = self.make_branch_and_tree('tree1',
852
 
            format='development-subtree')
 
742
            format='dirstate-with-subtree')
853
743
        sub_tree = self.make_branch_and_tree('tree1/subtree',
854
 
            format='development-subtree')
 
744
            format='dirstate-with-subtree')
855
745
        tree.add_reference(sub_tree)
856
746
        self.build_tree(['tree1/subtree/file'])
857
747
        sub_tree.add('file')
858
748
        tree.commit('Initial commit')
859
 
        # The following line force the orhaning to reveal bug #634470
860
 
        tree.branch.get_config_stack().set(
861
 
            'bzr.transform.orphan_policy', 'move')
862
749
        tree.bzrdir.destroy_workingtree()
863
 
        # FIXME: subtree/.bzr is left here which allows the test to pass (or
864
 
        # fail :-( ) -- vila 20100909
865
750
        repo = self.make_repository('repo', shared=True,
866
 
            format='development-subtree')
 
751
            format='dirstate-with-subtree')
867
752
        repo.set_make_working_trees(False)
868
 
        # FIXME: we just deleted the workingtree and now we want to use it ????
869
 
        # At a minimum, we should use tree.branch below (but this fails too
870
 
        # currently) or stop calling this test 'treeless'. Specifically, I've
871
 
        # turn the line below into an assertRaises when 'subtree/.bzr' is
872
 
        # orphaned and sprout tries to access the branch there (which is left
873
 
        # by bzrdir.BzrDirMeta1.destroy_workingtree when it ignores the
874
 
        # [DeletingParent('Not deleting', u'subtree', None)] conflict). See bug
875
 
        # #634470.  -- vila 20100909
876
 
        self.assertRaises(errors.NotBranchError,
877
 
                          tree.bzrdir.sprout, 'repo/tree2')
878
 
#        self.assertPathExists('repo/tree2/subtree')
879
 
#        self.assertPathDoesNotExist('repo/tree2/subtree/file')
 
753
        tree.bzrdir.sprout('repo/tree2')
 
754
        self.failUnlessExists('repo/tree2/subtree')
 
755
        self.failIfExists('repo/tree2/subtree/file')
880
756
 
881
757
    def make_foo_bar_baz(self):
882
758
        foo = bzrdir.BzrDir.create_branch_convenience('foo').bzrdir
886
762
 
887
763
    def test_find_bzrdirs(self):
888
764
        foo, bar, baz = self.make_foo_bar_baz()
889
 
        t = self.get_transport()
890
 
        self.assertEqualBzrdirs([baz, foo, bar], bzrdir.BzrDir.find_bzrdirs(t))
891
 
 
892
 
    def make_fake_permission_denied_transport(self, transport, paths):
893
 
        """Create a transport that raises PermissionDenied for some paths."""
894
 
        def filter(path):
895
 
            if path in paths:
896
 
                raise errors.PermissionDenied(path)
897
 
            return path
898
 
        path_filter_server = pathfilter.PathFilteringServer(transport, filter)
899
 
        path_filter_server.start_server()
900
 
        self.addCleanup(path_filter_server.stop_server)
901
 
        path_filter_transport = pathfilter.PathFilteringTransport(
902
 
            path_filter_server, '.')
903
 
        return (path_filter_server, path_filter_transport)
904
 
 
905
 
    def assertBranchUrlsEndWith(self, expect_url_suffix, actual_bzrdirs):
906
 
        """Check that each branch url ends with the given suffix."""
907
 
        for actual_bzrdir in actual_bzrdirs:
908
 
            self.assertEndsWith(actual_bzrdir.user_url, expect_url_suffix)
909
 
 
910
 
    def test_find_bzrdirs_permission_denied(self):
911
 
        foo, bar, baz = self.make_foo_bar_baz()
912
 
        t = self.get_transport()
913
 
        path_filter_server, path_filter_transport = \
914
 
            self.make_fake_permission_denied_transport(t, ['foo'])
915
 
        # local transport
916
 
        self.assertBranchUrlsEndWith('/baz/',
917
 
            bzrdir.BzrDir.find_bzrdirs(path_filter_transport))
918
 
        # smart server
919
 
        smart_transport = self.make_smart_server('.',
920
 
            backing_server=path_filter_server)
921
 
        self.assertBranchUrlsEndWith('/baz/',
922
 
            bzrdir.BzrDir.find_bzrdirs(smart_transport))
 
765
        transport = get_transport(self.get_url())
 
766
        self.assertEqualBzrdirs([baz, foo, bar],
 
767
                                bzrdir.BzrDir.find_bzrdirs(transport))
923
768
 
924
769
    def test_find_bzrdirs_list_current(self):
925
770
        def list_current(transport):
926
771
            return [s for s in transport.list_dir('') if s != 'baz']
927
772
 
928
773
        foo, bar, baz = self.make_foo_bar_baz()
929
 
        t = self.get_transport()
930
 
        self.assertEqualBzrdirs(
931
 
            [foo, bar],
932
 
            bzrdir.BzrDir.find_bzrdirs(t, list_current=list_current))
 
774
        transport = get_transport(self.get_url())
 
775
        self.assertEqualBzrdirs([foo, bar],
 
776
                                bzrdir.BzrDir.find_bzrdirs(transport,
 
777
                                    list_current=list_current))
 
778
 
933
779
 
934
780
    def test_find_bzrdirs_evaluate(self):
935
781
        def evaluate(bzrdir):
936
782
            try:
937
783
                repo = bzrdir.open_repository()
938
 
            except errors.NoRepositoryPresent:
 
784
            except NoRepositoryPresent:
939
785
                return True, bzrdir.root_transport.base
940
786
            else:
941
787
                return False, bzrdir.root_transport.base
942
788
 
943
789
        foo, bar, baz = self.make_foo_bar_baz()
944
 
        t = self.get_transport()
 
790
        transport = get_transport(self.get_url())
945
791
        self.assertEqual([baz.root_transport.base, foo.root_transport.base],
946
 
                         list(bzrdir.BzrDir.find_bzrdirs(t, evaluate=evaluate)))
 
792
                         list(bzrdir.BzrDir.find_bzrdirs(transport,
 
793
                                                         evaluate=evaluate)))
947
794
 
948
795
    def assertEqualBzrdirs(self, first, second):
949
796
        first = list(first)
956
803
        root = self.make_repository('', shared=True)
957
804
        foo, bar, baz = self.make_foo_bar_baz()
958
805
        qux = self.make_bzrdir('foo/qux')
959
 
        t = self.get_transport()
960
 
        branches = bzrdir.BzrDir.find_branches(t)
 
806
        transport = get_transport(self.get_url())
 
807
        branches = bzrdir.BzrDir.find_branches(transport)
961
808
        self.assertEqual(baz.root_transport.base, branches[0].base)
962
809
        self.assertEqual(foo.root_transport.base, branches[1].base)
963
810
        self.assertEqual(bar.root_transport.base, branches[2].base)
964
811
 
965
812
        # ensure this works without a top-level repo
966
 
        branches = bzrdir.BzrDir.find_branches(t.clone('foo'))
 
813
        branches = bzrdir.BzrDir.find_branches(transport.clone('foo'))
967
814
        self.assertEqual(foo.root_transport.base, branches[0].base)
968
815
        self.assertEqual(bar.root_transport.base, branches[1].base)
969
816
 
970
817
 
971
 
class TestMissingRepoBranchesSkipped(TestCaseWithMemoryTransport):
972
 
 
973
 
    def test_find_bzrdirs_missing_repo(self):
974
 
        t = self.get_transport()
975
 
        arepo = self.make_repository('arepo', shared=True)
976
 
        abranch_url = arepo.user_url + '/abranch'
977
 
        abranch = bzrdir.BzrDir.create(abranch_url).create_branch()
978
 
        t.delete_tree('arepo/.bzr')
979
 
        self.assertRaises(errors.NoRepositoryPresent,
980
 
            branch.Branch.open, abranch_url)
981
 
        self.make_branch('baz')
982
 
        for actual_bzrdir in bzrdir.BzrDir.find_branches(t):
983
 
            self.assertEndsWith(actual_bzrdir.user_url, '/baz/')
984
 
 
985
 
 
986
818
class TestMeta1DirFormat(TestCaseWithTransport):
987
819
    """Tests specific to the meta1 dir format."""
988
820
 
992
824
        branch_base = t.clone('branch').base
993
825
        self.assertEqual(branch_base, dir.get_branch_transport(None).base)
994
826
        self.assertEqual(branch_base,
995
 
                         dir.get_branch_transport(BzrBranchFormat5()).base)
 
827
                         dir.get_branch_transport(bzrlib.branch.BzrBranchFormat5()).base)
996
828
        repository_base = t.clone('repository').base
997
829
        self.assertEqual(repository_base, dir.get_repository_transport(None).base)
998
 
        repository_format = repository.format_registry.get_default()
999
830
        self.assertEqual(repository_base,
1000
 
                         dir.get_repository_transport(repository_format).base)
 
831
                         dir.get_repository_transport(weaverepo.RepositoryFormat7()).base)
1001
832
        checkout_base = t.clone('checkout').base
1002
833
        self.assertEqual(checkout_base, dir.get_workingtree_transport(None).base)
1003
834
        self.assertEqual(checkout_base,
1004
 
                         dir.get_workingtree_transport(workingtree_3.WorkingTreeFormat3()).base)
 
835
                         dir.get_workingtree_transport(workingtree.WorkingTreeFormat3()).base)
1005
836
 
1006
837
    def test_meta1dir_uses_lockdir(self):
1007
838
        """Meta1 format uses a LockDir to guard the whole directory, not a file."""
1015
846
        Metadirs should compare equal iff they have the same repo, branch and
1016
847
        tree formats.
1017
848
        """
1018
 
        mydir = controldir.format_registry.make_bzrdir('knit')
 
849
        mydir = bzrdir.format_registry.make_bzrdir('knit')
1019
850
        self.assertEqual(mydir, mydir)
1020
851
        self.assertFalse(mydir != mydir)
1021
 
        otherdir = controldir.format_registry.make_bzrdir('knit')
 
852
        otherdir = bzrdir.format_registry.make_bzrdir('knit')
1022
853
        self.assertEqual(otherdir, mydir)
1023
854
        self.assertFalse(otherdir != mydir)
1024
 
        otherdir2 = controldir.format_registry.make_bzrdir('development-subtree')
 
855
        otherdir2 = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
1025
856
        self.assertNotEqual(otherdir2, mydir)
1026
857
        self.assertFalse(otherdir2 == mydir)
1027
858
 
1028
 
    def test_with_features(self):
1029
 
        tree = self.make_branch_and_tree('tree', format='2a')
1030
 
        tree.bzrdir.update_feature_flags({"bar": "required"})
1031
 
        self.assertRaises(errors.MissingFeature, bzrdir.BzrDir.open, 'tree')
1032
 
        bzrdir.BzrDirMetaFormat1.register_feature('bar')
1033
 
        self.addCleanup(bzrdir.BzrDirMetaFormat1.unregister_feature, 'bar')
1034
 
        dir = bzrdir.BzrDir.open('tree')
1035
 
        self.assertEqual("required", dir._format.features.get("bar"))
1036
 
        tree.bzrdir.update_feature_flags({"bar": None, "nonexistant": None})
1037
 
        dir = bzrdir.BzrDir.open('tree')
1038
 
        self.assertEqual({}, dir._format.features)
1039
 
 
1040
859
    def test_needs_conversion_different_working_tree(self):
1041
860
        # meta1dirs need an conversion if any element is not the default.
1042
 
        new_format = controldir.format_registry.make_bzrdir('dirstate')
1043
 
        tree = self.make_branch_and_tree('tree', format='knit')
1044
 
        self.assertTrue(tree.bzrdir.needs_format_conversion(
1045
 
            new_format))
1046
 
 
1047
 
    def test_initialize_on_format_uses_smart_transport(self):
1048
 
        self.setup_smart_server_with_call_log()
1049
 
        new_format = controldir.format_registry.make_bzrdir('dirstate')
1050
 
        transport = self.get_transport('target')
1051
 
        transport.ensure_base()
1052
 
        self.reset_smart_call_log()
1053
 
        instance = new_format.initialize_on_transport(transport)
1054
 
        self.assertIsInstance(instance, remote.RemoteBzrDir)
1055
 
        rpc_count = len(self.hpss_calls)
1056
 
        # This figure represent the amount of work to perform this use case. It
1057
 
        # is entirely ok to reduce this number if a test fails due to rpc_count
1058
 
        # being too low. If rpc_count increases, more network roundtrips have
1059
 
        # become necessary for this use case. Please do not adjust this number
1060
 
        # upwards without agreement from bzr's network support maintainers.
1061
 
        self.assertEqual(2, rpc_count)
 
861
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
862
        # test with 
 
863
        new_default = bzrdir.format_registry.make_bzrdir('dirstate')
 
864
        bzrdir.BzrDirFormat._set_default_format(new_default)
 
865
        try:
 
866
            tree = self.make_branch_and_tree('tree', format='knit')
 
867
            self.assertTrue(tree.bzrdir.needs_format_conversion())
 
868
        finally:
 
869
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
870
 
 
871
 
 
872
class TestFormat5(TestCaseWithTransport):
 
873
    """Tests specific to the version 5 bzrdir format."""
 
874
 
 
875
    def test_same_lockfiles_between_tree_repo_branch(self):
 
876
        # this checks that only a single lockfiles instance is created 
 
877
        # for format 5 objects
 
878
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
879
        def check_dir_components_use_same_lock(dir):
 
880
            ctrl_1 = dir.open_repository().control_files
 
881
            ctrl_2 = dir.open_branch().control_files
 
882
            ctrl_3 = dir.open_workingtree()._control_files
 
883
            self.assertTrue(ctrl_1 is ctrl_2)
 
884
            self.assertTrue(ctrl_2 is ctrl_3)
 
885
        check_dir_components_use_same_lock(dir)
 
886
        # and if we open it normally.
 
887
        dir = bzrdir.BzrDir.open(self.get_url())
 
888
        check_dir_components_use_same_lock(dir)
 
889
    
 
890
    def test_can_convert(self):
 
891
        # format 5 dirs are convertable
 
892
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
893
        self.assertTrue(dir.can_convert_format())
 
894
    
 
895
    def test_needs_conversion(self):
 
896
        # format 5 dirs need a conversion if they are not the default.
 
897
        # and they start of not the default.
 
898
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
899
        bzrdir.BzrDirFormat._set_default_format(bzrdir.BzrDirFormat5())
 
900
        try:
 
901
            dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
 
902
            self.assertFalse(dir.needs_format_conversion())
 
903
        finally:
 
904
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
905
        self.assertTrue(dir.needs_format_conversion())
 
906
 
 
907
 
 
908
class TestFormat6(TestCaseWithTransport):
 
909
    """Tests specific to the version 6 bzrdir format."""
 
910
 
 
911
    def test_same_lockfiles_between_tree_repo_branch(self):
 
912
        # this checks that only a single lockfiles instance is created 
 
913
        # for format 6 objects
 
914
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
915
        def check_dir_components_use_same_lock(dir):
 
916
            ctrl_1 = dir.open_repository().control_files
 
917
            ctrl_2 = dir.open_branch().control_files
 
918
            ctrl_3 = dir.open_workingtree()._control_files
 
919
            self.assertTrue(ctrl_1 is ctrl_2)
 
920
            self.assertTrue(ctrl_2 is ctrl_3)
 
921
        check_dir_components_use_same_lock(dir)
 
922
        # and if we open it normally.
 
923
        dir = bzrdir.BzrDir.open(self.get_url())
 
924
        check_dir_components_use_same_lock(dir)
 
925
    
 
926
    def test_can_convert(self):
 
927
        # format 6 dirs are convertable
 
928
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
929
        self.assertTrue(dir.can_convert_format())
 
930
    
 
931
    def test_needs_conversion(self):
 
932
        # format 6 dirs need an conversion if they are not the default.
 
933
        old_format = bzrdir.BzrDirFormat.get_default_format()
 
934
        bzrdir.BzrDirFormat._set_default_format(bzrdir.BzrDirMetaFormat1())
 
935
        try:
 
936
            dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
 
937
            self.assertTrue(dir.needs_format_conversion())
 
938
        finally:
 
939
            bzrdir.BzrDirFormat._set_default_format(old_format)
 
940
 
 
941
 
 
942
class NotBzrDir(bzrlib.bzrdir.BzrDir):
 
943
    """A non .bzr based control directory."""
 
944
 
 
945
    def __init__(self, transport, format):
 
946
        self._format = format
 
947
        self.root_transport = transport
 
948
        self.transport = transport.clone('.not')
 
949
 
 
950
 
 
951
class NotBzrDirFormat(bzrlib.bzrdir.BzrDirFormat):
 
952
    """A test class representing any non-.bzr based disk format."""
 
953
 
 
954
    def initialize_on_transport(self, transport):
 
955
        """Initialize a new .not dir in the base directory of a Transport."""
 
956
        transport.mkdir('.not')
 
957
        return self.open(transport)
 
958
 
 
959
    def open(self, transport):
 
960
        """Open this directory."""
 
961
        return NotBzrDir(transport, self)
 
962
 
 
963
    @classmethod
 
964
    def _known_formats(self):
 
965
        return set([NotBzrDirFormat()])
 
966
 
 
967
    @classmethod
 
968
    def probe_transport(self, transport):
 
969
        """Our format is present if the transport ends in '.not/'."""
 
970
        if transport.has('.not'):
 
971
            return NotBzrDirFormat()
 
972
 
 
973
 
 
974
class TestNotBzrDir(TestCaseWithTransport):
 
975
    """Tests for using the bzrdir api with a non .bzr based disk format.
 
976
    
 
977
    If/when one of these is in the core, we can let the implementation tests
 
978
    verify this works.
 
979
    """
 
980
 
 
981
    def test_create_and_find_format(self):
 
982
        # create a .notbzr dir 
 
983
        format = NotBzrDirFormat()
 
984
        dir = format.initialize(self.get_url())
 
985
        self.assertIsInstance(dir, NotBzrDir)
 
986
        # now probe for it.
 
987
        bzrlib.bzrdir.BzrDirFormat.register_control_format(format)
 
988
        try:
 
989
            found = bzrlib.bzrdir.BzrDirFormat.find_format(
 
990
                get_transport(self.get_url()))
 
991
            self.assertIsInstance(found, NotBzrDirFormat)
 
992
        finally:
 
993
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(format)
 
994
 
 
995
    def test_included_in_known_formats(self):
 
996
        bzrlib.bzrdir.BzrDirFormat.register_control_format(NotBzrDirFormat)
 
997
        try:
 
998
            formats = bzrlib.bzrdir.BzrDirFormat.known_formats()
 
999
            for format in formats:
 
1000
                if isinstance(format, NotBzrDirFormat):
 
1001
                    return
 
1002
            self.fail("No NotBzrDirFormat in %s" % formats)
 
1003
        finally:
 
1004
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(NotBzrDirFormat)
1062
1005
 
1063
1006
 
1064
1007
class NonLocalTests(TestCaseWithTransport):
1066
1009
 
1067
1010
    def setUp(self):
1068
1011
        super(NonLocalTests, self).setUp()
1069
 
        self.vfs_transport_factory = memory.MemoryServer
1070
 
 
 
1012
        self.vfs_transport_factory = MemoryServer
 
1013
    
1071
1014
    def test_create_branch_convenience(self):
1072
1015
        # outside a repo the default convenience output is a repo+branch_tree
1073
 
        format = controldir.format_registry.make_bzrdir('knit')
 
1016
        format = bzrdir.format_registry.make_bzrdir('knit')
1074
1017
        branch = bzrdir.BzrDir.create_branch_convenience(
1075
1018
            self.get_url('foo'), format=format)
1076
1019
        self.assertRaises(errors.NoWorkingTree,
1079
1022
 
1080
1023
    def test_create_branch_convenience_force_tree_not_local_fails(self):
1081
1024
        # outside a repo the default convenience output is a repo+branch_tree
1082
 
        format = controldir.format_registry.make_bzrdir('knit')
 
1025
        format = bzrdir.format_registry.make_bzrdir('knit')
1083
1026
        self.assertRaises(errors.NotLocalUrl,
1084
1027
            bzrdir.BzrDir.create_branch_convenience,
1085
1028
            self.get_url('foo'),
1086
1029
            force_new_tree=True,
1087
1030
            format=format)
1088
 
        t = self.get_transport()
 
1031
        t = get_transport(self.get_url('.'))
1089
1032
        self.assertFalse(t.has('foo'))
1090
1033
 
1091
1034
    def test_clone(self):
1092
1035
        # clone into a nonlocal path works
1093
 
        format = controldir.format_registry.make_bzrdir('knit')
 
1036
        format = bzrdir.format_registry.make_bzrdir('knit')
1094
1037
        branch = bzrdir.BzrDir.create_branch_convenience('local',
1095
1038
                                                         format=format)
1096
1039
        branch.bzrdir.open_workingtree()
1107
1050
        my_bzrdir = bzrdir.BzrDir.open(self.get_url('branch-knit2'))
1108
1051
        checkout_format = my_bzrdir.checkout_metadir()
1109
1052
        self.assertIsInstance(checkout_format.workingtree_format,
1110
 
                              workingtree_4.WorkingTreeFormat4)
1111
 
 
1112
 
 
1113
 
class TestHTTPRedirections(object):
1114
 
    """Test redirection between two http servers.
 
1053
                              workingtree.WorkingTreeFormat3)
 
1054
 
 
1055
 
 
1056
class TestHTTPRedirectionLoop(object):
 
1057
    """Test redirection loop between two http servers.
1115
1058
 
1116
1059
    This MUST be used by daughter classes that also inherit from
1117
1060
    TestCaseWithTwoWebservers.
1118
1061
 
1119
1062
    We can't inherit directly from TestCaseWithTwoWebservers or the
1120
1063
    test framework will try to create an instance which cannot
1121
 
    run, its implementation being incomplete.
 
1064
    run, its implementation being incomplete. 
1122
1065
    """
1123
1066
 
 
1067
    # Should be defined by daughter classes to ensure redirection
 
1068
    # still use the same transport implementation (not currently
 
1069
    # enforced as it's a bit tricky to get right (see the FIXME
 
1070
    # in BzrDir.open_from_transport for the unique use case so
 
1071
    # far)
 
1072
    _qualifier = None
 
1073
 
1124
1074
    def create_transport_readonly_server(self):
1125
 
        # We don't set the http protocol version, relying on the default
1126
 
        return http_utils.HTTPServerRedirecting()
 
1075
        return HTTPServerRedirecting()
1127
1076
 
1128
1077
    def create_transport_secondary_server(self):
1129
 
        # We don't set the http protocol version, relying on the default
1130
 
        return http_utils.HTTPServerRedirecting()
 
1078
        return HTTPServerRedirecting()
1131
1079
 
1132
1080
    def setUp(self):
1133
 
        super(TestHTTPRedirections, self).setUp()
 
1081
        # Both servers redirect to each server creating a loop
 
1082
        super(TestHTTPRedirectionLoop, self).setUp()
1134
1083
        # The redirections will point to the new server
1135
1084
        self.new_server = self.get_readonly_server()
1136
1085
        # The requests to the old server will be redirected
1137
1086
        self.old_server = self.get_secondary_server()
1138
1087
        # Configure the redirections
1139
1088
        self.old_server.redirect_to(self.new_server.host, self.new_server.port)
 
1089
        self.new_server.redirect_to(self.old_server.host, self.old_server.port)
 
1090
 
 
1091
    def _qualified_url(self, host, port):
 
1092
        return 'http+%s://%s:%s' % (self._qualifier, host, port)
1140
1093
 
1141
1094
    def test_loop(self):
1142
 
        # Both servers redirect to each other creating a loop
1143
 
        self.new_server.redirect_to(self.old_server.host, self.old_server.port)
1144
1095
        # Starting from either server should loop
1145
 
        old_url = self._qualified_url(self.old_server.host,
 
1096
        old_url = self._qualified_url(self.old_server.host, 
1146
1097
                                      self.old_server.port)
1147
1098
        oldt = self._transport(old_url)
1148
1099
        self.assertRaises(errors.NotBranchError,
1149
1100
                          bzrdir.BzrDir.open_from_transport, oldt)
1150
 
        new_url = self._qualified_url(self.new_server.host,
 
1101
        new_url = self._qualified_url(self.new_server.host, 
1151
1102
                                      self.new_server.port)
1152
1103
        newt = self._transport(new_url)
1153
1104
        self.assertRaises(errors.NotBranchError,
1154
1105
                          bzrdir.BzrDir.open_from_transport, newt)
1155
1106
 
1156
 
    def test_qualifier_preserved(self):
1157
 
        wt = self.make_branch_and_tree('branch')
1158
 
        old_url = self._qualified_url(self.old_server.host,
1159
 
                                      self.old_server.port)
1160
 
        start = self._transport(old_url).clone('branch')
1161
 
        bdir = bzrdir.BzrDir.open_from_transport(start)
1162
 
        # Redirection should preserve the qualifier, hence the transport class
1163
 
        # itself.
1164
 
        self.assertIsInstance(bdir.root_transport, type(start))
1165
 
 
1166
 
 
1167
 
class TestHTTPRedirections_urllib(TestHTTPRedirections,
1168
 
                                  http_utils.TestCaseWithTwoWebservers):
 
1107
 
 
1108
class TestHTTPRedirections_urllib(TestHTTPRedirectionLoop,
 
1109
                                  TestCaseWithTwoWebservers):
1169
1110
    """Tests redirections for urllib implementation"""
1170
1111
 
 
1112
    _qualifier = 'urllib'
1171
1113
    _transport = HttpTransport_urllib
1172
1114
 
1173
 
    def _qualified_url(self, host, port):
1174
 
        result = 'http+urllib://%s:%s' % (host, port)
1175
 
        self.permit_url(result)
1176
 
        return result
1177
 
 
1178
1115
 
1179
1116
 
1180
1117
class TestHTTPRedirections_pycurl(TestWithTransport_pycurl,
1181
 
                                  TestHTTPRedirections,
1182
 
                                  http_utils.TestCaseWithTwoWebservers):
 
1118
                                  TestHTTPRedirectionLoop,
 
1119
                                  TestCaseWithTwoWebservers):
1183
1120
    """Tests redirections for pycurl implementation"""
1184
1121
 
1185
 
    def _qualified_url(self, host, port):
1186
 
        result = 'http+pycurl://%s:%s' % (host, port)
1187
 
        self.permit_url(result)
1188
 
        return result
1189
 
 
1190
 
 
1191
 
class TestHTTPRedirections_nosmart(TestHTTPRedirections,
1192
 
                                  http_utils.TestCaseWithTwoWebservers):
1193
 
    """Tests redirections for the nosmart decorator"""
1194
 
 
1195
 
    _transport = NoSmartTransportDecorator
1196
 
 
1197
 
    def _qualified_url(self, host, port):
1198
 
        result = 'nosmart+http://%s:%s' % (host, port)
1199
 
        self.permit_url(result)
1200
 
        return result
1201
 
 
1202
 
 
1203
 
class TestHTTPRedirections_readonly(TestHTTPRedirections,
1204
 
                                    http_utils.TestCaseWithTwoWebservers):
1205
 
    """Tests redirections for readonly decoratror"""
1206
 
 
1207
 
    _transport = ReadonlyTransportDecorator
1208
 
 
1209
 
    def _qualified_url(self, host, port):
1210
 
        result = 'readonly+http://%s:%s' % (host, port)
1211
 
        self.permit_url(result)
1212
 
        return result
 
1122
    _qualifier = 'pycurl'
1213
1123
 
1214
1124
 
1215
1125
class TestDotBzrHidden(TestCaseWithTransport):
1231
1141
            raise TestSkipped('unable to make file hidden without pywin32 library')
1232
1142
        b = bzrdir.BzrDir.create('.')
1233
1143
        self.build_tree(['a'])
1234
 
        self.assertEqual(['a'], self.get_ls())
 
1144
        self.assertEquals(['a'], self.get_ls())
1235
1145
 
1236
1146
    def test_dot_bzr_hidden_with_url(self):
1237
1147
        if sys.platform == 'win32' and not win32utils.has_win32file:
1238
1148
            raise TestSkipped('unable to make file hidden without pywin32 library')
1239
1149
        b = bzrdir.BzrDir.create(urlutils.local_path_to_url('.'))
1240
1150
        self.build_tree(['a'])
1241
 
        self.assertEqual(['a'], self.get_ls())
 
1151
        self.assertEquals(['a'], self.get_ls())
1242
1152
 
1243
1153
 
1244
1154
class _TestBzrDirFormat(bzrdir.BzrDirMetaFormat1):
1250
1160
 
1251
1161
class _TestBzrDir(bzrdir.BzrDirMeta1):
1252
1162
    """Test BzrDir implementation for TestBzrDirSprout.
1253
 
 
 
1163
    
1254
1164
    When created a _TestBzrDir already has repository and a branch.  The branch
1255
1165
    is a test double as well.
1256
1166
    """
1257
1167
 
1258
1168
    def __init__(self, *args, **kwargs):
1259
1169
        super(_TestBzrDir, self).__init__(*args, **kwargs)
1260
 
        self.test_branch = _TestBranch(self.transport)
 
1170
        self.test_branch = _TestBranch()
1261
1171
        self.test_branch.repository = self.create_repository()
1262
1172
 
1263
 
    def open_branch(self, unsupported=False, possible_transports=None):
 
1173
    def open_branch(self, unsupported=False):
1264
1174
        return self.test_branch
1265
1175
 
1266
1176
    def cloning_metadir(self, require_stacking=False):
1267
1177
        return _TestBzrDirFormat()
1268
1178
 
1269
1179
 
1270
 
class _TestBranchFormat(bzrlib.branch.BranchFormat):
1271
 
    """Test Branch format for TestBzrDirSprout."""
1272
 
 
1273
 
 
1274
1180
class _TestBranch(bzrlib.branch.Branch):
1275
1181
    """Test Branch implementation for TestBzrDirSprout."""
1276
1182
 
1277
 
    def __init__(self, transport, *args, **kwargs):
1278
 
        self._format = _TestBranchFormat()
1279
 
        self._transport = transport
1280
 
        self.base = transport.base
 
1183
    def __init__(self, *args, **kwargs):
1281
1184
        super(_TestBranch, self).__init__(*args, **kwargs)
1282
1185
        self.calls = []
1283
1186
        self._parent = None
1284
1187
 
1285
1188
    def sprout(self, *args, **kwargs):
1286
1189
        self.calls.append('sprout')
1287
 
        return _TestBranch(self._transport)
 
1190
        return _TestBranch()
1288
1191
 
1289
1192
    def copy_content_into(self, destination, revision_id=None):
1290
1193
        self.calls.append('copy_content_into')
1291
1194
 
1292
 
    def last_revision(self):
1293
 
        return _mod_revision.NULL_REVISION
1294
 
 
1295
1195
    def get_parent(self):
1296
1196
        return self._parent
1297
1197
 
1298
 
    def _get_config(self):
1299
 
        return config.TransportConfig(self._transport, 'branch.conf')
1300
 
 
1301
 
    def _get_config_store(self):
1302
 
        return config.BranchStore(self)
1303
 
 
1304
1198
    def set_parent(self, parent):
1305
1199
        self._parent = parent
1306
1200
 
1307
 
    def lock_read(self):
1308
 
        return lock.LogicalLockResult(self.unlock)
1309
 
 
1310
 
    def unlock(self):
1311
 
        return
1312
 
 
1313
1201
 
1314
1202
class TestBzrDirSprout(TestCaseWithMemoryTransport):
1315
1203
 
1319
1207
        Usually, BzrDir.sprout should delegate to the branch's sprout method
1320
1208
        for part of the work.  This allows the source branch to control the
1321
1209
        choice of format for the new branch.
1322
 
 
 
1210
        
1323
1211
        There are exceptions, but this tests avoids them:
1324
1212
          - if there's no branch in the source bzrdir,
1325
1213
          - or if the stacking has been requested and the format needs to be
1346
1234
        parent = grandparent_tree.bzrdir.sprout('parent').open_branch()
1347
1235
        branch_tree = parent.bzrdir.sprout('branch').open_branch()
1348
1236
        self.assertContainsRe(branch_tree.get_parent(), '/parent/$')
1349
 
 
1350
 
 
1351
 
class TestBzrDirHooks(TestCaseWithMemoryTransport):
1352
 
 
1353
 
    def test_pre_open_called(self):
1354
 
        calls = []
1355
 
        bzrdir.BzrDir.hooks.install_named_hook('pre_open', calls.append, None)
1356
 
        transport = self.get_transport('foo')
1357
 
        url = transport.base
1358
 
        self.assertRaises(errors.NotBranchError, bzrdir.BzrDir.open, url)
1359
 
        self.assertEqual([transport.base], [t.base for t in calls])
1360
 
 
1361
 
    def test_pre_open_actual_exceptions_raised(self):
1362
 
        count = [0]
1363
 
        def fail_once(transport):
1364
 
            count[0] += 1
1365
 
            if count[0] == 1:
1366
 
                raise errors.BzrError("fail")
1367
 
        bzrdir.BzrDir.hooks.install_named_hook('pre_open', fail_once, None)
1368
 
        transport = self.get_transport('foo')
1369
 
        url = transport.base
1370
 
        err = self.assertRaises(errors.BzrError, bzrdir.BzrDir.open, url)
1371
 
        self.assertEqual('fail', err._preformatted_string)
1372
 
 
1373
 
    def test_post_repo_init(self):
1374
 
        from bzrlib.controldir import RepoInitHookParams
1375
 
        calls = []
1376
 
        bzrdir.BzrDir.hooks.install_named_hook('post_repo_init',
1377
 
            calls.append, None)
1378
 
        self.make_repository('foo')
1379
 
        self.assertLength(1, calls)
1380
 
        params = calls[0]
1381
 
        self.assertIsInstance(params, RepoInitHookParams)
1382
 
        self.assertTrue(hasattr(params, 'bzrdir'))
1383
 
        self.assertTrue(hasattr(params, 'repository'))
1384
 
 
1385
 
    def test_post_repo_init_hook_repr(self):
1386
 
        param_reprs = []
1387
 
        bzrdir.BzrDir.hooks.install_named_hook('post_repo_init',
1388
 
            lambda params: param_reprs.append(repr(params)), None)
1389
 
        self.make_repository('foo')
1390
 
        self.assertLength(1, param_reprs)
1391
 
        param_repr = param_reprs[0]
1392
 
        self.assertStartsWith(param_repr, '<RepoInitHookParams for ')
1393
 
 
1394
 
 
1395
 
class TestGenerateBackupName(TestCaseWithMemoryTransport):
1396
 
    # FIXME: This may need to be unified with test_osutils.TestBackupNames or
1397
 
    # moved to per_bzrdir or per_transport for better coverage ?
1398
 
    # -- vila 20100909
1399
 
 
1400
 
    def setUp(self):
1401
 
        super(TestGenerateBackupName, self).setUp()
1402
 
        self._transport = self.get_transport()
1403
 
        bzrdir.BzrDir.create(self.get_url(),
1404
 
            possible_transports=[self._transport])
1405
 
        self._bzrdir = bzrdir.BzrDir.open_from_transport(self._transport)
1406
 
 
1407
 
    def test_new(self):
1408
 
        self.assertEqual("a.~1~", self._bzrdir._available_backup_name("a"))
1409
 
 
1410
 
    def test_exiting(self):
1411
 
        self._transport.put_bytes("a.~1~", "some content")
1412
 
        self.assertEqual("a.~2~", self._bzrdir._available_backup_name("a"))
1413
 
 
1414
 
 
1415
 
class TestMeta1DirColoFormat(TestCaseWithTransport):
1416
 
    """Tests specific to the meta1 dir with colocated branches format."""
1417
 
 
1418
 
    def test_supports_colo(self):
1419
 
        format = bzrdir.BzrDirMetaFormat1Colo()
1420
 
        self.assertTrue(format.colocated_branches)
1421
 
 
1422
 
    def test_upgrade_from_2a(self):
1423
 
        tree = self.make_branch_and_tree('.', format='2a')
1424
 
        format = bzrdir.BzrDirMetaFormat1Colo()
1425
 
        self.assertTrue(tree.bzrdir.needs_format_conversion(format))
1426
 
        converter = tree.bzrdir._format.get_converter(format)
1427
 
        result = converter.convert(tree.bzrdir, None)
1428
 
        self.assertIsInstance(result._format, bzrdir.BzrDirMetaFormat1Colo)
1429
 
        self.assertFalse(result.needs_format_conversion(format))
1430
 
 
1431
 
    def test_downgrade_to_2a(self):
1432
 
        tree = self.make_branch_and_tree('.', format='development-colo')
1433
 
        format = bzrdir.BzrDirMetaFormat1()
1434
 
        self.assertTrue(tree.bzrdir.needs_format_conversion(format))
1435
 
        converter = tree.bzrdir._format.get_converter(format)
1436
 
        result = converter.convert(tree.bzrdir, None)
1437
 
        self.assertIsInstance(result._format, bzrdir.BzrDirMetaFormat1)
1438
 
        self.assertFalse(result.needs_format_conversion(format))
1439
 
 
1440
 
    def test_downgrade_to_2a_too_many_branches(self):
1441
 
        tree = self.make_branch_and_tree('.', format='development-colo')
1442
 
        tree.bzrdir.create_branch(name="another-colocated-branch")
1443
 
        converter = tree.bzrdir._format.get_converter(
1444
 
            bzrdir.BzrDirMetaFormat1())
1445
 
        result = converter.convert(tree.bzrdir, bzrdir.BzrDirMetaFormat1())
1446
 
        self.assertIsInstance(result._format, bzrdir.BzrDirMetaFormat1)
1447
 
 
1448
 
    def test_nested(self):
1449
 
        tree = self.make_branch_and_tree('.', format='development-colo')
1450
 
        tree.bzrdir.create_branch(name='foo')
1451
 
        tree.bzrdir.create_branch(name='fool/bla')
1452
 
        self.assertRaises(
1453
 
            errors.ParentBranchExists, tree.bzrdir.create_branch,
1454
 
            name='foo/bar')
1455
 
 
1456
 
    def test_parent(self):
1457
 
        tree = self.make_branch_and_tree('.', format='development-colo')
1458
 
        tree.bzrdir.create_branch(name='fool/bla')
1459
 
        tree.bzrdir.create_branch(name='foo/bar')
1460
 
        self.assertRaises(
1461
 
            errors.AlreadyBranchError, tree.bzrdir.create_branch,
1462
 
            name='foo')
1463
 
 
1464
 
 
1465
 
class SampleBzrFormat(bzrdir.BzrFormat):
1466
 
 
1467
 
    @classmethod
1468
 
    def get_format_string(cls):
1469
 
        return "First line\n"
1470
 
 
1471
 
 
1472
 
class TestBzrFormat(TestCase):
1473
 
    """Tests for BzrFormat."""
1474
 
 
1475
 
    def test_as_string(self):
1476
 
        format = SampleBzrFormat()
1477
 
        format.features = {"foo": "required"}
1478
 
        self.assertEqual(format.as_string(),
1479
 
            "First line\n"
1480
 
            "required foo\n")
1481
 
        format.features["another"] = "optional"
1482
 
        self.assertEqual(format.as_string(),
1483
 
            "First line\n"
1484
 
            "required foo\n"
1485
 
            "optional another\n")
1486
 
 
1487
 
    def test_network_name(self):
1488
 
        # The network string should include the feature info
1489
 
        format = SampleBzrFormat()
1490
 
        format.features = {"foo": "required"}
1491
 
        self.assertEqual(
1492
 
            "First line\nrequired foo\n",
1493
 
            format.network_name())
1494
 
 
1495
 
    def test_from_string_no_features(self):
1496
 
        # No features
1497
 
        format = SampleBzrFormat.from_string(
1498
 
            "First line\n")
1499
 
        self.assertEqual({}, format.features)
1500
 
 
1501
 
    def test_from_string_with_feature(self):
1502
 
        # Proper feature
1503
 
        format = SampleBzrFormat.from_string(
1504
 
            "First line\nrequired foo\n")
1505
 
        self.assertEqual("required", format.features.get("foo"))
1506
 
 
1507
 
    def test_from_string_format_string_mismatch(self):
1508
 
        # The first line has to match the format string
1509
 
        self.assertRaises(AssertionError, SampleBzrFormat.from_string,
1510
 
            "Second line\nrequired foo\n")
1511
 
 
1512
 
    def test_from_string_missing_space(self):
1513
 
        # At least one space is required in the feature lines
1514
 
        self.assertRaises(errors.ParseFormatError, SampleBzrFormat.from_string,
1515
 
            "First line\nfoo\n")
1516
 
 
1517
 
    def test_from_string_with_spaces(self):
1518
 
        # Feature with spaces (in case we add stuff like this in the future)
1519
 
        format = SampleBzrFormat.from_string(
1520
 
            "First line\nrequired foo with spaces\n")
1521
 
        self.assertEqual("required", format.features.get("foo with spaces"))
1522
 
 
1523
 
    def test_eq(self):
1524
 
        format1 = SampleBzrFormat()
1525
 
        format1.features = {"nested-trees": "optional"}
1526
 
        format2 = SampleBzrFormat()
1527
 
        format2.features = {"nested-trees": "optional"}
1528
 
        self.assertEqual(format1, format1)
1529
 
        self.assertEqual(format1, format2)
1530
 
        format3 = SampleBzrFormat()
1531
 
        self.assertNotEqual(format1, format3)
1532
 
 
1533
 
    def test_check_support_status_optional(self):
1534
 
        # Optional, so silently ignore
1535
 
        format = SampleBzrFormat()
1536
 
        format.features = {"nested-trees": "optional"}
1537
 
        format.check_support_status(True)
1538
 
        self.addCleanup(SampleBzrFormat.unregister_feature, "nested-trees")
1539
 
        SampleBzrFormat.register_feature("nested-trees")
1540
 
        format.check_support_status(True)
1541
 
 
1542
 
    def test_check_support_status_required(self):
1543
 
        # Optional, so trigger an exception
1544
 
        format = SampleBzrFormat()
1545
 
        format.features = {"nested-trees": "required"}
1546
 
        self.assertRaises(errors.MissingFeature, format.check_support_status,
1547
 
            True)
1548
 
        self.addCleanup(SampleBzrFormat.unregister_feature, "nested-trees")
1549
 
        SampleBzrFormat.register_feature("nested-trees")
1550
 
        format.check_support_status(True)
1551
 
 
1552
 
    def test_check_support_status_unknown(self):
1553
 
        # treat unknown necessity as required
1554
 
        format = SampleBzrFormat()
1555
 
        format.features = {"nested-trees": "unknown"}
1556
 
        self.assertRaises(errors.MissingFeature, format.check_support_status,
1557
 
            True)
1558
 
        self.addCleanup(SampleBzrFormat.unregister_feature, "nested-trees")
1559
 
        SampleBzrFormat.register_feature("nested-trees")
1560
 
        format.check_support_status(True)
1561
 
 
1562
 
    def test_feature_already_registered(self):
1563
 
        # a feature can only be registered once
1564
 
        self.addCleanup(SampleBzrFormat.unregister_feature, "nested-trees")
1565
 
        SampleBzrFormat.register_feature("nested-trees")
1566
 
        self.assertRaises(errors.FeatureAlreadyRegistered,
1567
 
            SampleBzrFormat.register_feature, "nested-trees")
1568
 
 
1569
 
    def test_feature_with_space(self):
1570
 
        # spaces are not allowed in feature names
1571
 
        self.assertRaises(ValueError, SampleBzrFormat.register_feature,
1572
 
            "nested trees")