summaryrefslogtreecommitdiff
path: root/spec/unit/settings_spec.rb
blob: c40a01bbd7dfa88adb1f3d3acc7815529ed8fa20 (plain)
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
#! /usr/bin/env ruby
require 'spec_helper'
require 'ostruct'
require 'puppet/settings/errors'
require 'puppet_spec/files'
require 'matchers/resource'

describe Puppet::Settings do
  include PuppetSpec::Files
  include Matchers::Resource

  let(:main_config_file_default_location) do
    File.join(Puppet::Util::RunMode[:master].conf_dir, "puppet.conf")
  end

  let(:user_config_file_default_location) do
    File.join(Puppet::Util::RunMode[:user].conf_dir, "puppet.conf")
  end

  describe "when specifying defaults" do
    before do
      @settings = Puppet::Settings.new
    end

    it "should start with no defined parameters" do
      @settings.params.length.should == 0
    end

    it "should not allow specification of default values associated with a section as an array" do
      expect {
        @settings.define_settings(:section, :myvalue => ["defaultval", "my description"])
      }.to raise_error
    end

    it "should not allow duplicate parameter specifications" do
      @settings.define_settings(:section, :myvalue => { :default => "a", :desc => "b" })
      lambda { @settings.define_settings(:section, :myvalue => { :default => "c", :desc => "d" }) }.should raise_error(ArgumentError)
    end

    it "should allow specification of default values associated with a section as a hash" do
      @settings.define_settings(:section, :myvalue => {:default => "defaultval", :desc => "my description"})
    end

    it "should consider defined parameters to be valid" do
      @settings.define_settings(:section, :myvalue => { :default => "defaultval", :desc => "my description" })
      @settings.valid?(:myvalue).should be_true
    end

    it "should require a description when defaults are specified with a hash" do
      lambda { @settings.define_settings(:section, :myvalue => {:default => "a value"}) }.should raise_error(ArgumentError)
    end

    it "should support specifying owner, group, and mode when specifying files" do
      @settings.define_settings(:section, :myvalue => {:type => :file, :default => "/some/file", :owner => "service", :mode => "boo", :group => "service", :desc => "whatever"})
    end

    it "should support specifying a short name" do
      @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
    end

    it "should support specifying the setting type" do
      @settings.define_settings(:section, :myvalue => {:default => "/w", :desc => "b", :type => :string})
      @settings.setting(:myvalue).should be_instance_of(Puppet::Settings::StringSetting)
    end

    it "should fail if an invalid setting type is specified" do
      lambda { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :type => :foo}) }.should raise_error(ArgumentError)
    end

    it "should fail when short names conflict" do
      @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
      lambda { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"}) }.should raise_error(ArgumentError)
    end
  end


  describe "when initializing application defaults do" do
    let(:default_values) do
      values = {}
      PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS.keys.each do |key|
        values[key] = 'default value'
      end
      values
    end

    before do
      @settings = Puppet::Settings.new
      @settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
    end

    it "should fail if the app defaults hash is missing any required values" do
      incomplete_default_values = default_values.reject { |key, _| key == :confdir }
      expect {
        @settings.initialize_app_defaults(default_values.reject { |key, _| key == :confdir })
      }.to raise_error(Puppet::Settings::SettingsError)
    end

    # ultimately I'd like to stop treating "run_mode" as a normal setting, because it has so many special
    #  case behaviors / uses.  However, until that time... we need to make sure that our private run_mode=
    #  setter method gets properly called during app initialization.
    it "sets the preferred run mode when initializing the app defaults" do
      @settings.initialize_app_defaults(default_values.merge(:run_mode => :master))

      @settings.preferred_run_mode.should == :master
    end
  end

  describe "#call_hooks_deferred_to_application_initialization" do
    let(:good_default) { "yay" }
    let(:bad_default) { "$doesntexist" }
    before(:each) do
      @settings = Puppet::Settings.new
    end

    describe "when ignoring dependency interpolation errors" do
      let(:options) { {:ignore_interpolation_dependency_errors => true} }

      describe "if interpolation error" do
        it "should not raise an error" do
          hook_values = []
          @settings.define_settings(:section, :badhook => {:default => bad_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v  }})
          expect do
            @settings.send(:call_hooks_deferred_to_application_initialization, options)
          end.to_not raise_error
        end
      end
      describe "if no interpolation error" do
        it "should not raise an error" do
          hook_values = []
          @settings.define_settings(:section, :goodhook => {:default => good_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v  }})
          expect do
            @settings.send(:call_hooks_deferred_to_application_initialization, options)
          end.to_not raise_error
        end
      end
    end

    describe "when not ignoring dependency interpolation errors" do
      [ {}, {:ignore_interpolation_dependency_errors => false}].each do |options|
        describe "if interpolation error" do
          it "should raise an error" do
            hook_values = []
            @settings.define_settings(
              :section,
              :badhook => {
                :default => bad_default,
                :desc => "boo",
                :call_hook => :on_initialize_and_write,
                :hook => lambda { |v| hook_values << v }
              }
            )
            expect do
              @settings.send(:call_hooks_deferred_to_application_initialization, options)
            end.to raise_error(Puppet::Settings::InterpolationError)
          end
          it "should contain the setting name in error message" do
            hook_values = []
            @settings.define_settings(
              :section,
              :badhook => {
                :default => bad_default,
                :desc => "boo",
                :call_hook => :on_initialize_and_write,
                :hook => lambda { |v| hook_values << v }
              }
            )
            expect do
              @settings.send(:call_hooks_deferred_to_application_initialization, options)
            end.to raise_error(Puppet::Settings::InterpolationError, /badhook/)
          end
        end
        describe "if no interpolation error" do
          it "should not raise an error" do
            hook_values = []
            @settings.define_settings(
              :section,
              :goodhook => {
                :default => good_default,
                :desc => "boo",
                :call_hook => :on_initialize_and_write,
                :hook => lambda { |v| hook_values << v }
              }
            )
            expect do
              @settings.send(:call_hooks_deferred_to_application_initialization, options)
            end.to_not raise_error
          end
        end
      end
    end
  end

  describe "when setting values" do
    before do
      @settings = Puppet::Settings.new
      @settings.define_settings :main, :myval => { :default => "val", :desc => "desc" }
      @settings.define_settings :main, :bool => { :type => :boolean, :default => true, :desc => "desc" }
    end

    it "should provide a method for setting values from other objects" do
      @settings[:myval] = "something else"
      @settings[:myval].should == "something else"
    end

    it "should support a getopt-specific mechanism for setting values" do
      @settings.handlearg("--myval", "newval")
      @settings[:myval].should == "newval"
    end

    it "should support a getopt-specific mechanism for turning booleans off" do
      @settings.override_default(:bool, true)
      @settings.handlearg("--no-bool", "")
      @settings[:bool].should == false
    end

    it "should support a getopt-specific mechanism for turning booleans on" do
      # Turn it off first
      @settings.override_default(:bool, false)
      @settings.handlearg("--bool", "")
      @settings[:bool].should == true
    end

    it "should consider a cli setting with no argument to be a boolean" do
      # Turn it off first
      @settings.override_default(:bool, false)
      @settings.handlearg("--bool")
      @settings[:bool].should == true
    end

    it "should consider a cli setting with an empty string as an argument to be an empty argument, if the setting itself is not a boolean" do
      @settings.override_default(:myval, "bob")
      @settings.handlearg("--myval", "")
      @settings[:myval].should == ""
    end

    it "should consider a cli setting with a boolean as an argument to be a boolean" do
      # Turn it off first
      @settings.override_default(:bool, false)
      @settings.handlearg("--bool", "true")
      @settings[:bool].should == true
    end

    it "should not consider a cli setting of a non boolean with a boolean as an argument to be a boolean" do
      @settings.override_default(:myval, "bob")
      @settings.handlearg("--no-myval", "")
      @settings[:myval].should == ""
    end

    it "should flag string settings from the CLI" do
      @settings.handlearg("--myval", "12")
      @settings.set_by_cli?(:myval).should be_true
    end

    it "should flag bool settings from the CLI" do
      @settings.handlearg("--bool")
      @settings.set_by_cli?(:bool).should be_true
    end

    it "should not flag settings memory as from CLI" do
      @settings[:myval] = "12"
      @settings.set_by_cli?(:myval).should be_false
    end

    describe "setbycli" do
      it "should generate a deprecation warning" do
        Puppet.expects(:deprecation_warning).at_least(1)
        @settings.setting(:myval).setbycli = true
      end
      it "should set the value" do
        @settings[:myval] = "blah"
        @settings.setting(:myval).setbycli = true
        @settings.set_by_cli?(:myval).should be_true
      end
      it "should raise error if trying to unset value" do
        @settings.handlearg("--myval", "blah")
        expect do
          @settings.setting(:myval).setbycli = nil
        end.to raise_error(ArgumentError, /unset/)
      end
    end

    it "should clear the cache when setting getopt-specific values" do
      @settings.define_settings :mysection,
          :one => { :default => "whah", :desc => "yay" },
          :two => { :default => "$one yay", :desc => "bah" }
      @settings.expects(:unsafe_flush_cache)
      @settings[:two].should == "whah yay"
      @settings.handlearg("--one", "else")
      @settings[:two].should == "else yay"
    end

    it "should clear the cache when the preferred_run_mode is changed" do
      @settings.expects(:flush_cache)
      @settings.preferred_run_mode = :master
    end

    it "should not clear other values when setting getopt-specific values" do
      @settings[:myval] = "yay"
      @settings.handlearg("--no-bool", "")
      @settings[:myval].should == "yay"
    end

    it "should clear the list of used sections" do
      @settings.expects(:clearused)
      @settings[:myval] = "yay"
    end

    describe "call_hook" do
      Puppet::Settings::StringSetting.available_call_hook_values.each do |val|
        describe "when :#{val}" do
          describe "and definition invalid" do
            it "should raise error if no hook defined" do
              expect do
                @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => val})
              end.to raise_error(ArgumentError, /no :hook/)
            end
            it "should include the setting name in the error message" do
              expect do
                @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => val})
              end.to raise_error(ArgumentError, /for :hooker/)
            end
          end
          describe "and definition valid" do
            before(:each) do
              hook_values = []
              @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => val, :hook => lambda { |v| hook_values << v  }})
            end

            it "should call the hook when value written" do
              @settings.setting(:hooker).expects(:handle).with("something").once
              @settings[:hooker] = "something"
            end
          end
        end
      end

      it "should have a default value of :on_write_only" do
        @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v  }})
        @settings.setting(:hooker).call_hook.should == :on_write_only
      end

      describe "when nil" do
        it "should generate a warning" do
          Puppet.expects(:warning)
          @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v  }})
        end
        it "should use default" do
          @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v  }})
          @settings.setting(:hooker).call_hook.should == :on_write_only
        end
      end

      describe "when invalid" do
        it "should raise an error" do
          expect do
            @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :foo, :hook => lambda { |v| hook_values << v  }})
          end.to raise_error(ArgumentError, /invalid.*call_hook/i)
        end
      end

      describe "when :on_define_and_write" do
        it "should call the hook at definition" do
          hook_values = []
          @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v  }})
          @settings.setting(:hooker).call_hook.should == :on_define_and_write
          hook_values.should == %w{yay}
        end
      end

      describe "when :on_initialize_and_write" do
        before(:each) do
          @hook_values = []
          @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| @hook_values << v  }})
        end

        it "should not call the hook at definition" do
          @hook_values.should == []
          @hook_values.should_not == %w{yay}
        end

        it "should call the hook at initialization" do
          app_defaults = {}
          Puppet::Settings::REQUIRED_APP_SETTINGS.each do |key|
            app_defaults[key] = "foo"
          end
          app_defaults[:run_mode] = :user
          @settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)

          @settings.setting(:hooker).expects(:handle).with("yay").once

          @settings.initialize_app_defaults app_defaults
        end
      end
    end

    describe "call_on_define" do
      [true, false].each do |val|
        describe "to #{val}" do
          it "should generate a deprecation warning" do
            Puppet.expects(:deprecation_warning)
            values = []
            @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_on_define => val, :hook => lambda { |v| values << v }})
          end

          it "should should set call_hook" do
            values = []
            name = "hooker_#{val}".to_sym
            @settings.define_settings(:section, name => {:default => "yay", :desc => "boo", :call_on_define => val, :hook => lambda { |v| values << v }})

            @settings.setting(name).call_hook.should == :on_define_and_write if val
            @settings.setting(name).call_hook.should == :on_write_only unless val
          end
        end
      end
    end

    it "should call passed blocks when values are set" do
      values = []
      @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
      values.should == []

      @settings[:hooker] = "something"
      values.should == %w{something}
    end

    it "should call passed blocks when values are set via the command line" do
      values = []
      @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
      values.should == []

      @settings.handlearg("--hooker", "yay")

      values.should == %w{yay}
    end

    it "should provide an option to call passed blocks during definition" do
      values = []
      @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
      values.should == %w{yay}
    end

    it "should pass the fully interpolated value to the hook when called on definition" do
      values = []
      @settings.define_settings(:section, :one => { :default => "test", :desc => "a" })
      @settings.define_settings(:section, :hooker => {:default => "$one/yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
      values.should == %w{test/yay}
    end

    it "should munge values using the setting-specific methods" do
      @settings[:bool] = "false"
      @settings[:bool].should == false
    end

    it "should prefer values set in ruby to values set on the cli" do
      @settings[:myval] = "memarg"
      @settings.handlearg("--myval", "cliarg")

      @settings[:myval].should == "memarg"
    end

    it "should clear the list of environments" do
      Puppet::Node::Environment.expects(:clear).at_least(1)
      @settings[:myval] = "memarg"
    end

    it "should raise an error if we try to set a setting that hasn't been defined'" do
      lambda{
        @settings[:why_so_serious] = "foo"
      }.should raise_error(ArgumentError, /unknown setting/)
    end

    it "allows overriding cli args based on the cli-set value" do
      @settings.handlearg("--myval", "cliarg")
      @settings.set_value(:myval, "modified #{@settings[:myval]}", :cli)
      expect(@settings[:myval]).to eq("modified cliarg")
    end
  end

  describe "when returning values" do
    before do
      @settings = Puppet::Settings.new
      @settings.define_settings :section,
          :config => { :type => :file, :default => "/my/file", :desc => "eh" },
          :one    => { :default => "ONE", :desc => "a" },
          :two    => { :default => "$one TWO", :desc => "b"},
          :three  => { :default => "$one $two THREE", :desc => "c"},
          :four   => { :default => "$two $three FOUR", :desc => "d"},
          :five   => { :default => nil, :desc => "e" }
      Puppet::FileSystem.stubs(:exist?).returns true
    end

    describe "call_on_define" do
      it "should generate a deprecation warning" do
        Puppet.expects(:deprecation_warning)
        @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v  }})
        @settings.setting(:hooker).call_on_define
      end

      Puppet::Settings::StringSetting.available_call_hook_values.each do |val|
        it "should match value for call_hook => :#{val}" do
          hook_values = []
          @settings.define_settings(:section, :hooker => {:default => "yay", :desc => "boo", :call_hook => val, :hook => lambda { |v| hook_values << v  }})
          @settings.setting(:hooker).call_on_define.should == @settings.setting(:hooker).call_hook_on_define?
        end
      end
    end

    it "should provide a mechanism for returning set values" do
      @settings[:one] = "other"
      @settings[:one].should == "other"
    end

    it "setting a value to nil causes it to return to its default" do
      default_values = { :one => "skipped value" }
      [:logdir, :confdir, :vardir].each do |key|
        default_values[key] = 'default value'
      end
      @settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
      @settings.initialize_app_defaults(default_values)
      @settings[:one] = "value will disappear"

      @settings[:one] = nil

      @settings[:one].should == "ONE"
    end

    it "should interpolate default values for other parameters into returned parameter values" do
      @settings[:one].should == "ONE"
      @settings[:two].should == "ONE TWO"
      @settings[:three].should == "ONE ONE TWO THREE"
    end

    it "should interpolate default values that themselves need to be interpolated" do
      @settings[:four].should == "ONE TWO ONE ONE TWO THREE FOUR"
    end

    it "should provide a method for returning uninterpolated values" do
      @settings[:two] = "$one tw0"
      @settings.uninterpolated_value(:two).should  == "$one tw0"
      @settings.uninterpolated_value(:four).should == "$two $three FOUR"
    end

    it "should interpolate set values for other parameters into returned parameter values" do
      @settings[:one] = "on3"
      @settings[:two] = "$one tw0"
      @settings[:three] = "$one $two thr33"
      @settings[:four] = "$one $two $three f0ur"
      @settings[:one].should == "on3"
      @settings[:two].should == "on3 tw0"
      @settings[:three].should == "on3 on3 tw0 thr33"
      @settings[:four].should == "on3 on3 tw0 on3 on3 tw0 thr33 f0ur"
    end

    it "should not cache interpolated values such that stale information is returned" do
      @settings[:two].should == "ONE TWO"
      @settings[:one] = "one"
      @settings[:two].should == "one TWO"
    end

    it "should not cache values such that information from one environment is returned for another environment" do
      text = "[env1]\none = oneval\n[env2]\none = twoval\n"
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)

      @settings.value(:one, "env1").should == "oneval"
      @settings.value(:one, "env2").should == "twoval"
    end

    it "should have a run_mode that defaults to user" do
      @settings.preferred_run_mode.should == :user
    end

    it "interpolates a boolean false without raising an error" do
      @settings.define_settings(:section,
          :trip_wire => { :type => :boolean, :default => false, :desc => "a trip wire" },
          :tripping => { :default => '$trip_wire', :desc => "once tripped if interpolated was false" })
      @settings[:tripping].should == "false"
    end

    describe "setbycli" do
      it "should generate a deprecation warning" do
        @settings.handlearg("--one", "blah")
        Puppet.expects(:deprecation_warning)
        @settings.setting(:one).setbycli
      end
      it "should be true" do
        @settings.handlearg("--one", "blah")
        @settings.setting(:one).setbycli.should be_true
      end
    end
  end

  describe "when choosing which value to return" do
    before do
      @settings = Puppet::Settings.new
      @settings.define_settings :section,
        :config => { :type => :file, :default => "/my/file", :desc => "a" },
        :one => { :default => "ONE", :desc => "a" },
        :two => { :default => "TWO", :desc => "b" }
      Puppet::FileSystem.stubs(:exist?).returns true
      @settings.preferred_run_mode = :agent
    end

    it "should return default values if no values have been set" do
      @settings[:one].should == "ONE"
    end

    it "should return values set on the cli before values set in the configuration file" do
      text = "[main]\none = fileval\n"
      @settings.stubs(:read_file).returns(text)
      @settings.handlearg("--one", "clival")
      @settings.send(:parse_config_files)

      @settings[:one].should == "clival"
    end

    it "should return values set in the mode-specific section before values set in the main section" do
      text = "[main]\none = mainval\n[agent]\none = modeval\n"
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)

      @settings[:one].should == "modeval"
    end

    it "should not return values outside of its search path" do
      text = "[other]\none = oval\n"
      file = "/some/file"
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:one].should == "ONE"
    end

    it "should return values in a specified environment" do
      text = "[env]\none = envval\n"
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings.value(:one, "env").should == "envval"
    end

    it 'should use the current environment for $environment' do
      @settings.define_settings :main, :myval => { :default => "$environment/foo", :desc => "mydocs" }

      @settings.value(:myval, "myenv").should == "myenv/foo"
    end

    it "should interpolate found values using the current environment" do
      text = "[main]\none = mainval\n[myname]\none = nameval\ntwo = $one/two\n"
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)

      @settings.value(:two, "myname").should == "nameval/two"
    end

    it "should return values in a specified environment before values in the main or name sections" do
      text = "[env]\none = envval\n[main]\none = mainval\n[myname]\none = nameval\n"
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings.value(:one, "env").should == "envval"
    end

    context "when interpolating a dynamic environments setting" do
      let(:dynamic_manifestdir) { "manifestdir=/somewhere/$environment/manifests" }
      let(:environment) { "environment=anenv" }

      before(:each) do
        @settings.define_settings :main,
          :manifestdir => { :default => "/manifests", :desc => "manifestdir setting" },
          :environment => { :default => "production", :desc => "environment setting" }
      end

      it "interpolates default environment when no environment specified" do
        text = <<-EOF
