~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
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
# Copyright (C) 2006-2010 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 smart wire/domain protocol.

This module contains tests for the domain-level smart requests and responses,
such as the 'Branch.lock_write' request. Many of these use specific disk
formats to exercise calls that only make sense for formats with specific
properties.

Tests for low-level protocol encoding are found in test_smart_transport.
"""

import bz2
from cStringIO import StringIO
import tarfile

from bzrlib import (
    bencode,
    bzrdir,
    errors,
    pack,
    smart,
    tests,
    urlutils,
    versionedfile,
    )
from bzrlib.branch import Branch, BranchReferenceFormat
import bzrlib.smart.branch
import bzrlib.smart.bzrdir, bzrlib.smart.bzrdir as smart_dir
import bzrlib.smart.packrepository
import bzrlib.smart.repository
import bzrlib.smart.vfs
from bzrlib.smart.request import (
    FailedSmartServerResponse,
    SmartServerRequest,
    SmartServerResponse,
    SuccessfulSmartServerResponse,
    )
from bzrlib.tests import (
    split_suite_by_re,
    )
from bzrlib.transport import chroot, get_transport, local, memory


def load_tests(standard_tests, module, loader):
    """Multiply tests version and protocol consistency."""
    # FindRepository tests.
    bzrdir_mod = bzrlib.smart.bzrdir
    scenarios = [
        ("find_repository", {
            "_request_class":bzrdir_mod.SmartServerRequestFindRepositoryV1}),
        ("find_repositoryV2", {
            "_request_class":bzrdir_mod.SmartServerRequestFindRepositoryV2}),
        ("find_repositoryV3", {
            "_request_class":bzrdir_mod.SmartServerRequestFindRepositoryV3}),
        ]
    to_adapt, result = split_suite_by_re(standard_tests,
        "TestSmartServerRequestFindRepository")
    v2_only, v1_and_2 = split_suite_by_re(to_adapt,
        "_v2")
    tests.multiply_tests(v1_and_2, scenarios, result)
    # The first scenario is only applicable to v1 protocols, it is deleted
    # since.
    tests.multiply_tests(v2_only, scenarios[1:], result)
    return result


class TestCaseWithChrootedTransport(tests.TestCaseWithTransport):

    def setUp(self):
        self.vfs_transport_factory = memory.MemoryServer
        tests.TestCaseWithTransport.setUp(self)
        self._chroot_server = None

    def get_transport(self, relpath=None):
        if self._chroot_server is None:
            backing_transport = tests.TestCaseWithTransport.get_transport(self)
            self._chroot_server = chroot.ChrootServer(backing_transport)
            self.start_server(self._chroot_server)
        t = get_transport(self._chroot_server.get_url())
        if relpath is not None:
            t = t.clone(relpath)
        return t


class TestCaseWithSmartMedium(tests.TestCaseWithMemoryTransport):

    def setUp(self):
        super(TestCaseWithSmartMedium, self).setUp()
        # We're allowed to set  the transport class here, so that we don't use
        # the default or a parameterized class, but rather use the
        # TestCaseWithTransport infrastructure to set up a smart server and
        # transport.
        self.transport_server = self.make_transport_server

    def make_transport_server(self):
        return smart.server.SmartTCPServer_for_testing('-' + self.id())

    def get_smart_medium(self):
        """Get a smart medium to use in tests."""
        return self.get_transport().get_smart_medium()


class TestByteStreamToStream(tests.TestCase):

    def test_repeated_substreams_same_kind_are_one_stream(self):
        # Make a stream - an iterable of bytestrings.
        stream = [('text', [versionedfile.FulltextContentFactory(('k1',), None,
            None, 'foo')]),('text', [
            versionedfile.FulltextContentFactory(('k2',), None, None, 'bar')])]
        fmt = bzrdir.format_registry.get('pack-0.92')().repository_format
        bytes = smart.repository._stream_to_byte_stream(stream, fmt)
        streams = []
        # Iterate the resulting iterable; checking that we get only one stream
        # out.
        fmt, stream = smart.repository._byte_stream_to_stream(bytes)
        for kind, substream in stream:
            streams.append((kind, list(substream)))
        self.assertLength(1, streams)
        self.assertLength(2, streams[0][1])


class TestSmartServerResponse(tests.TestCase):

    def test__eq__(self):
        self.assertEqual(SmartServerResponse(('ok', )),
            SmartServerResponse(('ok', )))
        self.assertEqual(SmartServerResponse(('ok', ), 'body'),
            SmartServerResponse(('ok', ), 'body'))
        self.assertNotEqual(SmartServerResponse(('ok', )),
            SmartServerResponse(('notok', )))
        self.assertNotEqual(SmartServerResponse(('ok', ), 'body'),
            SmartServerResponse(('ok', )))
        self.assertNotEqual(None,
            SmartServerResponse(('ok', )))

    def test__str__(self):
        """SmartServerResponses can be stringified."""
        self.assertEqual(
            "<SuccessfulSmartServerResponse args=('args',) body='body'>",
            str(SuccessfulSmartServerResponse(('args',), 'body')))
        self.assertEqual(
            "<FailedSmartServerResponse args=('args',) body='body'>",
            str(FailedSmartServerResponse(('args',), 'body')))


class TestSmartServerRequest(tests.TestCaseWithMemoryTransport):

    def test_translate_client_path(self):
        transport = self.get_transport()
        request = SmartServerRequest(transport, 'foo/')
        self.assertEqual('./', request.translate_client_path('foo/'))
        self.assertRaises(
            errors.InvalidURLJoin, request.translate_client_path, 'foo/..')
        self.assertRaises(
            errors.PathNotChild, request.translate_client_path, '/')
        self.assertRaises(
            errors.PathNotChild, request.translate_client_path, 'bar/')
        self.assertEqual('./baz', request.translate_client_path('foo/baz'))
        e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
        self.assertEqual('./' + urlutils.escape(e_acute),
                         request.translate_client_path('foo/' + e_acute))

    def test_translate_client_path_vfs(self):
        """VfsRequests receive escaped paths rather than raw UTF-8."""
        transport = self.get_transport()
        request = smart.vfs.VfsRequest(transport, 'foo/')
        e_acute = u'\N{LATIN SMALL LETTER E WITH ACUTE}'.encode('utf-8')
        escaped = urlutils.escape('foo/' + e_acute)
        self.assertEqual('./' + urlutils.escape(e_acute),
                         request.translate_client_path(escaped))

    def test_transport_from_client_path(self):
        transport = self.get_transport()
        request = SmartServerRequest(transport, 'foo/')
        self.assertEqual(
            transport.base,
            request.transport_from_client_path('foo/').base)


class TestSmartServerBzrDirRequestCloningMetaDir(
    tests.TestCaseWithMemoryTransport):
    """Tests for BzrDir.cloning_metadir."""

    def test_cloning_metadir(self):
        """When there is a bzrdir present, the call succeeds."""
        backing = self.get_transport()
        dir = self.make_bzrdir('.')
        local_result = dir.cloning_metadir()
        request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
        request = request_class(backing)
        expected = SuccessfulSmartServerResponse(
            (local_result.network_name(),
            local_result.repository_format.network_name(),
            ('branch', local_result.get_branch_format().network_name())))
        self.assertEqual(expected, request.execute('', 'False'))

    def test_cloning_metadir_reference(self):
        """The request fails when bzrdir contains a branch reference."""
        backing = self.get_transport()
        referenced_branch = self.make_branch('referenced')
        dir = self.make_bzrdir('.')
        local_result = dir.cloning_metadir()
        reference = BranchReferenceFormat().initialize(dir, referenced_branch)
        reference_url = BranchReferenceFormat().get_reference(dir)
        # The server shouldn't try to follow the branch reference, so it's fine
        # if the referenced branch isn't reachable.
        backing.rename('referenced', 'moved')
        request_class = smart_dir.SmartServerBzrDirRequestCloningMetaDir
        request = request_class(backing)
        expected = FailedSmartServerResponse(('BranchReference',))
        self.assertEqual(expected, request.execute('', 'False'))


class TestSmartServerRequestCreateRepository(tests.TestCaseWithMemoryTransport):
    """Tests for BzrDir.create_repository."""

    def test_makes_repository(self):
        """When there is a bzrdir present, the call succeeds."""
        backing = self.get_transport()
        self.make_bzrdir('.')
        request_class = bzrlib.smart.bzrdir.SmartServerRequestCreateRepository
        request = request_class(backing)
        reference_bzrdir_format = bzrdir.format_registry.get('pack-0.92')()
        reference_format = reference_bzrdir_format.repository_format
        network_name = reference_format.network_name()
        expected = SuccessfulSmartServerResponse(
            ('ok', 'no', 'no', 'no', network_name))
        self.assertEqual(expected, request.execute('', network_name, 'True'))


class TestSmartServerRequestFindRepository(tests.TestCaseWithMemoryTransport):
    """Tests for BzrDir.find_repository."""

    def test_no_repository(self):
        """When there is no repository to be found, ('norepository', ) is returned."""
        backing = self.get_transport()
        request = self._request_class(backing)
        self.make_bzrdir('.')
        self.assertEqual(SmartServerResponse(('norepository', )),
            request.execute(''))

    def test_nonshared_repository(self):
        # nonshared repositorys only allow 'find' to return a handle when the
        # path the repository is being searched on is the same as that that
        # the repository is at.
        backing = self.get_transport()
        request = self._request_class(backing)
        result = self._make_repository_and_result()
        self.assertEqual(result, request.execute(''))
        self.make_bzrdir('subdir')
        self.assertEqual(SmartServerResponse(('norepository', )),
            request.execute('subdir'))

    def _make_repository_and_result(self, shared=False, format=None):
        """Convenience function to setup a repository.

        :result: The SmartServerResponse to expect when opening it.
        """
        repo = self.make_repository('.', shared=shared, format=format)
        if repo.supports_rich_root():
            rich_root = 'yes'
        else:
            rich_root = 'no'
        if repo._format.supports_tree_reference:
            subtrees = 'yes'
        else:
            subtrees = 'no'
        if repo._format.supports_external_lookups:
            external = 'yes'
        else:
            external = 'no'
        if (smart.bzrdir.SmartServerRequestFindRepositoryV3 ==
            self._request_class):
            return SuccessfulSmartServerResponse(
                ('ok', '', rich_root, subtrees, external,
                 repo._format.network_name()))
        elif (smart.bzrdir.SmartServerRequestFindRepositoryV2 ==
            self._request_class):
            # All tests so far are on formats, and for non-external
            # repositories.
            return SuccessfulSmartServerResponse(
                ('ok', '', rich_root, subtrees, external))
        else:
            return SuccessfulSmartServerResponse(('ok', '', rich_root, subtrees))

    def test_shared_repository(self):
        """When there is a shared repository, we get 'ok', 'relpath-to-repo'."""
        backing = self.get_transport()
        request = self._request_class(backing)
        result = self._make_repository_and_result(shared=True)
        self.assertEqual(result, request.execute(''))
        self.make_bzrdir('subdir')
        result2 = SmartServerResponse(result.args[0:1] + ('..', ) + result.args[2:])
        self.assertEqual(result2,
            request.execute('subdir'))
        self.make_bzrdir('subdir/deeper')
        result3 = SmartServerResponse(result.args[0:1] + ('../..', ) + result.args[2:])
        self.assertEqual(result3,
            request.execute('subdir/deeper'))

    def test_rich_root_and_subtree_encoding(self):
        """Test for the format attributes for rich root and subtree support."""
        backing = self.get_transport()
        request = self._request_class(backing)
        result = self._make_repository_and_result(format='dirstate-with-subtree')
        # check the test will be valid
        self.assertEqual('yes', result.args[2])
        self.assertEqual('yes', result.args[3])
        self.assertEqual(result, request.execute(''))

    def test_supports_external_lookups_no_v2(self):
        """Test for the supports_external_lookups attribute."""
        backing = self.get_transport()
        request = self._request_class(backing)
        result = self._make_repository_and_result(format='dirstate-with-subtree')
        # check the test will be valid
        self.assertEqual('no', result.args[4])
        self.assertEqual(result, request.execute(''))


class TestSmartServerBzrDirRequestGetConfigFile(
    tests.TestCaseWithMemoryTransport):
    """Tests for BzrDir.get_config_file."""

    def test_present(self):
        backing = self.get_transport()
        dir = self.make_bzrdir('.')
        dir.get_config().set_default_stack_on("/")
        local_result = dir._get_config()._get_config_file().read()
        request_class = smart_dir.SmartServerBzrDirRequestConfigFile
        request = request_class(backing)
        expected = SuccessfulSmartServerResponse((), local_result)
        self.assertEqual(expected, request.execute(''))

    def test_missing(self):
        backing = self.get_transport()
        dir = self.make_bzrdir('.')
        request_class = smart_dir.SmartServerBzrDirRequestConfigFile
        request = request_class(backing)
        expected = SuccessfulSmartServerResponse((), '')
        self.assertEqual(expected, request.execute(''))


class TestSmartServerRequestInitializeBzrDir(tests.TestCaseWithMemoryTransport):

    def test_empty_dir(self):
        """Initializing an empty dir should succeed and do it."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestInitializeBzrDir(backing)
        self.assertEqual(SmartServerResponse(('ok', )),
            request.execute(''))
        made_dir = bzrdir.BzrDir.open_from_transport(backing)
        # no branch, tree or repository is expected with the current
        # default formart.
        self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
        self.assertRaises(errors.NotBranchError, made_dir.open_branch)
        self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)

    def test_missing_dir(self):
        """Initializing a missing directory should fail like the bzrdir api."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestInitializeBzrDir(backing)
        self.assertRaises(errors.NoSuchFile,
            request.execute, 'subdir')

    def test_initialized_dir(self):
        """Initializing an extant bzrdir should fail like the bzrdir api."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestInitializeBzrDir(backing)
        self.make_bzrdir('subdir')
        self.assertRaises(errors.FileExists,
            request.execute, 'subdir')


