~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Tests for the BzrDir facility and any format specific tests.

For interface contract tests, see tests/bzr_dir_implementations.
"""

import os
import subprocess
import sys

from bzrlib import (
    bzrdir,
    errors,
    help_topics,
    repository,
    osutils,
    remote,
    urlutils,
    win32utils,
    workingtree,
    )
import bzrlib.branch
from bzrlib.errors import (NotBranchError,
                           UnknownFormatError,
                           UnsupportedFormatError,
                           )
from bzrlib.tests import (
    TestCase,
    TestCaseWithMemoryTransport,
    TestCaseWithTransport,
    TestSkipped,
    )
from bzrlib.tests import(
    http_server,
    http_utils,
    )
from bzrlib.tests.test_http import TestWithTransport_pycurl
from bzrlib.transport import get_transport
from bzrlib.transport.http._urllib import HttpTransport_urllib
from bzrlib.transport.memory import MemoryServer
from bzrlib.transport.nosmart import NoSmartTransportDecorator
from bzrlib.transport.readonly import ReadonlyTransportDecorator
from bzrlib.repofmt import knitrepo, weaverepo, pack_repo


class TestDefaultFormat(TestCase):

    def test_get_set_default_format(self):
        old_format = bzrdir.BzrDirFormat.get_default_format()
        # default is BzrDirFormat6
        self.failUnless(isinstance(old_format, bzrdir.BzrDirMetaFormat1))
        bzrdir.BzrDirFormat._set_default_format(SampleBzrDirFormat())
        # creating a bzr dir should now create an instrumented dir.
        try:
            result = bzrdir.BzrDir.create('memory:///')
            self.failUnless(isinstance(result, SampleBzrDir))
        finally:
            bzrdir.BzrDirFormat._set_default_format(old_format)
        self.assertEqual(old_format, bzrdir.BzrDirFormat.get_default_format())


class TestFormatRegistry(TestCase):

    def make_format_registry(self):
        my_format_registry = bzrdir.BzrDirFormatRegistry()
        my_format_registry.register('weave', bzrdir.BzrDirFormat6,
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
            ' repositories', deprecated=True)
        my_format_registry.register_lazy('lazy', 'bzrlib.bzrdir',
            'BzrDirFormat6', 'Format registered lazily', deprecated=True)
        my_format_registry.register_metadir('knit',
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
            'Format using knits',
            )
        my_format_registry.set_default('knit')
        my_format_registry.register_metadir(
            'branch6',
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
            'Experimental successor to knit.  Use at your own risk.',
            branch_format='bzrlib.branch.BzrBranchFormat6',
            experimental=True)
        my_format_registry.register_metadir(
            'hidden format',
            'bzrlib.repofmt.knitrepo.RepositoryFormatKnit3',
            'Experimental successor to knit.  Use at your own risk.',
            branch_format='bzrlib.branch.BzrBranchFormat6', hidden=True)
        my_format_registry.register('hiddenweave', bzrdir.BzrDirFormat6,
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
            ' repositories', hidden=True)
        my_format_registry.register_lazy('hiddenlazy', 'bzrlib.bzrdir',
            'BzrDirFormat6', 'Format registered lazily', deprecated=True,
            hidden=True)
        return my_format_registry

    def test_format_registry(self):
        my_format_registry = self.make_format_registry()
        my_bzrdir = my_format_registry.make_bzrdir('lazy')
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
        my_bzrdir = my_format_registry.make_bzrdir('weave')
        self.assertIsInstance(my_bzrdir, bzrdir.BzrDirFormat6)
        my_bzrdir = my_format_registry.make_bzrdir('default')
        self.assertIsInstance(my_bzrdir.repository_format,
            knitrepo.RepositoryFormatKnit1)
        my_bzrdir = my_format_registry.make_bzrdir('knit')
        self.assertIsInstance(my_bzrdir.repository_format,
            knitrepo.RepositoryFormatKnit1)
        my_bzrdir = my_format_registry.make_bzrdir('branch6')
        self.assertIsInstance(my_bzrdir.get_branch_format(),
                              bzrlib.branch.BzrBranchFormat6)

    def test_get_help(self):
        my_format_registry = self.make_format_registry()
        self.assertEqual('Format registered lazily',
                         my_format_registry.get_help('lazy'))
        self.assertEqual('Format using knits',
                         my_format_registry.get_help('knit'))
        self.assertEqual('Format using knits',
                         my_format_registry.get_help('default'))
        self.assertEqual('Pre-0.8 format.  Slower and does not support'
                         ' checkouts or shared repositories',
                         my_format_registry.get_help('weave'))

    def test_help_topic(self):
        topics = help_topics.HelpTopicRegistry()
        registry = self.make_format_registry()
        topics.register('current-formats', registry.help_topic,
                        'Current formats')
        topics.register('other-formats', registry.help_topic,
                        'Other formats')
        new = topics.get_detail('current-formats')
        rest = topics.get_detail('other-formats')
        experimental, deprecated = rest.split('Deprecated formats')
        self.assertContainsRe(new, 'bzr help formats')
        self.assertContainsRe(new,
                ':knit:\n    \(native\) \(default\) Format using knits\n')
        self.assertContainsRe(experimental,
                ':branch6:\n    \(native\) Experimental successor to knit')
        self.assertContainsRe(deprecated,
                ':lazy:\n    \(native\) Format registered lazily\n')
        self.assertNotContainsRe(new, 'hidden')

    def test_set_default_repository(self):
        default_factory = bzrdir.format_registry.get('default')
        old_default = [k for k, v in bzrdir.format_registry.iteritems()
                       if v == default_factory and k != 'default'][0]
        bzrdir.format_registry.set_default_repository('dirstate-with-subtree')
        try:
            self.assertIs(bzrdir.format_registry.get('dirstate-with-subtree'),
                          bzrdir.format_registry.get('default'))
            self.assertIs(
                repository.RepositoryFormat.get_default_format().__class__,
                knitrepo.RepositoryFormatKnit3)
        finally:
            bzrdir.format_registry.set_default_repository(old_default)

    def test_aliases(self):
        a_registry = bzrdir.BzrDirFormatRegistry()
        a_registry.register('weave', bzrdir.BzrDirFormat6,
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
            ' repositories', deprecated=True)
        a_registry.register('weavealias', bzrdir.BzrDirFormat6,
            'Pre-0.8 format.  Slower and does not support checkouts or shared'
            ' repositories', deprecated=True, alias=True)
        self.assertEqual(frozenset(['weavealias']), a_registry.aliases())


class SampleBranch(bzrlib.branch.Branch):
    """A dummy branch for guess what, dummy use."""

    def __init__(self, dir):
        self.bzrdir = dir


class SampleRepository(bzrlib.repository.Repository):
    """A dummy repo."""

    def __init__(self, dir):
        self.bzrdir = dir


class SampleBzrDir(bzrdir.BzrDir):
    """A sample BzrDir implementation to allow testing static methods."""

    def create_repository(self, shared=False):
        """See BzrDir.create_repository."""
        return "A repository"

    def open_repository(self):
        """See BzrDir.open_repository."""
        return SampleRepository(self)

    def create_branch(self):
        """See BzrDir.create_branch."""
        return SampleBranch(self)

    def create_workingtree(self):
        """See BzrDir.create_workingtree."""
        return "A tree"


class SampleBzrDirFormat(bzrdir.BzrDirFormat):
    """A sample format

    this format is initializable, unsupported to aid in testing the
    open and open_downlevel routines.
    """

    def get_format_string(self):
        """See BzrDirFormat.get_format_string()."""
        return "Sample .bzr dir format."

    def initialize_on_transport(self, t):
        """Create a bzr dir."""
        t.mkdir('.bzr')
        t.put_bytes('.bzr/branch-format', self.get_format_string())
        return SampleBzrDir(t, self)

    def is_supported(self):
        return False

    def open(self, transport, _found=None):
        return "opened branch."


class TestBzrDirFormat(TestCaseWithTransport):
    """Tests for the BzrDirFormat facility."""

    def test_find_format(self):
        # is the right format object found for a branch?
        # create a branch with a few known format objects.
        # this is not quite the same as
        t = get_transport(self.get_url())
        self.build_tree(["foo/", "bar/"], transport=t)
        def check_format(format, url):
            format.initialize(url)
            t = get_transport(url)
            found_format = bzrdir.BzrDirFormat.find_format(t)
            self.failUnless(isinstance(found_format, format.__class__))
        check_format(bzrdir.BzrDirFormat5(), "foo")
        check_format(bzrdir.BzrDirFormat6(), "bar")

    def test_find_format_nothing_there(self):
        self.assertRaises(NotBranchError,
                          bzrdir.BzrDirFormat.find_format,
                          get_transport('.'))

    def test_find_format_unknown_format(self):
        t = get_transport(self.get_url())
        t.mkdir('.bzr')
        t.put_bytes('.bzr/branch-format', '')
        self.assertRaises(UnknownFormatError,
                          bzrdir.BzrDirFormat.find_format,
                          get_transport('.'))

    def test_register_unregister_format(self):
        format = SampleBzrDirFormat()
        url = self.get_url()
        # make a bzrdir
        format.initialize(url)
        # register a format for it.
        bzrdir.BzrDirFormat.register_format(format)
        # which bzrdir.Open will refuse (not supported)
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open, url)
        # which bzrdir.open_containing will refuse (not supported)
        self.assertRaises(UnsupportedFormatError, bzrdir.BzrDir.open_containing, url)
        # but open_downlevel will work
        t = get_transport(url)
        self.assertEqual(format.open(t), bzrdir.BzrDir.open_unsupported(url))
        # unregister the format
        bzrdir.BzrDirFormat.unregister_format(format)
        # now open_downlevel should fail too.
        self.assertRaises(UnknownFormatError, bzrdir.BzrDir.open_unsupported, url)

    def test_create_branch_and_repo_uses_default(self):
        format = SampleBzrDirFormat()
        branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url(),
                                                      format=format)
        self.assertTrue(isinstance(branch, SampleBranch))

    def test_create_branch_and_repo_under_shared(self):
        # creating a branch and repo in a shared repo uses the
        # shared repository
        format = bzrdir.format_registry.make_bzrdir('knit')
        self.make_repository('.', shared=True, format=format)
        branch = bzrdir.BzrDir.create_branch_and_repo(
            self.get_url('child'), format=format)
        self.assertRaises(errors.NoRepositoryPresent,
                          branch.bzrdir.open_repository)

    def test_create_branch_and_repo_under_shared_force_new(self):
        # creating a branch and repo in a shared repo can be forced to
        # make a new repo
        format = bzrdir.format_registry.make_bzrdir('knit')
        self.make_repository('.', shared=True, format=format)
        branch = bzrdir.BzrDir.create_branch_and_repo(self.get_url('child'),
                                                      force_new_repo=True,
                                                      format=format)
        branch.bzrdir.open_repository()

    def test_create_standalone_working_tree(self):
        format = SampleBzrDirFormat()
        # note this is deliberately readonly, as this failure should
        # occur before any writes.
        self.assertRaises(errors.NotLocalUrl,
                          bzrdir.BzrDir.create_standalone_workingtree,
                          self.get_readonly_url(), format=format)
        tree = bzrdir.BzrDir.create_standalone_workingtree('.',
                                                           format=format)
        self.assertEqual('A tree', tree)

    def test_create_standalone_working_tree_under_shared_repo(self):
        # create standalone working tree always makes a repo.
        format = bzrdir.format_registry.make_bzrdir('knit')
        self.make_repository('.', shared=True, format=format)
        # note this is deliberately readonly, as this failure should
        # occur before any writes.
        self.assertRaises(errors.NotLocalUrl,
                          bzrdir.BzrDir.create_standalone_workingtree,
                          self.get_readonly_url('child'), format=format)
        tree = bzrdir.BzrDir.create_standalone_workingtree('child',
            format=format)
        tree.bzrdir.open_repository()

    def test_create_branch_convenience(self):
        # outside a repo the default convenience output is a repo+branch_tree
        format = bzrdir.format_registry.make_bzrdir('knit')
        branch = bzrdir.BzrDir.create_branch_convenience('.', format=format)
        branch.bzrdir.open_workingtree()
        branch.bzrdir.open_repository()

    def test_create_branch_convenience_possible_transports(self):
        """Check that the optional 'possible_transports' is recognized"""
        format = bzrdir.format_registry.make_bzrdir('knit')
        t = self.get_transport()
        branch = bzrdir.BzrDir.create_branch_convenience(
            '.', format=format, possible_transports=[t])
        branch.bzrdir.open_workingtree()
        branch.bzrdir.open_repository()

    def test_create_branch_convenience_root(self):
        """Creating a branch at the root of a fs should work."""
        self.vfs_transport_factory = MemoryServer
        # outside a repo the default convenience output is a repo+branch_tree
        format = bzrdir.format_registry.make_bzrdir('knit')
        branch = bzrdir.BzrDir.create_branch_convenience(self.get_url(),
                                                         format=format)
        self.assertRaises(errors.NoWorkingTree,
                          branch.bzrdir.open_workingtree)
        branch.bzrdir.open_repository()

    def test_create_branch_convenience_under_shared_repo(self):
        # inside a repo the default convenience output is a branch+ follow the
        # repo tree policy
        format = bzrdir.format_registry.make_bzrdir('knit')
        self.make_repository('.', shared=True, format=format)
        branch = bzrdir.BzrDir.create_branch_convenience('child',
            format=format)
        branch.bzrdir.open_workingtree()
        self.assertRaises(errors.NoRepositoryPresent,
                          branch.bzrdir.open_repository)

    def test_create_branch_convenience_under_shared_repo_force_no_tree(self):
        # inside a repo the default convenience output is a branch+ follow the
        # repo tree policy but we can override that
        format = bzrdir.format_registry.make_bzrdir('knit')
        self.make_repository('.', shared=True, format=format)
        branch = bzrdir.BzrDir.create_branch_convenience('child',
            force_new_tree=False, format=format)
        self.assertRaises(errors.NoWorkingTree,
                          branch.bzrdir.open_workingtree)
        self.assertRaises(errors.NoRepositoryPresent,
                          branch.bzrdir.open_repository)

    def test_create_branch_convenience_under_shared_repo_no_tree_policy(self):
        # inside a repo the default convenience output is a branch+ follow the
        # repo tree policy
        format = bzrdir.format_registry.make_bzrdir('knit')
        repo = self.make_repository('.', shared=True, format=format)
        repo.set_make_working_trees(False)
        branch = bzrdir.BzrDir.create_branch_convenience('child',
                                                         format=format)
        self.assertRaises(errors.NoWorkingTree,
                          branch.bzrdir.open_workingtree)
        self.assertRaises(errors.NoRepositoryPresent,
                          branch.bzrdir.open_repository)

    def test_create_branch_convenience_under_shared_repo_no_tree_policy_force_tree(self):
        # inside a repo the default convenience output is a branch+ follow the
        # repo tree policy but we can override that
        format = bzrdir.format_registry.make_bzrdir('knit')
        repo = self.make_repository('.', shared=True, format=format)
        repo.set_make_working_trees(False)
        branch = bzrdir.BzrDir.create_branch_convenience('child',
            force_new_tree=True, format=format)
        branch.bzrdir.open_workingtree()
        self.assertRaises(errors.NoRepositoryPresent,
                          branch.bzrdir.open_repository)

    def test_create_branch_convenience_under_shared_repo_force_new_repo(self):
        # inside a repo the default convenience output is overridable to give
        # repo+branch+tree
        format = bzrdir.format_registry.make_bzrdir('knit')
        self.make_repository('.', shared=True, format=format)
        branch = bzrdir.BzrDir.create_branch_convenience('child',
            force_new_repo=True, format=format)
        branch.bzrdir.open_repository()
        branch.bzrdir.open_workingtree()


class TestRepositoryAcquisitionPolicy(TestCaseWithTransport):

    def test_acquire_repository_standalone(self):
        """The default acquisition policy should create a standalone branch."""
        my_bzrdir = self.make_bzrdir('.')
        repo_policy = my_bzrdir.determine_repository_policy()
        repo, is_new = repo_policy.acquire_repository()
        self.assertEqual(repo.bzrdir.root_transport.base,
                         my_bzrdir.root_transport.base)
        self.assertFalse(repo.is_shared())

    def test_determine_stacking_policy(self):
        parent_bzrdir = self.make_bzrdir('.')
        child_bzrdir = self.make_bzrdir('child')
        parent_bzrdir.get_config().set_default_stack_on('http://example.org')
        repo_policy = child_bzrdir.determine_repository_policy()
        self.assertEqual('http://example.org', repo_policy._stack_on)

    def test_determine_stacking_policy_relative(self):
        parent_bzrdir = self.make_bzrdir('.')
        child_bzrdir = self.make_bzrdir('child')
        parent_bzrdir.get_config().set_default_stack_on('child2')
        repo_policy = child_bzrdir.determine_repository_policy()
        self.assertEqual('child2', repo_policy._stack_on)
        self.assertEqual(parent_bzrdir.root_transport.base,
                         repo_policy._stack_on_pwd)

    def prepare_default_stacking(self, child_format='1.6'):
        parent_bzrdir = self.make_bzrdir('.')
        child_branch = self.make_branch('child', format=child_format)
        parent_bzrdir.get_config().set_default_stack_on(child_branch.base)
        new_child_transport = parent_bzrdir.transport.clone('child2')
        return child_branch, new_child_transport

    def test_clone_on_transport_obeys_stacking_policy(self):
        child_branch, new_child_transport = self.prepare_default_stacking()
        new_child = child_branch.bzrdir.clone_on_transport(new_child_transport)
        self.assertEqual(child_branch.base,
                         new_child.open_branch().get_stacked_on_url())

    def test_default_stacking_with_stackable_branch_unstackable_repo(self):
        # Make stackable source branch with an unstackable repo format.
        source_bzrdir = self.make_bzrdir('source')
        pack_repo.RepositoryFormatKnitPack1().initialize(source_bzrdir)
        source_branch = bzrlib.branch.BzrBranchFormat7().initialize(source_bzrdir)
        # Make a directory with a default stacking policy
        parent_bzrdir = self.make_bzrdir('parent')
        stacked_on = self.make_branch('parent/stacked-on', format='pack-0.92')
        parent_bzrdir.get_config().set_default_stack_on(stacked_on.base)
        # Clone source into directory
        target = source_bzrdir.clone(self.get_url('parent/target'))

    def test_sprout_obeys_stacking_policy(self):
        child_branch, new_child_transport = self.prepare_default_stacking()
        new_child = child_branch.bzrdir.sprout(new_child_transport.base)
        self.assertEqual(child_branch.base,
                         new_child.open_branch().get_stacked_on_url())

    def test_clone_ignores_policy_for_unsupported_formats(self):
        child_branch, new_child_transport = self.prepare_default_stacking(
            child_format='pack-0.92')
        new_child = child_branch.bzrdir.clone_on_transport(new_child_transport)
        self.assertRaises(errors.UnstackableBranchFormat,
                          new_child.open_branch().get_stacked_on_url)

    def test_sprout_ignores_policy_for_unsupported_formats(self):
        child_branch, new_child_transport = self.prepare_default_stacking(
            child_format='pack-0.92')
        new_child = child_branch.bzrdir.sprout(new_child_transport.base)
        self.assertRaises(errors.UnstackableBranchFormat,
                          new_child.open_branch().get_stacked_on_url)

    def test_sprout_upgrades_format_if_stacked_specified(self):
        child_branch, new_child_transport = self.prepare_default_stacking(
            child_format='pack-0.92')
        new_child = child_branch.bzrdir.sprout(new_child_transport.base,
                                               stacked=True)
        self.assertEqual(child_branch.bzrdir.root_transport.base,
                         new_child.open_branch().get_stacked_on_url())
        repo = new_child.open_repository()
        self.assertTrue(repo._format.supports_external_lookups)
        self.assertFalse(repo.supports_rich_root())

    def test_clone_on_transport_upgrades_format_if_stacked_on_specified(self):
        child_branch, new_child_transport = self.prepare_default_stacking(
            child_format='pack-0.92')
        new_child = child_branch.bzrdir.clone_on_transport(new_child_transport,
            stacked_on=child_branch.bzrdir.root_transport.base)
        self.assertEqual(child_branch.bzrdir.root_transport.base,
                         new_child.open_branch().get_stacked_on_url())
        repo = new_child.open_repository()
        self.assertTrue(repo._format.supports_external_lookups)
        self.assertFalse(repo.supports_rich_root())

    def test_sprout_upgrades_to_rich_root_format_if_needed(self):
        child_branch, new_child_transport = self.prepare_default_stacking(
            child_format='rich-root-pack')
        new_child = child_branch.bzrdir.sprout(new_child_transport.base,
                                               stacked=True)
        repo = new_child.open_repository()
        self.assertTrue(repo._format.supports_external_lookups)
        self.assertTrue(repo.supports_rich_root())

    def test_add_fallback_repo_handles_absolute_urls(self):
        stack_on = self.make_branch('stack_on', format='1.6')
        repo = self.make_repository('repo', format='1.6')
        policy = bzrdir.UseExistingRepository(repo, stack_on.base)
        policy._add_fallback(repo)

    def test_add_fallback_repo_handles_relative_urls(self):
        stack_on = self.make_branch('stack_on', format='1.6')
        repo = self.make_repository('repo', format='1.6')
        policy = bzrdir.UseExistingRepository(repo, '.', stack_on.base)
        policy._add_fallback(repo)

    def test_configure_relative_branch_stacking_url(self):
        stack_on = self.make_branch('stack_on', format='1.6')
        stacked = self.make_branch('stack_on/stacked', format='1.6')
        policy = bzrdir.UseExistingRepository(stacked.repository,
            '.', stack_on.base)
        policy.configure_branch(stacked)
        self.assertEqual('..', stacked.get_stacked_on_url())

    def test_relative_branch_stacking_to_absolute(self):
        stack_on = self.make_branch('stack_on', format='1.6')
        stacked = self.make_branch('stack_on/stacked', format='1.6')
        policy = bzrdir.UseExistingRepository(stacked.repository,
            '.', self.get_readonly_url('stack_on'))
        policy.configure_branch(stacked)
        self.assertEqual(self.get_readonly_url('stack_on'),
                         stacked.get_stacked_on_url())


class ChrootedTests(TestCaseWithTransport):
    """A support class that provides readonly urls outside the local namespace.

    This is done by checking if self.transport_server is a MemoryServer. if it
    is then we are chrooted already, if it is not then an HttpServer is used
    for readonly urls.
    """

    def setUp(self):
        super(ChrootedTests, self).setUp()
        if not self.vfs_transport_factory == MemoryServer:
            self.transport_readonly_server = http_server.HttpServer

    def local_branch_path(self, branch):
         return os.path.realpath(urlutils.local_path_from_url(branch.base))

    def test_open_containing(self):
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing,
                          self.get_readonly_url(''))
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing,
                          self.get_readonly_url('g/p/q'))
        control = bzrdir.BzrDir.create(self.get_url())
        branch, relpath = bzrdir.BzrDir.open_containing(self.get_readonly_url(''))
        self.assertEqual('', relpath)
        branch, relpath = bzrdir.BzrDir.open_containing(self.get_readonly_url('g/p/q'))
        self.assertEqual('g/p/q', relpath)

    def test_open_containing_tree_branch_or_repository_empty(self):
        self.assertRaises(errors.NotBranchError,
            bzrdir.BzrDir.open_containing_tree_branch_or_repository,
            self.get_readonly_url(''))

    def test_open_containing_tree_branch_or_repository_all(self):
        self.make_branch_and_tree('topdir')
        tree, branch, repo, relpath = \
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
                'topdir/foo')
        self.assertEqual(os.path.realpath('topdir'),
                         os.path.realpath(tree.basedir))
        self.assertEqual(os.path.realpath('topdir'),
                         self.local_branch_path(branch))
        self.assertEqual(
            osutils.realpath(os.path.join('topdir', '.bzr', 'repository')),
            repo.bzrdir.transport.local_abspath('repository'))
        self.assertEqual(relpath, 'foo')

    def test_open_containing_tree_branch_or_repository_no_tree(self):
        self.make_branch('branch')
        tree, branch, repo, relpath = \
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
                'branch/foo')
        self.assertEqual(tree, None)
        self.assertEqual(os.path.realpath('branch'),
                         self.local_branch_path(branch))
        self.assertEqual(
            osutils.realpath(os.path.join('branch', '.bzr', 'repository')),
            repo.bzrdir.transport.local_abspath('repository'))
        self.assertEqual(relpath, 'foo')

    def test_open_containing_tree_branch_or_repository_repo(self):
        self.make_repository('repo')
        tree, branch, repo, relpath = \
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
                'repo')
        self.assertEqual(tree, None)
        self.assertEqual(branch, None)
        self.assertEqual(
            osutils.realpath(os.path.join('repo', '.bzr', 'repository')),
            repo.bzrdir.transport.local_abspath('repository'))
        self.assertEqual(relpath, '')

    def test_open_containing_tree_branch_or_repository_shared_repo(self):
        self.make_repository('shared', shared=True)
        bzrdir.BzrDir.create_branch_convenience('shared/branch',
                                                force_new_tree=False)
        tree, branch, repo, relpath = \
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
                'shared/branch')
        self.assertEqual(tree, None)
        self.assertEqual(os.path.realpath('shared/branch'),
                         self.local_branch_path(branch))
        self.assertEqual(
            osutils.realpath(os.path.join('shared', '.bzr', 'repository')),
            repo.bzrdir.transport.local_abspath('repository'))
        self.assertEqual(relpath, '')

    def test_open_containing_tree_branch_or_repository_branch_subdir(self):
        self.make_branch_and_tree('foo')
        self.build_tree(['foo/bar/'])
        tree, branch, repo, relpath = \
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
                'foo/bar')
        self.assertEqual(os.path.realpath('foo'),
                         os.path.realpath(tree.basedir))
        self.assertEqual(os.path.realpath('foo'),
                         self.local_branch_path(branch))
        self.assertEqual(
            osutils.realpath(os.path.join('foo', '.bzr', 'repository')),
            repo.bzrdir.transport.local_abspath('repository'))
        self.assertEqual(relpath, 'bar')

    def test_open_containing_tree_branch_or_repository_repo_subdir(self):
        self.make_repository('bar')
        self.build_tree(['bar/baz/'])
        tree, branch, repo, relpath = \
            bzrdir.BzrDir.open_containing_tree_branch_or_repository(
                'bar/baz')
        self.assertEqual(tree, None)
        self.assertEqual(branch, None)
        self.assertEqual(
            osutils.realpath(os.path.join('bar', '.bzr', 'repository')),
            repo.bzrdir.transport.local_abspath('repository'))
        self.assertEqual(relpath, 'baz')

    def test_open_containing_from_transport(self):
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
                          get_transport(self.get_readonly_url('')))
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_containing_from_transport,
                          get_transport(self.get_readonly_url('g/p/q')))
        control = bzrdir.BzrDir.create(self.get_url())
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
            get_transport(self.get_readonly_url('')))
        self.assertEqual('', relpath)
        branch, relpath = bzrdir.BzrDir.open_containing_from_transport(
            get_transport(self.get_readonly_url('g/p/q')))
        self.assertEqual('g/p/q', relpath)

    def test_open_containing_tree_or_branch(self):
        self.make_branch_and_tree('topdir')
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
            'topdir/foo')
        self.assertEqual(os.path.realpath('topdir'),
                         os.path.realpath(tree.basedir))
        self.assertEqual(os.path.realpath('topdir'),
                         self.local_branch_path(branch))
        self.assertIs(tree.bzrdir, branch.bzrdir)
        self.assertEqual('foo', relpath)
        # opening from non-local should not return the tree
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
            self.get_readonly_url('topdir/foo'))
        self.assertEqual(None, tree)
        self.assertEqual('foo', relpath)
        # without a tree:
        self.make_branch('topdir/foo')
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
            'topdir/foo')
        self.assertIs(tree, None)
        self.assertEqual(os.path.realpath('topdir/foo'),
                         self.local_branch_path(branch))
        self.assertEqual('', relpath)

    def test_open_tree_or_branch(self):
        self.make_branch_and_tree('topdir')
        tree, branch = bzrdir.BzrDir.open_tree_or_branch('topdir')
        self.assertEqual(os.path.realpath('topdir'),
                         os.path.realpath(tree.basedir))
        self.assertEqual(os.path.realpath('topdir'),
                         self.local_branch_path(branch))
        self.assertIs(tree.bzrdir, branch.bzrdir)
        # opening from non-local should not return the tree
        tree, branch = bzrdir.BzrDir.open_tree_or_branch(
            self.get_readonly_url('topdir'))
        self.assertEqual(None, tree)
        # without a tree:
        self.make_branch('topdir/foo')
        tree, branch = bzrdir.BzrDir.open_tree_or_branch('topdir/foo')
        self.assertIs(tree, None)
        self.assertEqual(os.path.realpath('topdir/foo'),
                         self.local_branch_path(branch))

    def test_open_from_transport(self):
        # transport pointing at bzrdir should give a bzrdir with root transport
        # set to the given transport
        control = bzrdir.BzrDir.create(self.get_url())
        transport = get_transport(self.get_url())
        opened_bzrdir = bzrdir.BzrDir.open_from_transport(transport)
        self.assertEqual(transport.base, opened_bzrdir.root_transport.base)
        self.assertIsInstance(opened_bzrdir, bzrdir.BzrDir)

    def test_open_from_transport_no_bzrdir(self):
        transport = get_transport(self.get_url())
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
                          transport)

    def test_open_from_transport_bzrdir_in_parent(self):
        control = bzrdir.BzrDir.create(self.get_url())
        transport = get_transport(self.get_url())
        transport.mkdir('subdir')
        transport = transport.clone('subdir')
        self.assertRaises(NotBranchError, bzrdir.BzrDir.open_from_transport,
                          transport)

    def test_sprout_recursive(self):
        tree = self.make_branch_and_tree('tree1',
                                         format='dirstate-with-subtree')
        sub_tree = self.make_branch_and_tree('tree1/subtree',
            format='dirstate-with-subtree')
        sub_tree.set_root_id('subtree-root')
        tree.add_reference(sub_tree)
        self.build_tree(['tree1/subtree/file'])
        sub_tree.add('file')
        tree.commit('Initial commit')
        tree2 = tree.bzrdir.sprout('tree2').open_workingtree()
        tree2.lock_read()
        self.addCleanup(tree2.unlock)
        self.failUnlessExists('tree2/subtree/file')
        self.assertEqual('tree-reference', tree2.kind('subtree-root'))

    def test_cloning_metadir(self):
        """Ensure that cloning metadir is suitable"""
        bzrdir = self.make_bzrdir('bzrdir')
        bzrdir.cloning_metadir()
        branch = self.make_branch('branch', format='knit')
        format = branch.bzrdir.cloning_metadir()
        self.assertIsInstance(format.workingtree_format,
            workingtree.WorkingTreeFormat3)

    def test_sprout_recursive_treeless(self):
        tree = self.make_branch_and_tree('tree1',
            format='dirstate-with-subtree')
        sub_tree = self.make_branch_and_tree('tree1/subtree',
            format='dirstate-with-subtree')
        tree.add_reference(sub_tree)
        self.build_tree(['tree1/subtree/file'])
        sub_tree.add('file')
        tree.commit('Initial commit')
        tree.bzrdir.destroy_workingtree()
        repo = self.make_repository('repo', shared=True,
            format='dirstate-with-subtree')
        repo.set_make_working_trees(False)
        tree.bzrdir.sprout('repo/tree2')
        self.failUnlessExists('repo/tree2/subtree')
        self.failIfExists('repo/tree2/subtree/file')

    def make_foo_bar_baz(self):
        foo = bzrdir.BzrDir.create_branch_convenience('foo').bzrdir
        bar = self.make_branch('foo/bar').bzrdir
        baz = self.make_branch('baz').bzrdir
        return foo, bar, baz

    def test_find_bzrdirs(self):
        foo, bar, baz = self.make_foo_bar_baz()
        transport = get_transport(self.get_url())
        self.assertEqualBzrdirs([baz, foo, bar],
                                bzrdir.BzrDir.find_bzrdirs(transport))

    def test_find_bzrdirs_list_current(self):
        def list_current(transport):
            return [s for s in transport.list_dir('') if s != 'baz']

        foo, bar, baz = self.make_foo_bar_baz()
        transport = get_transport(self.get_url())
        self.assertEqualBzrdirs([foo, bar],
                                bzrdir.BzrDir.find_bzrdirs(transport,
                                    list_current=list_current))


    def test_find_bzrdirs_evaluate(self):
        def evaluate(bzrdir):
            try:
                repo = bzrdir.open_repository()
            except NoRepositoryPresent:
                return True, bzrdir.root_transport.base
            else:
                return False, bzrdir.root_transport.base

        foo, bar, baz = self.make_foo_bar_baz()
        transport = get_transport(self.get_url())
        self.assertEqual([baz.root_transport.base, foo.root_transport.base],
                         list(bzrdir.BzrDir.find_bzrdirs(transport,
                                                         evaluate=evaluate)))

    def assertEqualBzrdirs(self, first, second):
        first = list(first)
        second = list(second)
        self.assertEqual(len(first), len(second))
        for x, y in zip(first, second):
            self.assertEqual(x.root_transport.base, y.root_transport.base)

    def test_find_branches(self):
        root = self.make_repository('', shared=True)
        foo, bar, baz = self.make_foo_bar_baz()
        qux = self.make_bzrdir('foo/qux')
        transport = get_transport(self.get_url())
        branches = bzrdir.BzrDir.find_branches(transport)
        self.assertEqual(baz.root_transport.base, branches[0].base)
        self.assertEqual(foo.root_transport.base, branches[1].base)
        self.assertEqual(bar.root_transport.base, branches[2].base)

        # ensure this works without a top-level repo
        branches = bzrdir.BzrDir.find_branches(transport.clone('foo'))
        self.assertEqual(foo.root_transport.base, branches[0].base)
        self.assertEqual(bar.root_transport.base, branches[1].base)


class TestMeta1DirFormat(TestCaseWithTransport):
    """Tests specific to the meta1 dir format."""

    def test_right_base_dirs(self):
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
        t = dir.transport
        branch_base = t.clone('branch').base
        self.assertEqual(branch_base, dir.get_branch_transport(None).base)
        self.assertEqual(branch_base,
                         dir.get_branch_transport(bzrlib.branch.BzrBranchFormat5()).base)
        repository_base = t.clone('repository').base
        self.assertEqual(repository_base, dir.get_repository_transport(None).base)
        self.assertEqual(repository_base,
                         dir.get_repository_transport(weaverepo.RepositoryFormat7()).base)
        checkout_base = t.clone('checkout').base
        self.assertEqual(checkout_base, dir.get_workingtree_transport(None).base)
        self.assertEqual(checkout_base,
                         dir.get_workingtree_transport(workingtree.WorkingTreeFormat3()).base)

    def test_meta1dir_uses_lockdir(self):
        """Meta1 format uses a LockDir to guard the whole directory, not a file."""
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
        t = dir.transport
        self.assertIsDirectory('branch-lock', t)

    def test_comparison(self):
        """Equality and inequality behave properly.

        Metadirs should compare equal iff they have the same repo, branch and
        tree formats.
        """
        mydir = bzrdir.format_registry.make_bzrdir('knit')
        self.assertEqual(mydir, mydir)
        self.assertFalse(mydir != mydir)
        otherdir = bzrdir.format_registry.make_bzrdir('knit')
        self.assertEqual(otherdir, mydir)
        self.assertFalse(otherdir != mydir)
        otherdir2 = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
        self.assertNotEqual(otherdir2, mydir)
        self.assertFalse(otherdir2 == mydir)

    def test_needs_conversion_different_working_tree(self):
        # meta1dirs need an conversion if any element is not the default.
        new_format = bzrdir.format_registry.make_bzrdir('dirstate')
        tree = self.make_branch_and_tree('tree', format='knit')
        self.assertTrue(tree.bzrdir.needs_format_conversion(
            new_format))

    def test_initialize_on_format_uses_smart_transport(self):
        self.setup_smart_server_with_call_log()
        new_format = bzrdir.format_registry.make_bzrdir('dirstate')
        transport = self.get_transport('target')
        transport.ensure_base()
        self.reset_smart_call_log()
        instance = new_format.initialize_on_transport(transport)
        self.assertIsInstance(instance, remote.RemoteBzrDir)
        rpc_count = len(self.hpss_calls)
        # This figure represent the amount of work to perform this use case. It
        # is entirely ok to reduce this number if a test fails due to rpc_count
        # being too low. If rpc_count increases, more network roundtrips have
        # become necessary for this use case. Please do not adjust this number
        # upwards without agreement from bzr's network support maintainers.
        self.assertEqual(2, rpc_count)


class TestFormat5(TestCaseWithTransport):
    """Tests specific to the version 5 bzrdir format."""

    def test_same_lockfiles_between_tree_repo_branch(self):
        # this checks that only a single lockfiles instance is created
        # for format 5 objects
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
        def check_dir_components_use_same_lock(dir):
            ctrl_1 = dir.open_repository().control_files
            ctrl_2 = dir.open_branch().control_files
            ctrl_3 = dir.open_workingtree()._control_files
            self.assertTrue(ctrl_1 is ctrl_2)
            self.assertTrue(ctrl_2 is ctrl_3)
        check_dir_components_use_same_lock(dir)
        # and if we open it normally.
        dir = bzrdir.BzrDir.open(self.get_url())
        check_dir_components_use_same_lock(dir)

    def test_can_convert(self):
        # format 5 dirs are convertable
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
        self.assertTrue(dir.can_convert_format())

    def test_needs_conversion(self):
        # format 5 dirs need a conversion if they are not the default,
        # and they aren't
        dir = bzrdir.BzrDirFormat5().initialize(self.get_url())
        # don't need to convert it to itself
        self.assertFalse(dir.needs_format_conversion(bzrdir.BzrDirFormat5()))
        # do need to convert it to the current default
        self.assertTrue(dir.needs_format_conversion(
            bzrdir.BzrDirFormat.get_default_format()))


class TestFormat6(TestCaseWithTransport):
    """Tests specific to the version 6 bzrdir format."""

    def test_same_lockfiles_between_tree_repo_branch(self):
        # this checks that only a single lockfiles instance is created
        # for format 6 objects
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
        def check_dir_components_use_same_lock(dir):
            ctrl_1 = dir.open_repository().control_files
            ctrl_2 = dir.open_branch().control_files
            ctrl_3 = dir.open_workingtree()._control_files
            self.assertTrue(ctrl_1 is ctrl_2)
            self.assertTrue(ctrl_2 is ctrl_3)
        check_dir_components_use_same_lock(dir)
        # and if we open it normally.
        dir = bzrdir.BzrDir.open(self.get_url())
        check_dir_components_use_same_lock(dir)

    def test_can_convert(self):
        # format 6 dirs are convertable
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
        self.assertTrue(dir.can_convert_format())

    def test_needs_conversion(self):
        # format 6 dirs need an conversion if they are not the default.
        dir = bzrdir.BzrDirFormat6().initialize(self.get_url())
        self.assertTrue(dir.needs_format_conversion(
            bzrdir.BzrDirFormat.get_default_format()))


class NotBzrDir(bzrlib.bzrdir.BzrDir):
    """A non .bzr based control directory."""

    def __init__(self, transport, format):
        self._format = format
        self.root_transport = transport
        self.transport = transport.clone('.not')


class NotBzrDirFormat(bzrlib.bzrdir.BzrDirFormat):
    """A test class representing any non-.bzr based disk format."""

    def initialize_on_transport(self, transport):
        """Initialize a new .not dir in the base directory of a Transport."""
        transport.mkdir('.not')
        return self.open(transport)

    def open(self, transport):
        """Open this directory."""
        return NotBzrDir(transport, self)

    @classmethod
    def _known_formats(self):
        return set([NotBzrDirFormat()])

    @classmethod
    def probe_transport(self, transport):
        """Our format is present if the transport ends in '.not/'."""
        if transport.has('.not'):
            return NotBzrDirFormat()


class TestNotBzrDir(TestCaseWithTransport):
    """Tests for using the bzrdir api with a non .bzr based disk format.

    If/when one of these is in the core, we can let the implementation tests
    verify this works.
    """

    def test_create_and_find_format(self):
        # create a .notbzr dir
        format = NotBzrDirFormat()
        dir = format.initialize(self.get_url())
        self.assertIsInstance(dir, NotBzrDir)
        # now probe for it.
        bzrlib.bzrdir.BzrDirFormat.register_control_format(format)
        try:
            found = bzrlib.bzrdir.BzrDirFormat.find_format(
                get_transport(self.get_url()))
            self.assertIsInstance(found, NotBzrDirFormat)
        finally:
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(format)

    def test_included_in_known_formats(self):
        bzrlib.bzrdir.BzrDirFormat.register_control_format(NotBzrDirFormat)
        try:
            formats = bzrlib.bzrdir.BzrDirFormat.known_formats()
            for format in formats:
                if isinstance(format, NotBzrDirFormat):
                    return
            self.fail("No NotBzrDirFormat in %s" % formats)
        finally:
            bzrlib.bzrdir.BzrDirFormat.unregister_control_format(NotBzrDirFormat)


class NonLocalTests(TestCaseWithTransport):
    """Tests for bzrdir static behaviour on non local paths."""

    def setUp(self):
        super(NonLocalTests, self).setUp()
        self.vfs_transport_factory = MemoryServer

    def test_create_branch_convenience(self):
        # outside a repo the default convenience output is a repo+branch_tree
        format = bzrdir.format_registry.make_bzrdir('knit')
        branch = bzrdir.BzrDir.create_branch_convenience(
            self.get_url('foo'), format=format)
        self.assertRaises(errors.NoWorkingTree,
                          branch.bzrdir.open_workingtree)
        branch.bzrdir.open_repository()

    def test_create_branch_convenience_force_tree_not_local_fails(self):
        # outside a repo the default convenience output is a repo+branch_tree
        format = bzrdir.format_registry.make_bzrdir('knit')
        self.assertRaises(errors.NotLocalUrl,
            bzrdir.BzrDir.create_branch_convenience,
            self.get_url('foo'),
            force_new_tree=True,
            format=format)
        t = get_transport(self.get_url('.'))
        self.assertFalse(t.has('foo'))

    def test_clone(self):
        # clone into a nonlocal path works
        format = bzrdir.format_registry.make_bzrdir('knit')
        branch = bzrdir.BzrDir.create_branch_convenience('local',
                                                         format=format)
        branch.bzrdir.open_workingtree()
        result = branch.bzrdir.clone(self.get_url('remote'))
        self.assertRaises(errors.NoWorkingTree,
                          result.open_workingtree)
        result.open_branch()
        result.open_repository()

    def test_checkout_metadir(self):
        # checkout_metadir has reasonable working tree format even when no
        # working tree is present
        self.make_branch('branch-knit2', format='dirstate-with-subtree')
        my_bzrdir = bzrdir.BzrDir.open(self.get_url('branch-knit2'))
        checkout_format = my_bzrdir.checkout_metadir()
        self.assertIsInstance(checkout_format.workingtree_format,
                              workingtree.WorkingTreeFormat3)


class TestHTTPRedirections(object):
    """Test redirection between two http servers.

    This MUST be used by daughter classes that also inherit from
    TestCaseWithTwoWebservers.

    We can't inherit directly from TestCaseWithTwoWebservers or the
    test framework will try to create an instance which cannot
    run, its implementation being incomplete.
    """

    def create_transport_readonly_server(self):
        return http_utils.HTTPServerRedirecting()

    def create_transport_secondary_server(self):
        return http_utils.HTTPServerRedirecting()

    def setUp(self):
        super(TestHTTPRedirections, self).setUp()
        # The redirections will point to the new server
        self.new_server = self.get_readonly_server()
        # The requests to the old server will be redirected
        self.old_server = self.get_secondary_server()
        # Configure the redirections
        self.old_server.redirect_to(self.new_server.host, self.new_server.port)

    def test_loop(self):
        # Both servers redirect to each other creating a loop
        self.new_server.redirect_to(self.old_server.host, self.old_server.port)
        # Starting from either server should loop
        old_url = self._qualified_url(self.old_server.host,
                                      self.old_server.port)
        oldt = self._transport(old_url)
        self.assertRaises(errors.NotBranchError,
                          bzrdir.BzrDir.open_from_transport, oldt)
        new_url = self._qualified_url(self.new_server.host,
                                      self.new_server.port)
        newt = self._transport(new_url)
        self.assertRaises(errors.NotBranchError,
                          bzrdir.BzrDir.open_from_transport, newt)

    def test_qualifier_preserved(self):
        wt = self.make_branch_and_tree('branch')
        old_url = self._qualified_url(self.old_server.host,
                                      self.old_server.port)
        start = self._transport(old_url).clone('branch')
        bdir = bzrdir.BzrDir.open_from_transport(start)
        # Redirection should preserve the qualifier, hence the transport class
        # itself.
        self.assertIsInstance(bdir.root_transport, type(start))


class TestHTTPRedirections_urllib(TestHTTPRedirections,
                                  http_utils.TestCaseWithTwoWebservers):
    """Tests redirections for urllib implementation"""

    _transport = HttpTransport_urllib

    def _qualified_url(self, host, port):
        return 'http+urllib://%s:%s' % (host, port)



class TestHTTPRedirections_pycurl(TestWithTransport_pycurl,
                                  TestHTTPRedirections,
                                  http_utils.TestCaseWithTwoWebservers):
    """Tests redirections for pycurl implementation"""

    def _qualified_url(self, host, port):
        return 'http+pycurl://%s:%s' % (host, port)


class TestHTTPRedirections_nosmart(TestHTTPRedirections,
                                  http_utils.TestCaseWithTwoWebservers):
    """Tests redirections for the nosmart decorator"""

    _transport = NoSmartTransportDecorator

    def _qualified_url(self, host, port):
        return 'nosmart+http://%s:%s' % (host, port)


class TestHTTPRedirections_readonly(TestHTTPRedirections,
                                    http_utils.TestCaseWithTwoWebservers):
    """Tests redirections for readonly decoratror"""

    _transport = ReadonlyTransportDecorator

    def _qualified_url(self, host, port):
        return 'readonly+http://%s:%s' % (host, port)


class TestDotBzrHidden(TestCaseWithTransport):

    ls = ['ls']
    if sys.platform == 'win32':
        ls = [os.environ['COMSPEC'], '/C', 'dir', '/B']

    def get_ls(self):
        f = subprocess.Popen(self.ls, stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        out, err = f.communicate()
        self.assertEqual(0, f.returncode, 'Calling %s failed: %s'
                         % (self.ls, err))
        return out.splitlines()

    def test_dot_bzr_hidden(self):
        if sys.platform == 'win32' and not win32utils.has_win32file:
            raise TestSkipped('unable to make file hidden without pywin32 library')
        b = bzrdir.BzrDir.create('.')
        self.build_tree(['a'])
        self.assertEquals(['a'], self.get_ls())

    def test_dot_bzr_hidden_with_url(self):
        if sys.platform == 'win32' and not win32utils.has_win32file:
            raise TestSkipped('unable to make file hidden without pywin32 library')
        b = bzrdir.BzrDir.create(urlutils.local_path_to_url('.'))
        self.build_tree(['a'])
        self.assertEquals(['a'], self.get_ls())


class _TestBzrDirFormat(bzrdir.BzrDirMetaFormat1):
    """Test BzrDirFormat implementation for TestBzrDirSprout."""

    def _open(self, transport):
        return _TestBzrDir(transport, self)


class _TestBzrDir(bzrdir.BzrDirMeta1):
    """Test BzrDir implementation for TestBzrDirSprout.

    When created a _TestBzrDir already has repository and a branch.  The branch
    is a test double as well.
    """

    def __init__(self, *args, **kwargs):
        super(_TestBzrDir, self).__init__(*args, **kwargs)
        self.test_branch = _TestBranch()
        self.test_branch.repository = self.create_repository()

    def open_branch(self, unsupported=False):
        return self.test_branch

    def cloning_metadir(self, require_stacking=False):
        return _TestBzrDirFormat()


class _TestBranchFormat(bzrlib.branch.BranchFormat):
    """Test Branch format for TestBzrDirSprout."""


class _TestBranch(bzrlib.branch.Branch):
    """Test Branch implementation for TestBzrDirSprout."""

    def __init__(self, *args, **kwargs):
        self._format = _TestBranchFormat()
        super(_TestBranch, self).__init__(*args, **kwargs)
        self.calls = []
        self._parent = None

    def sprout(self, *args, **kwargs):
        self.calls.append('sprout')
        return _TestBranch()

    def copy_content_into(self, destination, revision_id=None):
        self.calls.append('copy_content_into')

    def get_parent(self):
        return self._parent

    def set_parent(self, parent):
        self._parent = parent


class TestBzrDirSprout(TestCaseWithMemoryTransport):

    def test_sprout_uses_branch_sprout(self):
        """BzrDir.sprout calls Branch.sprout.

        Usually, BzrDir.sprout should delegate to the branch's sprout method
        for part of the work.  This allows the source branch to control the
        choice of format for the new branch.

        There are exceptions, but this tests avoids them:
          - if there's no branch in the source bzrdir,
          - or if the stacking has been requested and the format needs to be
            overridden to satisfy that.
        """
        # Make an instrumented bzrdir.
        t = self.get_transport('source')
        t.ensure_base()
        source_bzrdir = _TestBzrDirFormat().initialize_on_transport(t)
        # The instrumented bzrdir has a test_branch attribute that logs calls
        # made to the branch contained in that bzrdir.  Initially the test
        # branch exists but no calls have been made to it.
        self.assertEqual([], source_bzrdir.test_branch.calls)

        # Sprout the bzrdir
        target_url = self.get_url('target')
        result = source_bzrdir.sprout(target_url, recurse='no')

        # The bzrdir called the branch's sprout method.
        self.assertSubset(['sprout'], source_bzrdir.test_branch.calls)

    def test_sprout_parent(self):
        grandparent_tree = self.make_branch('grandparent')
        parent = grandparent_tree.bzrdir.sprout('parent').open_branch()
        branch_tree = parent.bzrdir.sprout('branch').open_branch()
        self.assertContainsRe(branch_tree.get_parent(), '/parent/$')


class TestBzrDirHooks(TestCaseWithMemoryTransport):

    def test_pre_open_called(self):
        calls = []
        bzrdir.BzrDir.hooks.install_named_hook('pre_open', calls.append, None)
        transport = self.get_transport('foo')
        url = transport.base
        self.assertRaises(errors.NotBranchError, bzrdir.BzrDir.open, url)
        self.assertEqual([transport.base], [t.base for t in calls])

    def test_pre_open_actual_exceptions_raised(self):
        count = [0]
        def fail_once(transport):
            count[0] += 1
            if count[0] == 1:
                raise errors.BzrError("fail")
        bzrdir.BzrDir.hooks.install_named_hook('pre_open', fail_once, None)
        transport = self.get_transport('foo')
        url = transport.base
        err = self.assertRaises(errors.BzrError, bzrdir.BzrDir.open, url)
        self.assertEqual('fail', err._preformatted_string)