[main]
#{dynamic_manifestdir}
        EOF
        @settings.stubs(:read_file).returns(text)
        @settings.send(:parse_config_files)
        expect(@settings.value(:manifestdir)).to eq("/somewhere/production/manifests")
      end

      it "interpolates the set environment when no environment specified" do
        text = <<-EOF
[main]
#{dynamic_manifestdir}
#{environment}
        EOF
        @settings.stubs(:read_file).returns(text)
        @settings.send(:parse_config_files)
        expect(@settings.value(:manifestdir)).to eq("/somewhere/anenv/manifests")
      end
    end
  end


  describe "when locating config files" do
    before do
      @settings = Puppet::Settings.new
    end

    describe "when root" do
      it "should look for the main config file default location config settings haven't been overridden'" do
        Puppet.features.stubs(:root?).returns(true)
        Puppet::FileSystem.expects(:exist?).with(main_config_file_default_location).returns(false)
        Puppet::FileSystem.expects(:exist?).with(user_config_file_default_location).never

        @settings.send(:parse_config_files)
      end
    end

    describe "when not root" do
      it "should look for user config file default location if config settings haven't been overridden'" do
        Puppet.features.stubs(:root?).returns(false)

        seq = sequence "load config files"
        Puppet::FileSystem.expects(:exist?).with(user_config_file_default_location).returns(false).in_sequence(seq)

        @settings.send(:parse_config_files)
      end
    end
  end

  describe "when parsing its configuration" do
    before do
      @settings = Puppet::Settings.new
      @settings.stubs(:service_user_available?).returns true
      @settings.stubs(:service_group_available?).returns true
      @file = make_absolute("/some/file")
      @userconfig = make_absolute("/test/userconfigfile")
      @settings.define_settings :section, :user => { :default => "suser", :desc => "doc" }, :group => { :default => "sgroup", :desc => "doc" }
      @settings.define_settings :section,
          :config => { :type => :file, :default => @file, :desc => "eh" },
          :one => { :default => "ONE", :desc => "a" },
          :two => { :default => "$one TWO", :desc => "b" },
          :three => { :default => "$one $two THREE", :desc => "c" }
      @settings.stubs(:user_config_file).returns(@userconfig)
      Puppet::FileSystem.stubs(:exist?).with(@file).returns true
      Puppet::FileSystem.stubs(:exist?).with(@userconfig).returns false
    end

    it "should not ignore the report setting" do
      @settings.define_settings :section, :report => { :default => "false", :desc => "a" }
      # This is needed in order to make sure we pass on windows
      myfile = File.expand_path(@file)
      @settings[:config] = myfile
      text = <<-CONF
        [puppetd]
          report=true
      CONF
      Puppet::FileSystem.expects(:exist?).with(myfile).returns(true)
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:report].should be_true
    end

    it "should use its current ':config' value for the file to parse" do
      myfile = make_absolute("/my/file") # do not stub expand_path here, as this leads to a stack overflow, when mocha tries to use it
      @settings[:config] = myfile

      Puppet::FileSystem.expects(:exist?).with(myfile).returns(true)

      Puppet::FileSystem.expects(:read).with(myfile).returns "[main]"

      @settings.send(:parse_config_files)
    end

    it "should not try to parse non-existent files" do
      Puppet::FileSystem.expects(:exist?).with(@file).returns false

      File.expects(:read).with(@file).never

      @settings.send(:parse_config_files)
    end

    it "should return values set in the configuration file" do
      text = "[main]
      one = fileval
      "
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:one].should == "fileval"
    end

    #484 - this should probably be in the regression area
    it "should not throw an exception on unknown parameters" do
      text = "[main]\nnosuchparam = mval\n"
      @settings.expects(:read_file).returns(text)
      lambda { @settings.send(:parse_config_files) }.should_not raise_error
    end

    it "should convert booleans in the configuration file into Ruby booleans" do
      text = "[main]
      one = true
      two = false
      "
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:one].should == true
      @settings[:two].should == false
    end

    it "should convert integers in the configuration file into Ruby Integers" do
      text = "[main]
      one = 65
      "
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:one].should == 65
    end

    it "should support specifying all metadata (owner, group, mode) in the configuration file" do
      @settings.define_settings :section, :myfile => { :type => :file, :default => make_absolute("/myfile"), :desc => "a" }

      otherfile = make_absolute("/other/file")
      @settings.parse_config(<<-CONF)
      [main]
      myfile = #{otherfile} {owner = service, group = service, mode = 644}
      CONF

      @settings[:myfile].should == otherfile
      @settings.metadata(:myfile).should == {:owner => "suser", :group => "sgroup", :mode => "644"}
    end

    it "should support specifying a single piece of metadata (owner, group, or mode) in the configuration file" do
      @settings.define_settings :section, :myfile => { :type => :file, :default => make_absolute("/myfile"), :desc => "a" }

      otherfile = make_absolute("/other/file")
      @settings.parse_config(<<-CONF)
      [main]
      myfile = #{otherfile} {owner = service}
      CONF

      @settings[:myfile].should == otherfile
      @settings.metadata(:myfile).should == {:owner => "suser"}
    end

    it "should support loading metadata (owner, group, or mode) from a run_mode section in the configuration file" do
      default_values = {}
      PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS.keys.each do |key|
        default_values[key] = 'default value'
      end
      @settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
      @settings.define_settings :master, :myfile => { :type => :file, :default => make_absolute("/myfile"), :desc => "a" }

      otherfile = make_absolute("/other/file")
      text = "[master]
      myfile = #{otherfile} {mode = 664}
      "
      @settings.expects(:read_file).returns(text)

      # will start initialization as user
      @settings.preferred_run_mode.should == :user
      @settings.send(:parse_config_files)

      # change app run_mode to master
      @settings.initialize_app_defaults(default_values.merge(:run_mode => :master))
      @settings.preferred_run_mode.should == :master

      # initializing the app should have reloaded the metadata based on run_mode
      @settings[:myfile].should == otherfile
      @settings.metadata(:myfile).should == {:mode => "664"}
    end

    it "does not use the metadata from the same setting in a different section" do
      default_values = {}
      PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS.keys.each do |key|
        default_values[key] = 'default value'
      end

      file = make_absolute("/file")
      default_mode = "0600"
      @settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
      @settings.define_settings :master, :myfile => { :type => :file, :default => file, :desc => "a", :mode => default_mode }

      text = "[master]
      myfile = #{file}/foo
      [agent]
      myfile = #{file} {mode = 664}
      "
      @settings.expects(:read_file).returns(text)

      # will start initialization as user
      @settings.preferred_run_mode.should == :user
      @settings.send(:parse_config_files)

      # change app run_mode to master
      @settings.initialize_app_defaults(default_values.merge(:run_mode => :master))
      @settings.preferred_run_mode.should == :master

      # initializing the app should have reloaded the metadata based on run_mode
      @settings[:myfile].should == "#{file}/foo"
      @settings.metadata(:myfile).should == { :mode => default_mode }
    end

    it "should call hooks associated with values set in the configuration file" do
      values = []
      @settings.define_settings :section, :mysetting => {:default => "defval", :desc => "a", :hook => proc { |v| values << v }}

      text = "[main]
      mysetting = setval
      "
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      values.should == ["setval"]
    end

    it "should not call the same hook for values set multiple times in the configuration file" do
      values = []
      @settings.define_settings :section, :mysetting => {:default => "defval", :desc => "a", :hook => proc { |v| values << v }}

      text = "[user]
      mysetting = setval
      [main]
      mysetting = other
      "
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      values.should == ["setval"]
    end

    it "should pass the environment-specific value to the hook when one is available" do
      values = []
      @settings.define_settings :section, :mysetting => {:default => "defval", :desc => "a", :hook => proc { |v| values << v }}
      @settings.define_settings :section, :environment => { :default => "yay", :desc => "a" }
      @settings.define_settings :section, :environments => { :default => "yay,foo", :desc => "a" }

      text = "[main]
      mysetting = setval
      [yay]
      mysetting = other
      "
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      values.should == ["other"]
    end

    it "should pass the interpolated value to the hook when one is available" do
      values = []
      @settings.define_settings :section, :base => {:default => "yay", :desc => "a", :hook => proc { |v| values << v }}
      @settings.define_settings :section, :mysetting => {:default => "defval", :desc => "a", :hook => proc { |v| values << v }}

      text = "[main]
      mysetting = $base/setval
      "
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      values.should == ["yay/setval"]
    end

    it "should allow hooks invoked at parse time to be deferred" do
      hook_invoked = false
      @settings.define_settings :section, :deferred  => {:desc => '',
                                                         :hook => proc { |v| hook_invoked = true },
                                                         :call_hook => :on_initialize_and_write, }

      @settings.define_settings(:main,
        :logdir       => { :type => :directory, :default => nil, :desc => "logdir" },
        :confdir      => { :type => :directory, :default => nil, :desc => "confdir" },
        :vardir       => { :type => :directory, :default => nil, :desc => "vardir" })

      text = <<-EOD
      [main]
      deferred=$confdir/goose
      EOD

      @settings.stubs(:read_file).returns(text)
      @settings.initialize_global_settings

      hook_invoked.should be_false

      @settings.initialize_app_defaults(:logdir => '/path/to/logdir', :confdir => '/path/to/confdir', :vardir => '/path/to/vardir')

      hook_invoked.should be_true
      @settings[:deferred].should eq(File.expand_path('/path/to/confdir/goose'))
    end

    it "does not require the value for a setting without a hook to resolve during global setup" do
      hook_invoked = false
      @settings.define_settings :section, :can_cause_problems  => {:desc => '' }

      @settings.define_settings(:main,
        :logdir       => { :type => :directory, :default => nil, :desc => "logdir" },
        :confdir      => { :type => :directory, :default => nil, :desc => "confdir" },
        :vardir       => { :type => :directory, :default => nil, :desc => "vardir" })

      text = <<-EOD
      [main]
      can_cause_problems=$confdir/goose
      EOD

      @settings.stubs(:read_file).returns(text)
      @settings.initialize_global_settings
      @settings.initialize_app_defaults(:logdir => '/path/to/logdir', :confdir => '/path/to/confdir', :vardir => '/path/to/vardir')

      @settings[:can_cause_problems].should eq(File.expand_path('/path/to/confdir/goose'))
    end

    it "should allow empty values" do
      @settings.define_settings :section, :myarg => { :default => "myfile", :desc => "a" }

      text = "[main]
      myarg =
      "
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:myarg].should == ""
    end

    describe "deprecations" do
      let(:settings) { Puppet::Settings.new }
      let(:app_defaults) {
        {
          :logdir     => "/dev/null",
          :confdir    => "/dev/null",
          :vardir     => "/dev/null",
        }
      }

      def assert_accessing_setting_is_deprecated(settings, setting)
        Puppet.expects(:deprecation_warning).with("Accessing '#{setting}' as a setting is deprecated. See http://links.puppetlabs.com/env-settings-deprecations")
        Puppet.expects(:deprecation_warning).with("Modifying '#{setting}' as a setting is deprecated. See http://links.puppetlabs.com/env-settings-deprecations")
        settings[setting.intern] = apath = File.expand_path('foo')
        expect(settings[setting.intern]).to eq(apath)
      end

      before(:each) do
        settings.define_settings(:main, {
          :logdir => { :default => 'a', :desc => 'a' },
          :confdir => { :default => 'b', :desc => 'b' },
          :vardir => { :default => 'c', :desc => 'c' },
        })
      end

      context "complete" do
        let(:completely_deprecated_settings) do
          settings.define_settings(:main, {
            :manifestdir => {
              :default => 'foo',
              :desc    => 'a deprecated setting',
              :deprecated => :completely,
            }
          })
          settings
        end

        it "warns when set in puppet.conf" do
          Puppet.expects(:deprecation_warning).with(regexp_matches(/manifestdir is deprecated\./), 'setting-manifestdir')

          completely_deprecated_settings.parse_config(<<-CONF)
            manifestdir='should warn'
          CONF
          completely_deprecated_settings.initialize_app_defaults(app_defaults)
        end

        it "warns when set on the commandline" do
          Puppet.expects(:deprecation_warning).with(regexp_matches(/manifestdir is deprecated\./), 'setting-manifestdir')

          args = ["--manifestdir", "/some/value"]
          completely_deprecated_settings.send(:parse_global_options, args)
          completely_deprecated_settings.initialize_app_defaults(app_defaults)
        end

        it "warns when set in code" do
          assert_accessing_setting_is_deprecated(completely_deprecated_settings, 'manifestdir')
        end
      end

      context "partial" do
        let(:partially_deprecated_settings) do
          settings.define_settings(:main, {
            :modulepath => {
              :default => 'foo',
              :desc    => 'a partially deprecated setting',
              :deprecated => :allowed_on_commandline,
            }
          })
          settings
        end

        it "warns for a deprecated setting allowed on the command line set in puppet.conf" do
          Puppet.expects(:deprecation_warning).with(regexp_matches(/modulepath is deprecated in puppet\.conf/), 'puppet-conf-setting-modulepath')
          partially_deprecated_settings.parse_config(<<-CONF)
            modulepath='should warn'
          CONF
          partially_deprecated_settings.initialize_app_defaults(app_defaults)
        end

        it "does not warn when manifest is set on command line" do
          Puppet.expects(:deprecation_warning).never

          args = ["--modulepath", "/some/value"]
          partially_deprecated_settings.send(:parse_global_options, args)
          partially_deprecated_settings.initialize_app_defaults(app_defaults)
        end

        it "warns when set in code" do
          assert_accessing_setting_is_deprecated(partially_deprecated_settings, 'modulepath')
        end
      end
    end
  end

  describe "when there are multiple config files" do
    let(:main_config_text) { "[main]\none = main\ntwo = main2" }
    let(:user_config_text) { "[main]\none = user\n" }
    let(:seq) { sequence "config_file_sequence" }

    before :each do
      @settings = Puppet::Settings.new
      @settings.define_settings(:section,
          { :confdir => { :default => nil,                    :desc => "Conf dir" },
            :config  => { :default => "$confdir/puppet.conf", :desc => "Config" },
            :one     => { :default => "ONE",                  :desc => "a" },
            :two     => { :default => "TWO",                  :desc => "b" }, })
    end

    context "running non-root without explicit config file" do
      before :each do
        Puppet.features.stubs(:root?).returns(false)
        Puppet::FileSystem.expects(:exist?).
          with(user_config_file_default_location).
          returns(true).in_sequence(seq)
        @settings.expects(:read_file).
          with(user_config_file_default_location).
          returns(user_config_text).in_sequence(seq)
      end

      it "should return values from the user config file" do
        @settings.send(:parse_config_files)
        @settings[:one].should == "user"
      end

      it "should not return values from the main config file" do
        @settings.send(:parse_config_files)
        @settings[:two].should == "TWO"
      end
    end

    context "running as root without explicit config file" do
      before :each do
        Puppet.features.stubs(:root?).returns(true)
        Puppet::FileSystem.expects(:exist?).
          with(main_config_file_default_location).
          returns(true).in_sequence(seq)
        @settings.expects(:read_file).
          with(main_config_file_default_location).
          returns(main_config_text).in_sequence(seq)
      end

      it "should return values from the main config file" do
        @settings.send(:parse_config_files)
        @settings[:one].should == "main"
      end

      it "should not return values from the user config file" do
        @settings.send(:parse_config_files)
        @settings[:two].should == "main2"
      end
    end

    context "running with an explicit config file as a user (e.g. Apache + Passenger)" do
      before :each do
        Puppet.features.stubs(:root?).returns(false)
        @settings[:confdir] = File.dirname(main_config_file_default_location)
        Puppet::FileSystem.expects(:exist?).
          with(main_config_file_default_location).
          returns(true).in_sequence(seq)
        @settings.expects(:read_file).
          with(main_config_file_default_location).
          returns(main_config_text).in_sequence(seq)
      end

      it "should return values from the main config file" do
        @settings.send(:parse_config_files)
        @settings[:one].should == "main"
      end

      it "should not return values from the user config file" do
        @settings.send(:parse_config_files)
        @settings[:two].should == "main2"
      end
    end
  end

  describe "when reparsing its configuration" do
    before do
      @file = make_absolute("/test/file")
      @userconfig = make_absolute("/test/userconfigfile")
      @settings = Puppet::Settings.new
      @settings.define_settings :section,
          :config => { :type => :file, :default => @file, :desc => "a" },
          :one => { :default => "ONE", :desc => "a" },
          :two => { :default => "$one TWO", :desc => "b" },
          :three => { :default => "$one $two THREE", :desc => "c" }
      Puppet::FileSystem.stubs(:exist?).with(@file).returns true
      Puppet::FileSystem.stubs(:exist?).with(@userconfig).returns false
      @settings.stubs(:user_config_file).returns(@userconfig)
    end

    it "does not create the WatchedFile instance and should not parse if the file does not exist" do
      Puppet::FileSystem.expects(:exist?).with(@file).returns false
      Puppet::Util::WatchedFile.expects(:new).never

      @settings.expects(:parse_config_files).never

      @settings.reparse_config_files
    end

    context "and watched file exists" do
      before do
        @watched_file = Puppet::Util::WatchedFile.new(@file)
        Puppet::Util::WatchedFile.expects(:new).with(@file).returns @watched_file
      end

      it "uses a WatchedFile instance to determine if the file has changed" do
        @watched_file.expects(:changed?)

        @settings.reparse_config_files
      end

      it "does not reparse if the file has not changed" do
        @watched_file.expects(:changed?).returns false

        @settings.expects(:parse_config_files).never

        @settings.reparse_config_files
      end

      it "reparses if the file has changed" do
        @watched_file.expects(:changed?).returns true

        @settings.expects(:parse_config_files)

        @settings.reparse_config_files
      end

      it "replaces in-memory values with on-file values" do
        @watched_file.stubs(:changed?).returns(true)
        @settings[:one] = "init"

        # Now replace the value
        text = "[main]\none = disk-replace\n"
        @settings.stubs(:read_file).returns(text)
        @settings.reparse_config_files
        @settings[:one].should == "disk-replace"
      end
    end

    it "should retain parameters set by cli when configuration files are reparsed" do
      @settings.handlearg("--one", "clival")

      text = "[main]\none = on-disk\n"
      @settings.stubs(:read_file).returns(text)
      @settings.send(:parse_config_files)

      @settings[:one].should == "clival"
    end

    it "should remove in-memory values that are no longer set in the file" do
      # Init the value
      text = "[main]\none = disk-init\n"
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:one].should == "disk-init"

      # Now replace the value
      text = "[main]\ntwo = disk-replace\n"
      @settings.expects(:read_file).returns(text)
      @settings.send(:parse_config_files)

      # The originally-overridden value should be replaced with the default
      @settings[:one].should == "ONE"

      # and we should now have the new value in memory
      @settings[:two].should == "disk-replace"
    end

    it "should retain in-memory values if the file has a syntax error" do
      # Init the value
      text = "[main]\none = initial-value\n"
      @settings.expects(:read_file).with(@file).returns(text)
      @settings.send(:parse_config_files)
      @settings[:one].should == "initial-value"

      # Now replace the value with something bogus
      text = "[main]\nkenny = killed-by-what-follows\n1 is 2, blah blah florp\n"
      @settings.expects(:read_file).with(@file).returns(text)
      @settings.send(:parse_config_files)

      # The originally-overridden value should not be replaced with the default
      @settings[:one].should == "initial-value"

      # and we should not have the new value in memory
      @settings[:kenny].should be_nil
    end
  end

  it "should provide a method for creating a catalog of resources from its configuration" do
    Puppet::Settings.new.should respond_to(:to_catalog)
  end

  describe "when creating a catalog" do
    before do
      @settings = Puppet::Settings.new
      @settings.stubs(:service_user_available?).returns true
      @prefix = Puppet.features.posix? ? "" : "C:"
    end

    it "should add all file resources to the catalog if no sections have been specified" do
      @settings.define_settings :main,
          :maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a"},
          :seconddir => { :type => :directory, :default => @prefix+"/seconddir", :desc => "a"}
      @settings.define_settings :other,
          :otherdir => { :type => :directory, :default => @prefix+"/otherdir", :desc => "a" }

      catalog = @settings.to_catalog

      [@prefix+"/maindir", @prefix+"/seconddir", @prefix+"/otherdir"].each do |path|
        catalog.resource(:file, path).should be_instance_of(Puppet::Resource)
      end
    end

    it "should add only files in the specified sections if section names are provided" do
      @settings.define_settings :main, :maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
      @settings.define_settings :other, :otherdir => { :type => :directory, :default => @prefix+"/otherdir", :desc => "a" }
      catalog = @settings.to_catalog(:main)
      catalog.resource(:file, @prefix+"/otherdir").should be_nil
      catalog.resource(:file, @prefix+"/maindir").should be_instance_of(Puppet::Resource)
    end

    it "should not try to add the same file twice" do
      @settings.define_settings :main, :maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
      @settings.define_settings :other, :otherdir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
      lambda { @settings.to_catalog }.should_not raise_error
    end

    it "should ignore files whose :to_resource method returns nil" do
      @settings.define_settings :main, :maindir => { :type => :directory, :default => @prefix+"/maindir", :desc => "a" }
      @settings.setting(:maindir).expects(:to_resource).returns nil

      Puppet::Resource::Catalog.any_instance.expects(:add_resource).never
      @settings.to_catalog
    end

    it "should ignore manifestdir if environmentpath is set" do
      @settings.define_settings :main,
        :manifestdir => { :type => :directory, :default => @prefix+"/manifestdir", :desc => "a" },
        :environmentpath => { :type => :path, :default => @prefix+"/envs", :desc => "a" }

      catalog = @settings.to_catalog(:main)

      expect(catalog).to_not have_resource("File[#{@prefix}/manifestdir]")
    end

    describe "on Microsoft Windows" do
      before :each do
        Puppet.features.stubs(:root?).returns true
        Puppet.features.stubs(:microsoft_windows?).returns true

        @settings.define_settings :foo,
            :mkusers => { :type => :boolean, :default => true, :desc => "e" },
            :user => { :default => "suser", :desc => "doc" },
            :group => { :default => "sgroup", :desc => "doc" }
        @settings.define_settings :other,
            :otherdir => { :type => :directory, :default => "/otherdir", :desc => "a", :owner => "service", :group => "service"}

        @catalog = @settings.to_catalog
      end

      it "it should not add users and groups to the catalog" do
        @catalog.resource(:user, "suser").should be_nil
        @catalog.resource(:group, "sgroup").should be_nil
      end
    end

    describe "adding default directory environment to the catalog" do
      let(:tmpenv) { tmpdir("envs") }
      let(:default_path) { "#{tmpenv}/environments" }
      before(:each) do
        @settings.define_settings :main,
          :environment     => { :default => "production", :desc => "env"},
          :environmentpath => { :type => :path, :default => default_path, :desc => "envpath"}
      end

      it "adds if environmentpath exists" do
        envpath = "#{tmpenv}/custom_envpath"
        @settings[:environmentpath] = envpath
        Dir.mkdir(envpath)
        catalog = @settings.to_catalog
        expect(catalog.resource_keys).to include(["File", "#{envpath}/production"])
      end

      it "adds the first directory of environmentpath" do
        envdir = "#{tmpenv}/custom_envpath"
        envpath = "#{envdir}#{File::PATH_SEPARATOR}/some/other/envdir"
        @settings[:environmentpath] = envpath
        Dir.mkdir(envdir)
        catalog = @settings.to_catalog
        expect(catalog.resource_keys).to include(["File", "#{envdir}/production"])
      end

      it "handles a non-existent environmentpath" do
        catalog = @settings.to_catalog
        expect(catalog.resource_keys).to be_empty
      end

      it "handles a default environmentpath" do
        Dir.mkdir(default_path)
        catalog = @settings.to_catalog
        expect(catalog.resource_keys).to include(["File", "#{default_path}/production"])
      end

      it "does not add if the path to the default directory environment exists as a symlink", :if => Puppet.features.manages_symlinks? do
        Dir.mkdir(default_path)
        Puppet::FileSystem.symlink("#{tmpenv}/nowhere", File.join(default_path, 'production'))
        catalog = @settings.to_catalog
        expect(catalog.resource_keys).to_not include(["File", "#{default_path}/production"])
      end
    end

    describe "when adding users and groups to the catalog" do
      before do
        Puppet.features.stubs(:root?).returns true
        Puppet.features.stubs(:microsoft_windows?).returns false

        @settings.define_settings :foo,
            :mkusers => { :type => :boolean, :default => true, :desc => "e" },
            :user => { :default => "suser", :desc => "doc" },
            :group => { :default => "sgroup", :desc => "doc" }
        @settings.define_settings :other, :otherdir => {:type => :directory, :default => "/otherdir", :desc => "a", :owner => "service", :group => "service"}

        @catalog = @settings.to_catalog
      end

      it "should add each specified user and group to the catalog if :mkusers is a valid setting, is enabled, and we're running as root" do
        @catalog.resource(:user, "suser").should be_instance_of(Puppet::Resource)
        @catalog.resource(:group, "sgroup").should be_instance_of(Puppet::Resource)
      end

      it "should only add users and groups to the catalog from specified sections" do
        @settings.define_settings :yay, :yaydir => { :type => :directory, :default => "/yaydir", :desc => "a", :owner => "service", :group => "service"}
        catalog = @settings.to_catalog(:other)
        catalog.resource(:user, "jane").should be_nil
        catalog.resource(:group, "billy").should be_nil
      end

      it "should not add users or groups to the catalog if :mkusers not running as root" do
        Puppet.features.stubs(:root?).returns false

        catalog = @settings.to_catalog
        catalog.resource(:user, "suser").should be_nil
        catalog.resource(:group, "sgroup").should be_nil
      end

      it "should not add users or groups to the catalog if :mkusers is not a valid setting" do
        Puppet.features.stubs(:root?).returns true
        settings = Puppet::Settings.new
        settings.define_settings :other, :otherdir => {:type => :directory, :default => "/otherdir", :desc => "a", :owner => "service", :group => "service"}

        catalog = settings.to_catalog
        catalog.resource(:user, "suser").should be_nil
        catalog.resource(:group, "sgroup").should be_nil
      end

      it "should not add users or groups to the catalog if :mkusers is a valid setting but is disabled" do
        @settings[:mkusers] = false

        catalog = @settings.to_catalog
        catalog.resource(:user, "suser").should be_nil
        catalog.resource(:group, "sgroup").should be_nil
      end

      it "should not try to add users or groups to the catalog twice" do
        @settings.define_settings :yay, :yaydir => {:type => :directory, :default => "/yaydir", :desc => "a", :owner => "service", :group => "service"}

        # This would fail if users/groups were added twice
        lambda { @settings.to_catalog }.should_not raise_error
      end

      it "should set :ensure to :present on each created user and group" do
        @catalog.resource(:user, "suser")[:ensure].should == :present
        @catalog.resource(:group, "sgroup")[:ensure].should == :present
      end

      it "should set each created user's :gid to the service group" do
        @settings.to_catalog.resource(:user, "suser")[:gid].should == "sgroup"
      end

      it "should not attempt to manage the root user" do
        Puppet.features.stubs(:root?).returns true
        @settings.define_settings :foo, :foodir => {:type => :directory, :default => "/foodir", :desc => "a", :owner => "root", :group => "service"}

        @settings.to_catalog.resource(:user, "root").should be_nil
      end
    end
  end

  it "should be able to be converted to a manifest" do
    Puppet::Settings.new.should respond_to(:to_manifest)
  end

  describe "when being converted to a manifest" do
    it "should produce a string with the code for each resource joined by two carriage returns" do
      @settings = Puppet::Settings.new
      @settings.define_settings :main,
          :maindir => { :type => :directory, :default => "/maindir", :desc => "a"},
          :seconddir => { :type => :directory, :default => "/seconddir", :desc => "a"}

      main = stub 'main_resource', :ref => "File[/maindir]"
      main.expects(:to_manifest).returns "maindir"
      second = stub 'second_resource', :ref => "File[/seconddir]"
      second.expects(:to_manifest).returns "seconddir"
      @settings.setting(:maindir).expects(:to_resource).returns main
      @settings.setting(:seconddir).expects(:to_resource).returns second

      @settings.to_manifest.split("\n\n").sort.should == %w{maindir seconddir}
    end
  end

  describe "when using sections of the configuration to manage the local host" do
    before do
      @settings = Puppet::Settings.new
      @settings.stubs(:service_user_available?).returns true
      @settings.stubs(:service_group_available?).returns true
      @settings.define_settings :main, :noop => { :default => false, :desc => "", :type => :boolean }
      @settings.define_settings :main,
          :maindir => { :type => :directory, :default => make_absolute("/maindir"), :desc => "a" },
          :seconddir => { :type => :directory, :default => make_absolute("/seconddir"), :desc => "a"}
      @settings.define_settings :main, :user => { :default => "suser", :desc => "doc" }, :group => { :default => "sgroup", :desc => "doc" }
      @settings.define_settings :other, :otherdir => {:type => :directory, :default => make_absolute("/otherdir"), :desc => "a", :owner => "service", :group => "service", :mode => '0755'}
      @settings.define_settings :third, :thirddir => { :type => :directory, :default => make_absolute("/thirddir"), :desc => "b"}
      @settings.define_settings :files, :myfile => {:type => :file, :default => make_absolute("/myfile"), :desc => "a", :mode => '0755'}
    end

    it "should provide a method that creates directories with the correct modes" do
      Puppet::Util::SUIDManager.expects(:asuser).with("suser", "sgroup").yields
      Dir.expects(:mkdir).with(make_absolute("/otherdir"), '0755')
      @settings.mkdir(:otherdir)
    end

    it "should create a catalog with the specified sections" do
      @settings.expects(:to_catalog).with(:main, :other).returns Puppet::Resource::Catalog.new("foo")
      @settings.use(:main, :other)
    end

    it "should canonicalize the sections" do
      @settings.expects(:to_catalog).with(:main, :other).returns Puppet::Resource::Catalog.new("foo")
      @settings.use("main", "other")
    end

    it "should ignore sections that have already been used" do
      @settings.expects(:to_catalog).with(:main).returns Puppet::Resource::Catalog.new("foo")
      @settings.use(:main)
      @settings.expects(:to_catalog).with(:other).returns Puppet::Resource::Catalog.new("foo")
      @settings.use(:main, :other)
    end

    it "should convert the created catalog to a RAL catalog" do
      @catalog = Puppet::Resource::Catalog.new("foo")
      @settings.expects(:to_catalog).with(:main).returns @catalog

      @catalog.expects(:to_ral).returns @catalog
      @settings.use(:main)
    end

    it "should specify that it is not managing a host catalog" do
      catalog = Puppet::Resource::Catalog.new("foo")
      catalog.expects(:apply)
      @settings.expects(:to_catalog).returns catalog

      catalog.stubs(:to_ral).returns catalog

      catalog.expects(:host_config=).with false

      @settings.use(:main)
    end

    it "should support a method for re-using all currently used sections" do
      @settings.expects(:to_catalog).with(:main, :third).times(2).returns Puppet::Resource::Catalog.new("foo")

      @settings.use(:main, :third)
      @settings.reuse
    end

    it "should fail with an appropriate message if any resources fail" do
      @catalog = Puppet::Resource::Catalog.new("foo")
      @catalog.stubs(:to_ral).returns @catalog
      @settings.expects(:to_catalog).returns @catalog

      @trans = mock("transaction")
      @catalog.expects(:apply).yields(@trans)

      @trans.expects(:any_failed?).returns(true)

      resource = Puppet::Type.type(:notify).new(:title => 'failed')
      status = Puppet::Resource::Status.new(resource)
      event = Puppet::Transaction::Event.new(
        :name => 'failure',
        :status => 'failure',
        :message => 'My failure')
      status.add_event(event)

      report = Puppet::Transaction::Report.new('apply')
      report.add_resource_status(status)

      @trans.expects(:report).returns report

      @settings.expects(:raise).with(includes("My failure"))
      @settings.use(:whatever)
    end
  end

  describe "when dealing with printing configs" do
    before do
      @settings = Puppet::Settings.new
      #these are the magic default values
      @settings.stubs(:value).with(:configprint).returns("")
      @settings.stubs(:value).with(:genconfig).returns(false)
      @settings.stubs(:value).with(:genmanifest).returns(false)
      @settings.stubs(:value).with(:environment).returns(nil)
    end

    describe "when checking print_config?" do
      it "should return false when the :configprint, :genconfig and :genmanifest are not set" do
        @settings.print_configs?.should be_false
      end

      it "should return true when :configprint has a value" do
        @settings.stubs(:value).with(:configprint).returns("something")
        @settings.print_configs?.should be_true
      end

      it "should return true when :genconfig has a value" do
        @settings.stubs(:value).with(:genconfig).returns(true)
        @settings.print_configs?.should be_true
      end

      it "should return true when :genmanifest has a value" do
        @settings.stubs(:value).with(:genmanifest).returns(true)
        @settings.print_configs?.should be_true
      end
    end

    describe "when printing configs" do
      describe "when :configprint has a value" do
        it "should call print_config_options" do
          @settings.stubs(:value).with(:configprint).returns("something")
          @settings.expects(:print_config_options)
          @settings.print_configs
        end

        it "should get the value of the option using the environment" do
          @settings.stubs(:value).with(:configprint).returns("something")
          @settings.stubs(:include?).with("something").returns(true)
          @settings.expects(:value).with(:environment).returns("env")
          @settings.expects(:value).with("something", "env").returns("foo")
          @settings.stubs(:puts).with("foo")
          @settings.print_configs
        end

        it "should print the value of the option" do
          @settings.stubs(:value).with(:configprint).returns("something")
          @settings.stubs(:include?).with("something").returns(true)
          @settings.stubs(:value).with("something", nil).returns("foo")
          @settings.expects(:puts).with("foo")
          @settings.print_configs
        end

        it "should print the value pairs if there are multiple options" do
          @settings.stubs(:value).with(:configprint).returns("bar,baz")
          @settings.stubs(:include?).with("bar").returns(true)
          @settings.stubs(:include?).with("baz").returns(true)
          @settings.stubs(:value).with("bar", nil).returns("foo")
          @settings.stubs(:value).with("baz", nil).returns("fud")
          @settings.expects(:puts).with("bar = foo")
          @settings.expects(:puts).with("baz = fud")
          @settings.print_configs
        end

        it "should return true after printing" do
          @settings.stubs(:value).with(:configprint).returns("something")
          @settings.stubs(:include?).with("something").returns(true)
          @settings.stubs(:value).with("something", nil).returns("foo")
          @settings.stubs(:puts).with("foo")
          @settings.print_configs.should be_true
        end

        it "should return false if a config param is not found" do
          @settings.stubs :puts
          @settings.stubs(:value).with(:configprint).returns("something")
          @settings.stubs(:include?).with("something").returns(false)
          @settings.print_configs.should be_false
        end
      end

      describe "when genconfig is true" do
        before do
          @settings.stubs :puts
        end

        it "should call to_config" do
          @settings.stubs(:value).with(:genconfig).returns(true)
          @settings.expects(:to_config)
          @settings.print_configs
        end

        it "should return true from print_configs" do
          @settings.stubs(:value).with(:genconfig).returns(true)
          @settings.stubs(:to_config)
          @settings.print_configs.should be_true
        end
      end

      describe "when genmanifest is true" do
        before do
          @settings.stubs :puts
        end

        it "should call to_config" do
          @settings.stubs(:value).with(:genmanifest).returns(true)
          @settings.expects(:to_manifest)
          @settings.print_configs
        end

        it "should return true from print_configs" do
          @settings.stubs(:value).with(:genmanifest).returns(true)
          @settings.stubs(:to_manifest)
          @settings.print_configs.should be_true
        end
      end
    end
  end

  describe "when determining if the service user is available" do
    let(:settings) do
      settings = Puppet::Settings.new
      settings.define_settings :main, :user => { :default => nil, :desc => "doc" }
      settings
    end

    def a_user_type_for(username)
      user = mock 'user'
      Puppet::Type.type(:user).expects(:new).with { |args| args[:name] == username }.returns user
      user
    end

    it "should return false if there is no user setting" do
      settings.should_not be_service_user_available
    end

    it "should return false if the user provider says the user is missing" do
      settings[:user] = "foo"

      a_user_type_for("foo").expects(:exists?).returns false

      settings.should_not be_service_user_available
    end

    it "should return true if the user provider says the user is present" do
      settings[:user] = "foo"

      a_user_type_for("foo").expects(:exists?).returns true

      settings.should be_service_user_available
    end

    it "caches the result of determining if the user is present" do
      settings[:user] = "foo"

      a_user_type_for("foo").expects(:exists?).returns true
      settings.should be_service_user_available

      settings.should be_service_user_available
    end
  end

  describe "when determining if the service group is available" do
    let(:settings) do
      settings = Puppet::Settings.new
      settings.define_settings :main, :group => { :default => nil, :desc => "doc" }
      settings
    end

    def a_group_type_for(groupname)
      group = mock 'group'
      Puppet::Type.type(:group).expects(:new).with { |args| args[:name] == groupname }.returns group
      group
    end

    it "should return false if there is no group setting" do
      settings.should_not be_service_group_available
    end

    it "should return false if the group provider says the group is missing" do
      settings[:group] = "foo"

      a_group_type_for("foo").expects(:exists?).returns false

      settings.should_not be_service_group_available
    end

    it "should return true if the group provider says the group is present" do
      settings[:group] = "foo"

      a_group_type_for("foo").expects(:exists?).returns true

      settings.should be_service_group_available
    end

    it "caches the result of determining if the group is present" do
      settings[:group] = "foo"

      a_group_type_for("foo").expects(:exists?).returns true
      settings.should be_service_group_available

      settings.should be_service_group_available
    end
  end

  describe "when dealing with command-line options" do
    let(:settings) { Puppet::Settings.new }

    it "should get options from Puppet.settings.optparse_addargs" do
      settings.expects(:optparse_addargs).returns([])

      settings.send(:parse_global_options, [])
    end

    it "should add options to OptionParser" do
      settings.stubs(:optparse_addargs).returns( [["--option","-o", "Funny Option", :NONE]])
      settings.expects(:handlearg).with("--option", true)
      settings.send(:parse_global_options, ["--option"])
    end

    it "should not die if it sees an unrecognized option, because the app/face may handle it later" do
      expect { settings.send(:parse_global_options, ["--topuppet", "value"]) } .to_not raise_error
    end

    it "should not pass an unrecognized option to handleargs" do
      settings.expects(:handlearg).with("--topuppet", "value").never
      expect { settings.send(:parse_global_options, ["--topuppet", "value"]) } .to_not raise_error
    end

    it "should pass valid puppet settings options to handlearg even if they appear after an unrecognized option" do
      settings.stubs(:optparse_addargs).returns( [["--option","-o", "Funny Option", :NONE]])
      settings.expects(:handlearg).with("--option", true)
      settings.send(:parse_global_options, ["--invalidoption", "--option"])
    end

    it "should transform boolean option to normal form" do
      Puppet::Settings.clean_opt("--[no-]option", true).should == ["--option", true]
    end

    it "should transform boolean option to no- form" do
      Puppet::Settings.clean_opt("--[no-]option", false).should == ["--no-option", false]
    end

    it "should set preferred run mode from --run_mode <foo> string without error" do
      args = ["--run_mode", "master"]
      settings.expects(:handlearg).with("--run_mode", "master").never
      expect { settings.send(:parse_global_options, args) } .to_not raise_error
      Puppet.settings.preferred_run_mode.should == :master
      args.empty?.should == true
    end

    it "should set preferred run mode from --run_mode=<foo> string without error" do
      args = ["--run_mode=master"]
      settings.expects(:handlearg).with("--run_mode", "master").never
      expect { settings.send(:parse_global_options, args) } .to_not raise_error
      Puppet.settings.preferred_run_mode.should == :master
      args.empty?.should == true
    end
  end

  describe "default_certname" do
    describe "using hostname and domainname" do
      before :each do
        Puppet::Settings.stubs(:hostname_fact).returns("testhostname")
        Puppet::Settings.stubs(:domain_fact).returns("domain.test.")
      end

      it "should use both to generate fqdn" do
        Puppet::Settings.default_certname.should =~ /testhostname\.domain\.test/
      end
      it "should remove trailing dots from fqdn" do
        Puppet::Settings.default_certname.should == 'testhostname.domain.test'
      end
    end

    describe "using just hostname" do
      before :each do
        Puppet::Settings.stubs(:hostname_fact).returns("testhostname")
        Puppet::Settings.stubs(:domain_fact).returns("")
      end

      it "should use only hostname to generate fqdn" do
        Puppet::Settings.default_certname.should == "testhostname"
      end
      it "should removing trailing dots from fqdn" do
        Puppet::Settings.default_certname.should == "testhostname"
      end
    end
  end
end