class TestSmartServerRequestBzrDirInitializeEx(tests.TestCaseWithMemoryTransport):
    """Basic tests for BzrDir.initialize_ex_1.16 in the smart server.

    The main unit tests in test_bzrdir exercise the API comprehensively.
    """

    def test_empty_dir(self):
        """Initializing an empty dir should succeed and do it."""
        backing = self.get_transport()
        name = self.make_bzrdir('reference')._format.network_name()
        request = smart.bzrdir.SmartServerRequestBzrDirInitializeEx(backing)
        self.assertEqual(SmartServerResponse(('', '', '', '', '', '', name,
            'False', '', '', '')),
            request.execute(name, '', 'True', 'False', 'False', '', '', '', '',
            'False'))
        made_dir = bzrdir.BzrDir.open_from_transport(backing)
        # no branch, tree or repository is expected with the current
        # default format.
        self.assertRaises(errors.NoWorkingTree, made_dir.open_workingtree)
        self.assertRaises(errors.NotBranchError, made_dir.open_branch)
        self.assertRaises(errors.NoRepositoryPresent, made_dir.open_repository)

    def test_missing_dir(self):
        """Initializing a missing directory should fail like the bzrdir api."""
        backing = self.get_transport()
        name = self.make_bzrdir('reference')._format.network_name()
        request = smart.bzrdir.SmartServerRequestBzrDirInitializeEx(backing)
        self.assertRaises(errors.NoSuchFile, request.execute, name,
            'subdir/dir', 'False', 'False', 'False', '', '', '', '', 'False')

    def test_initialized_dir(self):
        """Initializing an extant directory should fail like the bzrdir api."""
        backing = self.get_transport()
        name = self.make_bzrdir('reference')._format.network_name()
        request = smart.bzrdir.SmartServerRequestBzrDirInitializeEx(backing)
        self.make_bzrdir('subdir')
        self.assertRaises(errors.FileExists, request.execute, name, 'subdir',
            'False', 'False', 'False', '', '', '', '', 'False')


class TestSmartServerRequestOpenBzrDir(tests.TestCaseWithMemoryTransport):
    
    def test_no_directory(self):
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBzrDir(backing)
        self.assertEqual(SmartServerResponse(('no', )),
            request.execute('does-not-exist'))

    def test_empty_directory(self):
        backing = self.get_transport()
        backing.mkdir('empty')
        request = smart.bzrdir.SmartServerRequestOpenBzrDir(backing)
        self.assertEqual(SmartServerResponse(('no', )),
            request.execute('empty'))

    def test_outside_root_client_path(self):
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBzrDir(backing,
            root_client_path='root')
        self.assertEqual(SmartServerResponse(('no', )),
            request.execute('not-root'))

    
