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
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
|
# Copyright (C) 2005-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 finding and reading the bzr config file[s]."""
# import system imports here
from cStringIO import StringIO
import os
import sys
import threading
from testtools import matchers
#import bzrlib specific imports here
from bzrlib import (
branch,
bzrdir,
config,
diff,
errors,
osutils,
mail_client,
ui,
urlutils,
tests,
trace,
transport,
)
from bzrlib.tests import (
features,
scenarios,
)
from bzrlib.util.configobj import configobj
def lockable_config_scenarios():
return [
('global',
{'config_class': config.GlobalConfig,
'config_args': [],
'config_section': 'DEFAULT'}),
('locations',
{'config_class': config.LocationConfig,
'config_args': ['.'],
'config_section': '.'}),]
load_tests = scenarios.load_tests_apply_scenarios
sample_long_alias="log -r-15..-1 --line"
sample_config_text = u"""
[DEFAULT]
email=Erik B\u00e5gfors <erik@bagfors.nu>
editor=vim
change_editor=vimdiff -of @new_path @old_path
gpg_signing_command=gnome-gpg
log_format=short
user_global_option=something
[ALIASES]
h=help
ll=""" + sample_long_alias + "\n"
sample_always_signatures = """
[DEFAULT]
check_signatures=ignore
create_signatures=always
"""
sample_ignore_signatures = """
[DEFAULT]
check_signatures=require
create_signatures=never
"""
sample_maybe_signatures = """
[DEFAULT]
check_signatures=ignore
create_signatures=when-required
"""
sample_branches_text = """
[http://www.example.com]
# Top level policy
email=Robert Collins <robertc@example.org>
normal_option = normal
appendpath_option = append
appendpath_option:policy = appendpath
norecurse_option = norecurse
norecurse_option:policy = norecurse
[http://www.example.com/ignoreparent]
# different project: ignore parent dir config
ignore_parents=true
[http://www.example.com/norecurse]
# configuration items that only apply to this dir
recurse=false
normal_option = norecurse
[http://www.example.com/dir]
appendpath_option = normal
[/b/]
check_signatures=require
# test trailing / matching with no children
[/a/]
check_signatures=check-available
gpg_signing_command=false
user_local_option=local
# test trailing / matching
[/a/*]
#subdirs will match but not the parent
[/a/c]
check_signatures=ignore
post_commit=bzrlib.tests.test_config.post_commit
#testing explicit beats globs
"""
def create_configs(test):
"""Create configuration files for a given test.
This requires creating a tree (and populate the ``test.tree`` attribute)
and its associated branch and will populate the following attributes:
- branch_config: A BranchConfig for the associated branch.
- locations_config : A LocationConfig for the associated branch
- bazaar_config: A GlobalConfig.
The tree and branch are created in a 'tree' subdirectory so the tests can
still use the test directory to stay outside of the branch.
"""
tree = test.make_branch_and_tree('tree')
test.tree = tree
test.branch_config = config.BranchConfig(tree.branch)
test.locations_config = config.LocationConfig(tree.basedir)
test.bazaar_config = config.GlobalConfig()
def create_configs_with_file_option(test):
"""Create configuration files with a ``file`` option set in each.
This builds on ``create_configs`` and add one ``file`` option in each
configuration with a value which allows identifying the configuration file.
"""
create_configs(test)
test.bazaar_config.set_user_option('file', 'bazaar')
test.locations_config.set_user_option('file', 'locations')
test.branch_config.set_user_option('file', 'branch')
class TestOptionsMixin:
def assertOptions(self, expected, conf):
# We don't care about the parser (as it will make tests hard to write
# and error-prone anyway)
self.assertThat([opt[:4] for opt in conf._get_options()],
matchers.Equals(expected))
class InstrumentedConfigObj(object):
"""A config obj look-enough-alike to record calls made to it."""
def __contains__(self, thing):
self._calls.append(('__contains__', thing))
return False
def __getitem__(self, key):
self._calls.append(('__getitem__', key))
return self
def __init__(self, input, encoding=None):
self._calls = [('__init__', input, encoding)]
def __setitem__(self, key, value):
self._calls.append(('__setitem__', key, value))
def __delitem__(self, key):
self._calls.append(('__delitem__', key))
def keys(self):
self._calls.append(('keys',))
return []
def reload(self):
self._calls.append(('reload',))
def write(self, arg):
self._calls.append(('write',))
def as_bool(self, value):
self._calls.append(('as_bool', value))
return False
def get_value(self, section, name):
self._calls.append(('get_value', section, name))
return None
class FakeBranch(object):
def __init__(self, base=None, user_id=None):
if base is None:
self.base = "http://example.com/branches/demo"
else:
self.base = base
self._transport = self.control_files = \
FakeControlFilesAndTransport(user_id=user_id)
def _get_config(self):
return config.TransportConfig(self._transport, 'branch.conf')
def lock_write(self):
pass
def unlock(self):
pass
class FakeControlFilesAndTransport(object):
def __init__(self, user_id=None):
self.files = {}
if user_id:
self.files['email'] = user_id
self._transport = self
def get_utf8(self, filename):
# from LockableFiles
raise AssertionError("get_utf8 should no longer be used")
def get(self, filename):
# from Transport
try:
return StringIO(self.files[filename])
except KeyError:
raise errors.NoSuchFile(filename)
def get_bytes(self, filename):
# from Transport
try:
return self.files[filename]
except KeyError:
raise errors.NoSuchFile(filename)
def put(self, filename, fileobj):
self.files[filename] = fileobj.read()
def put_file(self, filename, fileobj):
return self.put(filename, fileobj)
class InstrumentedConfig(config.Config):
"""An instrumented config that supplies stubs for template methods."""
def __init__(self):
super(InstrumentedConfig, self).__init__()
self._calls = []
self._signatures = config.CHECK_NEVER
def _get_user_id(self):
self._calls.append('_get_user_id')
return "Robert Collins <robert.collins@example.org>"
def _get_signature_checking(self):
self._calls.append('_get_signature_checking')
return self._signatures
def _get_change_editor(self):
self._calls.append('_get_change_editor')
return 'vimdiff -fo @new_path @old_path'
bool_config = """[DEFAULT]
active = true
inactive = false
[UPPERCASE]
active = True
nonactive = False
"""
class TestConfigObj(tests.TestCase):
def test_get_bool(self):
co = config.ConfigObj(StringIO(bool_config))
self.assertIs(co.get_bool('DEFAULT', 'active'), True)
self.assertIs(co.get_bool('DEFAULT', 'inactive'), False)
self.assertIs(co.get_bool('UPPERCASE', 'active'), True)
self.assertIs(co.get_bool('UPPERCASE', 'nonactive'), False)
def test_hash_sign_in_value(self):
"""
Before 4.5.0, ConfigObj did not quote # signs in values, so they'd be
treated as comments when read in again. (#86838)
"""
co = config.ConfigObj()
co['test'] = 'foo#bar'
lines = co.write()
self.assertEqual(lines, ['test = "foo#bar"'])
co2 = config.ConfigObj(lines)
self.assertEqual(co2['test'], 'foo#bar')
erroneous_config = """[section] # line 1
good=good # line 2
[section] # line 3
whocares=notme # line 4
"""
class TestConfigObjErrors(tests.TestCase):
def test_duplicate_section_name_error_line(self):
try:
co = configobj.ConfigObj(StringIO(erroneous_config),
raise_errors=True)
except config.configobj.DuplicateError, e:
self.assertEqual(3, e.line_number)
else:
self.fail('Error in config file not detected')
class TestConfig(tests.TestCase):
def test_constructs(self):
config.Config()
def test_no_default_editor(self):
self.assertRaises(NotImplementedError, config.Config().get_editor)
def test_user_email(self):
my_config = InstrumentedConfig()
self.assertEqual('robert.collins@example.org', my_config.user_email())
self.assertEqual(['_get_user_id'], my_config._calls)
def test_username(self):
my_config = InstrumentedConfig()
self.assertEqual('Robert Collins <robert.collins@example.org>',
my_config.username())
self.assertEqual(['_get_user_id'], my_config._calls)
def test_signatures_default(self):
my_config = config.Config()
self.assertFalse(my_config.signature_needed())
self.assertEqual(config.CHECK_IF_POSSIBLE,
my_config.signature_checking())
self.assertEqual(config.SIGN_WHEN_REQUIRED,
my_config.signing_policy())
def test_signatures_template_method(self):
my_config = InstrumentedConfig()
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
self.assertEqual(['_get_signature_checking'], my_config._calls)
def test_signatures_template_method_none(self):
my_config = InstrumentedConfig()
my_config._signatures = None
self.assertEqual(config.CHECK_IF_POSSIBLE,
my_config.signature_checking())
self.assertEqual(['_get_signature_checking'], my_config._calls)
def test_gpg_signing_command_default(self):
my_config = config.Config()
self.assertEqual('gpg', my_config.gpg_signing_command())
def test_get_user_option_default(self):
my_config = config.Config()
self.assertEqual(None, my_config.get_user_option('no_option'))
def test_post_commit_default(self):
my_config = config.Config()
self.assertEqual(None, my_config.post_commit())
def test_log_format_default(self):
my_config = config.Config()
self.assertEqual('long', my_config.log_format())
def test_get_change_editor(self):
my_config = InstrumentedConfig()
change_editor = my_config.get_change_editor('old_tree', 'new_tree')
self.assertEqual(['_get_change_editor'], my_config._calls)
self.assertIs(diff.DiffFromTool, change_editor.__class__)
self.assertEqual(['vimdiff', '-fo', '@new_path', '@old_path'],
change_editor.command_template)
class TestConfigPath(tests.TestCase):
def setUp(self):
super(TestConfigPath, self).setUp()
os.environ['HOME'] = '/home/bogus'
os.environ['XDG_CACHE_DIR'] = ''
if sys.platform == 'win32':
os.environ['BZR_HOME'] = \
r'C:\Documents and Settings\bogus\Application Data'
self.bzr_home = \
'C:/Documents and Settings/bogus/Application Data/bazaar/2.0'
else:
self.bzr_home = '/home/bogus/.bazaar'
def test_config_dir(self):
self.assertEqual(config.config_dir(), self.bzr_home)
def test_config_filename(self):
self.assertEqual(config.config_filename(),
self.bzr_home + '/bazaar.conf')
def test_locations_config_filename(self):
self.assertEqual(config.locations_config_filename(),
self.bzr_home + '/locations.conf')
def test_authentication_config_filename(self):
self.assertEqual(config.authentication_config_filename(),
self.bzr_home + '/authentication.conf')
def test_xdg_cache_dir(self):
self.assertEqual(config.xdg_cache_dir(),
'/home/bogus/.cache')
class TestIniConfig(tests.TestCaseInTempDir):
def make_config_parser(self, s):
conf = config.IniBasedConfig.from_string(s)
return conf, conf._get_parser()
class TestIniConfigBuilding(TestIniConfig):
def test_contructs(self):
my_config = config.IniBasedConfig()
def test_from_fp(self):
my_config = config.IniBasedConfig.from_string(sample_config_text)
self.assertIsInstance(my_config._get_parser(), configobj.ConfigObj)
def test_cached(self):
my_config = config.IniBasedConfig.from_string(sample_config_text)
parser = my_config._get_parser()
self.failUnless(my_config._get_parser() is parser)
def _dummy_chown(self, path, uid, gid):
self.path, self.uid, self.gid = path, uid, gid
def test_ini_config_ownership(self):
"""Ensure that chown is happening during _write_config_file"""
self.requireFeature(features.chown_feature)
self.overrideAttr(os, 'chown', self._dummy_chown)
self.path = self.uid = self.gid = None
conf = config.IniBasedConfig(file_name='./foo.conf')
conf._write_config_file()
self.assertEquals(self.path, './foo.conf')
self.assertTrue(isinstance(self.uid, int))
self.assertTrue(isinstance(self.gid, int))
def test_get_filename_parameter_is_deprecated_(self):
conf = self.callDeprecated([
'IniBasedConfig.__init__(get_filename) was deprecated in 2.3.'
' Use file_name instead.'],
config.IniBasedConfig, lambda: 'ini.conf')
self.assertEqual('ini.conf', conf.file_name)
def test_get_parser_file_parameter_is_deprecated_(self):
config_file = StringIO(sample_config_text.encode('utf-8'))
conf = config.IniBasedConfig.from_string(sample_config_text)
conf = self.callDeprecated([
'IniBasedConfig._get_parser(file=xxx) was deprecated in 2.3.'
' Use IniBasedConfig(_content=xxx) instead.'],
conf._get_parser, file=config_file)
class TestIniConfigSaving(tests.TestCaseInTempDir):
def test_cant_save_without_a_file_name(self):
conf = config.IniBasedConfig()
self.assertRaises(AssertionError, conf._write_config_file)
def test_saved_with_content(self):
content = 'foo = bar\n'
conf = config.IniBasedConfig.from_string(
content, file_name='./test.conf', save=True)
self.assertFileEqual(content, 'test.conf')
class TestIniBaseConfigOnDisk(tests.TestCaseInTempDir):
def test_cannot_reload_without_name(self):
conf = config.IniBasedConfig.from_string(sample_config_text)
self.assertRaises(AssertionError, conf.reload)
def test_reload_see_new_value(self):
c1 = config.IniBasedConfig.from_string('editor=vim\n',
file_name='./test/conf')
c1._write_config_file()
c2 = config.IniBasedConfig.from_string('editor=emacs\n',
file_name='./test/conf')
c2._write_config_file()
self.assertEqual('vim', c1.get_user_option('editor'))
self.assertEqual('emacs', c2.get_user_option('editor'))
# Make sure we get the Right value
c1.reload()
self.assertEqual('emacs', c1.get_user_option('editor'))
class TestLockableConfig(tests.TestCaseInTempDir):
scenarios = lockable_config_scenarios()
# Set by load_tests
config_class = None
config_args = None
config_section = None
def setUp(self):
super(TestLockableConfig, self).setUp()
self._content = '[%s]\none=1\ntwo=2\n' % (self.config_section,)
self.config = self.create_config(self._content)
def get_existing_config(self):
return self.config_class(*self.config_args)
def create_config(self, content):
kwargs = dict(save=True)
c = self.config_class.from_string(content, *self.config_args, **kwargs)
return c
def test_simple_read_access(self):
self.assertEquals('1', self.config.get_user_option('one'))
def test_simple_write_access(self):
self.config.set_user_option('one', 'one')
self.assertEquals('one', self.config.get_user_option('one'))
def test_listen_to_the_last_speaker(self):
c1 = self.config
c2 = self.get_existing_config()
c1.set_user_option('one', 'ONE')
c2.set_user_option('two', 'TWO')
self.assertEquals('ONE', c1.get_user_option('one'))
self.assertEquals('TWO', c2.get_user_option('two'))
# The second update respect the first one
self.assertEquals('ONE', c2.get_user_option('one'))
def test_last_speaker_wins(self):
# If the same config is not shared, the same variable modified twice
# can only see a single result.
c1 = self.config
c2 = self.get_existing_config()
c1.set_user_option('one', 'c1')
c2.set_user_option('one', 'c2')
self.assertEquals('c2', c2._get_user_option('one'))
# The first modification is still available until another refresh
# occur
self.assertEquals('c1', c1._get_user_option('one'))
c1.set_user_option('two', 'done')
self.assertEquals('c2', c1._get_user_option('one'))
def test_writes_are_serialized(self):
c1 = self.config
c2 = self.get_existing_config()
# We spawn a thread that will pause *during* the write
before_writing = threading.Event()
after_writing = threading.Event()
writing_done = threading.Event()
c1_orig = c1._write_config_file
def c1_write_config_file():
before_writing.set()
c1_orig()
# The lock is held we wait for the main thread to decide when to
# continue
after_writing.wait()
c1._write_config_file = c1_write_config_file
def c1_set_option():
c1.set_user_option('one', 'c1')
writing_done.set()
t1 = threading.Thread(target=c1_set_option)
# Collect the thread after the test
self.addCleanup(t1.join)
# Be ready to unblock the thread if the test goes wrong
self.addCleanup(after_writing.set)
t1.start()
before_writing.wait()
self.assertTrue(c1._lock.is_held)
self.assertRaises(errors.LockContention,
c2.set_user_option, 'one', 'c2')
self.assertEquals('c1', c1.get_user_option('one'))
# Let the lock be released
after_writing.set()
writing_done.wait()
c2.set_user_option('one', 'c2')
self.assertEquals('c2', c2.get_user_option('one'))
def test_read_while_writing(self):
c1 = self.config
# We spawn a thread that will pause *during* the write
ready_to_write = threading.Event()
do_writing = threading.Event()
writing_done = threading.Event()
c1_orig = c1._write_config_file
def c1_write_config_file():
ready_to_write.set()
# The lock is held we wait for the main thread to decide when to
# continue
do_writing.wait()
c1_orig()
writing_done.set()
c1._write_config_file = c1_write_config_file
def c1_set_option():
c1.set_user_option('one', 'c1')
t1 = threading.Thread(target=c1_set_option)
# Collect the thread after the test
self.addCleanup(t1.join)
# Be ready to unblock the thread if the test goes wrong
self.addCleanup(do_writing.set)
t1.start()
# Ensure the thread is ready to write
ready_to_write.wait()
self.assertTrue(c1._lock.is_held)
self.assertEquals('c1', c1.get_user_option('one'))
# If we read during the write, we get the old value
c2 = self.get_existing_config()
self.assertEquals('1', c2.get_user_option('one'))
# Let the writing occur and ensure it occurred
do_writing.set()
writing_done.wait()
# Now we get the updated value
c3 = self.get_existing_config()
self.assertEquals('c1', c3.get_user_option('one'))
class TestGetUserOptionAs(TestIniConfig):
def test_get_user_option_as_bool(self):
conf, parser = self.make_config_parser("""
a_true_bool = true
a_false_bool = 0
an_invalid_bool = maybe
a_list = hmm, who knows ? # This is interpreted as a list !
""")
get_bool = conf.get_user_option_as_bool
self.assertEqual(True, get_bool('a_true_bool'))
self.assertEqual(False, get_bool('a_false_bool'))
warnings = []
def warning(*args):
warnings.append(args[0] % args[1:])
self.overrideAttr(trace, 'warning', warning)
msg = 'Value "%s" is not a boolean for "%s"'
self.assertIs(None, get_bool('an_invalid_bool'))
self.assertEquals(msg % ('maybe', 'an_invalid_bool'), warnings[0])
warnings = []
self.assertIs(None, get_bool('not_defined_in_this_config'))
self.assertEquals([], warnings)
def test_get_user_option_as_list(self):
conf, parser = self.make_config_parser("""
a_list = a,b,c
length_1 = 1,
one_item = x
""")
get_list = conf.get_user_option_as_list
self.assertEqual(['a', 'b', 'c'], get_list('a_list'))
self.assertEqual(['1'], get_list('length_1'))
self.assertEqual('x', conf.get_user_option('one_item'))
# automatically cast to list
self.assertEqual(['x'], get_list('one_item'))
class TestSupressWarning(TestIniConfig):
def make_warnings_config(self, s):
conf, parser = self.make_config_parser(s)
return conf.suppress_warning
def test_suppress_warning_unknown(self):
suppress_warning = self.make_warnings_config('')
self.assertEqual(False, suppress_warning('unknown_warning'))
def test_suppress_warning_known(self):
suppress_warning = self.make_warnings_config('suppress_warnings=a,b')
self.assertEqual(False, suppress_warning('c'))
self.assertEqual(True, suppress_warning('a'))
self.assertEqual(True, suppress_warning('b'))
class TestGetConfig(tests.TestCase):
def test_constructs(self):
my_config = config.GlobalConfig()
def test_calls_read_filenames(self):
# replace the class that is constructed, to check its parameters
oldparserclass = config.ConfigObj
config.ConfigObj = InstrumentedConfigObj
my_config = config.GlobalConfig()
try:
parser = my_config._get_parser()
finally:
config.ConfigObj = oldparserclass
self.failUnless(isinstance(parser, InstrumentedConfigObj))
self.assertEqual(parser._calls, [('__init__', config.config_filename(),
'utf-8')])
class TestBranchConfig(tests.TestCaseWithTransport):
def test_constructs(self):
branch = FakeBranch()
my_config = config.BranchConfig(branch)
self.assertRaises(TypeError, config.BranchConfig)
def test_get_location_config(self):
branch = FakeBranch()
my_config = config.BranchConfig(branch)
location_config = my_config._get_location_config()
self.assertEqual(branch.base, location_config.location)
self.failUnless(location_config is my_config._get_location_config())
def test_get_config(self):
"""The Branch.get_config method works properly"""
b = bzrdir.BzrDir.create_standalone_workingtree('.').branch
my_config = b.get_config()
self.assertIs(my_config.get_user_option('wacky'), None)
my_config.set_user_option('wacky', 'unlikely')
self.assertEqual(my_config.get_user_option('wacky'), 'unlikely')
# Ensure we get the same thing if we start again
b2 = branch.Branch.open('.')
my_config2 = b2.get_config()
self.assertEqual(my_config2.get_user_option('wacky'), 'unlikely')
def test_has_explicit_nickname(self):
b = self.make_branch('.')
self.assertFalse(b.get_config().has_explicit_nickname())
b.nick = 'foo'
self.assertTrue(b.get_config().has_explicit_nickname())
def test_config_url(self):
"""The Branch.get_config will use section that uses a local url"""
branch = self.make_branch('branch')
self.assertEqual('branch', branch.nick)
local_url = urlutils.local_path_to_url('branch')
conf = config.LocationConfig.from_string(
'[%s]\nnickname = foobar' % (local_url,),
local_url, save=True)
self.assertEqual('foobar', branch.nick)
def test_config_local_path(self):
"""The Branch.get_config will use a local system path"""
branch = self.make_branch('branch')
self.assertEqual('branch', branch.nick)
local_path = osutils.getcwd().encode('utf8')
conf = config.LocationConfig.from_string(
'[%s/branch]\nnickname = barry' % (local_path,),
'branch', save=True)
self.assertEqual('barry', branch.nick)
def test_config_creates_local(self):
"""Creating a new entry in config uses a local path."""
branch = self.make_branch('branch', format='knit')
branch.set_push_location('http://foobar')
local_path = osutils.getcwd().encode('utf8')
# Surprisingly ConfigObj doesn't create a trailing newline
self.check_file_contents(config.locations_config_filename(),
'[%s/branch]\n'
'push_location = http://foobar\n'
'push_location:policy = norecurse\n'
% (local_path,))
def test_autonick_urlencoded(self):
b = self.make_branch('!repo')
self.assertEqual('!repo', b.get_config().get_nickname())
def test_warn_if_masked(self):
warnings = []
def warning(*args):
warnings.append(args[0] % args[1:])
self.overrideAttr(trace, 'warning', warning)
def set_option(store, warn_masked=True):
warnings[:] = []
conf.set_user_option('example_option', repr(store), store=store,
warn_masked=warn_masked)
def assertWarning(warning):
if warning is None:
self.assertEqual(0, len(warnings))
else:
self.assertEqual(1, len(warnings))
self.assertEqual(warning, warnings[0])
branch = self.make_branch('.')
conf = branch.get_config()
set_option(config.STORE_GLOBAL)
assertWarning(None)
set_option(config.STORE_BRANCH)
assertWarning(None)
set_option(config.STORE_GLOBAL)
assertWarning('Value "4" is masked by "3" from branch.conf')
set_option(config.STORE_GLOBAL, warn_masked=False)
assertWarning(None)
set_option(config.STORE_LOCATION)
assertWarning(None)
set_option(config.STORE_BRANCH)
assertWarning('Value "3" is masked by "0" from locations.conf')
set_option(config.STORE_BRANCH, warn_masked=False)
assertWarning(None)
class TestGlobalConfigItems(tests.TestCaseInTempDir):
def test_user_id(self):
my_config = config.GlobalConfig.from_string(sample_config_text)
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
my_config._get_user_id())
def test_absent_user_id(self):
my_config = config.GlobalConfig()
self.assertEqual(None, my_config._get_user_id())
def test_configured_editor(self):
my_config = config.GlobalConfig.from_string(sample_config_text)
self.assertEqual("vim", my_config.get_editor())
def test_signatures_always(self):
my_config = config.GlobalConfig.from_string(sample_always_signatures)
self.assertEqual(config.CHECK_NEVER,
my_config.signature_checking())
self.assertEqual(config.SIGN_ALWAYS,
my_config.signing_policy())
self.assertEqual(True, my_config.signature_needed())
def test_signatures_if_possible(self):
my_config = config.GlobalConfig.from_string(sample_maybe_signatures)
self.assertEqual(config.CHECK_NEVER,
my_config.signature_checking())
self.assertEqual(config.SIGN_WHEN_REQUIRED,
my_config.signing_policy())
self.assertEqual(False, my_config.signature_needed())
def test_signatures_ignore(self):
my_config = config.GlobalConfig.from_string(sample_ignore_signatures)
self.assertEqual(config.CHECK_ALWAYS,
my_config.signature_checking())
self.assertEqual(config.SIGN_NEVER,
my_config.signing_policy())
self.assertEqual(False, my_config.signature_needed())
def _get_sample_config(self):
my_config = config.GlobalConfig.from_string(sample_config_text)
return my_config
def test_gpg_signing_command(self):
my_config = self._get_sample_config()
self.assertEqual("gnome-gpg", my_config.gpg_signing_command())
self.assertEqual(False, my_config.signature_needed())
def _get_empty_config(self):
my_config = config.GlobalConfig()
return my_config
def test_gpg_signing_command_unset(self):
my_config = self._get_empty_config()
self.assertEqual("gpg", my_config.gpg_signing_command())
def test_get_user_option_default(self):
my_config = self._get_empty_config()
self.assertEqual(None, my_config.get_user_option('no_option'))
def test_get_user_option_global(self):
my_config = self._get_sample_config()
self.assertEqual("something",
my_config.get_user_option('user_global_option'))
def test_post_commit_default(self):
my_config = self._get_sample_config()
self.assertEqual(None, my_config.post_commit())
def test_configured_logformat(self):
my_config = self._get_sample_config()
self.assertEqual("short", my_config.log_format())
def test_get_alias(self):
my_config = self._get_sample_config()
self.assertEqual('help', my_config.get_alias('h'))
def test_get_aliases(self):
my_config = self._get_sample_config()
aliases = my_config.get_aliases()
self.assertEqual(2, len(aliases))
sorted_keys = sorted(aliases)
self.assertEqual('help', aliases[sorted_keys[0]])
self.assertEqual(sample_long_alias, aliases[sorted_keys[1]])
def test_get_no_alias(self):
my_config = self._get_sample_config()
self.assertEqual(None, my_config.get_alias('foo'))
def test_get_long_alias(self):
my_config = self._get_sample_config()
self.assertEqual(sample_long_alias, my_config.get_alias('ll'))
def test_get_change_editor(self):
my_config = self._get_sample_config()
change_editor = my_config.get_change_editor('old', 'new')
self.assertIs(diff.DiffFromTool, change_editor.__class__)
self.assertEqual('vimdiff -of @new_path @old_path',
' '.join(change_editor.command_template))
def test_get_no_change_editor(self):
my_config = self._get_empty_config()
change_editor = my_config.get_change_editor('old', 'new')
self.assertIs(None, change_editor)
class TestGlobalConfigSavingOptions(tests.TestCaseInTempDir):
def test_empty(self):
my_config = config.GlobalConfig()
self.assertEqual(0, len(my_config.get_aliases()))
def test_set_alias(self):
my_config = config.GlobalConfig()
alias_value = 'commit --strict'
my_config.set_alias('commit', alias_value)
new_config = config.GlobalConfig()
self.assertEqual(alias_value, new_config.get_alias('commit'))
def test_remove_alias(self):
my_config = config.GlobalConfig()
my_config.set_alias('commit', 'commit --strict')
# Now remove the alias again.
my_config.unset_alias('commit')
new_config = config.GlobalConfig()
self.assertIs(None, new_config.get_alias('commit'))
class TestLocationConfig(tests.TestCaseInTempDir, TestOptionsMixin):
def test_constructs(self):
my_config = config.LocationConfig('http://example.com')
self.assertRaises(TypeError, config.LocationConfig)
def test_branch_calls_read_filenames(self):
# This is testing the correct file names are provided.
# TODO: consolidate with the test for GlobalConfigs filename checks.
#
# replace the class that is constructed, to check its parameters
oldparserclass = config.ConfigObj
config.ConfigObj = InstrumentedConfigObj
try:
my_config = config.LocationConfig('http://www.example.com')
parser = my_config._get_parser()
finally:
config.ConfigObj = oldparserclass
self.failUnless(isinstance(parser, InstrumentedConfigObj))
self.assertEqual(parser._calls,
[('__init__', config.locations_config_filename(),
'utf-8')])
def test_get_global_config(self):
my_config = config.BranchConfig(FakeBranch('http://example.com'))
global_config = my_config._get_global_config()
self.failUnless(isinstance(global_config, config.GlobalConfig))
self.failUnless(global_config is my_config._get_global_config())
def test__get_matching_sections_no_match(self):
self.get_branch_config('/')
self.assertEqual([], self.my_location_config._get_matching_sections())
def test__get_matching_sections_exact(self):
self.get_branch_config('http://www.example.com')
self.assertEqual([('http://www.example.com', '')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_suffix_does_not(self):
self.get_branch_config('http://www.example.com-com')
self.assertEqual([], self.my_location_config._get_matching_sections())
def test__get_matching_sections_subdir_recursive(self):
self.get_branch_config('http://www.example.com/com')
self.assertEqual([('http://www.example.com', 'com')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_ignoreparent(self):
self.get_branch_config('http://www.example.com/ignoreparent')
self.assertEqual([('http://www.example.com/ignoreparent', '')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_ignoreparent_subdir(self):
self.get_branch_config(
'http://www.example.com/ignoreparent/childbranch')
self.assertEqual([('http://www.example.com/ignoreparent',
'childbranch')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_subdir_trailing_slash(self):
self.get_branch_config('/b')
self.assertEqual([('/b/', '')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_subdir_child(self):
self.get_branch_config('/a/foo')
self.assertEqual([('/a/*', ''), ('/a/', 'foo')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_subdir_child_child(self):
self.get_branch_config('/a/foo/bar')
self.assertEqual([('/a/*', 'bar'), ('/a/', 'foo/bar')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_trailing_slash_with_children(self):
self.get_branch_config('/a/')
self.assertEqual([('/a/', '')],
self.my_location_config._get_matching_sections())
def test__get_matching_sections_explicit_over_glob(self):
# XXX: 2006-09-08 jamesh
# This test only passes because ord('c') > ord('*'). If there
# was a config section for '/a/?', it would get precedence
# over '/a/c'.
self.get_branch_config('/a/c')
self.assertEqual([('/a/c', ''), ('/a/*', ''), ('/a/', 'c')],
self.my_location_config._get_matching_sections())
def test__get_option_policy_normal(self):
self.get_branch_config('http://www.example.com')
self.assertEqual(
self.my_location_config._get_config_policy(
'http://www.example.com', 'normal_option'),
config.POLICY_NONE)
def test__get_option_policy_norecurse(self):
self.get_branch_config('http://www.example.com')
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com', 'norecurse_option'),
config.POLICY_NORECURSE)
# Test old recurse=False setting:
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com/norecurse', 'normal_option'),
config.POLICY_NORECURSE)
def test__get_option_policy_normal(self):
self.get_branch_config('http://www.example.com')
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com', 'appendpath_option'),
config.POLICY_APPENDPATH)
def test__get_options_with_policy(self):
self.get_branch_config('/dir/subdir',
location_config="""\
[/dir]
other_url = /other-dir
other_url:policy = appendpath
[/dir/subdir]
other_url = /other-subdir
""")
self.assertOptions(
[(u'other_url', u'/other-subdir', u'/dir/subdir', 'locations'),
(u'other_url', u'/other-dir', u'/dir', 'locations'),
(u'other_url:policy', u'appendpath', u'/dir', 'locations')],
self.my_location_config)
def test_location_without_username(self):
self.get_branch_config('http://www.example.com/ignoreparent')
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
self.my_config.username())
def test_location_not_listed(self):
"""Test that the global username is used when no location matches"""
self.get_branch_config('/home/robertc/sources')
self.assertEqual(u'Erik B\u00e5gfors <erik@bagfors.nu>',
self.my_config.username())
def test_overriding_location(self):
self.get_branch_config('http://www.example.com/foo')
self.assertEqual('Robert Collins <robertc@example.org>',
self.my_config.username())
def test_signatures_not_set(self):
self.get_branch_config('http://www.example.com',
global_config=sample_ignore_signatures)
self.assertEqual(config.CHECK_ALWAYS,
self.my_config.signature_checking())
self.assertEqual(config.SIGN_NEVER,
self.my_config.signing_policy())
def test_signatures_never(self):
self.get_branch_config('/a/c')
self.assertEqual(config.CHECK_NEVER,
self.my_config.signature_checking())
def test_signatures_when_available(self):
self.get_branch_config('/a/', global_config=sample_ignore_signatures)
self.assertEqual(config.CHECK_IF_POSSIBLE,
self.my_config.signature_checking())
def test_signatures_always(self):
self.get_branch_config('/b')
self.assertEqual(config.CHECK_ALWAYS,
self.my_config.signature_checking())
def test_gpg_signing_command(self):
self.get_branch_config('/b')
self.assertEqual("gnome-gpg", self.my_config.gpg_signing_command())
def test_gpg_signing_command_missing(self):
self.get_branch_config('/a')
self.assertEqual("false", self.my_config.gpg_signing_command())
def test_get_user_option_global(self):
self.get_branch_config('/a')
self.assertEqual('something',
self.my_config.get_user_option('user_global_option'))
def test_get_user_option_local(self):
self.get_branch_config('/a')
self.assertEqual('local',
self.my_config.get_user_option('user_local_option'))
def test_get_user_option_appendpath(self):
# returned as is for the base path:
self.get_branch_config('http://www.example.com')
self.assertEqual('append',
self.my_config.get_user_option('appendpath_option'))
# Extra path components get appended:
self.get_branch_config('http://www.example.com/a/b/c')
self.assertEqual('append/a/b/c',
self.my_config.get_user_option('appendpath_option'))
# Overriden for http://www.example.com/dir, where it is a
# normal option:
self.get_branch_config('http://www.example.com/dir/a/b/c')
self.assertEqual('normal',
self.my_config.get_user_option('appendpath_option'))
def test_get_user_option_norecurse(self):
self.get_branch_config('http://www.example.com')
self.assertEqual('norecurse',
self.my_config.get_user_option('norecurse_option'))
self.get_branch_config('http://www.example.com/dir')
self.assertEqual(None,
self.my_config.get_user_option('norecurse_option'))
# http://www.example.com/norecurse is a recurse=False section
# that redefines normal_option. Subdirectories do not pick up
# this redefinition.
self.get_branch_config('http://www.example.com/norecurse')
self.assertEqual('norecurse',
self.my_config.get_user_option('normal_option'))
self.get_branch_config('http://www.example.com/norecurse/subdir')
self.assertEqual('normal',
self.my_config.get_user_option('normal_option'))
def test_set_user_option_norecurse(self):
self.get_branch_config('http://www.example.com')
self.my_config.set_user_option('foo', 'bar',
store=config.STORE_LOCATION_NORECURSE)
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com', 'foo'),
config.POLICY_NORECURSE)
def test_set_user_option_appendpath(self):
self.get_branch_config('http://www.example.com')
self.my_config.set_user_option('foo', 'bar',
store=config.STORE_LOCATION_APPENDPATH)
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com', 'foo'),
config.POLICY_APPENDPATH)
def test_set_user_option_change_policy(self):
self.get_branch_config('http://www.example.com')
self.my_config.set_user_option('norecurse_option', 'normal',
store=config.STORE_LOCATION)
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com', 'norecurse_option'),
config.POLICY_NONE)
def test_set_user_option_recurse_false_section(self):
# The following section has recurse=False set. The test is to
# make sure that a normal option can be added to the section,
# converting recurse=False to the norecurse policy.
self.get_branch_config('http://www.example.com/norecurse')
self.callDeprecated(['The recurse option is deprecated as of 0.14. '
'The section "http://www.example.com/norecurse" '
'has been converted to use policies.'],
self.my_config.set_user_option,
'foo', 'bar', store=config.STORE_LOCATION)
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com/norecurse', 'foo'),
config.POLICY_NONE)
# The previously existing option is still norecurse:
self.assertEqual(
self.my_location_config._get_option_policy(
'http://www.example.com/norecurse', 'normal_option'),
config.POLICY_NORECURSE)
def test_post_commit_default(self):
self.get_branch_config('/a/c')
self.assertEqual('bzrlib.tests.test_config.post_commit',
self.my_config.post_commit())
def get_branch_config(self, location, global_config=None,
location_config=None):
my_branch = FakeBranch(location)
if global_config is None:
global_config = sample_config_text
if location_config is None:
location_config = sample_branches_text
my_global_config = config.GlobalConfig.from_string(global_config,
save=True)
my_location_config = config.LocationConfig.from_string(
location_config, my_branch.base, save=True)
my_config = config.BranchConfig(my_branch)
self.my_config = my_config
self.my_location_config = my_config._get_location_config()
def test_set_user_setting_sets_and_saves(self):
self.get_branch_config('/a/c')
record = InstrumentedConfigObj("foo")
self.my_location_config._parser = record
self.callDeprecated(['The recurse option is deprecated as of '
'0.14. The section "/a/c" has been '
'converted to use policies.'],
self.my_config.set_user_option,
'foo', 'bar', store=config.STORE_LOCATION)
self.assertEqual([('reload',),
('__contains__', '/a/c'),
('__contains__', '/a/c/'),
('__setitem__', '/a/c', {}),
('__getitem__', '/a/c'),
('__setitem__', 'foo', 'bar'),
('__getitem__', '/a/c'),
('as_bool', 'recurse'),
('__getitem__', '/a/c'),
('__delitem__', 'recurse'),
('__getitem__', '/a/c'),
('keys',),
('__getitem__', '/a/c'),
('__contains__', 'foo:policy'),
('write',)],
record._calls[1:])
def test_set_user_setting_sets_and_saves2(self):
self.get_branch_config('/a/c')
self.assertIs(self.my_config.get_user_option('foo'), None)
self.my_config.set_user_option('foo', 'bar')
self.assertEqual(
self.my_config.branch.control_files.files['branch.conf'].strip(),
'foo = bar')
self.assertEqual(self.my_config.get_user_option('foo'), 'bar')
self.my_config.set_user_option('foo', 'baz',
store=config.STORE_LOCATION)
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
self.my_config.set_user_option('foo', 'qux')
self.assertEqual(self.my_config.get_user_option('foo'), 'baz')
def test_get_bzr_remote_path(self):
my_config = config.LocationConfig('/a/c')
self.assertEqual('bzr', my_config.get_bzr_remote_path())
my_config.set_user_option('bzr_remote_path', '/path-bzr')
self.assertEqual('/path-bzr', my_config.get_bzr_remote_path())
os.environ['BZR_REMOTE_PATH'] = '/environ-bzr'
self.assertEqual('/environ-bzr', my_config.get_bzr_remote_path())
precedence_global = 'option = global'
precedence_branch = 'option = branch'
precedence_location = """
[http://]
recurse = true
option = recurse
[http://example.com/specific]
option = exact
"""
class TestBranchConfigItems(tests.TestCaseInTempDir):
def get_branch_config(self, global_config=None, location=None,
location_config=None, branch_data_config=None):
my_branch = FakeBranch(location)
if global_config is not None:
my_global_config = config.GlobalConfig.from_string(global_config,
save=True)
if location_config is not None:
my_location_config = config.LocationConfig.from_string(
location_config, my_branch.base, save=True)
my_config = config.BranchConfig(my_branch)
if branch_data_config is not None:
my_config.branch.control_files.files['branch.conf'] = \
branch_data_config
return my_config
def test_user_id(self):
branch = FakeBranch(user_id='Robert Collins <robertc@example.net>')
my_config = config.BranchConfig(branch)
self.assertEqual("Robert Collins <robertc@example.net>",
my_config.username())
my_config.branch.control_files.files['email'] = "John"
my_config.set_user_option('email',
"Robert Collins <robertc@example.org>")
self.assertEqual("John", my_config.username())
del my_config.branch.control_files.files['email']
self.assertEqual("Robert Collins <robertc@example.org>",
my_config.username())
def test_not_set_in_branch(self):
my_config = self.get_branch_config(global_config=sample_config_text)
self.assertEqual(u"Erik B\u00e5gfors <erik@bagfors.nu>",
my_config._get_user_id())
my_config.branch.control_files.files['email'] = "John"
self.assertEqual("John", my_config._get_user_id())
def test_BZR_EMAIL_OVERRIDES(self):
os.environ['BZR_EMAIL'] = "Robert Collins <robertc@example.org>"
branch = FakeBranch()
my_config = config.BranchConfig(branch)
self.assertEqual("Robert Collins <robertc@example.org>",
my_config.username())
def test_signatures_forced(self):
my_config = self.get_branch_config(
global_config=sample_always_signatures)
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
self.assertTrue(my_config.signature_needed())
def test_signatures_forced_branch(self):
my_config = self.get_branch_config(
global_config=sample_ignore_signatures,
branch_data_config=sample_always_signatures)
self.assertEqual(config.CHECK_NEVER, my_config.signature_checking())
self.assertEqual(config.SIGN_ALWAYS, my_config.signing_policy())
self.assertTrue(my_config.signature_needed())
def test_gpg_signing_command(self):
my_config = self.get_branch_config(
global_config=sample_config_text,
# branch data cannot set gpg_signing_command
branch_data_config="gpg_signing_command=pgp")
self.assertEqual('gnome-gpg', my_config.gpg_signing_command())
def test_get_user_option_global(self):
my_config = self.get_branch_config(global_config=sample_config_text)
self.assertEqual('something',
my_config.get_user_option('user_global_option'))
def test_post_commit_default(self):
my_config = self.get_branch_config(global_config=sample_config_text,
location='/a/c',
location_config=sample_branches_text)
self.assertEqual(my_config.branch.base, '/a/c')
self.assertEqual('bzrlib.tests.test_config.post_commit',
my_config.post_commit())
my_config.set_user_option('post_commit', 'rmtree_root')
# post-commit is ignored when present in branch data
self.assertEqual('bzrlib.tests.test_config.post_commit',
my_config.post_commit())
my_config.set_user_option('post_commit', 'rmtree_root',
store=config.STORE_LOCATION)
self.assertEqual('rmtree_root', my_config.post_commit())
def test_config_precedence(self):
# FIXME: eager test, luckily no persitent config file makes it fail
# -- vila 20100716
my_config = self.get_branch_config(global_config=precedence_global)
self.assertEqual(my_config.get_user_option('option'), 'global')
my_config = self.get_branch_config(global_config=precedence_global,
branch_data_config=precedence_branch)
self.assertEqual(my_config.get_user_option('option'), 'branch')
my_config = self.get_branch_config(
global_config=precedence_global,
branch_data_config=precedence_branch,
location_config=precedence_location)
self.assertEqual(my_config.get_user_option('option'), 'recurse')
my_config = self.get_branch_config(
global_config=precedence_global,
branch_data_config=precedence_branch,
location_config=precedence_location,
location='http://example.com/specific')
self.assertEqual(my_config.get_user_option('option'), 'exact')
def test_get_mail_client(self):
config = self.get_branch_config()
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.DefaultMail)
# Specific clients
config.set_user_option('mail_client', 'evolution')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.Evolution)
config.set_user_option('mail_client', 'kmail')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.KMail)
config.set_user_option('mail_client', 'mutt')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.Mutt)
config.set_user_option('mail_client', 'thunderbird')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.Thunderbird)
# Generic options
config.set_user_option('mail_client', 'default')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.DefaultMail)
config.set_user_option('mail_client', 'editor')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.Editor)
config.set_user_option('mail_client', 'mapi')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.MAPIClient)
config.set_user_option('mail_client', 'xdg-email')
client = config.get_mail_client()
self.assertIsInstance(client, mail_client.XDGEmail)
config.set_user_option('mail_client', 'firebird')
self.assertRaises(errors.UnknownMailClient, config.get_mail_client)
class TestMailAddressExtraction(tests.TestCase):
def test_extract_email_address(self):
self.assertEqual('jane@test.com',
config.extract_email_address('Jane <jane@test.com>'))
self.assertRaises(errors.NoEmailInUsername,
config.extract_email_address, 'Jane Tester')
def test_parse_username(self):
self.assertEqual(('', 'jdoe@example.com'),
config.parse_username('jdoe@example.com'))
self.assertEqual(('', 'jdoe@example.com'),
config.parse_username('<jdoe@example.com>'))
self.assertEqual(('John Doe', 'jdoe@example.com'),
config.parse_username('John Doe <jdoe@example.com>'))
self.assertEqual(('John Doe', ''),
config.parse_username('John Doe'))
self.assertEqual(('John Doe', 'jdoe@example.com'),
config.parse_username('John Doe jdoe@example.com'))
class TestTreeConfig(tests.TestCaseWithTransport):
def test_get_value(self):
"""Test that retreiving a value from a section is possible"""
branch = self.make_branch('.')
tree_config = config.TreeConfig(branch)
tree_config.set_option('value', 'key', 'SECTION')
tree_config.set_option('value2', 'key2')
tree_config.set_option('value3-top', 'key3')
tree_config.set_option('value3-section', 'key3', 'SECTION')
value = tree_config.get_option('key', 'SECTION')
self.assertEqual(value, 'value')
value = tree_config.get_option('key2')
self.assertEqual(value, 'value2')
self.assertEqual(tree_config.get_option('non-existant'), None)
value = tree_config.get_option('non-existant', 'SECTION')
self.assertEqual(value, None)
value = tree_config.get_option('non-existant', default='default')
self.assertEqual(value, 'default')
self.assertEqual(tree_config.get_option('key2', 'NOSECTION'), None)
value = tree_config.get_option('key2', 'NOSECTION', default='default')
self.assertEqual(value, 'default')
value = tree_config.get_option('key3')
self.assertEqual(value, 'value3-top')
value = tree_config.get_option('key3', 'SECTION')
self.assertEqual(value, 'value3-section')
class TestTransportConfig(tests.TestCaseWithTransport):
def test_get_value(self):
"""Test that retreiving a value from a section is possible"""
bzrdir_config = config.TransportConfig(transport.get_transport('.'),
'control.conf')
bzrdir_config.set_option('value', 'key', 'SECTION')
bzrdir_config.set_option('value2', 'key2')
bzrdir_config.set_option('value3-top', 'key3')
bzrdir_config.set_option('value3-section', 'key3', 'SECTION')
value = bzrdir_config.get_option('key', 'SECTION')
self.assertEqual(value, 'value')
value = bzrdir_config.get_option('key2')
self.assertEqual(value, 'value2')
self.assertEqual(bzrdir_config.get_option('non-existant'), None)
value = bzrdir_config.get_option('non-existant', 'SECTION')
self.assertEqual(value, None)
value = bzrdir_config.get_option('non-existant', default='default')
self.assertEqual(value, 'default')
self.assertEqual(bzrdir_config.get_option('key2', 'NOSECTION'), None)
value = bzrdir_config.get_option('key2', 'NOSECTION',
default='default')
self.assertEqual(value, 'default')
value = bzrdir_config.get_option('key3')
self.assertEqual(value, 'value3-top')
value = bzrdir_config.get_option('key3', 'SECTION')
self.assertEqual(value, 'value3-section')
def test_set_unset_default_stack_on(self):
my_dir = self.make_bzrdir('.')
bzrdir_config = config.BzrDirConfig(my_dir)
self.assertIs(None, bzrdir_config.get_default_stack_on())
bzrdir_config.set_default_stack_on('Foo')
self.assertEqual('Foo', bzrdir_config._config.get_option(
'default_stack_on'))
self.assertEqual('Foo', bzrdir_config.get_default_stack_on())
bzrdir_config.set_default_stack_on(None)
self.assertIs(None, bzrdir_config.get_default_stack_on())
class TestConfigGetOptions(tests.TestCaseWithTransport, TestOptionsMixin):
def setUp(self):
super(TestConfigGetOptions, self).setUp()
create_configs(self)
# One variable in none of the above
def test_no_variable(self):
# Using branch should query branch, locations and bazaar
self.assertOptions([], self.branch_config)
def test_option_in_bazaar(self):
self.bazaar_config.set_user_option('file', 'bazaar')
self.assertOptions([('file', 'bazaar', 'DEFAULT', 'bazaar')],
self.bazaar_config)
def test_option_in_locations(self):
self.locations_config.set_user_option('file', 'locations')
self.assertOptions(
[('file', 'locations', self.tree.basedir, 'locations')],
self.locations_config)
def test_option_in_branch(self):
self.branch_config.set_user_option('file', 'branch')
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch')],
self.branch_config)
def test_option_in_bazaar_and_branch(self):
self.bazaar_config.set_user_option('file', 'bazaar')
self.branch_config.set_user_option('file', 'branch')
self.assertOptions([('file', 'branch', 'DEFAULT', 'branch'),
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
self.branch_config)
def test_option_in_branch_and_locations(self):
# Hmm, locations override branch :-/
self.locations_config.set_user_option('file', 'locations')
self.branch_config.set_user_option('file', 'branch')
self.assertOptions(
[('file', 'locations', self.tree.basedir, 'locations'),
('file', 'branch', 'DEFAULT', 'branch'),],
self.branch_config)
def test_option_in_bazaar_locations_and_branch(self):
self.bazaar_config.set_user_option('file', 'bazaar')
self.locations_config.set_user_option('file', 'locations')
self.branch_config.set_user_option('file', 'branch')
self.assertOptions(
[('file', 'locations', self.tree.basedir, 'locations'),
('file', 'branch', 'DEFAULT', 'branch'),
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
self.branch_config)
class TestConfigRemoveOption(tests.TestCaseWithTransport, TestOptionsMixin):
def setUp(self):
super(TestConfigRemoveOption, self).setUp()
create_configs_with_file_option(self)
def test_remove_in_locations(self):
self.locations_config.remove_user_option('file', self.tree.basedir)
self.assertOptions(
[('file', 'branch', 'DEFAULT', 'branch'),
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
self.branch_config)
def test_remove_in_branch(self):
self.branch_config.remove_user_option('file')
self.assertOptions(
[('file', 'locations', self.tree.basedir, 'locations'),
('file', 'bazaar', 'DEFAULT', 'bazaar'),],
self.branch_config)
def test_remove_in_bazaar(self):
self.bazaar_config.remove_user_option('file')
self.assertOptions(
[('file', 'locations', self.tree.basedir, 'locations'),
('file', 'branch', 'DEFAULT', 'branch'),],
self.branch_config)
class TestConfigGetSections(tests.TestCaseWithTransport):
def setUp(self):
super(TestConfigGetSections, self).setUp()
create_configs(self)
def assertSectionNames(self, expected, conf, name=None):
"""Check which sections are returned for a given config.
If fallback configurations exist their sections can be included.
:param expected: A list of section names.
:param conf: The configuration that will be queried.
:param name: An optional section name that will be passed to
get_sections().
"""
sections = list(conf._get_sections(name))
self.assertLength(len(expected), sections)
self.assertEqual(expected, [name for name, _, _ in sections])
def test_bazaar_default_section(self):
self.assertSectionNames(['DEFAULT'], self.bazaar_config)
def test_locations_default_section(self):
# No sections are defined in an empty file
self.assertSectionNames([], self.locations_config)
def test_locations_named_section(self):
self.locations_config.set_user_option('file', 'locations')
self.assertSectionNames([self.tree.basedir], self.locations_config)
def test_locations_matching_sections(self):
loc_config = self.locations_config
loc_config.set_user_option('file', 'locations')
# We need to cheat a bit here to create an option in sections above and
# below the 'location' one.
parser = loc_config._get_parser()
# locations.cong deals with '/' ignoring native os.sep
location_names = self.tree.basedir.split('/')
parent = '/'.join(location_names[:-1])
child = '/'.join(location_names + ['child'])
parser[parent] = {}
parser[parent]['file'] = 'parent'
parser[child] = {}
parser[child]['file'] = 'child'
self.assertSectionNames([self.tree.basedir, parent], loc_config)
def test_branch_data_default_section(self):
self.assertSectionNames([None],
self.branch_config._get_branch_data_config())
def test_branch_default_sections(self):
# No sections are defined in an empty locations file
self.assertSectionNames([None, 'DEFAULT'],
self.branch_config)
# Unless we define an option
self.branch_config._get_location_config().set_user_option(
'file', 'locations')
self.assertSectionNames([self.tree.basedir, None, 'DEFAULT'],
self.branch_config)
def test_bazaar_named_section(self):
# We need to cheat as the API doesn't give direct access to sections
# other than DEFAULT.
self.bazaar_config.set_alias('bazaar', 'bzr')
self.assertSectionNames(['ALIASES'], self.bazaar_config, 'ALIASES')
class TestAuthenticationConfigFile(tests.TestCase):
"""Test the authentication.conf file matching"""
def _got_user_passwd(self, expected_user, expected_password,
config, *args, **kwargs):
credentials = config.get_credentials(*args, **kwargs)
if credentials is None:
user = None
password = None
else:
user = credentials['user']
password = credentials['password']
self.assertEquals(expected_user, user)
self.assertEquals(expected_password, password)
def test_empty_config(self):
conf = config.AuthenticationConfig(_file=StringIO())
self.assertEquals({}, conf._get_config())
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
def test_missing_auth_section_header(self):
conf = config.AuthenticationConfig(_file=StringIO('foo = bar'))
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
def test_auth_section_header_not_closed(self):
conf = config.AuthenticationConfig(_file=StringIO('[DEF'))
self.assertRaises(errors.ParseConfigError, conf._get_config)
def test_auth_value_not_boolean(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""[broken]
scheme=ftp
user=joe
verify_certificates=askme # Error: Not a boolean
"""))
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
def test_auth_value_not_int(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""[broken]
scheme=ftp
user=joe
port=port # Error: Not an int
"""))
self.assertRaises(ValueError, conf.get_credentials, 'ftp', 'foo.net')
def test_unknown_password_encoding(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""[broken]
scheme=ftp
user=joe
password_encoding=unknown
"""))
self.assertRaises(ValueError, conf.get_password,
'ftp', 'foo.net', 'joe')
def test_credentials_for_scheme_host(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""# Identity on foo.net
[ftp definition]
scheme=ftp
host=foo.net
user=joe
password=secret-pass
"""))
# Basic matching
self._got_user_passwd('joe', 'secret-pass', conf, 'ftp', 'foo.net')
# different scheme
self._got_user_passwd(None, None, conf, 'http', 'foo.net')
# different host
self._got_user_passwd(None, None, conf, 'ftp', 'bar.net')
def test_credentials_for_host_port(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""# Identity on foo.net
[ftp definition]
scheme=ftp
port=10021
host=foo.net
user=joe
password=secret-pass
"""))
# No port
self._got_user_passwd('joe', 'secret-pass',
conf, 'ftp', 'foo.net', port=10021)
# different port
self._got_user_passwd(None, None, conf, 'ftp', 'foo.net')
def test_for_matching_host(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""# Identity on foo.net
[sourceforge]
scheme=bzr
host=bzr.sf.net
user=joe
password=joepass
[sourceforge domain]
scheme=bzr
host=.bzr.sf.net
user=georges
password=bendover
"""))
# matching domain
self._got_user_passwd('georges', 'bendover',
conf, 'bzr', 'foo.bzr.sf.net')
# phishing attempt
self._got_user_passwd(None, None,
conf, 'bzr', 'bbzr.sf.net')
def test_for_matching_host_None(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""# Identity on foo.net
[catchup bzr]
scheme=bzr
user=joe
password=joepass
[DEFAULT]
user=georges
password=bendover
"""))
# match no host
self._got_user_passwd('joe', 'joepass',
conf, 'bzr', 'quux.net')
# no host but different scheme
self._got_user_passwd('georges', 'bendover',
conf, 'ftp', 'quux.net')
def test_credentials_for_path(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""
[http dir1]
scheme=http
host=bar.org
path=/dir1
user=jim
password=jimpass
[http dir2]
scheme=http
host=bar.org
path=/dir2
user=georges
password=bendover
"""))
# no path no dice
self._got_user_passwd(None, None,
conf, 'http', host='bar.org', path='/dir3')
# matching path
self._got_user_passwd('georges', 'bendover',
conf, 'http', host='bar.org', path='/dir2')
# matching subdir
self._got_user_passwd('jim', 'jimpass',
conf, 'http', host='bar.org',path='/dir1/subdir')
def test_credentials_for_user(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""
[with user]
scheme=http
host=bar.org
user=jim
password=jimpass
"""))
# Get user
self._got_user_passwd('jim', 'jimpass',
conf, 'http', 'bar.org')
# Get same user
self._got_user_passwd('jim', 'jimpass',
conf, 'http', 'bar.org', user='jim')
# Don't get a different user if one is specified
self._got_user_passwd(None, None,
conf, 'http', 'bar.org', user='georges')
def test_credentials_for_user_without_password(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""
[without password]
scheme=http
host=bar.org
user=jim
"""))
# Get user but no password
self._got_user_passwd('jim', None,
conf, 'http', 'bar.org')
def test_verify_certificates(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""
[self-signed]
scheme=https
host=bar.org
user=jim
password=jimpass
verify_certificates=False
[normal]
scheme=https
host=foo.net
user=georges
password=bendover
"""))
credentials = conf.get_credentials('https', 'bar.org')
self.assertEquals(False, credentials.get('verify_certificates'))
credentials = conf.get_credentials('https', 'foo.net')
self.assertEquals(True, credentials.get('verify_certificates'))
class TestAuthenticationStorage(tests.TestCaseInTempDir):
def test_set_credentials(self):
conf = config.AuthenticationConfig()
conf.set_credentials('name', 'host', 'user', 'scheme', 'password',
99, path='/foo', verify_certificates=False, realm='realm')
credentials = conf.get_credentials(host='host', scheme='scheme',
port=99, path='/foo',
realm='realm')
CREDENTIALS = {'name': 'name', 'user': 'user', 'password': 'password',
'verify_certificates': False, 'scheme': 'scheme',
'host': 'host', 'port': 99, 'path': '/foo',
'realm': 'realm'}
self.assertEqual(CREDENTIALS, credentials)
credentials_from_disk = config.AuthenticationConfig().get_credentials(
host='host', scheme='scheme', port=99, path='/foo', realm='realm')
self.assertEqual(CREDENTIALS, credentials_from_disk)
def test_reset_credentials_different_name(self):
conf = config.AuthenticationConfig()
conf.set_credentials('name', 'host', 'user', 'scheme', 'password'),
conf.set_credentials('name2', 'host', 'user2', 'scheme', 'password'),
self.assertIs(None, conf._get_config().get('name'))
credentials = conf.get_credentials(host='host', scheme='scheme')
CREDENTIALS = {'name': 'name2', 'user': 'user2', 'password':
'password', 'verify_certificates': True,
'scheme': 'scheme', 'host': 'host', 'port': None,
'path': None, 'realm': None}
self.assertEqual(CREDENTIALS, credentials)
class TestAuthenticationConfig(tests.TestCase):
"""Test AuthenticationConfig behaviour"""
def _check_default_password_prompt(self, expected_prompt_format, scheme,
host=None, port=None, realm=None,
path=None):
if host is None:
host = 'bar.org'
user, password = 'jim', 'precious'
expected_prompt = expected_prompt_format % {
'scheme': scheme, 'host': host, 'port': port,
'user': user, 'realm': realm}
stdout = tests.StringIOWrapper()
stderr = tests.StringIOWrapper()
ui.ui_factory = tests.TestUIFactory(stdin=password + '\n',
stdout=stdout, stderr=stderr)
# We use an empty conf so that the user is always prompted
conf = config.AuthenticationConfig()
self.assertEquals(password,
conf.get_password(scheme, host, user, port=port,
realm=realm, path=path))
self.assertEquals(expected_prompt, stderr.getvalue())
self.assertEquals('', stdout.getvalue())
def _check_default_username_prompt(self, expected_prompt_format, scheme,
host=None, port=None, realm=None,
path=None):
if host is None:
host = 'bar.org'
username = 'jim'
expected_prompt = expected_prompt_format % {
'scheme': scheme, 'host': host, 'port': port,
'realm': realm}
stdout = tests.StringIOWrapper()
stderr = tests.StringIOWrapper()
ui.ui_factory = tests.TestUIFactory(stdin=username+ '\n',
stdout=stdout, stderr=stderr)
# We use an empty conf so that the user is always prompted
conf = config.AuthenticationConfig()
self.assertEquals(username, conf.get_user(scheme, host, port=port,
realm=realm, path=path, ask=True))
self.assertEquals(expected_prompt, stderr.getvalue())
self.assertEquals('', stdout.getvalue())
def test_username_defaults_prompts(self):
# HTTP prompts can't be tested here, see test_http.py
self._check_default_username_prompt('FTP %(host)s username: ', 'ftp')
self._check_default_username_prompt(
'FTP %(host)s:%(port)d username: ', 'ftp', port=10020)
self._check_default_username_prompt(
'SSH %(host)s:%(port)d username: ', 'ssh', port=12345)
def test_username_default_no_prompt(self):
conf = config.AuthenticationConfig()
self.assertEquals(None,
conf.get_user('ftp', 'example.com'))
self.assertEquals("explicitdefault",
conf.get_user('ftp', 'example.com', default="explicitdefault"))
def test_password_default_prompts(self):
# HTTP prompts can't be tested here, see test_http.py
self._check_default_password_prompt(
'FTP %(user)s@%(host)s password: ', 'ftp')
self._check_default_password_prompt(
'FTP %(user)s@%(host)s:%(port)d password: ', 'ftp', port=10020)
self._check_default_password_prompt(
'SSH %(user)s@%(host)s:%(port)d password: ', 'ssh', port=12345)
# SMTP port handling is a bit special (it's handled if embedded in the
# host too)
# FIXME: should we: forbid that, extend it to other schemes, leave
# things as they are that's fine thank you ?
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
'smtp')
self._check_default_password_prompt('SMTP %(user)s@%(host)s password: ',
'smtp', host='bar.org:10025')
self._check_default_password_prompt(
'SMTP %(user)s@%(host)s:%(port)d password: ',
'smtp', port=10025)
def test_ssh_password_emits_warning(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""
[ssh with password]
scheme=ssh
host=bar.org
user=jim
password=jimpass
"""))
entered_password = 'typed-by-hand'
stdout = tests.StringIOWrapper()
stderr = tests.StringIOWrapper()
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
stdout=stdout, stderr=stderr)
# Since the password defined in the authentication config is ignored,
# the user is prompted
self.assertEquals(entered_password,
conf.get_password('ssh', 'bar.org', user='jim'))
self.assertContainsRe(
self.get_log(),
'password ignored in section \[ssh with password\]')
def test_ssh_without_password_doesnt_emit_warning(self):
conf = config.AuthenticationConfig(_file=StringIO(
"""
[ssh with password]
scheme=ssh
host=bar.org
user=jim
"""))
entered_password = 'typed-by-hand'
stdout = tests.StringIOWrapper()
stderr = tests.StringIOWrapper()
ui.ui_factory = tests.TestUIFactory(stdin=entered_password + '\n',
stdout=stdout,
stderr=stderr)
# Since the password defined in the authentication config is ignored,
# the user is prompted
self.assertEquals(entered_password,
conf.get_password('ssh', 'bar.org', user='jim'))
# No warning shoud be emitted since there is no password. We are only
# providing "user".
self.assertNotContainsRe(
self.get_log(),
'password ignored in section \[ssh with password\]')
def test_uses_fallback_stores(self):
self.overrideAttr(config, 'credential_store_registry',
config.CredentialStoreRegistry())
store = StubCredentialStore()
store.add_credentials("http", "example.com", "joe", "secret")
config.credential_store_registry.register("stub", store, fallback=True)
conf = config.AuthenticationConfig(_file=StringIO())
creds = conf.get_credentials("http", "example.com")
self.assertEquals("joe", creds["user"])
self.assertEquals("secret", creds["password"])
class StubCredentialStore(config.CredentialStore):
def __init__(self):
self._username = {}
self._password = {}
def add_credentials(self, scheme, host, user, password=None):
self._username[(scheme, host)] = user
self._password[(scheme, host)] = password
def get_credentials(self, scheme, host, port=None, user=None,
path=None, realm=None):
key = (scheme, host)
if not key in self._username:
return None
return { "scheme": scheme, "host": host, "port": port,
"user": self._username[key], "password": self._password[key]}
class CountingCredentialStore(config.CredentialStore):
def __init__(self):
self._calls = 0
def get_credentials(self, scheme, host, port=None, user=None,
path=None, realm=None):
self._calls += 1
return None
class TestCredentialStoreRegistry(tests.TestCase):
def _get_cs_registry(self):
return config.credential_store_registry
def test_default_credential_store(self):
r = self._get_cs_registry()
default = r.get_credential_store(None)
self.assertIsInstance(default, config.PlainTextCredentialStore)
def test_unknown_credential_store(self):
r = self._get_cs_registry()
# It's hard to imagine someone creating a credential store named
# 'unknown' so we use that as an never registered key.
self.assertRaises(KeyError, r.get_credential_store, 'unknown')
def test_fallback_none_registered(self):
r = config.CredentialStoreRegistry()
self.assertEquals(None,
r.get_fallback_credentials("http", "example.com"))
def test_register(self):
r = config.CredentialStoreRegistry()
r.register("stub", StubCredentialStore(), fallback=False)
r.register("another", StubCredentialStore(), fallback=True)
self.assertEquals(["another", "stub"], r.keys())
def test_register_lazy(self):
r = config.CredentialStoreRegistry()
r.register_lazy("stub", "bzrlib.tests.test_config",
"StubCredentialStore", fallback=False)
self.assertEquals(["stub"], r.keys())
self.assertIsInstance(r.get_credential_store("stub"),
StubCredentialStore)
def test_is_fallback(self):
r = config.CredentialStoreRegistry()
r.register("stub1", None, fallback=False)
r.register("stub2", None, fallback=True)
self.assertEquals(False, r.is_fallback("stub1"))
self.assertEquals(True, r.is_fallback("stub2"))
def test_no_fallback(self):
r = config.CredentialStoreRegistry()
store = CountingCredentialStore()
r.register("count", store, fallback=False)
self.assertEquals(None,
r.get_fallback_credentials("http", "example.com"))
self.assertEquals(0, store._calls)
def test_fallback_credentials(self):
r = config.CredentialStoreRegistry()
store = StubCredentialStore()
store.add_credentials("http", "example.com",
"somebody", "geheim")
r.register("stub", store, fallback=True)
creds = r.get_fallback_credentials("http", "example.com")
self.assertEquals("somebody", creds["user"])
self.assertEquals("geheim", creds["password"])
def test_fallback_first_wins(self):
r = config.CredentialStoreRegistry()
stub1 = StubCredentialStore()
stub1.add_credentials("http", "example.com",
"somebody", "stub1")
r.register("stub1", stub1, fallback=True)
stub2 = StubCredentialStore()
stub2.add_credentials("http", "example.com",
"somebody", "stub2")
r.register("stub2", stub1, fallback=True)
creds = r.get_fallback_credentials("http", "example.com")
self.assertEquals("somebody", creds["user"])
self.assertEquals("stub1", creds["password"])
class TestPlainTextCredentialStore(tests.TestCase):
def test_decode_password(self):
r = config.credential_store_registry
plain_text = r.get_credential_store()
decoded = plain_text.decode_password(dict(password='secret'))
self.assertEquals('secret', decoded)
# FIXME: Once we have a way to declare authentication to all test servers, we
# can implement generic tests.
# test_user_password_in_url
# test_user_in_url_password_from_config
# test_user_in_url_password_prompted
# test_user_in_config
# test_user_getpass.getuser
# test_user_prompted ?
class TestAuthenticationRing(tests.TestCaseWithTransport):
pass
|