class TestSmartServerRequestOpenBzrDir_2_1(tests.TestCaseWithMemoryTransport):
    
    def test_no_directory(self):
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBzrDir_2_1(backing)
        self.assertEqual(SmartServerResponse(('no', )),
            request.execute('does-not-exist'))

    def test_empty_directory(self):
        backing = self.get_transport()
        backing.mkdir('empty')
        request = smart.bzrdir.SmartServerRequestOpenBzrDir_2_1(backing)
        self.assertEqual(SmartServerResponse(('no', )),
            request.execute('empty'))

    def test_present_without_workingtree(self):
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBzrDir_2_1(backing)
        self.make_bzrdir('.')
        self.assertEqual(SmartServerResponse(('yes', 'no')),
            request.execute(''))

    def test_outside_root_client_path(self):
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBzrDir_2_1(backing,
            root_client_path='root')
        self.assertEqual(SmartServerResponse(('no',)),
            request.execute('not-root'))

    
class TestSmartServerRequestOpenBzrDir_2_1_disk(TestCaseWithChrootedTransport):

    def test_present_with_workingtree(self):
        self.vfs_transport_factory = local.LocalURLServer
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBzrDir_2_1(backing)
        bd = self.make_bzrdir('.')
        bd.create_repository()
        bd.create_branch()
        bd.create_workingtree()
        self.assertEqual(SmartServerResponse(('yes', 'yes')),
            request.execute(''))


class TestSmartServerRequestOpenBranch(TestCaseWithChrootedTransport):

    def test_no_branch(self):
        """When there is no branch, ('nobranch', ) is returned."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranch(backing)
        self.make_bzrdir('.')
        self.assertEqual(SmartServerResponse(('nobranch', )),
            request.execute(''))

    def test_branch(self):
        """When there is a branch, 'ok' is returned."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranch(backing)
        self.make_branch('.')
        self.assertEqual(SmartServerResponse(('ok', '')),
            request.execute(''))

    def test_branch_reference(self):
        """When there is a branch reference, the reference URL is returned."""
        self.vfs_transport_factory = local.LocalURLServer
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranch(backing)
        branch = self.make_branch('branch')
        checkout = branch.create_checkout('reference',lightweight=True)
        reference_url = BranchReferenceFormat().get_reference(checkout.bzrdir)
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
        self.assertEqual(SmartServerResponse(('ok', reference_url)),
            request.execute('reference'))

    def test_notification_on_branch_from_repository(self):
        """When there is a repository, the error should return details."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranch(backing)
        repo = self.make_repository('.')
        self.assertEqual(SmartServerResponse(('nobranch',)),
            request.execute(''))


class TestSmartServerRequestOpenBranchV2(TestCaseWithChrootedTransport):

    def test_no_branch(self):
        """When there is no branch, ('nobranch', ) is returned."""
        backing = self.get_transport()
        self.make_bzrdir('.')
        request = smart.bzrdir.SmartServerRequestOpenBranchV2(backing)
        self.assertEqual(SmartServerResponse(('nobranch', )),
            request.execute(''))

    def test_branch(self):
        """When there is a branch, 'ok' is returned."""
        backing = self.get_transport()
        expected = self.make_branch('.')._format.network_name()
        request = smart.bzrdir.SmartServerRequestOpenBranchV2(backing)
        self.assertEqual(SuccessfulSmartServerResponse(('branch', expected)),
            request.execute(''))

    def test_branch_reference(self):
        """When there is a branch reference, the reference URL is returned."""
        self.vfs_transport_factory = local.LocalURLServer
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranchV2(backing)
        branch = self.make_branch('branch')
        checkout = branch.create_checkout('reference',lightweight=True)
        reference_url = BranchReferenceFormat().get_reference(checkout.bzrdir)
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
        self.assertEqual(SuccessfulSmartServerResponse(('ref', reference_url)),
            request.execute('reference'))

    def test_stacked_branch(self):
        """Opening a stacked branch does not open the stacked-on branch."""
        trunk = self.make_branch('trunk')
        feature = self.make_branch('feature')
        feature.set_stacked_on_url(trunk.base)
        opened_branches = []
        Branch.hooks.install_named_hook('open', opened_branches.append, None)
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranchV2(backing)
        request.setup_jail()
        try:
            response = request.execute('feature')
        finally:
            request.teardown_jail()
        expected_format = feature._format.network_name()
        self.assertEqual(
            SuccessfulSmartServerResponse(('branch', expected_format)),
            response)
        self.assertLength(1, opened_branches)

    def test_notification_on_branch_from_repository(self):
        """When there is a repository, the error should return details."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranchV2(backing)
        repo = self.make_repository('.')
        self.assertEqual(SmartServerResponse(('nobranch',)),
            request.execute(''))


class TestSmartServerRequestOpenBranchV3(TestCaseWithChrootedTransport):

    def test_no_branch(self):
        """When there is no branch, ('nobranch', ) is returned."""
        backing = self.get_transport()
        self.make_bzrdir('.')
        request = smart.bzrdir.SmartServerRequestOpenBranchV3(backing)
        self.assertEqual(SmartServerResponse(('nobranch',)),
            request.execute(''))

    def test_branch(self):
        """When there is a branch, 'ok' is returned."""
        backing = self.get_transport()
        expected = self.make_branch('.')._format.network_name()
        request = smart.bzrdir.SmartServerRequestOpenBranchV3(backing)
        self.assertEqual(SuccessfulSmartServerResponse(('branch', expected)),
            request.execute(''))

    def test_branch_reference(self):
        """When there is a branch reference, the reference URL is returned."""
        self.vfs_transport_factory = local.LocalURLServer
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranchV3(backing)
        branch = self.make_branch('branch')
        checkout = branch.create_checkout('reference',lightweight=True)
        reference_url = BranchReferenceFormat().get_reference(checkout.bzrdir)
        self.assertFileEqual(reference_url, 'reference/.bzr/branch/location')
        self.assertEqual(SuccessfulSmartServerResponse(('ref', reference_url)),
            request.execute('reference'))

    def test_stacked_branch(self):
        """Opening a stacked branch does not open the stacked-on branch."""
        trunk = self.make_branch('trunk')
        feature = self.make_branch('feature')
        feature.set_stacked_on_url(trunk.base)
        opened_branches = []
        Branch.hooks.install_named_hook('open', opened_branches.append, None)
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranchV3(backing)
        request.setup_jail()
        try:
            response = request.execute('feature')
        finally:
            request.teardown_jail()
        expected_format = feature._format.network_name()
        self.assertEqual(
            SuccessfulSmartServerResponse(('branch', expected_format)),
            response)
        self.assertLength(1, opened_branches)

    def test_notification_on_branch_from_repository(self):
        """When there is a repository, the error should return details."""
        backing = self.get_transport()
        request = smart.bzrdir.SmartServerRequestOpenBranchV3(backing)
        repo = self.make_repository('.')
        self.assertEqual(
            SmartServerResponse(('nobranch', 'location is a repository')),
            request.execute(''))


class TestSmartServerRequestRevisionHistory(tests.TestCaseWithMemoryTransport):

    def test_empty(self):
        """For an empty branch, the body is empty."""
        backing = self.get_transport()
        request = smart.branch.SmartServerRequestRevisionHistory(backing)
        self.make_branch('.')
        self.assertEqual(SmartServerResponse(('ok', ), ''),
            request.execute(''))

    def test_not_empty(self):
        """For a non-empty branch, the body is empty."""
        backing = self.get_transport()
        request = smart.branch.SmartServerRequestRevisionHistory(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        r1 = tree.commit('1st commit')
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
        tree.unlock()
        self.assertEqual(
            SmartServerResponse(('ok', ), ('\x00'.join([r1, r2]))),
            request.execute(''))


class TestSmartServerBranchRequest(tests.TestCaseWithMemoryTransport):

    def test_no_branch(self):
        """When there is a bzrdir and no branch, NotBranchError is raised."""
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequest(backing)
        self.make_bzrdir('.')
        self.assertRaises(errors.NotBranchError,
            request.execute, '')

    def test_branch_reference(self):
        """When there is a branch reference, NotBranchError is raised."""
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequest(backing)
        branch = self.make_branch('branch')
        checkout = branch.create_checkout('reference',lightweight=True)
        self.assertRaises(errors.NotBranchError,
            request.execute, 'checkout')


class TestSmartServerBranchRequestLastRevisionInfo(tests.TestCaseWithMemoryTransport):

    def test_empty(self):
        """For an empty branch, the result is ('ok', '0', 'null:')."""
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestLastRevisionInfo(backing)
        self.make_branch('.')
        self.assertEqual(SmartServerResponse(('ok', '0', 'null:')),
            request.execute(''))

    def test_not_empty(self):
        """For a non-empty branch, the result is ('ok', 'revno', 'revid')."""
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestLastRevisionInfo(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        rev_id_utf8 = u'\xc8'.encode('utf-8')
        r1 = tree.commit('1st commit')
        r2 = tree.commit('2nd commit', rev_id=rev_id_utf8)
        tree.unlock()
        self.assertEqual(
            SmartServerResponse(('ok', '2', rev_id_utf8)),
            request.execute(''))


class TestSmartServerBranchRequestGetConfigFile(tests.TestCaseWithMemoryTransport):

    def test_default(self):
        """With no file, we get empty content."""
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchGetConfigFile(backing)
        branch = self.make_branch('.')
        # there should be no file by default
        content = ''
        self.assertEqual(SmartServerResponse(('ok', ), content),
            request.execute(''))

    def test_with_content(self):
        # SmartServerBranchGetConfigFile should return the content from
        # branch.control_files.get('branch.conf') for now - in the future it may
        # perform more complex processing.
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchGetConfigFile(backing)
        branch = self.make_branch('.')
        branch._transport.put_bytes('branch.conf', 'foo bar baz')
        self.assertEqual(SmartServerResponse(('ok', ), 'foo bar baz'),
            request.execute(''))


class TestLockedBranch(tests.TestCaseWithMemoryTransport):

    def get_lock_tokens(self, branch):
        branch_token = branch.lock_write()
        repo_token = branch.repository.lock_write()
        branch.repository.unlock()
        return branch_token, repo_token


class TestSmartServerBranchRequestSetConfigOption(TestLockedBranch):

    def test_value_name(self):
        branch = self.make_branch('.')
        request = smart.branch.SmartServerBranchRequestSetConfigOption(
            branch.bzrdir.root_transport)
        branch_token, repo_token = self.get_lock_tokens(branch)
        config = branch._get_config()
        result = request.execute('', branch_token, repo_token, 'bar', 'foo',
            '')
        self.assertEqual(SuccessfulSmartServerResponse(()), result)
        self.assertEqual('bar', config.get_option('foo'))
        # Cleanup
        branch.unlock()

    def test_value_name_section(self):
        branch = self.make_branch('.')
        request = smart.branch.SmartServerBranchRequestSetConfigOption(
            branch.bzrdir.root_transport)
        branch_token, repo_token = self.get_lock_tokens(branch)
        config = branch._get_config()
        result = request.execute('', branch_token, repo_token, 'bar', 'foo',
            'gam')
        self.assertEqual(SuccessfulSmartServerResponse(()), result)
        self.assertEqual('bar', config.get_option('foo', 'gam'))
        # Cleanup
        branch.unlock()


class TestSmartServerBranchRequestSetTagsBytes(TestLockedBranch):
    # Only called when the branch format and tags match [yay factory
    # methods] so only need to test straight forward cases.

    def test_set_bytes(self):
        base_branch = self.make_branch('base')
        tag_bytes = base_branch._get_tags_bytes()
        # get_lock_tokens takes out a lock.
        branch_token, repo_token = self.get_lock_tokens(base_branch)
        request = smart.branch.SmartServerBranchSetTagsBytes(
            self.get_transport())
        response = request.execute('base', branch_token, repo_token)
        self.assertEqual(None, response)
        response = request.do_chunk(tag_bytes)
        self.assertEqual(None, response)
        response = request.do_end()
        self.assertEquals(
            SuccessfulSmartServerResponse(()), response)
        base_branch.unlock()

    def test_lock_failed(self):
        base_branch = self.make_branch('base')
        base_branch.lock_write()
        tag_bytes = base_branch._get_tags_bytes()
        request = smart.branch.SmartServerBranchSetTagsBytes(
            self.get_transport())
        self.assertRaises(errors.TokenMismatch, request.execute,
            'base', 'wrong token', 'wrong token')
        # The request handler will keep processing the message parts, so even
        # if the request fails immediately do_chunk and do_end are still
        # called.
        request.do_chunk(tag_bytes)
        request.do_end()
        base_branch.unlock()



class SetLastRevisionTestBase(TestLockedBranch):
    """Base test case for verbs that implement set_last_revision."""

    def setUp(self):
        tests.TestCaseWithMemoryTransport.setUp(self)
        backing_transport = self.get_transport()
        self.request = self.request_class(backing_transport)
        self.tree = self.make_branch_and_memory_tree('.')

    def lock_branch(self):
        return self.get_lock_tokens(self.tree.branch)

    def unlock_branch(self):
        self.tree.branch.unlock()

    def set_last_revision(self, revision_id, revno):
        branch_token, repo_token = self.lock_branch()
        response = self._set_last_revision(
            revision_id, revno, branch_token, repo_token)
        self.unlock_branch()
        return response

    def assertRequestSucceeds(self, revision_id, revno):
        response = self.set_last_revision(revision_id, revno)
        self.assertEqual(SuccessfulSmartServerResponse(('ok',)), response)


class TestSetLastRevisionVerbMixin(object):
    """Mixin test case for verbs that implement set_last_revision."""

    def test_set_null_to_null(self):
        """An empty branch can have its last revision set to 'null:'."""
        self.assertRequestSucceeds('null:', 0)

    def test_NoSuchRevision(self):
        """If the revision_id is not present, the verb returns NoSuchRevision.
        """
        revision_id = 'non-existent revision'
        self.assertEqual(
            FailedSmartServerResponse(('NoSuchRevision', revision_id)),
            self.set_last_revision(revision_id, 1))

    def make_tree_with_two_commits(self):
        self.tree.lock_write()
        self.tree.add('')
        rev_id_utf8 = u'\xc8'.encode('utf-8')
        r1 = self.tree.commit('1st commit', rev_id=rev_id_utf8)
        r2 = self.tree.commit('2nd commit', rev_id='rev-2')
        self.tree.unlock()

    def test_branch_last_revision_info_is_updated(self):
        """A branch's tip can be set to a revision that is present in its
        repository.
        """
        # Make a branch with an empty revision history, but two revisions in
        # its repository.
        self.make_tree_with_two_commits()
        rev_id_utf8 = u'\xc8'.encode('utf-8')
        self.tree.branch.set_revision_history([])
        self.assertEqual(
            (0, 'null:'), self.tree.branch.last_revision_info())
        # We can update the branch to a revision that is present in the
        # repository.
        self.assertRequestSucceeds(rev_id_utf8, 1)
        self.assertEqual(
            (1, rev_id_utf8), self.tree.branch.last_revision_info())

    def test_branch_last_revision_info_rewind(self):
        """A branch's tip can be set to a revision that is an ancestor of the
        current tip.
        """
        self.make_tree_with_two_commits()
        rev_id_utf8 = u'\xc8'.encode('utf-8')
        self.assertEqual(
            (2, 'rev-2'), self.tree.branch.last_revision_info())
        self.assertRequestSucceeds(rev_id_utf8, 1)
        self.assertEqual(
            (1, rev_id_utf8), self.tree.branch.last_revision_info())

    def test_TipChangeRejected(self):
        """If a pre_change_branch_tip hook raises TipChangeRejected, the verb
        returns TipChangeRejected.
        """
        rejection_message = u'rejection message\N{INTERROBANG}'
        def hook_that_rejects(params):
            raise errors.TipChangeRejected(rejection_message)
        Branch.hooks.install_named_hook(
            'pre_change_branch_tip', hook_that_rejects, None)
        self.assertEqual(
            FailedSmartServerResponse(
                ('TipChangeRejected', rejection_message.encode('utf-8'))),
            self.set_last_revision('null:', 0))


class TestSmartServerBranchRequestSetLastRevision(
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
    """Tests for Branch.set_last_revision verb."""

    request_class = smart.branch.SmartServerBranchRequestSetLastRevision

    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
        return self.request.execute(
            '', branch_token, repo_token, revision_id)


class TestSmartServerBranchRequestSetLastRevisionInfo(
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
    """Tests for Branch.set_last_revision_info verb."""

    request_class = smart.branch.SmartServerBranchRequestSetLastRevisionInfo

    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
        return self.request.execute(
            '', branch_token, repo_token, revno, revision_id)

    def test_NoSuchRevision(self):
        """Branch.set_last_revision_info does not have to return
        NoSuchRevision if the revision_id is absent.
        """
        raise tests.TestNotApplicable()


class TestSmartServerBranchRequestSetLastRevisionEx(
        SetLastRevisionTestBase, TestSetLastRevisionVerbMixin):
    """Tests for Branch.set_last_revision_ex verb."""

    request_class = smart.branch.SmartServerBranchRequestSetLastRevisionEx

    def _set_last_revision(self, revision_id, revno, branch_token, repo_token):
        return self.request.execute(
            '', branch_token, repo_token, revision_id, 0, 0)

    def assertRequestSucceeds(self, revision_id, revno):
        response = self.set_last_revision(revision_id, revno)
        self.assertEqual(
            SuccessfulSmartServerResponse(('ok', revno, revision_id)),
            response)

    def test_branch_last_revision_info_rewind(self):
        """A branch's tip can be set to a revision that is an ancestor of the
        current tip, but only if allow_overwrite_descendant is passed.
        """
        self.make_tree_with_two_commits()
        rev_id_utf8 = u'\xc8'.encode('utf-8')
        self.assertEqual(
            (2, 'rev-2'), self.tree.branch.last_revision_info())
        # If allow_overwrite_descendant flag is 0, then trying to set the tip
        # to an older revision ID has no effect.
        branch_token, repo_token = self.lock_branch()
        response = self.request.execute(
            '', branch_token, repo_token, rev_id_utf8, 0, 0)
        self.assertEqual(
            SuccessfulSmartServerResponse(('ok', 2, 'rev-2')),
            response)
        self.assertEqual(
            (2, 'rev-2'), self.tree.branch.last_revision_info())

        # If allow_overwrite_descendant flag is 1, then setting the tip to an
        # ancestor works.
        response = self.request.execute(
            '', branch_token, repo_token, rev_id_utf8, 0, 1)
        self.assertEqual(
            SuccessfulSmartServerResponse(('ok', 1, rev_id_utf8)),
            response)
        self.unlock_branch()
        self.assertEqual(
            (1, rev_id_utf8), self.tree.branch.last_revision_info())

    def make_branch_with_divergent_history(self):
        """Make a branch with divergent history in its repo.

        The branch's tip will be 'child-2', and the repo will also contain
        'child-1', which diverges from a common base revision.
        """
        self.tree.lock_write()
        self.tree.add('')
        r1 = self.tree.commit('1st commit')
        revno_1, revid_1 = self.tree.branch.last_revision_info()
        r2 = self.tree.commit('2nd commit', rev_id='child-1')
        # Undo the second commit
        self.tree.branch.set_last_revision_info(revno_1, revid_1)
        self.tree.set_parent_ids([revid_1])
        # Make a new second commit, child-2.  child-2 has diverged from
        # child-1.
        new_r2 = self.tree.commit('2nd commit', rev_id='child-2')
        self.tree.unlock()

    def test_not_allow_diverged(self):
        """If allow_diverged is not passed, then setting a divergent history
        returns a Diverged error.
        """
        self.make_branch_with_divergent_history()
        self.assertEqual(
            FailedSmartServerResponse(('Diverged',)),
            self.set_last_revision('child-1', 2))
        # The branch tip was not changed.
        self.assertEqual('child-2', self.tree.branch.last_revision())

    def test_allow_diverged(self):
        """If allow_diverged is passed, then setting a divergent history
        succeeds.
        """
        self.make_branch_with_divergent_history()
        branch_token, repo_token = self.lock_branch()
        response = self.request.execute(
            '', branch_token, repo_token, 'child-1', 1, 0)
        self.assertEqual(
            SuccessfulSmartServerResponse(('ok', 2, 'child-1')),
            response)
        self.unlock_branch()
        # The branch tip was changed.
        self.assertEqual('child-1', self.tree.branch.last_revision())


class TestSmartServerBranchRequestGetParent(tests.TestCaseWithMemoryTransport):

    def test_get_parent_none(self):
        base_branch = self.make_branch('base')
        request = smart.branch.SmartServerBranchGetParent(self.get_transport())
        response = request.execute('base')
        self.assertEquals(
            SuccessfulSmartServerResponse(('',)), response)

    def test_get_parent_something(self):
        base_branch = self.make_branch('base')
        base_branch.set_parent(self.get_url('foo'))
        request = smart.branch.SmartServerBranchGetParent(self.get_transport())
        response = request.execute('base')
        self.assertEquals(
            SuccessfulSmartServerResponse(("../foo",)),
            response)


class TestSmartServerBranchRequestSetParent(tests.TestCaseWithMemoryTransport):

    def test_set_parent_none(self):
        branch = self.make_branch('base', format="1.9")
        branch.lock_write()
        branch._set_parent_location('foo')
        branch.unlock()
        request = smart.branch.SmartServerBranchRequestSetParentLocation(
            self.get_transport())
        branch_token = branch.lock_write()
        repo_token = branch.repository.lock_write()
        try:
            response = request.execute('base', branch_token, repo_token, '')
        finally:
            branch.repository.unlock()
            branch.unlock()
        self.assertEqual(SuccessfulSmartServerResponse(()), response)
        self.assertEqual(None, branch.get_parent())

    def test_set_parent_something(self):
        branch = self.make_branch('base', format="1.9")
        request = smart.branch.SmartServerBranchRequestSetParentLocation(
            self.get_transport())
        branch_token = branch.lock_write()
        repo_token = branch.repository.lock_write()
        try:
            response = request.execute('base', branch_token, repo_token,
            'http://bar/')
        finally:
            branch.repository.unlock()
            branch.unlock()
        self.assertEqual(SuccessfulSmartServerResponse(()), response)
        self.assertEqual('http://bar/', branch.get_parent())


class TestSmartServerBranchRequestGetTagsBytes(tests.TestCaseWithMemoryTransport):
    # Only called when the branch format and tags match [yay factory
    # methods] so only need to test straight forward cases.

    def test_get_bytes(self):
        base_branch = self.make_branch('base')
        request = smart.branch.SmartServerBranchGetTagsBytes(
            self.get_transport())
        response = request.execute('base')
        self.assertEquals(
            SuccessfulSmartServerResponse(('',)), response)


class TestSmartServerBranchRequestGetStackedOnURL(tests.TestCaseWithMemoryTransport):

    def test_get_stacked_on_url(self):
        base_branch = self.make_branch('base', format='1.6')
        stacked_branch = self.make_branch('stacked', format='1.6')
        # typically should be relative
        stacked_branch.set_stacked_on_url('../base')
        request = smart.branch.SmartServerBranchRequestGetStackedOnURL(
            self.get_transport())
        response = request.execute('stacked')
        self.assertEquals(
            SmartServerResponse(('ok', '../base')),
            response)


class TestSmartServerBranchRequestLockWrite(tests.TestCaseWithMemoryTransport):

    def setUp(self):
        tests.TestCaseWithMemoryTransport.setUp(self)

    def test_lock_write_on_unlocked_branch(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestLockWrite(backing)
        branch = self.make_branch('.', format='knit')
        repository = branch.repository
        response = request.execute('')
        branch_nonce = branch.control_files._lock.peek().get('nonce')
        repository_nonce = repository.control_files._lock.peek().get('nonce')
        self.assertEqual(
            SmartServerResponse(('ok', branch_nonce, repository_nonce)),
            response)
        # The branch (and associated repository) is now locked.  Verify that
        # with a new branch object.
        new_branch = repository.bzrdir.open_branch()
        self.assertRaises(errors.LockContention, new_branch.lock_write)
        # Cleanup
        request = smart.branch.SmartServerBranchRequestUnlock(backing)
        response = request.execute('', branch_nonce, repository_nonce)

    def test_lock_write_on_locked_branch(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestLockWrite(backing)
        branch = self.make_branch('.')
        branch_token = branch.lock_write()
        branch.leave_lock_in_place()
        branch.unlock()
        response = request.execute('')
        self.assertEqual(
            SmartServerResponse(('LockContention',)), response)
        # Cleanup
        branch.lock_write(branch_token)
        branch.dont_leave_lock_in_place()
        branch.unlock()

    def test_lock_write_with_tokens_on_locked_branch(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestLockWrite(backing)
        branch = self.make_branch('.', format='knit')
        branch_token = branch.lock_write()
        repo_token = branch.repository.lock_write()
        branch.repository.unlock()
        branch.leave_lock_in_place()
        branch.repository.leave_lock_in_place()
        branch.unlock()
        response = request.execute('',
                                   branch_token, repo_token)
        self.assertEqual(
            SmartServerResponse(('ok', branch_token, repo_token)), response)
        # Cleanup
        branch.repository.lock_write(repo_token)
        branch.repository.dont_leave_lock_in_place()
        branch.repository.unlock()
        branch.lock_write(branch_token)
        branch.dont_leave_lock_in_place()
        branch.unlock()

    def test_lock_write_with_mismatched_tokens_on_locked_branch(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestLockWrite(backing)
        branch = self.make_branch('.', format='knit')
        branch_token = branch.lock_write()
        repo_token = branch.repository.lock_write()
        branch.repository.unlock()
        branch.leave_lock_in_place()
        branch.repository.leave_lock_in_place()
        branch.unlock()
        response = request.execute('',
                                   branch_token+'xxx', repo_token)
        self.assertEqual(
            SmartServerResponse(('TokenMismatch',)), response)
        # Cleanup
        branch.repository.lock_write(repo_token)
        branch.repository.dont_leave_lock_in_place()
        branch.repository.unlock()
        branch.lock_write(branch_token)
        branch.dont_leave_lock_in_place()
        branch.unlock()

    def test_lock_write_on_locked_repo(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestLockWrite(backing)
        branch = self.make_branch('.', format='knit')
        repo = branch.repository
        repo_token = repo.lock_write()
        repo.leave_lock_in_place()
        repo.unlock()
        response = request.execute('')
        self.assertEqual(
            SmartServerResponse(('LockContention',)), response)
        # Cleanup
        repo.lock_write(repo_token)
        repo.dont_leave_lock_in_place()
        repo.unlock()

    def test_lock_write_on_readonly_transport(self):
        backing = self.get_readonly_transport()
        request = smart.branch.SmartServerBranchRequestLockWrite(backing)
        branch = self.make_branch('.')
        root = self.get_transport().clone('/')
        path = urlutils.relative_url(root.base, self.get_transport().base)
        response = request.execute(path)
        error_name, lock_str, why_str = response.args
        self.assertFalse(response.is_successful())
        self.assertEqual('LockFailed', error_name)


class TestSmartServerBranchRequestUnlock(tests.TestCaseWithMemoryTransport):

    def setUp(self):
        tests.TestCaseWithMemoryTransport.setUp(self)

    def test_unlock_on_locked_branch_and_repo(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestUnlock(backing)
        branch = self.make_branch('.', format='knit')
        # Lock the branch
        branch_token = branch.lock_write()
        repo_token = branch.repository.lock_write()
        branch.repository.unlock()
        # Unlock the branch (and repo) object, leaving the physical locks
        # in place.
        branch.leave_lock_in_place()
        branch.repository.leave_lock_in_place()
        branch.unlock()
        response = request.execute('',
                                   branch_token, repo_token)
        self.assertEqual(
            SmartServerResponse(('ok',)), response)
        # The branch is now unlocked.  Verify that with a new branch
        # object.
        new_branch = branch.bzrdir.open_branch()
        new_branch.lock_write()
        new_branch.unlock()

    def test_unlock_on_unlocked_branch_unlocked_repo(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestUnlock(backing)
        branch = self.make_branch('.', format='knit')
        response = request.execute(
            '', 'branch token', 'repo token')
        self.assertEqual(
            SmartServerResponse(('TokenMismatch',)), response)

    def test_unlock_on_unlocked_branch_locked_repo(self):
        backing = self.get_transport()
        request = smart.branch.SmartServerBranchRequestUnlock(backing)
        branch = self.make_branch('.', format='knit')
        # Lock the repository.
        repo_token = branch.repository.lock_write()
        branch.repository.leave_lock_in_place()
        branch.repository.unlock()
        # Issue branch lock_write request on the unlocked branch (with locked
        # repo).
        response = request.execute(
            '', 'branch token', repo_token)
        self.assertEqual(
            SmartServerResponse(('TokenMismatch',)), response)
        # Cleanup
        branch.repository.lock_write(repo_token)
        branch.repository.dont_leave_lock_in_place()
        branch.repository.unlock()


class TestSmartServerRepositoryRequest(tests.TestCaseWithMemoryTransport):

    def test_no_repository(self):
        """Raise NoRepositoryPresent when there is a bzrdir and no repo."""
        # we test this using a shared repository above the named path,
        # thus checking the right search logic is used - that is, that
        # its the exact path being looked at and the server is not
        # searching.
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryRequest(backing)
        self.make_repository('.', shared=True)
        self.make_bzrdir('subdir')
        self.assertRaises(errors.NoRepositoryPresent,
            request.execute, 'subdir')


class TestSmartServerRepositoryGetParentMap(tests.TestCaseWithMemoryTransport):

    def test_trivial_bzipped(self):
        # This tests that the wire encoding is actually bzipped
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetParentMap(backing)
        tree = self.make_branch_and_memory_tree('.')

        self.assertEqual(None,
            request.execute('', 'missing-id'))
        # Note that it returns a body that is bzipped.
        self.assertEqual(
            SuccessfulSmartServerResponse(('ok', ), bz2.compress('')),
            request.do_body('\n\n0\n'))

    def test_trivial_include_missing(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetParentMap(backing)
        tree = self.make_branch_and_memory_tree('.')

        self.assertEqual(None,
            request.execute('', 'missing-id', 'include-missing:'))
        self.assertEqual(
            SuccessfulSmartServerResponse(('ok', ),
                bz2.compress('missing:missing-id')),
            request.do_body('\n\n0\n'))


class TestSmartServerRepositoryGetRevisionGraph(tests.TestCaseWithMemoryTransport):

    def test_none_argument(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetRevisionGraph(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        r1 = tree.commit('1st commit')
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
        tree.unlock()

        # the lines of revision_id->revision_parent_list has no guaranteed
        # order coming out of a dict, so sort both our test and response
        lines = sorted([' '.join([r2, r1]), r1])
        response = request.execute('', '')
        response.body = '\n'.join(sorted(response.body.split('\n')))

        self.assertEqual(
            SmartServerResponse(('ok', ), '\n'.join(lines)), response)

    def test_specific_revision_argument(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetRevisionGraph(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        rev_id_utf8 = u'\xc9'.encode('utf-8')
        r1 = tree.commit('1st commit', rev_id=rev_id_utf8)
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
        tree.unlock()

        self.assertEqual(SmartServerResponse(('ok', ), rev_id_utf8),
            request.execute('', rev_id_utf8))

    def test_no_such_revision(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetRevisionGraph(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        r1 = tree.commit('1st commit')
        tree.unlock()

        # Note that it still returns body (of zero bytes).
        self.assertEqual(
            SmartServerResponse(('nosuchrevision', 'missingrevision', ), ''),
            request.execute('', 'missingrevision'))


class TestSmartServerRepositoryGetRevIdForRevno(tests.TestCaseWithMemoryTransport):

    def test_revno_found(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetRevIdForRevno(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        rev1_id_utf8 = u'\xc8'.encode('utf-8')
        rev2_id_utf8 = u'\xc9'.encode('utf-8')
        tree.commit('1st commit', rev_id=rev1_id_utf8)
        tree.commit('2nd commit', rev_id=rev2_id_utf8)
        tree.unlock()

        self.assertEqual(SmartServerResponse(('ok', rev1_id_utf8)),
            request.execute('', 1, (2, rev2_id_utf8)))

    def test_known_revid_missing(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetRevIdForRevno(backing)
        repo = self.make_repository('.')
        self.assertEqual(
            FailedSmartServerResponse(('nosuchrevision', 'ghost')),
            request.execute('', 1, (2, 'ghost')))

    def test_history_incomplete(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetRevIdForRevno(backing)
        parent = self.make_branch_and_memory_tree('parent', format='1.9')
        parent.lock_write()
        parent.add([''], ['TREE_ROOT'])
        r1 = parent.commit(message='first commit')
        r2 = parent.commit(message='second commit')
        parent.unlock()
        local = self.make_branch_and_memory_tree('local', format='1.9')
        local.branch.pull(parent.branch)
        local.set_parent_ids([r2])
        r3 = local.commit(message='local commit')
        local.branch.create_clone_on_transport(
            self.get_transport('stacked'), stacked_on=self.get_url('parent'))
        self.assertEqual(
            SmartServerResponse(('history-incomplete', 2, r2)),
            request.execute('stacked', 1, (3, r3)))


class TestSmartServerRepositoryGetStream(tests.TestCaseWithMemoryTransport):

    def make_two_commit_repo(self):
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        r1 = tree.commit('1st commit')
        r2 = tree.commit('2nd commit', rev_id=u'\xc8'.encode('utf-8'))
        tree.unlock()
        repo = tree.branch.repository
        return repo, r1, r2

    def test_ancestry_of(self):
        """The search argument may be a 'ancestry-of' some heads'."""
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetStream(backing)
        repo, r1, r2 = self.make_two_commit_repo()
        fetch_spec = ['ancestry-of', r2]
        lines = '\n'.join(fetch_spec)
        request.execute('', repo._format.network_name())
        response = request.do_body(lines)
        self.assertEqual(('ok',), response.args)
        stream_bytes = ''.join(response.body_stream)
        self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')

    def test_search(self):
        """The search argument may be a 'search' of some explicit keys."""
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGetStream(backing)
        repo, r1, r2 = self.make_two_commit_repo()
        fetch_spec = ['search', '%s %s' % (r1, r2), 'null:', '2']
        lines = '\n'.join(fetch_spec)
        request.execute('', repo._format.network_name())
        response = request.do_body(lines)
        self.assertEqual(('ok',), response.args)
        stream_bytes = ''.join(response.body_stream)
        self.assertStartsWith(stream_bytes, 'Bazaar pack format 1')


class TestSmartServerRequestHasRevision(tests.TestCaseWithMemoryTransport):

    def test_missing_revision(self):
        """For a missing revision, ('no', ) is returned."""
        backing = self.get_transport()
        request = smart.repository.SmartServerRequestHasRevision(backing)
        self.make_repository('.')
        self.assertEqual(SmartServerResponse(('no', )),
            request.execute('', 'revid'))

    def test_present_revision(self):
        """For a present revision, ('yes', ) is returned."""
        backing = self.get_transport()
        request = smart.repository.SmartServerRequestHasRevision(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
        r1 = tree.commit('a commit', rev_id=rev_id_utf8)
        tree.unlock()
        self.assertTrue(tree.branch.repository.has_revision(rev_id_utf8))
        self.assertEqual(SmartServerResponse(('yes', )),
            request.execute('', rev_id_utf8))


class TestSmartServerRepositoryGatherStats(tests.TestCaseWithMemoryTransport):

    def test_empty_revid(self):
        """With an empty revid, we get only size an number and revisions"""
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryGatherStats(backing)
        repository = self.make_repository('.')
        stats = repository.gather_stats()
        expected_body = 'revisions: 0\n'
        self.assertEqual(SmartServerResponse(('ok', ), expected_body),
                         request.execute('', '', 'no'))

    def test_revid_with_committers(self):
        """For a revid we get more infos."""
        backing = self.get_transport()
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
        request = smart.repository.SmartServerRepositoryGatherStats(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        # Let's build a predictable result
        tree.commit('a commit', timestamp=123456.2, timezone=3600)
        tree.commit('a commit', timestamp=654321.4, timezone=0,
                    rev_id=rev_id_utf8)
        tree.unlock()

        stats = tree.branch.repository.gather_stats()
        expected_body = ('firstrev: 123456.200 3600\n'
                         'latestrev: 654321.400 0\n'
                         'revisions: 2\n')
        self.assertEqual(SmartServerResponse(('ok', ), expected_body),
                         request.execute('',
                                         rev_id_utf8, 'no'))

    def test_not_empty_repository_with_committers(self):
        """For a revid and requesting committers we get the whole thing."""
        backing = self.get_transport()
        rev_id_utf8 = u'\xc8abc'.encode('utf-8')
        request = smart.repository.SmartServerRepositoryGatherStats(backing)
        tree = self.make_branch_and_memory_tree('.')
        tree.lock_write()
        tree.add('')
        # Let's build a predictable result
        tree.commit('a commit', timestamp=123456.2, timezone=3600,
                    committer='foo')
        tree.commit('a commit', timestamp=654321.4, timezone=0,
                    committer='bar', rev_id=rev_id_utf8)
        tree.unlock()
        stats = tree.branch.repository.gather_stats()

        expected_body = ('committers: 2\n'
                         'firstrev: 123456.200 3600\n'
                         'latestrev: 654321.400 0\n'
                         'revisions: 2\n')
        self.assertEqual(SmartServerResponse(('ok', ), expected_body),
                         request.execute('',
                                         rev_id_utf8, 'yes'))


class TestSmartServerRepositoryIsShared(tests.TestCaseWithMemoryTransport):

    def test_is_shared(self):
        """For a shared repository, ('yes', ) is returned."""
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryIsShared(backing)
        self.make_repository('.', shared=True)
        self.assertEqual(SmartServerResponse(('yes', )),
            request.execute('', ))

    def test_is_not_shared(self):
        """For a shared repository, ('no', ) is returned."""
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryIsShared(backing)
        self.make_repository('.', shared=False)
        self.assertEqual(SmartServerResponse(('no', )),
            request.execute('', ))


class TestSmartServerRepositoryLockWrite(tests.TestCaseWithMemoryTransport):

    def test_lock_write_on_unlocked_repo(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryLockWrite(backing)
        repository = self.make_repository('.', format='knit')
        response = request.execute('')
        nonce = repository.control_files._lock.peek().get('nonce')
        self.assertEqual(SmartServerResponse(('ok', nonce)), response)
        # The repository is now locked.  Verify that with a new repository
        # object.
        new_repo = repository.bzrdir.open_repository()
        self.assertRaises(errors.LockContention, new_repo.lock_write)
        # Cleanup
        request = smart.repository.SmartServerRepositoryUnlock(backing)
        response = request.execute('', nonce)

    def test_lock_write_on_locked_repo(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryLockWrite(backing)
        repository = self.make_repository('.', format='knit')
        repo_token = repository.lock_write()
        repository.leave_lock_in_place()
        repository.unlock()
        response = request.execute('')
        self.assertEqual(
            SmartServerResponse(('LockContention',)), response)
        # Cleanup
        repository.lock_write(repo_token)
        repository.dont_leave_lock_in_place()
        repository.unlock()

    def test_lock_write_on_readonly_transport(self):
        backing = self.get_readonly_transport()
        request = smart.repository.SmartServerRepositoryLockWrite(backing)
        repository = self.make_repository('.', format='knit')
        response = request.execute('')
        self.assertFalse(response.is_successful())
        self.assertEqual('LockFailed', response.args[0])


class TestInsertStreamBase(tests.TestCaseWithMemoryTransport):

    def make_empty_byte_stream(self, repo):
        byte_stream = smart.repository._stream_to_byte_stream([], repo._format)
        return ''.join(byte_stream)


class TestSmartServerRepositoryInsertStream(TestInsertStreamBase):

    def test_insert_stream_empty(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryInsertStream(backing)
        repository = self.make_repository('.')
        response = request.execute('', '')
        self.assertEqual(None, response)
        response = request.do_chunk(self.make_empty_byte_stream(repository))
        self.assertEqual(None, response)
        response = request.do_end()
        self.assertEqual(SmartServerResponse(('ok', )), response)
        

class TestSmartServerRepositoryInsertStreamLocked(TestInsertStreamBase):

    def test_insert_stream_empty(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryInsertStreamLocked(
            backing)
        repository = self.make_repository('.', format='knit')
        lock_token = repository.lock_write()
        response = request.execute('', '', lock_token)
        self.assertEqual(None, response)
        response = request.do_chunk(self.make_empty_byte_stream(repository))
        self.assertEqual(None, response)
        response = request.do_end()
        self.assertEqual(SmartServerResponse(('ok', )), response)
        repository.unlock()

    def test_insert_stream_with_wrong_lock_token(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryInsertStreamLocked(
            backing)
        repository = self.make_repository('.', format='knit')
        lock_token = repository.lock_write()
        self.assertRaises(
            errors.TokenMismatch, request.execute, '', '', 'wrong-token')
        repository.unlock()


class TestSmartServerRepositoryUnlock(tests.TestCaseWithMemoryTransport):

    def setUp(self):
        tests.TestCaseWithMemoryTransport.setUp(self)

    def test_unlock_on_locked_repo(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryUnlock(backing)
        repository = self.make_repository('.', format='knit')
        token = repository.lock_write()
        repository.leave_lock_in_place()
        repository.unlock()
        response = request.execute('', token)
        self.assertEqual(
            SmartServerResponse(('ok',)), response)
        # The repository is now unlocked.  Verify that with a new repository
        # object.
        new_repo = repository.bzrdir.open_repository()
        new_repo.lock_write()
        new_repo.unlock()

    def test_unlock_on_unlocked_repo(self):
        backing = self.get_transport()
        request = smart.repository.SmartServerRepositoryUnlock(backing)
        repository = self.make_repository('.', format='knit')
        response = request.execute('', 'some token')
        self.assertEqual(
            SmartServerResponse(('TokenMismatch',)), response)


class TestSmartServerIsReadonly(tests.TestCaseWithMemoryTransport):

    def test_is_readonly_no(self):
        backing = self.get_transport()
        request = smart.request.SmartServerIsReadonly(backing)
        response = request.execute()
        self.assertEqual(
            SmartServerResponse(('no',)), response)

    def test_is_readonly_yes(self):
        backing = self.get_readonly_transport()
        request = smart.request.SmartServerIsReadonly(backing)
        response = request.execute()
        self.assertEqual(
            SmartServerResponse(('yes',)), response)


class TestSmartServerRepositorySetMakeWorkingTrees(tests.TestCaseWithMemoryTransport):

    def test_set_false(self):
        backing = self.get_transport()
        repo = self.make_repository('.', shared=True)
        repo.set_make_working_trees(True)
        request_class = smart.repository.SmartServerRepositorySetMakeWorkingTrees
        request = request_class(backing)
        self.assertEqual(SuccessfulSmartServerResponse(('ok',)),
            request.execute('', 'False'))
        repo = repo.bzrdir.open_repository()
        self.assertFalse(repo.make_working_trees())

    def test_set_true(self):
        backing = self.get_transport()
        repo = self.make_repository('.', shared=True)
        repo.set_make_working_trees(False)
        request_class = smart.repository.SmartServerRepositorySetMakeWorkingTrees
        request = request_class(backing)
        self.assertEqual(SuccessfulSmartServerResponse(('ok',)),
            request.execute('', 'True'))
        repo = repo.bzrdir.open_repository()
        self.assertTrue(repo.make_working_trees())


class TestSmartServerPackRepositoryAutopack(tests.TestCaseWithTransport):

    def make_repo_needing_autopacking(self, path='.'):
        # Make a repo in need of autopacking.
        tree = self.make_branch_and_tree('.', format='pack-0.92')
        repo = tree.branch.repository
        # monkey-patch the pack collection to disable autopacking
        repo._pack_collection._max_pack_count = lambda count: count
        for x in range(10):
            tree.commit('commit %s' % x)
        self.assertEqual(10, len(repo._pack_collection.names()))
        del repo._pack_collection._max_pack_count
        return repo

    def test_autopack_needed(self):
        repo = self.make_repo_needing_autopacking()
        repo.lock_write()
        self.addCleanup(repo.unlock)
        backing = self.get_transport()
        request = smart.packrepository.SmartServerPackRepositoryAutopack(
            backing)
        response = request.execute('')
        self.assertEqual(SmartServerResponse(('ok',)), response)
        repo._pack_collection.reload_pack_names()
        self.assertEqual(1, len(repo._pack_collection.names()))

    def test_autopack_not_needed(self):
        tree = self.make_branch_and_tree('.', format='pack-0.92')
        repo = tree.branch.repository
        repo.lock_write()
        self.addCleanup(repo.unlock)
        for x in range(9):
            tree.commit('commit %s' % x)
        backing = self.get_transport()
        request = smart.packrepository.SmartServerPackRepositoryAutopack(
            backing)
        response = request.execute('')
        self.assertEqual(SmartServerResponse(('ok',)), response)
        repo._pack_collection.reload_pack_names()
        self.assertEqual(9, len(repo._pack_collection.names()))

    def test_autopack_on_nonpack_format(self):
        """A request to autopack a non-pack repo is a no-op."""
        repo = self.make_repository('.', format='knit')
        backing = self.get_transport()
        request = smart.packrepository.SmartServerPackRepositoryAutopack(
            backing)
        response = request.execute('')
        self.assertEqual(SmartServerResponse(('ok',)), response)


class TestSmartServerVfsGet(tests.TestCaseWithMemoryTransport):

    def test_unicode_path(self):
        """VFS requests expect unicode paths to be escaped."""
        filename = u'foo\N{INTERROBANG}'
        filename_escaped = urlutils.escape(filename)
        backing = self.get_transport()
        request = smart.vfs.GetRequest(backing)
        backing.put_bytes_non_atomic(filename_escaped, 'contents')
        self.assertEqual(SmartServerResponse(('ok', ), 'contents'),
            request.execute(filename_escaped))


class TestHandlers(tests.TestCase):
    """Tests for the request.request_handlers object."""

    def test_all_registrations_exist(self):
        """All registered request_handlers can be found."""
        # If there's a typo in a register_lazy call, this loop will fail with
        # an AttributeError.
        for key, item in smart.request.request_handlers.iteritems():
            pass

    def assertHandlerEqual(self, verb, handler):
        self.assertEqual(smart.request.request_handlers.get(verb), handler)

    def test_registered_methods(self):
        """Test that known methods are registered to the correct object."""
        self.assertHandlerEqual('Branch.get_config_file',
            smart.branch.SmartServerBranchGetConfigFile)
        self.assertHandlerEqual('Branch.get_parent',
            smart.branch.SmartServerBranchGetParent)
        self.assertHandlerEqual('Branch.get_tags_bytes',
            smart.branch.SmartServerBranchGetTagsBytes)
        self.assertHandlerEqual('Branch.lock_write',
            smart.branch.SmartServerBranchRequestLockWrite)
        self.assertHandlerEqual('Branch.last_revision_info',
            smart.branch.SmartServerBranchRequestLastRevisionInfo)
        self.assertHandlerEqual('Branch.revision_history',
            smart.branch.SmartServerRequestRevisionHistory)
        self.assertHandlerEqual('Branch.set_config_option',
            smart.branch.SmartServerBranchRequestSetConfigOption)
        self.assertHandlerEqual('Branch.set_last_revision',
            smart.branch.SmartServerBranchRequestSetLastRevision)
        self.assertHandlerEqual('Branch.set_last_revision_info',
            smart.branch.SmartServerBranchRequestSetLastRevisionInfo)
        self.assertHandlerEqual('Branch.set_last_revision_ex',
            smart.branch.SmartServerBranchRequestSetLastRevisionEx)
        self.assertHandlerEqual('Branch.set_parent_location',
            smart.branch.SmartServerBranchRequestSetParentLocation)
        self.assertHandlerEqual('Branch.unlock',
            smart.branch.SmartServerBranchRequestUnlock)
        self.assertHandlerEqual('BzrDir.find_repository',
            smart.bzrdir.SmartServerRequestFindRepositoryV1)
        self.assertHandlerEqual('BzrDir.find_repositoryV2',
            smart.bzrdir.SmartServerRequestFindRepositoryV2)
        self.assertHandlerEqual('BzrDirFormat.initialize',
            smart.bzrdir.SmartServerRequestInitializeBzrDir)
        self.assertHandlerEqual('BzrDirFormat.initialize_ex_1.16',
            smart.bzrdir.SmartServerRequestBzrDirInitializeEx)
        self.assertHandlerEqual('BzrDir.cloning_metadir',
            smart.bzrdir.SmartServerBzrDirRequestCloningMetaDir)
        self.assertHandlerEqual('BzrDir.get_config_file',
            smart.bzrdir.SmartServerBzrDirRequestConfigFile)
        self.assertHandlerEqual('BzrDir.open_branch',
            smart.bzrdir.SmartServerRequestOpenBranch)
        self.assertHandlerEqual('BzrDir.open_branchV2',
            smart.bzrdir.SmartServerRequestOpenBranchV2)
        self.assertHandlerEqual('BzrDir.open_branchV3',
            smart.bzrdir.SmartServerRequestOpenBranchV3)
        self.assertHandlerEqual('PackRepository.autopack',
            smart.packrepository.SmartServerPackRepositoryAutopack)
        self.assertHandlerEqual('Repository.gather_stats',
            smart.repository.SmartServerRepositoryGatherStats)
        self.assertHandlerEqual('Repository.get_parent_map',
            smart.repository.SmartServerRepositoryGetParentMap)
        self.assertHandlerEqual('Repository.get_rev_id_for_revno',
            smart.repository.SmartServerRepositoryGetRevIdForRevno)
        self.assertHandlerEqual('Repository.get_revision_graph',
            smart.repository.SmartServerRepositoryGetRevisionGraph)
        self.assertHandlerEqual('Repository.get_stream',
            smart.repository.SmartServerRepositoryGetStream)
        self.assertHandlerEqual('Repository.has_revision',
            smart.repository.SmartServerRequestHasRevision)
        self.assertHandlerEqual('Repository.insert_stream',
            smart.repository.SmartServerRepositoryInsertStream)
        self.assertHandlerEqual('Repository.insert_stream_locked',
            smart.repository.SmartServerRepositoryInsertStreamLocked)
        self.assertHandlerEqual('Repository.is_shared',
            smart.repository.SmartServerRepositoryIsShared)
        self.assertHandlerEqual('Repository.lock_write',
            smart.repository.SmartServerRepositoryLockWrite)
        self.assertHandlerEqual('Repository.tarball',
            smart.repository.SmartServerRepositoryTarball)
        self.assertHandlerEqual('Repository.unlock',
            smart.repository.SmartServerRepositoryUnlock)
        self.assertHandlerEqual('Transport.is_readonly',
            smart.request.SmartServerIsReadonly)