File: lookup_spec.rb

package info (click to toggle)
puppet 5.5.22-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 21,316 kB
  • sloc: ruby: 254,925; sh: 1,608; xml: 219; makefile: 153; sql: 103
file content (3351 lines) | stat: -rw-r--r-- 126,314 bytes parent folder | download
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
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet_spec/files'
require 'puppet/pops'
require 'deep_merge/core'

describe "The lookup function" do
  include PuppetSpec::Compiler
  include PuppetSpec::Files

  let(:env_name) { 'spec' }
  let(:code_dir_files) { {} }
  let(:code_dir) { tmpdir('code') }
  let(:ruby_dir) { tmpdir('ruby') }
  let(:env_modules) { {} }
  let(:env_hiera_yaml) do
    <<-YAML.unindent
      ---
      version: 5
      hierarchy:
        - name: "Common"
          data_hash: yaml_data
          path: "common.yaml"
      YAML
  end

  let(:env_data) { {} }

  let(:environment_files) do
    {
      env_name => {
        'modules' => env_modules,
        'hiera.yaml' => env_hiera_yaml,
        'data' => env_data
      }
    }
  end

  let(:ruby_dir_files) { {} }

  let(:logs) { [] }
  let(:scope_additions ) { {} }
  let(:notices) { logs.select { |log| log.level == :notice }.map { |log| log.message } }
  let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
  let(:debugs) { logs.select { |log| log.level == :debug }.map { |log| log.message } }
  let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, env_name, 'modules')]) }
  let(:environments) { Puppet::Environments::Directories.new(populated_env_dir, []) }
  let(:node) { Puppet::Node.new('test_lookup', :environment => env) }
  let(:compiler) { Puppet::Parser::Compiler.new(node) }
  let(:lookup_func) { Puppet.lookup(:loaders).puppet_system_loader.load(:function, 'lookup') }
  let(:invocation_with_explain) { Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true) }
  let(:explanation) { invocation_with_explain.explainer.explain }

  let(:populated_code_dir) do
    dir_contained_in(code_dir, code_dir_files)
    code_dir
  end

  let(:populated_ruby_dir) do
    dir_contained_in(ruby_dir, ruby_dir_files)
    ruby_dir
  end

  let(:env_dir) do
    d = File.join(populated_code_dir, 'environments')
    Dir.mkdir(d)
    d
  end

  let(:populated_env_dir) do
    dir_contained_in(env_dir, environment_files)
    env_dir
  end

  before(:each) do
    Puppet.settings[:codedir] = code_dir
    Puppet.push_context(:environments => environments, :current_environment => env)
  end

  after(:each) do
    Puppet.pop_context
    if Object.const_defined?(:Hiera)
      Hiera.send(:remove_instance_variable, :@config) if Hiera.instance_variable_defined?(:@config)
      Hiera.send(:remove_instance_variable, :@logger) if Hiera.instance_variable_defined?(:@logger)
      if Hiera.const_defined?(:Config)
        Hiera::Config.send(:remove_instance_variable, :@config) if Hiera::Config.instance_variable_defined?(:@config)
      end
      if Hiera.const_defined?(:Backend) && Hiera::Backend.respond_to?(:clear!)
        Hiera::Backend.clear!
      end
    end
  end

  def collect_notices(code, explain = false, &block)
    Puppet[:code] = code
    Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
      scope = compiler.topscope
      scope['domain'] = 'example.com'
      scope_additions.each_pair { |k, v| scope[k] = v }
      if explain
        begin
          invocation_with_explain.lookup('dummy', nil) do
            if block_given?
              compiler.compile { |catalog| block.call(compiler.topscope); catalog }
            else
              compiler.compile
            end
          end
        rescue RuntimeError => e
          invocation_with_explain.report_text { e.message }
        end
      else
        if block_given?
          compiler.compile { |catalog| block.call(compiler.topscope); catalog }
        else
          compiler.compile
        end
      end
    end
    nil
  end

  def lookup(key, options = {}, explain = false)
    nc_opts = options.empty? ? '' : ", #{Puppet::Pops::Types::TypeFormatter.string(options)}"
    keys = key.is_a?(Array) ? key : [key]
    collect_notices(keys.map { |k| "notice(String(lookup('#{k}'#{nc_opts}), '%p'))" }.join("\n"), explain)
    if explain
      explanation
    else
      result = notices.map { |n| Puppet::Pops::Types::TypeParser.singleton.parse_literal(n) }
      key.is_a?(Array) ? result : result[0]
    end
  end

  def explain(key, options = {})
    lookup(key, options, true)[1]
    explanation
  end

  context 'with faulty hiera.yaml configuration' do
    context 'in global layer' do
      let(:global_data) do
        {
          'common.yaml' => <<-YAML.unindent
            a: value a (from global)
            YAML
        }
      end

      let(:code_dir_files) do
        {
          'hiera.yaml' => hiera_yaml,
          'data' => global_data
        }
      end

      before(:each) do
        # Need to set here since spec_helper defines these settings in its "before each"
        Puppet.settings[:codedir] = populated_code_dir
        Puppet.settings[:hiera_config] = File.join(code_dir, 'hiera.yaml')
      end

      context 'using a not yet supported hiera version' do
        let(:hiera_yaml) { <<-YAML.unindent }
          version: 6
          YAML

        it 'fails and reports error' do
          expect { lookup('a') }.to raise_error("This runtime does not support hiera.yaml version 6 (file: #{code_dir}/hiera.yaml)")
        end
      end

      context 'with multiply defined backend using hiera version 3' do
        let(:hiera_yaml) { <<-YAML.unindent }
          :version: 3
          :backends:
            - yaml
            - json
            - yaml
          YAML

        it 'fails and reports error' do
          expect { lookup('a') }.to raise_error(
            "Backend 'yaml' is defined more than once. First defined at (line: 3) (file: #{code_dir}/hiera.yaml, line: 5)")
        end
      end

      context 'using hiera version 4' do
        let(:hiera_yaml) { <<-YAML.unindent }
          version: 4
          YAML

        it 'fails and reports error' do
          expect { lookup('a') }.to raise_error(
            "hiera.yaml version 4 cannot be used in the global layer (file: #{code_dir}/hiera.yaml)")
        end
      end

      context 'using hiera version 5' do
        context 'with multiply defined hierarchy' do
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common
                path: common.yaml
              - name: Other
                path: other.yaml
              - name: Common
                path: common.yaml
            YAML

          it 'fails and reports error' do
            expect { lookup('a') }.to raise_error(
              "Hierarchy name 'Common' defined more than once. First defined at (line: 3) (file: #{code_dir}/hiera.yaml, line: 7)")
          end
        end

        context 'with hiera3_backend that is provided as data_hash function' do
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common
                hiera3_backend: hocon
                path: common.conf
            YAML

          it 'fails and reports error' do
            expect { lookup('a') }.to raise_error(
              "Use \"data_hash: hocon_data\" instead of \"hiera3_backend: hocon\" (file: #{code_dir}/hiera.yaml, line: 4)")
          end
        end

        context 'with no data provider function defined' do
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            defaults:
              datadir: data
            hierarchy:
              - name: Common
                path: common.txt
            YAML

          it 'fails and reports error' do
            expect { lookup('a') }.to raise_error(
              "One of data_hash, lookup_key, data_dig, or hiera3_backend must be defined in hierarchy 'Common' (file: #{code_dir}/hiera.yaml)")
          end
        end

        context 'with multiple data providers in defaults' do
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            defaults:
              data_hash: yaml_data
              lookup_key: eyaml_lookup_key
              datadir: data
            hierarchy:
              - name: Common
                path: common.txt
            YAML

          it 'fails and reports error' do
            expect { lookup('a') }.to raise_error(
              "Only one of data_hash, lookup_key, data_dig, or hiera3_backend can be defined in defaults (file: #{code_dir}/hiera.yaml)")
          end
        end

        context 'with non existing data provider function' do
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common
                data_hash: nonesuch_txt_data
                path: common.yaml
            YAML

          it 'fails and reports error' do
            Puppet[:strict] = :error
            expect { lookup('a') }.to raise_error(
              "Unable to find 'data_hash' function named 'nonesuch_txt_data' (file: #{code_dir}/hiera.yaml)")
          end
        end

        context 'with a declared default_hierarchy' do
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common
                path: common.yaml
            default_hierarchy:
              - name: Defaults
                path: defaults.yaml
            YAML

          it 'fails and reports error' do
            Puppet[:strict] = :error
            expect { lookup('a') }.to raise_error(
              "'default_hierarchy' is only allowed in the module layer (file: #{code_dir}/hiera.yaml, line: 5)")
          end
        end

        context 'with missing variables' do
          let(:scope_additions) { { 'fqdn' => 'test.example.com' } }
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common # don't report this line %{::nonesuch}
                path: "%{::fqdn}/%{::nonesuch}/data.yaml"
            YAML

          it 'fails and reports errors when strict == error' do
            Puppet[:strict] = :error
            expect { lookup('a') }.to raise_error("Undefined variable '::nonesuch' (file: #{code_dir}/hiera.yaml, line: 4)")
          end
        end

        context 'using interpolation functions' do
          let(:hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common # don't report this line %{::nonesuch}
                path: "%{lookup('fqdn')}/data.yaml"
            YAML

          it 'fails and reports errors when strict == error' do
            Puppet[:strict] = :error
            expect { lookup('a') }.to raise_error("Interpolation using method syntax is not allowed in this context (file: #{code_dir}/hiera.yaml)")
          end
        end
      end
    end

    context 'in environment layer' do
      context 'using hiera version 4' do
        context 'with an unknown backend' do
          let(:env_hiera_yaml) { <<-YAML.unindent }
            version: 4
            hierarchy:
              - name: Common
                backend: nonesuch
                path: common.yaml
            YAML

          it 'fails and reports error' do
            expect { lookup('a') }.to raise_error(
              "No data provider is registered for backend 'nonesuch' (file: #{env_dir}/spec/hiera.yaml, line: 4)")
          end
        end

        context 'with multiply defined hierarchy' do
          let(:env_hiera_yaml) { <<-YAML.unindent }
            version: 4
            hierarchy:
              - name: Common
                backend: yaml
                path: common.yaml
              - name: Other
                backend: yaml
                path: other.yaml
              - name: Common
                backend: yaml
                path: common.yaml
            YAML

          it 'fails and reports error' do
            expect { lookup('a') }.to raise_error(
              "Hierarchy name 'Common' defined more than once. First defined at (line: 3) (file: #{env_dir}/spec/hiera.yaml, line: 9)")
          end
        end
      end

      context 'using hiera version 5' do
        context 'with a hiera3_backend declaration' do
          let(:env_hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common
                hiera3_backend: something
            YAML

          it 'fails and reports error' do
            expect { lookup('a') }.to raise_error(
              "'hiera3_backend' is only allowed in the global layer (file: #{env_dir}/spec/hiera.yaml, line: 4)")
          end
        end

        context 'with a declared default_hierarchy' do
          let(:env_hiera_yaml) { <<-YAML.unindent }
            version: 5
            hierarchy:
              - name: Common
                path: common.yaml
            default_hierarchy:
              - name: Defaults
                path: defaults.yaml
            YAML

          it 'fails and reports error' do
            Puppet[:strict] = :error
            expect { lookup('a') }.to raise_error(
              "'default_hierarchy' is only allowed in the module layer (file: #{env_dir}/spec/hiera.yaml, line: 5)")
          end
        end
      end
    end
  end

  context 'with an environment' do
    let(:env_data) do
      {
        'common.yaml' => <<-YAML.unindent
        ---
        a: value a (from environment)
        c:
          c_b: value c_b (from environment)
        mod_a::a: value mod_a::a (from environment)
        mod_a::hash_a:
          a: value mod_a::hash_a.a (from environment)
        mod_a::hash_b:
          a: value mod_a::hash_b.a (from environment)
        hash_b:
          hash_ba:
            bab: value hash_b.hash_ba.bab (from environment)
        hash_c:
          hash_ca:
            caa: value hash_c.hash_ca.caa (from environment)
        lookup_options:
          mod_a::hash_b:
            merge: hash
          hash_c:
            merge: hash
      YAML
      }
    end

    it 'finds data in the environment' do
      expect(lookup('a')).to eql('value a (from environment)')
    end

    context 'with log-level debug' do
      before(:each) { Puppet[:log_level] = 'debug' }

      it 'does not report a regular lookup as APL' do
        expect(lookup('a')).to eql('value a (from environment)')
        expect(debugs.count { |dbg| dbg =~ /\A\s*Automatic Parameter Lookup of/ }).to eql(0)
      end

      it 'reports regular lookup as lookup' do
        expect(lookup('a')).to eql('value a (from environment)')
        expect(debugs.count { |dbg| dbg =~ /\A\s*Lookup of/ }).to eql(1)
      end

      it 'does not report APL as lookup' do
        collect_notices("class mod_a($a) { notice($a) }; include mod_a")
        expect(debugs.count { |dbg| dbg =~ /\A\s*Lookup of/ }).to eql(0)
      end

      it 'reports APL as APL' do
        collect_notices("class mod_a($a) { notice($a) }; include mod_a")
        expect(debugs.count { |dbg| dbg =~ /\A\s*Automatic Parameter Lookup of/ }).to eql(1)
      end
    end

    context 'that has no lookup configured' do
      let(:environment_files) do
        {
          env_name => {
            'data' => env_data
          }
        }
      end

      it 'does not find data in the environment' do
        expect { lookup('a') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'a'/)
      end

      context "but an environment.conf with 'environment_data_provider=hiera'" do
        let(:environment_files) do
          {
            env_name => {
              'environment.conf' => "environment_data_provider=hiera\n",
              'data' => env_data
            }
          }
        end

        it 'finds data in the environment and reports deprecation warning for environment.conf' do
          expect(lookup('a')).to eql('value a (from environment)')
          expect(warnings).to include(/Defining environment_data_provider='hiera' in environment.conf is deprecated. A 'hiera.yaml' file should be used instead/)
        end

        context 'and a hiera.yaml file' do
          let(:env_hiera_yaml) do
            <<-YAML.unindent
              ---
              version: 4
              hierarchy:
                - name: common
                  backend: yaml
              YAML
          end

          let(:environment_files) do
            {
              env_name => {
                'hiera.yaml' => env_hiera_yaml,
                'environment.conf' => "environment_data_provider=hiera\n",
                'data' => env_data
              }
            }
          end

          it 'finds data in the environment and reports deprecation warnings for both environment.conf and hiera.yaml' do
            expect(lookup('a')).to eql('value a (from environment)')
            expect(warnings).to include(/Defining environment_data_provider='hiera' in environment.conf is deprecated/)
            expect(warnings).to include(/Use of 'hiera.yaml' version 4 is deprecated. It should be converted to version 5/)
          end
        end
      end

      context "but an environment.conf with 'environment_data_provider=function'" do
        let(:environment_files) do
          {
            env_name => {
              'environment.conf' => "environment_data_provider=function\n",
              'functions' => {
                'environment' => { 'data.pp' => <<-PUPPET.unindent }
                    function environment::data() {
                      { 'a' => 'value a' }
                    }
                    PUPPET
              }
            }
          }
        end

        it 'finds data in the environment and reports deprecation warning for environment.conf' do
          expect(lookup('a')).to eql('value a')
          expect(warnings).to include(/Defining environment_data_provider='function' in environment.conf is deprecated. A 'hiera.yaml' file should be used instead/)
          expect(warnings).to include(/Using of legacy data provider function 'environment::data'. Please convert to a 'data_hash' function/)
        end
      end
    end

    context 'that has interpolated paths configured' do
      let(:env_hiera_yaml) do
        <<-YAML.unindent
          ---
          version: 5
          hierarchy:
            - name: "Varying"
              data_hash: yaml_data
              path: "#{data_path}"
          YAML
      end

      let(:environment_files) do
        {
          env_name => {
            'hiera.yaml' => env_hiera_yaml,
            'modules' => {},
            'data' => {
              'x.yaml' => <<-YAML.unindent,
                y: value y from x
                YAML
              'x_d.yaml' => <<-YAML.unindent,
                y: value y from x_d
                YAML
              'x_e.yaml' => <<-YAML.unindent,
                y: value y from x_e
                YAML
            }
          }
        }
      end

      context 'using local variable reference' do
        let(:data_path) { 'x%{var.sub}.yaml' }

        it 'reloads the configuration if interpolated values change' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            expect(lookup_func.call(scope, 'y')).to eql('value y from x')
            scope['var'] = { 'sub' => '_d' }
            expect(lookup_func.call(scope, 'y')).to eql('value y from x_d')
            nested_scope = scope.compiler.newscope(scope)
            nested_scope['var'] = { 'sub' => '_e' }
            expect(lookup_func.call(nested_scope, 'y')).to eql('value y from x_e')
          end
          expect(notices).to eql(['success'])
          expect(debugs.any? { |m| m =~ /Hiera configuration recreated due to change of scope variables used in interpolation expressions/ }).to be_truthy
        end

        it 'does not include the lookups performed during stability check in explain output' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            var = { 'sub' => '_d' }
            scope['var'] = var
            expect(lookup_func.call(scope, 'y')).to eql('value y from x_d')

            # Second call triggers the check
            expect(lookup_func.call(scope, 'y')).to eql('value y from x_d')
          end
          expect(notices).to eql(['success'])
          expect(debugs.any? { |m| m =~ /Sub key: "sub"/ }).to be_falsey
        end
      end

      context 'using global variable reference' do
        let(:data_path) { 'x%{::var.sub}.yaml' }

        it 'reloads the configuration if interpolated that was previously undefined, gets defined' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            expect(lookup_func.call(scope, 'y')).to eql('value y from x')
            scope['var'] = { 'sub' => '_d' }
            expect(lookup_func.call(scope, 'y')).to eql('value y from x_d')
          end
          expect(notices).to eql(['success'])
          expect(debugs.any? { |m| m =~ /Hiera configuration recreated due to change of scope variables used in interpolation expressions/ }).to be_truthy
        end

        it 'does not reload the configuration if value changes locally' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            scope['var'] = { 'sub' => '_d' }
            expect(lookup_func.call(scope, 'y')).to eql('value y from x_d')
            nested_scope = scope.compiler.newscope(scope)
            nested_scope['var'] = { 'sub' => '_e' }
            expect(lookup_func.call(nested_scope, 'y')).to eql('value y from x_d')
          end
          expect(notices).to eql(['success'])
          expect(debugs.any? { |m| m =~ /Hiera configuration recreated due to change of scope variables used in interpolation expressions/ }).to be_falsey
        end
      end
    end

    context 'that uses reserved' do
       let(:environment_files) do
        { env_name => { 'hiera.yaml' => hiera_yaml } }
      end

      context 'option' do
       let(:hiera_yaml) { <<-YAML.unindent }
          version: 5
          hierarchy:
            - name: "Illegal"
              options:
                #{opt_spec}
              data_hash: yaml_data
          YAML

        context 'path' do
          let(:opt_spec) { 'path: data/foo.yaml' }

          it 'fails and reports the reserved option key' do
            expect { lookup('a') }.to raise_error do |e|
              expect(e.message).to match(/Option key 'path' used in hierarchy 'Illegal' is reserved by Puppet/)
            end
          end
        end

        context 'uri' do
          let(:opt_spec) { 'uri: file:///data/foo.yaml' }

          it 'fails and reports the reserved option key' do
            expect { lookup('a') }.to raise_error do |e|
              expect(e.message).to match(/Option key 'uri' used in hierarchy 'Illegal' is reserved by Puppet/)
            end
          end
        end
      end

      context 'default option' do
        let(:hiera_yaml) { <<-YAML.unindent }
          ---
          version: 5
          defaults:
              options:
                #{opt_spec}
          hierarchy:
            - name: "Illegal"
              data_hash: yaml_data
          YAML

        context 'path' do
          let(:opt_spec) { 'path: data/foo.yaml' }

          it 'fails and reports the reserved option key' do
            expect { lookup('a') }.to raise_error do |e|
              expect(e.message).to match(/Option key 'path' used in defaults is reserved by Puppet/)
            end
          end
        end

        context 'uri' do
          let(:opt_spec) { 'uri: file:///data/foo.yaml' }

          it 'fails and reports the reserved option key' do
            expect { lookup('a') }.to raise_error do |e|
              expect(e.message).to match(/Option key 'uri' used in defaults is reserved by Puppet/)
            end
          end
        end
      end
    end

    context 'with yaml data file' do
      let(:environment_files) do
        {
          env_name => {
            'hiera.yaml' => <<-YAML.unindent,
              ---
              version: 5
              YAML
            'data' => {
              'common.yaml' => common_yaml
            }
          }
        }
      end

      context 'that contains hash values with interpolated keys' do
        let(:common_yaml) do
          <<-YAML.unindent
          ---
          a:
              "%{key}": "the %{value}"
          b:  "Detail in %{lookup('a.a_key')}"
          YAML
        end

        it 'interpolates both key and value"' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            expect(lookup_func.call(scope, 'a')).to eql({'' => 'the '})
            scope['key'] = 'a_key'
            scope['value'] = 'interpolated value'
            expect(lookup_func.call(scope, 'a')).to eql({'a_key' => 'the interpolated value'})
          end
          expect(notices).to eql(['success'])
        end

        it 'navigates to a value behind an interpolated key"' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            scope['key'] = 'a_key'
            scope['value'] = 'interpolated value'
            expect(lookup_func.call(scope, 'a.a_key')).to eql('the interpolated value')
          end
          expect(notices).to eql(['success'])
        end

        it 'navigates to a value behind an interpolated key using an interpolated value"' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            scope['key'] = 'a_key'
            scope['value'] = 'interpolated value'
            expect(lookup_func.call(scope, 'b')).to eql('Detail in the interpolated value')
          end
          expect(notices).to eql(['success'])
        end
      end

      context 'that is empty' do
        let(:common_yaml) { '' }

        it 'fails with a "did not find"' do
          expect { lookup('a') }.to raise_error do |e|
            expect(e.message).to match(/did not find a value for the name 'a'/)
          end
        end

        it 'logs a warning that the file does not contain a hash' do
          expect { lookup('a') }.to raise_error(Puppet::DataBinding::LookupError)
          expect(warnings).to include(/spec\/data\/common.yaml: file does not contain a valid yaml hash/)
        end
      end

      context 'that contains illegal yaml' do
        let(:common_yaml) { "@!#%**&:\n" }

        it 'fails lookup and that the key is not found' do
          expect { lookup('a') }.to raise_error do |e|
            expect(e.message).to match(/Unable to parse/)
          end
        end
      end

      context 'that contains a legal yaml that is not a hash' do
        let(:common_yaml) { "- A list\n- of things" }

        it 'fails with a "did not find"' do
          expect { lookup('a') }.to raise_error do |e|
            expect(e.message).to match(/did not find a value for the name 'a'/)
          end
        end

        it 'logs a warning that the file does not contain a hash' do
          expect { lookup('a') }.to raise_error(Puppet::DataBinding::LookupError)
          expect(warnings).to include(/spec\/data\/common.yaml: file does not contain a valid yaml hash/)
        end
      end

      context 'that contains a legal yaml hash with illegal types' do
        let(:common_yaml) do
          <<-YAML.unindent
          ---
          a: !ruby/object:Puppet::Graph::Key
              value: x
          YAML
        end

        it 'fails lookup and reports a type mismatch' do
          expect { lookup('a') }.to raise_error do |e|
            expect(e.message).to match(/key 'a'.*data_hash function 'yaml_data'.*using location.*wrong type, expects Puppet::LookupValue, got Runtime/)
          end
        end
      end

      context 'that contains illegal interpolations' do
        context 'in the form of an alias that is not the entire string' do
          let(:common_yaml) { <<-YAML.unindent }
            a: "%{alias('x')} and then some"
            x: value x
            YAML

          it 'fails lookup and reports a type mismatch' do
            expect { lookup('a') }.to raise_error("'alias' interpolation is only permitted if the expression is equal to the entire string")
          end
        end

        context 'in the form of an unknown function name' do
          let(:common_yaml) { <<-YAML.unindent }
            a: "%{what('x')}"
            x: value x
            YAML

          it 'fails lookup and reports a type mismatch' do
            expect { lookup('a') }.to raise_error("Unknown interpolation method 'what'")
          end
        end
      end

      context 'that contains an array with duplicates' do
        let(:common_yaml) { <<-YAML.unindent }
          a:
           - alpha
           - bravo
           - charlie
           - bravo
          YAML

        it 'retains the duplicates when using default merge strategy' do
          expect(lookup('a')).to eql(%w(alpha bravo charlie bravo))
        end

        it 'does deduplification when using merge strategy "unique"' do
          expect(lookup('a', :merge => 'unique')).to eql(%w(alpha bravo charlie))
        end
      end
    end

    context 'with lookup_options configured using patterns' do
      let(:mod_common) {
        <<-YAML.unindent
          mod::hash_a:
            aa:
              aaa: aaa (from module)
            ab:
              aba: aba (from module)
          mod::hash_b:
            ba:
              baa: baa (from module)
            bb:
              bba: bba (from module)
          lookup_options:
            '^mod::ha.*_a':
              merge: deep
            '^mod::ha.*_b':
              merge: deep
        YAML
      }

      let(:mod_base) do
        {
          'hiera.yaml' => <<-YAML.unindent,
            version: 5
            YAML
          'data' => {
            'common.yaml' => mod_common
          }
        }
      end

      let(:env_modules) do
        {
          'mod' => mod_base
        }
      end

      let(:env_hiera_yaml) do
        <<-YAML.unindent
          ---
          version: 5
          hierarchy:
            - name: X
              paths:
              - first.yaml
              - second.yaml
          YAML
      end

      let(:env_lookup_options) { <<-YAML.unindent }
        lookup_options:
          b:
            merge: hash
          '^[^b]$':
             merge: deep
          '^c':
             merge: first
          '^b':
             merge: first
          '^mod::ha.*_b':
            merge: hash
        YAML

      let(:env_data) do
        {
          'first.yaml' => <<-YAML.unindent + env_lookup_options,
            a:
              aa:
                aaa: a.aa.aaa
            b:
              ba:
                baa: b.ba.baa
              bb:
                bba: b.bb.bba
            c:
              ca:
                caa: c.ca.caa
            mod::hash_a:
              aa:
                aab: aab (from environment)
              ab:
                aba: aba (from environment)
                abb: abb (from environment)
            mod::hash_b:
              ba:
                bab: bab (from environment)
              bc:
                bca: bca (from environment)
            sa:
              sa1: ['e', 'd', '--f']
            YAML
          'second.yaml' => <<-YAML.unindent,
            a:
              aa:
                aab: a.aa.aab
            b:
              ba:
                bab: b.ba.bab
              bb:
                bbb: b.bb.bbb
            c:
              ca:
                cab: c.ca.cab
            sa:
              sa1: ['b', 'a', 'f', 'c']
            YAML
        }
      end

      it 'finds lookup_options that matches a pattern' do
        expect(lookup('a')).to eql({'aa' => { 'aaa' => 'a.aa.aaa', 'aab' => 'a.aa.aab' }})
      end

      it 'gives a direct key match higher priority than a matching pattern' do
        expect(lookup('b')).to eql({'ba' => { 'baa' => 'b.ba.baa' }, 'bb' => { 'bba'=>'b.bb.bba' }})
      end

      it 'uses the first matching pattern' do
        expect(lookup('c')).to eql({'ca' => { 'caa' => 'c.ca.caa', 'cab' => 'c.ca.cab' }})
      end

      it 'uses lookup_option found by pattern from module' do
        expect(lookup('mod::hash_a')).to eql({
          'aa' => {
            'aaa' => 'aaa (from module)',
            'aab' => 'aab (from environment)'
          },
          'ab' => {
            'aba' => 'aba (from environment)',
            'abb' => 'abb (from environment)'
          }
        })
      end

      it 'merges lookup_options found by pattern in environment and module (environment wins)' do
        expect(lookup('mod::hash_b')).to eql({
          'ba' => {
            'bab' => 'bab (from environment)'
          },
          'bb' => {
            'bba' => 'bba (from module)'
          },
          'bc' => {
            'bca' => 'bca (from environment)'
          }
        })
      end

      context 'and patterns in module are not limited to module keys' do
        let(:mod_common) {
          <<-YAML.unindent
          mod::hash_a:
            aa:
              aaa: aaa (from module)
            ab:
              aba: aba (from module)
          lookup_options:
            '^.*_a':
              merge: deep
          YAML
        }

        it 'fails with error' do
          expect { lookup('mod::a') }.to raise_error(Puppet::DataBinding::LookupError, /all lookup_options patterns must match a key starting with module name/)
        end
      end

      context 'and there are no lookup options that do not use patterns' do

        let(:env_lookup_options) { <<-YAML.unindent }
          lookup_options:
            '^[^b]$':
              merge: deep
            '^c':
              merge: first
            '^b':
              merge: first
            '^mod::ha.*_b':
              merge: hash
          YAML

        it 'finds lookup_options that matches a pattern' do
          expect(lookup('a')).to eql({'aa' => { 'aaa' => 'a.aa.aaa', 'aab' => 'a.aa.aab' }})
        end
      end

      context 'and lookup options use a hash' do

        let(:env_lookup_options) { <<-YAML.unindent }
          lookup_options:
            'sa':
              merge:
                strategy: deep
                knockout_prefix: --
                sort_merged_arrays: true
        YAML

        it 'applies knockout_prefix and sort_merged_arrays' do
          expect(lookup('sa')).to eql({ 'sa1' => %w(a b c d e) })
        end

        it 'overrides knockout_prefix and sort_merged_arrays with explicitly given values' do
          expect(
            lookup('sa', 'merge' => { 'strategy' => 'deep', 'knockout_prefix' => '##', 'sort_merged_arrays' => false })).to(
              eql({ 'sa1' => %w(b a f c e d --f) }))
        end
      end
    end

    context 'and an environment Hiera v5 configuration using globs' do
      let(:env_hiera_yaml) do
        <<-YAML.unindent
        ---
        version: 5
        hierarchy:
          - name: Globs
            globs:
              - "globs/*.yaml"
              - "globs_%{domain}/*.yaml"
        YAML
      end

      let(:env_data) do
        {
          'globs' => {
            'a.yaml' => <<-YAML.unindent,
              glob_a: value glob_a
              YAML
            'b.yaml' => <<-YAML.unindent
              glob_b:
                a: value glob_b.a
                b: value glob_b.b
            YAML
          },
          'globs_example.com' => {
            'a.yaml' => <<-YAML.unindent,
              glob_c: value glob_a
              YAML
            'b.yaml' => <<-YAML.unindent
              glob_d:
                a: value glob_d.a
                b: value glob_d.b
            YAML

          }
        }
      end

      it 'finds environment data using globs' do
        expect(lookup('glob_a')).to eql('value glob_a')
        expect(warnings).to be_empty
      end

      it 'finds environment data using interpolated globs' do
        expect(lookup('glob_d.a')).to eql('value glob_d.a')
        expect(warnings).to be_empty
      end
    end

    context 'and an environment Hiera v5 configuration using uris' do
      let(:env_hiera_yaml) do
        <<-YAML.unindent
        ---
        version: 5
        hierarchy:
          - name: Uris
            uris:
              - "http://test.example.com"
              - "/some/arbitrary/path"
              - "urn:with:opaque:path"
              - "dothis%20-f%20bar"
            data_hash: mod::uri_test_func
        YAML
      end

      let(:env_modules) do
        {
          'mod' => { 'lib' => { 'puppet' => { 'functions' => { 'mod' => { 'uri_test_func.rb' => <<-RUBY } } } } }
            Puppet::Functions.create_function(:'mod::uri_test_func') do
              dispatch :uri_test_func do
                param 'Hash', :options
                param 'Puppet::LookupContext', :context
              end

              def uri_test_func(options, context)
                { 'uri' => [ options['uri'] ] }
              end
            end
            RUBY
        }
      end

      it 'The uris are propagated in the options hash' do
        expect(lookup('uri', 'merge' => 'unique')).to eql(
          %w(http://test.example.com /some/arbitrary/path urn:with:opaque:path dothis%20-f%20bar))
        expect(warnings).to be_empty
      end

      context 'and a uri uses bad syntax' do
        let(:env_hiera_yaml) do
          <<-YAML.unindent
        ---
        version: 5
        hierarchy:
          - name: Uris
            uri: "dothis -f bar"
            data_hash: mod::uri_test_func
          YAML
        end

        it 'an attempt to lookup raises InvalidURIError' do
          expect{ lookup('uri', 'merge' => 'unique') }.to raise_error(/bad URI/)
        end
      end
    end

    context 'and an environment Hiera v5 configuration using mapped_paths' do
      let(:scope_additions) do
        {
          'mapped' =>  {
            'array_var' => ['a', 'b', 'c'],
            'hash_var' => { 'x' => 'a', 'y' => 'b', 'z' => 'c' },
            'string_var' => 's' },
          'var' => 'global_var' # overridden by mapped path variable
        }
      end

      let(:env_hiera_yaml) do
        <<-YAML.unindent
        ---
        version: 5
        hierarchy:
          - name: Mapped Paths
            mapped_paths: #{mapped_paths}
          - name: Global Path
            path: "%{var}.yaml"
        YAML
      end

      let(:environment_files) do
        {
          env_name => {
            'hiera.yaml' => env_hiera_yaml,
            'data' => env_data
          }
        }
      end

      context 'that originates from an array' do
        let (:mapped_paths) { '[mapped.array_var, var, "paths/%{var}.yaml"]' }

        let(:env_data) do
          {
            'paths' => {
              'a.yaml' => <<-YAML.unindent,
                path_a: value path_a
                path_h:
                  a: value path_h.a
                  c: value path_h.c
                YAML
              'b.yaml' => <<-YAML.unindent,
                path_h:
                  b: value path_h.b
                  d: value path_h.d
                YAML
              'd.yaml' => <<-YAML.unindent
                path_h:
                  b: value path_h.b (from d.yaml)
                  d: value path_h.d (from d.yaml)
                YAML
            },
            'global_var.yaml' => <<-YAML.unindent,
              path_h:
                e: value path_h.e
              YAML
            'other_var.yaml' => <<-YAML.unindent
              path_h:
                e: value path_h.e (from other_var.yaml)
              YAML
          }
        end

        it 'finds environment data using mapped_paths' do
          expect(lookup('path_a')).to eql('value path_a')
          expect(warnings).to be_empty
        end

        it 'includes mapped path in explain output' do
          explanation = explain('path_h', 'merge' => 'deep')
          ['a', 'b', 'c'].each do |var|
            expect(explanation).to match(/^\s+Path "#{env_dir}\/spec\/data\/paths\/#{var}\.yaml"\n\s+Original path: "paths\/%\{var\}\.yaml"/)
          end
          expect(warnings).to be_empty
        end

        it 'performs merges between mapped paths and global path interpolated using same key' do
          expect(lookup('path_h', 'merge' => 'hash')).to eql(
            {
              'a' => 'value path_h.a',
              'b' => 'value path_h.b',
              'c' => 'value path_h.c',
              'd' => 'value path_h.d',
              'e' => 'value path_h.e'
            })
          expect(warnings).to be_empty
        end

        it 'keeps track of changes in key overridden by interpolated key' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            expect(lookup_func.call(scope, 'path_h', 'merge' => 'hash')).to eql(
              {
                'a' => 'value path_h.a',
                'b' => 'value path_h.b',
                'c' => 'value path_h.c',
                'd' => 'value path_h.d',
                'e' => 'value path_h.e'
              })
            scope.with_local_scope('var' => 'other_var') do
              expect(lookup_func.call(scope, 'path_h', 'merge' => 'hash')).to eql(
                {
                  'a' => 'value path_h.a',
                  'b' => 'value path_h.b',
                  'c' => 'value path_h.c',
                  'd' => 'value path_h.d',
                  'e' => 'value path_h.e (from other_var.yaml)'
                })
            end
          end
          expect(notices).to eql(['success'])
          expect(debugs.any? { |m| m =~ /Hiera configuration recreated due to change of scope variables used in interpolation expressions/ }).to be_truthy
        end

        it 'keeps track of changes in elements of mapped key' do
          Puppet[:log_level] = 'debug'
          collect_notices("notice('success')") do |scope|
            expect(lookup_func.call(scope, 'path_h', 'merge' => 'hash')).to eql(
              {
                'a' => 'value path_h.a',
                'b' => 'value path_h.b',
                'c' => 'value path_h.c',
                'd' => 'value path_h.d',
                'e' => 'value path_h.e'
              })
            scope['mapped']['array_var'] = ['a', 'c', 'd']
            expect(lookup_func.call(scope, 'path_h', 'merge' => 'hash')).to eql(
              {
                'a' => 'value path_h.a',
                'b' => 'value path_h.b (from d.yaml)',
                'c' => 'value path_h.c',
                'd' => 'value path_h.d (from d.yaml)',
                'e' => 'value path_h.e'
              })
          end
          expect(notices).to eql(['success'])
          expect(debugs.any? { |m| m =~ /Hiera configuration recreated due to change of scope variables used in interpolation expressions/ }).to be_truthy
        end
      end

      context 'that originates from a hash' do
        let (:mapped_paths) { '[mapped.hash_var, var, "paths/%{var.0}.%{var.1}.yaml"]' }

        let(:env_data) do
          {
            'paths' => {
              'x.a.yaml' => <<-YAML.unindent,
                path_xa: value path_xa
                path_m:
                  a: value path_m.a
                  c: value path_m.c
                YAML
              'y.b.yaml' => <<-YAML.unindent
                path_m:
                  b: value path_m.b
                  d: value path_m.d
                YAML
            },
            'global_var.yaml' => <<-YAML.unindent
              path_m:
                e: value path_m.e
              YAML
          }
        end

        it 'finds environment data using mapped_paths' do
          expect(lookup('path_xa')).to eql('value path_xa')
          expect(warnings).to be_empty
        end

        it 'includes mapped path in explain output' do
          explanation = explain('path_h', 'merge' => 'deep')
          ['x\.a', 'y\.b', 'z\.c'].each do |var|
            expect(explanation).to match(/^\s+Path "#{env_dir}\/spec\/data\/paths\/#{var}\.yaml"\n\s+Original path: "paths\/%\{var\.0\}\.%\{var\.1\}\.yaml"/)
          end
          expect(warnings).to be_empty
        end

        it 'performs merges between mapped paths' do
          expect(lookup('path_m', 'merge' => 'hash')).to eql(
            {
              'a' => 'value path_m.a',
              'b' => 'value path_m.b',
              'c' => 'value path_m.c',
              'd' => 'value path_m.d',
              'e' => 'value path_m.e'
            })
          expect(warnings).to be_empty
        end
      end

      context 'that originates from a string' do
        let (:mapped_paths) { '[mapped.string_var, var, "paths/%{var}.yaml"]' }

        let(:env_data) do
          {
            'paths' => {
              's.yaml' => <<-YAML.unindent,
                path_s: value path_s
                YAML
            }
          }
        end

        it 'includes mapped path in explain output' do
          expect(explain('path_s')).to match(/^\s+Path "#{env_dir}\/spec\/data\/paths\/s\.yaml"\n\s+Original path: "paths\/%\{var\}\.yaml"/)
          expect(warnings).to be_empty
        end

        it 'finds environment data using mapped_paths' do
          expect(lookup('path_s')).to eql('value path_s')
          expect(warnings).to be_empty
        end
      end

      context 'where the enty does not exist' do
        let (:mapped_paths) { '[mapped.nosuch_var, var, "paths/%{var}.yaml"]' }

        it 'finds environment data using mapped_paths' do
          expect(explain('hello')).to match(/No such key: "hello"/)
          expect(warnings).to be_empty
        end
      end
    end

    context 'and an environment Hiera v3 configuration' do
      let(:env_hiera_yaml) do
        <<-YAML.unindent
          ---
          :backends: yaml
          :yaml:
            :datadir:  #{env_dir}/#{env_name}/hieradata
          YAML
      end

      let(:environment_files) do
        {
          env_name => {
            'hiera.yaml' => env_hiera_yaml,
            'hieradata' => {
              'common.yaml' => <<-YAML.unindent,
                g: Value g
                YAML
            }
          }
        }
      end

      it 'will raise an error if --strict is set to error' do
        Puppet[:strict] = :error
        expect { lookup('g') }.to raise_error(Puppet::Error, /hiera.yaml version 3 cannot be used in an environment/)
      end

      it 'will log a warning and ignore the file if --strict is set to warning' do
        Puppet[:strict] = :warning
        expect { lookup('g') }.to raise_error(Puppet::Error, /did not find a value for the name 'g'/)
      end

      it 'will not log a warning and ignore the file if --strict is set to off' do
        Puppet[:strict] = :off
        expect { lookup('g') }.to raise_error(Puppet::Error, /did not find a value for the name 'g'/)
        expect(warnings).to include(/hiera.yaml version 3 found at the environment root was ignored/)
      end

      it 'will use the configuration if appointed by global setting but still warn when encountered by environment data provider' do
        Puppet[:strict] = :warning
        Puppet.settings[:hiera_config] = File.join(env_dir, env_name, 'hiera.yaml')
        expect(lookup('g')).to eql('Value g')
        expect(warnings).to include(/hiera.yaml version 3 found at the environment root was ignored/)
      end
    end

    context 'and a global empty Hiera configuration' do
      let(:hiera_yaml_path) { File.join(code_dir, 'hiera.yaml') }
      let(:code_dir_files) do
        {
          'hiera.yaml' => '',
        }
      end

      let(:environment_files) do
        {
          env_name => {
            'hieradata' => {
              'common.yaml' =>  <<-YAML.unindent,
                x: value x (from environment)
                YAML
            }
          }
        }
      end

      before(:each) do
        # Need to set here since spec_helper defines these settings in its "before each"
        Puppet.settings[:hiera_config] = hiera_yaml_path
      end

      it 'uses a Hiera version 3 defaults' do
        expect(lookup('x')).to eql('value x (from environment)')
      end

      context 'obtained using /dev/null', :unless => Puppet.features.microsoft_windows? do
        let(:code_dir_files) { {} }

        it 'uses a Hiera version 3 defaults' do
          Puppet[:hiera_config] = '/dev/null'
          expect(lookup('x')).to eql('value x (from environment)')
        end
      end
    end

    context 'and a global configuration' do
      let(:hiera_yaml) do
        <<-YAML.unindent
        ---
        :backends:
          - yaml
          - json
          - custom
          - hocon
        :yaml:
          :datadir: #{code_dir}/hieradata
        :json:
          :datadir: #{code_dir}/hieradata
        :hocon:
          :datadir: #{code_dir}/hieradata
        :hierarchy:
          - common
          - "%{domain}"
        :merge_behavior: deeper
        YAML
      end

      let(:code_dir_files) do
        {
          'hiera.yaml' => hiera_yaml,
          'hieradata' => {
            'common.yaml' =>  <<-YAML.unindent,
              a: value a (from global)
              hash_b:
                hash_ba:
                  bab: value hash_b.hash_ba.bab (from global)
              hash_c:
                hash_ca:
                  cab: value hash_c.hash_ca.cab (from global)
              ipl_hiera_env: "environment value '%{hiera('mod_a::hash_a.a')}'"
              ipl_hiera_mod: "module value '%{hiera('mod_a::abc')}'"
              ipl_hiera_modc: "module value '%{hiera('mod_a::caller')}'"
              YAML
            'example.com.yaml' =>  <<-YAML.unindent,
              x: value x (from global example.com.yaml)
              YAML
            'common.json' =>  <<-JSON.unindent,
              {
                "hash_b": {
                  "hash_ba": {
                    "bac": "value hash_b.hash_ba.bac (from global json)"
                  }
                },
                "hash_c": {
                  "hash_ca": {
                    "cac": "value hash_c.hash_ca.cac (from global json)"
                  }
                }
              }
              JSON
            'common.conf' =>  <<-HOCON.unindent,
              // The 'xs' is a value used for testing
              xs = { subkey = value xs.subkey (from global hocon) }
              HOCON
          }
        }
      end

      let(:ruby_dir_files) do
        {
          'hiera' => {
            'backend' => {
              'custom_backend.rb' => <<-RUBY.unindent,
            class Hiera::Backend::Custom_backend
              def lookup(key, scope, order_override, resolution_type, context)
                case key
                when 'hash_c'
                  { 'hash_ca' => { 'cad' => 'value hash_c.hash_ca.cad (from global custom)' }}
                when 'hash'
                  { 'array' => [ 'x5,x6' ] }
                when 'array'
                  [ 'x5,x6' ]
                when 'datasources'
                  Hiera::Backend.datasources(scope, order_override) { |source| source }
                when 'dotted.key'
                  'custom backend received request for dotted.key value'
                else
                  throw :no_such_key
                end
              end
            end
            RUBY
            'other_backend.rb' => <<-RUBY.unindent,
            class Hiera::Backend::Other_backend
              def lookup(key, scope, order_override, resolution_type, context)
                value = Hiera::Config[:other][key.to_sym]
                throw :no_such_key if value.nil?
                value
              end
            end
            RUBY
            }
          }
        }
      end

      before(:each) do
        # Need to set here since spec_helper defines these settings in its "before each"
        Puppet.settings[:codedir] = populated_code_dir
        Puppet.settings[:hiera_config] = File.join(code_dir, 'hiera.yaml')
      end

      around(:each) do |example|
        # Faking the load path to enable 'require' to load from 'ruby_stuff'. It removes the need for a static fixture
        # for the custom backend
        $LOAD_PATH.unshift(populated_ruby_dir)
        begin
          Puppet.override(:environments => environments, :current_environment => env) do
            example.run
          end
        ensure
          if Kernel.const_defined?(:Hiera) && Hiera.const_defined?(:Backend)
            Hiera::Backend.send(:remove_const, :Custom_backend) if Hiera::Backend.const_defined?(:Custom_backend)
            Hiera::Backend.send(:remove_const, :Other_backend) if Hiera::Backend.const_defined?(:Other_backend)
          end
          $LOAD_PATH.shift
        end
      end

      context 'version 3' do
        it 'finds data in in global layer and reports deprecation warnings for hiera.yaml' do
          expect(lookup('a')).to eql('value a (from global)')
          expect(warnings).to include(/Use of 'hiera.yaml' version 3 is deprecated. It should be converted to version 5/)
        end

        it 'explain contains output from global layer' do
          explanation = explain('a')
          expect(explanation).to include('Global Data Provider (hiera configuration version 3)')
          expect(explanation).to include('Hierarchy entry "yaml"')
          expect(explanation).to include('Hierarchy entry "json"')
          expect(explanation).to include('Found key: "a" value: "value a (from global)"')
        end

        it 'ignores merge behavior specified in global hiera.yaml' do
          expect(lookup('hash_b')).to eql(
            { 'hash_ba' => { 'bab' => 'value hash_b.hash_ba.bab (from global)'} })
        end

        it 'uses the merge from lookup options to merge all layers' do
          expect(lookup('hash_c')).to eql(
            { 'hash_ca' => { 'cab' => 'value hash_c.hash_ca.cab (from global)' } })
        end

        it 'uses the explicitly given merge to override lookup options and to merge all layers' do
          expect(lookup('hash_c', 'merge' => 'deep')).to eql(
            {
              'hash_ca' =>
              {
                'caa' => 'value hash_c.hash_ca.caa (from environment)',
                'cab' => 'value hash_c.hash_ca.cab (from global)',
                'cac' => 'value hash_c.hash_ca.cac (from global json)',
                'cad' => 'value hash_c.hash_ca.cad (from global custom)'
              }
            })
        end

        it 'paths are interpolated' do
          expect(lookup('x')).to eql('value x (from global example.com.yaml)')
        end

        it 'backend data sources are propagated to custom backend' do
          expect(lookup('datasources')).to eql(['common', 'example.com'])
        end

        it 'delegates configured hocon backend to hocon_data function' do
          expect(explain('xs')).to match(/Hierarchy entry "hocon"\n.*\n.*\n.*"common"\n\s*Found key: "xs"/m)
        end

        it 'can dig down into subkeys provided by hocon_data function' do
          expect(lookup('xs.subkey')).to eql('value xs.subkey (from global hocon)')
        end

        context 'with a module data provider' do
          let(:module_files) do
            {
              'mod_a' => {
                'hiera.yaml' => <<-YAML.unindent,
                  version: 5
                  hierarchy:
                    - name: Common
                      path: common.yaml
                  YAML
                'data' => {
                  'common.yaml' =>  <<-YAML.unindent
                    mod_a::abc: value mod_a::abc (from module)
                    mod_a::caller: "calling module is %{calling_module}"
                  YAML
                }
              }
            }
          end

          let(:environment_files) do
            {
              env_name => {
                'hiera.yaml' => env_hiera_yaml,
                'data' => env_data,
                'modules' => module_files
              }
            }
          end

          it "interpolation function 'hiera' finds values in environment" do
            expect(lookup('ipl_hiera_env')).to eql("environment value 'value mod_a::hash_a.a (from environment)'")
          end

          it "interpolation function 'hiera' finds values in module" do
            expect(lookup('ipl_hiera_mod')).to eql("module value 'value mod_a::abc (from module)'")
          end

          it "interpolation function 'hiera' finds values in module and that module does not find %{calling_module}" do
            expect(lookup('ipl_hiera_modc')).to eql("module value 'calling module is '")
          end

          context 'but no environment data provider' do
            let(:environment_files) do
              {
                env_name => {
                  'modules' => module_files
                }
              }
            end

            it "interpolation function 'hiera' does not find values in a module" do
              expect(lookup('ipl_hiera_mod')).to eql("module value ''")
            end
          end
        end


        context 'using an eyaml backend' do
          let(:private_key_name) { 'private_key.pkcs7.pem' }
          let(:public_key_name) { 'public_key.pkcs7.pem' }

          let(:private_key) do
            <<-PKCS7.unindent
              -----BEGIN RSA PRIVATE KEY-----
              MIIEogIBAAKCAQEAwHB3GvImq59em4LV9DMfP0Zjs21eW3Jd5I9fuY0jLJhIkH6f
              CR7tyOpYV6xUj+TF8giq9WLxZI7sourMJMWjEWhVjgUr5lqp1RLv4lwfDv3Wk4XC
              2LUuqj1IAErUXKeRz8i3lUSZW1Pf4CaMpnIiPdWbz6f0KkaJSFi9bqexONBx4fKQ
              NlgZwm2/aYjjrYng788I0QhWDKUqsQOi5mZKlHNRsDlk7J3Afhsx/jTLrCX/G8+2
              tPtLsHyRN39kluM5vYHbKXDsCG/a88Z2yUE2+r4Clp0FUKffiEDBPm0/H0sQ4Q1o
              EfQFDQRKaIkhpsm0nOnLYTy3/xJc5uqDNkLiawIDAQABAoIBAE98pNXOe8ab93oI
              mtNZYmjCbGAqprTjEoFb71A3SfYbmK2Gf65GxjUdBwx/tBYTiuekSOk+yzKcDoZk
              sZnmwKpqDByzaiSmAkxunANFxdZtZvpcX9UfUX0j/t+QCROUa5gF8j6HrUiZ5nkx
              sxr1PcuItekaGLJ1nDLz5JsWTQ+H4M+GXQw7/t96x8v8g9el4exTiAHGk6Fv16kD
              017T02M9qTTmV3Ab/enDIBmKVD42Ta36K/wc4l1aoUQNiRbIGVh96Cgd1CFXLF3x
              CsaNbYT4SmRXaYqoj6MKq+QFEGxadFmJy48NoSd4joirIn2lUjHxJebw3lLbNLDR
              uvQnQ2ECgYEA/nD94wEMr6078uMv6nKxPpNGq7fihwSKf0G/PQDqrRmjUCewuW+k
              /iXMe1Y/y0PjFeNlSbUsUvKQ5xF7F/1AnpuPHIrn3cjGVLb71W+zen1m8SnhsW/f
              7dPgtcb4SCvfhmLgoov+P34YcNfGi6qgPUu6319IqoB3BIi7PvfEomkCgYEAwZ4+
              V0bMjFdDn2hnYzjTNcF2aUQ1jPvtuETizGwyCbbMLl9522lrjC2DrH41vvqX35ct
              CBJkhQFbtHM8Gnmozv0vxhI2jP+u14mzfePZsaXuYrEgWRj+BCsYUHodXryxnEWj
              yVrTNskab1B5jFm2SCJDmKcycBOYpRBLCMx6W7MCgYBA99z7/6KboOIzzKrJdGup
              jLV410UyMIikoccQ7pD9jhRTPS80yjsY4dHqlEVJw5XSWvPb9DTTITi6p44EvBep
              6BKMuTMnQELUEr0O7KypVCfa4FTOl8BX28f+4kU3OGykxc6R8qkC0VGwTohV1UWB
              ITsgGhZV4uOA9uDI3T8KMQKBgEnQY2HwmuDSD/TA39GDA3qV8+ez2lqSXRGIKZLX
              mMf9SaBQQ+uzKA4799wWDbVuYeIbB07xfCL83pJP8FUDlqi6+7Celu9wNp7zX1ua
              Nw8z/ErhzjxJe+Xo7A8aTwIkG+5A2m1UU/up9YsEeiJYvVaIwY58B42U2vfq20BS
              fD9jAoGAX2MscBzIsmN+U9R0ptL4SXcPiVnOl8mqvQWr1B4OLgxX7ghht5Fs956W
              bHipxOWMFCPJA/AhNB8q1DvYiD1viZbIALSCJVUkzs4AEFIjiPsCBKxerl7jF6Xp
              1WYSaCmfvoCVEpFNt8cKp4Gq+zEBYAV4Q6TkcD2lDtEW49MuN8A=
              -----END RSA PRIVATE KEY-----
              PKCS7
          end

          let(:public_key) do
            <<-PKCS7.unindent
              -----BEGIN CERTIFICATE-----
              MIIC2TCCAcGgAwIBAgIBATANBgkqhkiG9w0BAQUFADAAMCAXDTE3MDExMzA5MTY1
              MloYDzIwNjcwMTAxMDkxNjUyWjAAMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
              CgKCAQEAwHB3GvImq59em4LV9DMfP0Zjs21eW3Jd5I9fuY0jLJhIkH6fCR7tyOpY
              V6xUj+TF8giq9WLxZI7sourMJMWjEWhVjgUr5lqp1RLv4lwfDv3Wk4XC2LUuqj1I
              AErUXKeRz8i3lUSZW1Pf4CaMpnIiPdWbz6f0KkaJSFi9bqexONBx4fKQNlgZwm2/
              aYjjrYng788I0QhWDKUqsQOi5mZKlHNRsDlk7J3Afhsx/jTLrCX/G8+2tPtLsHyR
              N39kluM5vYHbKXDsCG/a88Z2yUE2+r4Clp0FUKffiEDBPm0/H0sQ4Q1oEfQFDQRK
              aIkhpsm0nOnLYTy3/xJc5uqDNkLiawIDAQABo1wwWjAPBgNVHRMBAf8EBTADAQH/
              MB0GA1UdDgQWBBSejWrVnw7QaBjNFCHMNFi+doSOcTAoBgNVHSMEITAfgBSejWrV
              nw7QaBjNFCHMNFi+doSOcaEEpAIwAIIBATANBgkqhkiG9w0BAQUFAAOCAQEAAe85
              BQ1ydAHFqo0ib38VRPOwf5xPHGbYGhvQi4/sU6aTuR7pxaOJPYz05jLhS+utEmy1
              sknBq60G67yhQE7IHcfwrl1arirG2WmKGvAbjeYL2K1UiU0pVD3D+Klkv/pK6jIQ
              eOJRGb3qNUn0Sq9EoYIOXiGXQ641F0bZZ0+5H92kT1lmnF5oLfCb84ImD9T3snH6
              pIr5RKRx/0YmJIcv3WdpoPT903rOJiRIEgIj/hDk9QZTBpm222Ul5yQQ5pBywpSp
              xh0bmJKAQWhQm7QlybKfyaQmg5ot1jEzWAvD2I5FjHQxmAlchjb6RreaRhExj+JE
              5O117dMBdzDBjcNMOA==
              -----END CERTIFICATE-----
              PKCS7
          end

          let(:keys_dir) do
            keys = tmpdir('keys')
            dir_contained_in(keys, {
              private_key_name => private_key,
              public_key_name => public_key
            })
            keys
          end

          let(:private_key_path) { File.join(keys_dir, private_key_name) }
          let(:public_key_path) { File.join(keys_dir, public_key_name) }
          let(:hiera_yaml) do
            <<-YAML.unindent
            :backends:
              - eyaml
              - yaml
            :eyaml:
              :datadir: #{code_dir}/hieradata
              :pkcs7_private_key: #{private_key_path}
              :pkcs7_public_key: #{public_key_path}
            :yaml:
              :datadir: #{code_dir}/hieradata
            :hierarchy:
              - common
           YAML
          end

          let(:data_files) do
            {
              'common.yaml' => <<-YAML.unindent,
                b: value 'b' (from global)
                c:
                  c_a: value c_a (from global)
                YAML
              'common.eyaml' => <<-YAML.unindent
                a: >
                  ENC[PKCS7,MIIBmQYJKoZIhvcNAQcDoIIBijCCAYYCAQAxggEhMIIBHQIBADAFMAACAQEw
                  DQYJKoZIhvcNAQEBBQAEggEAH457bsfL8kYw9O50roE3dcE21nCnmPnQ2XSX
                  LYRJ2C78LarbfFonKz0gvDW7tyhsLWASFCFaiU8T1QPBd2b3hoQK8E4B2Ual
                  xga/K7r9y3OSgRomTm9tpTltC6re0Ubh3Dy71H61obwxEdNVTqjPe95+m2b8
                  6zWZVnzZzXXsTG1S17yJn1zaB/LXHbWNy4KyLLKCGAml+Gfl6ZMjmaplTmUA
                  QIC5rI8abzbPP3TDMmbLOGNkrmLqI+3uS8tSueTMoJmWaMF6c+H/cA7oRxmV
                  QCeEUVXjyFvCHcmbA+keS/RK9XF+vc07/XS4XkYSPs/I5hLQji1y9bkkGAs0
                  tehxQjBcBgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBDHpA6Fcl/R16aIYcow
                  oiO4gDAvfFH6jLUwXkcYtagnwdmhkd9TQJtxNWcIwMpvmk036MqIoGwwhQdg
                  gV4beiCFtLU=]
                a_ref: "A reference to %{hiera('a')}"
                b_ref: "A reference to %{hiera('b')}"
                c_ref: "%{alias('c')}"
                YAML
            }
          end

          let(:code_dir_files) do
            {
              'hiera.yaml' => hiera_yaml,
              'hieradata' => data_files
            }
          end

          before(:each) do
            Puppet.settings[:hiera_config] = File.join(code_dir, 'hiera.yaml')
          end

          it 'finds data in the global layer' do
            expect(lookup('a')).to eql("Encrypted value 'a' (from global)")
          end

          it 'can use a hiera interpolation' do
            expect(lookup('a_ref')).to eql("A reference to Encrypted value 'a' (from global)")
          end

          it 'can use a hiera interpolation that refers back to yaml' do
            expect(lookup('b_ref')).to eql("A reference to value 'b' (from global)")
          end

          it 'can use a hiera interpolation that refers back to yaml, but only in global layer' do
            expect(lookup(['c', 'c_ref'], 'merge' => 'deep')).to eql([{'c_a' => 'value c_a (from global)', 'c_b' => 'value c_b (from environment)'}, { 'c_a' => 'value c_a (from global)' }])
          end

          it 'delegates configured eyaml backend to eyaml_lookup_key function' do
            expect(explain('a')).to match(/Hierarchy entry "eyaml"\n.*\n.*\n.*"common"\n\s*Found key: "a"/m)
          end
        end

        context 'using deep_merge_options' do
          let(:hiera_yaml) do
            <<-YAML.unindent
              ---
              :backends:
                - yaml
              :yaml:
                :datadir: #{code_dir}/hieradata
              :hierarchy:
                - common
                - other
              :merge_behavior: deeper
              :deep_merge_options:
                :unpack_arrays: ','
              YAML
          end

          let(:code_dir_files) do
            {
              'hiera.yaml' => hiera_yaml,
              'hieradata' => {
                'common.yaml' => <<-YAML.unindent,
                  hash:
                    array:
                      - x1,x2
                  array:
                    - x1,x2
                  str: a string
                  mixed:
                    x: hx
                    y: hy
                  YAML
                'other.yaml' => <<-YAML.unindent,
                  hash:
                    array:
                      - x3
                      - x4
                  array:
                    - x3
                    - x4
                  str: another string
                  mixed:
                    - h1
                    - h2
                  YAML
              }
            }
          end

          it 'ignores configured merge_behavior when looking up arrays' do
            expect(lookup('array')).to eql(['x1,x2'])
          end

          it 'ignores configured merge_behavior when merging arrays' do
            expect(lookup('array', 'merge' => 'unique')).to eql(['x1,x2', 'x3', 'x4'])
          end

          it 'ignores configured merge_behavior when looking up hashes' do
            expect(lookup('hash')).to eql({'array' => ['x1,x2']})
          end

          it 'ignores configured merge_behavior when merging hashes' do
            expect(lookup('hash', 'merge' => 'hash')).to eql({'array' => ['x1,x2']})
          end
        end

        context 'using relative datadir paths' do
          let(:hiera_yaml) do
            <<-YAML.unindent
          ---
          :backends:
            - yaml
          :yaml:
            :datadir: relative_data
          :hierarchy:
            - common
            YAML
          end

          let(:populated_code_dir) do
            dir_contained_in(code_dir, code_dir_files.merge({
              'fake_cwd' => {
                'relative_data' => {
                  'common.yaml' => <<-YAML.unindent
                    a: value a (from fake_cwd/relative_data/common.yaml)
                  YAML
                }
              }
            }))
            code_dir
          end

          around(:each) do |example|
            cwd = Dir.pwd
            Dir.chdir(File.join(code_dir, 'fake_cwd'))
            begin
              example.run
            ensure
              Dir.chdir(cwd)
            end
          end

          it 'finds data from data file beneath relative datadir' do
            expect(lookup('a')).to eql('value a (from fake_cwd/relative_data/common.yaml)')
          end
        end
      end

      context 'version 5' do
        let(:scope_additions) { { 'ipl_datadir' => 'hieradata' } }
        let(:hiera_yaml) do
          <<-YAML.unindent
          ---
          version: 5
          defaults:
            datadir: "%{ipl_datadir}"

          hierarchy:
            - name: Yaml
              data_hash: yaml_data
              paths:
                - common.yaml
                - "%{domain}.yaml"
            - name: Json
              data_hash: json_data
              paths:
                - common.json
                - "%{domain}.json"
            - name: Hocon
              data_hash: hocon_data
              paths:
                - common.conf
                - "%{domain}.conf"
            - name: Custom
              hiera3_backend: custom
              paths:
                - common.custom
                - "%{domain}.custom"
            - name: Other
              hiera3_backend: other
              options:
                other_option: value of other_option
              paths:
                - common.other
                - "%{domain}.other"
              YAML
        end

        it 'finds global data and reports no deprecation warnings' do
          expect(lookup('a')).to eql('value a (from global)')
          expect(warnings).to be_empty
        end

        it 'explain contains output from global layer' do
          explanation = explain('a')
          expect(explanation).to include('Global Data Provider (hiera configuration version 5)')
          expect(explanation).to include('Hierarchy entry "Yaml"')
          expect(explanation).to include('Hierarchy entry "Json"')
          expect(explanation).to include('Hierarchy entry "Hocon"')
          expect(explanation).to include('Hierarchy entry "Custom"')
          expect(explanation).to include('Found key: "a" value: "value a (from global)"')
        end

        it 'uses the explicitly given merge to override lookup options and to merge all layers' do
          expect(lookup('hash_c', 'merge' => 'deep')).to eql(
            {
              'hash_ca' =>
                {
                  'caa' => 'value hash_c.hash_ca.caa (from environment)',
                  'cab' => 'value hash_c.hash_ca.cab (from global)',
                  'cac' => 'value hash_c.hash_ca.cac (from global json)',
                  'cad' => 'value hash_c.hash_ca.cad (from global custom)'
                }
            })
        end

        it 'backend data sources are propagated to custom backend' do
          expect(lookup('datasources')).to eql(['common', 'example.com'])
        end

        it 'backend specific options are propagated to custom backend' do
          expect(lookup('other_option')).to eql('value of other_option')
        end

        it 'dotted keys are passed down to custom backend' do
          expect(lookup('dotted.key')).to eql('custom backend received request for dotted.key value')
        end

        it 'multiple hiera3_backend declarations can be used and are merged into the generated config' do
          expect(lookup(['datasources', 'other_option'])).to eql([['common', 'example.com'], 'value of other_option'])
          expect(Hiera::Config.instance_variable_get(:@config)).to eql(
            {
              :backends => ['custom', 'other'],
              :hierarchy => ['common', '%{domain}'],
              :custom => { :datadir => "#{code_dir}/hieradata" },
              :other => { :other_option => 'value of other_option', :datadir=>"#{code_dir}/hieradata" },
              :logger => 'puppet'
            })
        end

        it 'provides a sensible error message when the hocon library is not loaded' do
          allow(Puppet.features).to receive(:hocon?).and_return(false)

          expect { lookup('a') }.to raise_error do |e|
            expect(e.message).to match(/Lookup using Hocon data_hash function is not supported without hocon library/)
          end
        end

        context 'with missing path declaraion' do
          context 'and yaml_data function' do
            let(:hiera_yaml) { <<-YAML.unindent }
              version: 5
              hierarchy:
                - name: Yaml
                  data_hash: yaml_data
              YAML

            it 'fails and reports the missing path' do
              expect { lookup('a') }.to raise_error(/one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function/)
            end
          end

          context 'and json_data function' do
            let(:hiera_yaml) { <<-YAML.unindent }
              version: 5
              hierarchy:
                - name: Json
                  data_hash: json_data
              YAML

            it 'fails and reports the missing path' do
              expect { lookup('a') }.to raise_error(/one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function/)
            end
          end

          context 'and hocon_data function' do
            let(:hiera_yaml) { <<-YAML.unindent }
              version: 5
              hierarchy:
                - name: Hocon
                  data_hash: hocon_data
              YAML

            it 'fails and reports the missing path' do
              expect { lookup('a') }.to raise_error(/one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function/)
            end
          end

          context 'and eyaml_lookup_key function' do
            let(:hiera_yaml) { <<-YAML.unindent }
              version: 5
              hierarchy:
                - name: Yaml
                  lookup_key: eyaml_lookup_key
              YAML

            it 'fails and reports the missing path' do
              expect { lookup('a') }.to raise_error(/one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this lookup_key function/)
            end
          end
        end
      end

      context 'with a hiera3_backend that has no paths' do
        let(:hiera_yaml) do
          <<-YAML.unindent
          ---
          version: 5
          hierarchy:
            - name: Custom
              hiera3_backend: custom
          YAML
        end

        it 'calls the backend' do
          expect(lookup('hash_c')).to eql(
            { 'hash_ca' => { 'cad' => 'value hash_c.hash_ca.cad (from global custom)' }})
        end
      end
    end

    context 'and a module' do
      let(:mod_a_files) { {} }

      let(:populated_env_dir) do
        dir_contained_in(env_dir, DeepMerge.deep_merge!(environment_files, env_name => { 'modules' => mod_a_files }))
        env_dir
      end

      context 'that has no lookup configured' do
        let(:mod_a_files) do
          {
            'mod_a' => {
              'data' => {
                'common.yaml' => <<-YAML.unindent
                ---
                mod_a::b: value mod_a::b (from mod_a)
              YAML
              }
            }
          }
        end

        it 'does not find data in the module' do
          expect { lookup('mod_a::b') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value for the name 'mod_a::b'/)
        end

        context 'with a Hiera v3 configuration' do
          let(:mod_a_files) do
            {
              'mod_a' => {
                'hiera.yaml' => <<-YAML.unindent
                  ---
                  :backends: yaml
                  YAML
              }
            }
          end

          it 'raises a warning' do
            expect(lookup('mod_a::a')).to eql('value mod_a::a (from environment)')
            expect(warnings).to include(/hiera.yaml version 3 found at module root was ignored/)
          end
        end

        context "but a metadata.json with 'module_data_provider=hiera'" do
          let(:mod_a_files_1) { DeepMerge.deep_merge!(mod_a_files, 'mod_a' => { 'metadata.json' => <<-JSON.unindent }) }
              {
                  "name": "example/mod_a",
                  "version": "0.0.2",
                  "source": "git@github.com/example/mod_a.git",
                  "dependencies": [],
                  "author": "Bob the Builder",
                  "license": "Apache-2.0",
                  "data_provider": "hiera"
              }
              JSON

          let(:populated_env_dir) do
            dir_contained_in(env_dir, DeepMerge.deep_merge!(environment_files, env_name => { 'modules' => mod_a_files_1 }))
            env_dir
          end

          it 'finds data in the module and reports deprecation warning for metadata.json' do
            expect(lookup('mod_a::b')).to eql('value mod_a::b (from mod_a)')
            expect(warnings).to include(/Defining "data_provider": "hiera" in metadata.json is deprecated. A 'hiera.yaml' file should be used instead/)
          end

          context 'and a hiera.yaml file' do
            let(:mod_a_files_2) { DeepMerge.deep_merge!(mod_a_files_1, 'mod_a' => { 'hiera.yaml' => <<-YAML.unindent }) }
            ---
            version: 4
            hierarchy:
              - name: common
                backend: yaml
            YAML

            let(:populated_env_dir) do
              dir_contained_in(env_dir, DeepMerge.deep_merge!(environment_files, env_name => { 'modules' => mod_a_files_2 }))
              env_dir
            end

            it 'finds data in the module and reports deprecation warnings for both metadata.json and hiera.yaml' do
              expect(lookup('mod_a::b')).to eql('value mod_a::b (from mod_a)')
              expect(warnings).to include(/Defining "data_provider": "hiera" in metadata.json is deprecated/)
              expect(warnings).to include(/Use of 'hiera.yaml' version 4 is deprecated. It should be converted to version 5/)
            end
          end
        end
      end

      context 'using deep merge and module values that aliases environment values' do
        let(:mod_a_files) do
          {
            'mod_a' => {
              'data' => {
                'common.yaml' => <<-YAML.unindent,
                  ---
                  mod_a::hash:
                    b: value b (from module)
                  lookup_options:
                    mod_a::hash:
                      merge: deep
                  YAML
              },
              'hiera.yaml' => <<-YAML.unindent,
                ---
                version: 5
                hierarchy:
                  - name: "Common"
                    path: "common.yaml"
                  - name: "Other"
                    path: "other.yaml"
                YAML
            }
          }
        end
        let(:env_data) do
          {
            'common.yaml' => <<-YAML.unindent
              a: value a (from environment)
              mod_a::hash:
                a: value mod_a::hash.a (from environment)
                c: '%{alias("a")}'
              YAML
          }
        end

        it 'continues with module lookup after alias is resolved in environment' do
          expect(lookup('mod_a::hash')).to eql(
            {
              'a' => 'value mod_a::hash.a (from environment)',
              'b' => 'value b (from module)',
              'c' => 'value a (from environment)'
            })
        end
      end

      context 'using a data_hash that reads a yaml file' do
        let(:defaults) {
          {
            'mod_a::xd' => 'value mod_a::xd (from default)',
            'mod_a::xd_found' => 'value mod_a::xd_found (from default)',
            'scope_xd' => 'value scope_xd (from default)'
          }}
        let(:overrides) {
          {
            'mod_a::xo' => 'value mod_a::xo (from override)',
            'scope_xo' => 'value scope_xo (from override)'
          }}

        let(:scope_additions) do
          {
            'scope_scalar' => 'scope scalar value',
            'scope_hash' => { 'a' => 'scope hash a', 'b' => 'scope hash b' }
          }
        end
        let(:mod_a_files) do
          {
            'mod_a' => {
              'data' => {
                'common.yaml' => <<-YAML.unindent
                ---
                mod_a::a: value mod_a::a (from mod_a)
                mod_a::b: value mod_a::b (from mod_a)
                mod_a::xo: value mod_a::xo (from mod_a)
                mod_a::xd_found: value mod_a::xd_found (from mod_a)
                mod_a::interpolate_xo: "-- %{lookup('mod_a::xo')} --"
                mod_a::interpolate_xd: "-- %{lookup('mod_a::xd')} --"
                mod_a::interpolate_scope_xo: "-- %{scope_xo} --"
                mod_a::interpolate_scope_xd: "-- %{scope_xd} --"
                mod_a::hash_a:
                  a: value mod_a::hash_a.a (from mod_a)
                  b: value mod_a::hash_a.b (from mod_a)
                mod_a::hash_b:
                  a: value mod_a::hash_b.a (from mod_a)
                  b: value mod_a::hash_b.b (from mod_a)
                mod_a::interpolated: "-- %{lookup('mod_a::a')} --"
                mod_a::a_a: "-- %{lookup('mod_a::hash_a.a')} --"
                mod_a::a_b: "-- %{lookup('mod_a::hash_a.b')} --"
                mod_a::b_a: "-- %{lookup('mod_a::hash_b.a')} --"
                mod_a::b_b: "-- %{lookup('mod_a::hash_b.b')} --"
                mod_a::interpolate_array:
                  - "-- %{lookup('mod_a::a')} --"
                  - "-- %{lookup('mod_a::b')} --"
                mod_a::interpolate_literal: "-- %{literal('hello')} --"
                mod_a::interpolate_scope: "-- %{scope_scalar} --"
                mod_a::interpolate_scope_not_found: "-- %{scope_nope} --"
                mod_a::interpolate_scope_dig: "-- %{scope_hash.a} --"
                mod_a::interpolate_scope_dig_not_found: "-- %{scope_hash.nope} --"
                mod_a::quoted_interpolation: '-- %{lookup(''"mod_a::a.quoted.key"'')} --'
                "mod_a::a.quoted.key": "value mod_a::a.quoted.key (from mod_a)"
              YAML
              },
              'hiera.yaml' => <<-YAML.unindent,
              ---
              version: 5
              hierarchy:
                - name: "Common"
                  data_hash: yaml_data
                  path: "common.yaml"
            YAML
            }
          }
        end

        it 'finds data in the module' do
          expect(lookup('mod_a::b')).to eql('value mod_a::b (from mod_a)')
        end

        it 'environment data has higher priority than module data' do
          expect(lookup('mod_a::a')).to eql('value mod_a::a (from environment)')
        end

        it 'environment data has higher priority than module data in interpolated module data' do
          expect(lookup('mod_a::interpolated')).to eql('-- value mod_a::a (from environment) --')
        end

        it 'overrides have higher priority than found data' do
          expect(lookup('mod_a::xo', { 'override' => overrides })).to eql('value mod_a::xo (from override)')
        end

        it 'overrides have higher priority than found data in lookup interpolations' do
          expect(lookup('mod_a::interpolate_xo', { 'override' => overrides })).to eql('-- value mod_a::xo (from override) --')
        end

        it 'overrides have higher priority than found data in scope interpolations' do
          expect(lookup('mod_a::interpolate_scope_xo', { 'override' => overrides })).to eql('-- value scope_xo (from override) --')
        end

        it 'defaults have lower priority than found data' do
          expect(lookup('mod_a::xd_found', { 'default_values_hash' => defaults })).to eql('value mod_a::xd_found (from mod_a)')
        end

        it 'defaults are used when data is not found' do
          expect(lookup('mod_a::xd', { 'default_values_hash' => defaults })).to eql('value mod_a::xd (from default)')
        end

        it 'defaults are used when data is not found in lookup interpolations' do
          expect(lookup('mod_a::interpolate_xd', { 'default_values_hash' => defaults })).to eql('-- value mod_a::xd (from default) --')
        end

        it 'defaults are used when data is not found in scope interpolations' do
          expect(lookup('mod_a::interpolate_scope_xd', { 'default_values_hash' => defaults })).to eql('-- value scope_xd (from default) --')
        end

        it 'merges hashes from environment and module unless strategy hash is used' do
          expect(lookup('mod_a::hash_a')).to eql({'a' => 'value mod_a::hash_a.a (from environment)'})
        end

        it 'merges hashes from environment and module when merge strategy hash is used' do
          expect(lookup('mod_a::hash_a', :merge => 'hash')).to eql(
            {'a' => 'value mod_a::hash_a.a (from environment)', 'b' => 'value mod_a::hash_a.b (from mod_a)'})
        end

        it 'will not merge hashes from environment and module in interpolated expressions' do
          expect(lookup(['mod_a::a_a', 'mod_a::a_b'])).to eql(
            ['-- value mod_a::hash_a.a (from environment) --', '--  --']) # root key found in environment, no hash merge is performed
        end

        it 'interpolates arrays' do
          expect(lookup('mod_a::interpolate_array')).to eql(['-- value mod_a::a (from environment) --', '-- value mod_a::b (from mod_a) --'])
        end

        it 'can dig into arrays using subkeys' do
          expect(lookup('mod_a::interpolate_array.1')).to eql('-- value mod_a::b (from mod_a) --')
        end

        it 'treats an out of range subkey as not found' do
          expect(explain('mod_a::interpolate_array.2')).to match(/No such key: "2"/)
        end

        it 'interpolates a literal' do
          expect(lookup('mod_a::interpolate_literal')).to eql('-- hello --')
        end

        it 'interpolates scalar from scope' do
          expect(lookup('mod_a::interpolate_scope')).to eql('-- scope scalar value --')
        end

        it 'interpolates not found in scope as empty string' do
          expect(lookup('mod_a::interpolate_scope_not_found')).to eql('--  --')
        end

        it 'interpolates dotted key from scope' do
          expect(lookup('mod_a::interpolate_scope_dig')).to eql('-- scope hash a --')
        end

        it 'treates interpolated dotted key but not found in scope as empty string' do
          expect(lookup('mod_a::interpolate_scope_dig_not_found')).to eql('--  --')
        end

        it 'can use quoted keys in interpolation' do
          expect(lookup('mod_a::quoted_interpolation')).to eql('-- value mod_a::a.quoted.key (from mod_a) --') # root key found in environment, no hash merge is performed
        end

        it 'merges hashes from environment and module in interpolated expressions if hash merge is specified in lookup options' do
          expect(lookup(['mod_a::b_a', 'mod_a::b_b'])).to eql(
            ['-- value mod_a::hash_b.a (from environment) --', '-- value mod_a::hash_b.b (from mod_a) --'])
        end
      end

      context 'using a lookup_key that uses a path' do
        let(:mod_a_files) do
          {
            'mod_a' => {
              'functions' => {
                'pp_lookup_key.pp' => <<-PUPPET.unindent
                  function mod_a::pp_lookup_key($key, $options, $context) {
                    if !$context.cache_has_key(undef) {
                      $context.cache_all(yaml_data($options, $context))
                      $context.cache(undef, true)
                    }
                    if $context.cache_has_key($key) { $context.cached_value($key) } else { $context.not_found }
                  }
                  PUPPET
              },
              'hiera.yaml' => <<-YAML.unindent,
                ---
                version: 5
                hierarchy:
                  - name: "Common"
                    lookup_key: mod_a::pp_lookup_key
                    path: common.yaml
                YAML
              'data' => {
                'common.yaml' => <<-YAML.unindent
                  mod_a::b: value mod_a::b (from mod_a)
                  YAML
              }
            }
          }
        end

        it 'finds data in the module' do
          expect(lookup('mod_a::b')).to eql('value mod_a::b (from mod_a)')
        end
      end

      context 'using a lookup_key that is a puppet function' do
        let(:puppet_function) { <<-PUPPET.unindent }
          function mod_a::pp_lookup_key(Puppet::LookupKey $key, Hash[String,String] $options, Puppet::LookupContext $context) >> Puppet::LookupValue {
            case $key {
              'mod_a::really_interpolated': { $context.interpolate("-- %{lookup('mod_a::a')} --") }
              'mod_a::recursive': { lookup($key) }
              default: {
                if $context.cache_has_key(mod_a::a) {
                  $context.explain || { 'reusing cache' }
                } else {
                  $context.explain || { 'initializing cache' }
                  $context.cache_all({
                    mod_a::a => 'value mod_a::a (from mod_a)',
                    mod_a::b => 'value mod_a::b (from mod_a)',
                    mod_a::c => 'value mod_a::c (from mod_a)',
                    mod_a::hash_a => {
                      a => 'value mod_a::hash_a.a (from mod_a)',
                      b => 'value mod_a::hash_a.b (from mod_a)'
                    },
                    mod_a::hash_b => {
                      a => 'value mod_a::hash_b.a (from mod_a)',
                      b => 'value mod_a::hash_b.b (from mod_a)'
                    },
                    mod_a::interpolated => "-- %{lookup('mod_a::a')} --",
                    mod_a::a_a => "-- %{lookup('mod_a::hash_a.a')} --",
                    mod_a::a_b => "-- %{lookup('mod_a::hash_a.b')} --",
                    mod_a::b_a => "-- %{lookup('mod_a::hash_b.a')} --",
                    mod_a::b_b => "-- %{lookup('mod_a::hash_b.b')} --",
                    'mod_a::a.quoted.key' => 'value mod_a::a.quoted.key (from mod_a)',
                    mod_a::sensitive => Sensitive('reduct me please'),
                    mod_a::type => Object[{name => 'FindMe', 'attributes' => {'x' => String}}],
                    mod_a::version => SemVer('3.4.1'),
                    mod_a::version_range => SemVerRange('>=3.4.1'),
                    mod_a::timestamp => Timestamp("1994-03-25T19:30:00"),
                    mod_a::timespan => Timespan("3-10:00:00")
                  })
                }
                if !$context.cache_has_key($key) {
                  $context.not_found
                }
                $context.explain || { "returning value for $key" }
                $context.cached_value($key)
              }
            }
          }
        PUPPET

        let(:mod_a_files) do
          {
            'mod_a' => {
              'functions' => {
                'pp_lookup_key.pp' => puppet_function
              },
              'hiera.yaml' => <<-YAML.unindent,
              ---
              version: 5
              hierarchy:
                - name: "Common"
                  lookup_key: mod_a::pp_lookup_key
            YAML
            }
          }
        end

        it 'finds data in the module' do
          expect(lookup('mod_a::b')).to eql('value mod_a::b (from mod_a)')
        end

        it 'environment data has higher priority than module data' do
          expect(lookup('mod_a::a')).to eql('value mod_a::a (from environment)')
        end

        it 'finds quoted keys in the module' do
          expect(lookup('"mod_a::a.quoted.key"')).to eql('value mod_a::a.quoted.key (from mod_a)')
        end

        it 'will not resolve interpolated expressions' do
          expect(lookup('mod_a::interpolated')).to eql("-- %{lookup('mod_a::a')} --")
        end

        it 'resolves interpolated expressions using Context#interpolate' do
          expect(lookup('mod_a::really_interpolated')).to eql("-- value mod_a::a (from environment) --")
        end

        it 'will not merge hashes from environment and module unless strategy hash is used' do
          expect(lookup('mod_a::hash_a')).to eql({ 'a' => 'value mod_a::hash_a.a (from environment)' })
        end

        it 'merges hashes from environment and module when merge strategy hash is used' do
          expect(lookup('mod_a::hash_a', :merge => 'hash')).to eql({ 'a' => 'value mod_a::hash_a.a (from environment)', 'b' => 'value mod_a::hash_a.b (from mod_a)' })
        end

        it 'traps recursive lookup trapped' do
          expect(explain('mod_a::recursive')).to include('Recursive lookup detected')
        end

        it 'private cache is persisted over multiple calls' do
          collect_notices("notice(lookup('mod_a::b')) notice(lookup('mod_a::c'))", true)
          expect(notices).to eql(['value mod_a::b (from mod_a)', 'value mod_a::c (from mod_a)'])
          expect(explanation).to match(/initializing cache.*reusing cache/m)
          expect(explanation).not_to match(/initializing cache.*initializing cache/m)
        end

        it 'the same key is requested only once' do
          collect_notices("notice(lookup('mod_a::b')) notice(lookup('mod_a::b'))", true)
          expect(notices).to eql(['value mod_a::b (from mod_a)', 'value mod_a::b (from mod_a)'])
          expect(explanation).to match(/Found key: "mod_a::b".*Found key: "mod_a::b"/m)
          expect(explanation).to match(/returning value for mod_a::b/m)
          expect(explanation).not_to match(/returning value for mod_a::b.*returning value for mod_a::b/m)
        end

        context 'and calling function via API' do
          it 'finds and delivers rich data' do
            collect_notices("notice('success')") do |scope|
              expect(lookup_func.call(scope, 'mod_a::sensitive')).to be_a(Puppet::Pops::Types::PSensitiveType::Sensitive)
              expect(lookup_func.call(scope, 'mod_a::type')).to be_a(Puppet::Pops::Types::PObjectType)
              expect(lookup_func.call(scope, 'mod_a::version')).to eql(SemanticPuppet::Version.parse('3.4.1'))
              expect(lookup_func.call(scope, 'mod_a::version_range')).to eql(SemanticPuppet::VersionRange.parse('>=3.4.1'))
              expect(lookup_func.call(scope, 'mod_a::timestamp')).to eql(Puppet::Pops::Time::Timestamp.parse('1994-03-25T19:30:00'))
              expect(lookup_func.call(scope, 'mod_a::timespan')).to eql(Puppet::Pops::Time::Timespan.parse('3-10:00:00'))
            end
            expect(notices).to eql(['success'])
          end
        end

        context 'with declared but incompatible return_type' do
          let(:puppet_function) { <<-PUPPET.unindent }
            function mod_a::pp_lookup_key(Puppet::LookupKey $key, Hash[String,String] $options, Puppet::LookupContext $context) >> Runtime['ruby','Symbol'] {
              undef
            }
            PUPPET

          it 'fails and reports error' do
            expect{lookup('mod_a::a')}.to raise_error(
              "Return type of 'lookup_key' function named 'mod_a::pp_lookup_key' is incorrect, expects a RichData value, got Runtime")
          end
        end
      end

      context 'using a data_dig that is a ruby function' do
        let(:mod_a_files) do
          {
            'mod_a' => {
              'lib' => {
                'puppet' => {
                  'functions' => {
                    'mod_a' => {
                      'ruby_dig.rb' => <<-RUBY.unindent
                      Puppet::Functions.create_function(:'mod_a::ruby_dig') do
                        dispatch :ruby_dig do
                          param 'Array[String[1]]', :segments
                          param 'Hash[String,Any]', :options
                          param 'Puppet::LookupContext', :context
                          return_type 'Puppet::LookupValue'
                        end

                        def ruby_dig(segments, options, context)
                          sub_segments = segments.dup
                          root_key = sub_segments.shift
                          case root_key
                          when 'mod_a::options'
                            hash = { 'mod_a::options' => options }
                          when 'mod_a::lookup'
                            return call_function('lookup', segments.join('.'))
                          else
                            hash = {
                              'mod_a::a' => 'value mod_a::a (from mod_a)',
                              'mod_a::b' => 'value mod_a::b (from mod_a)',
                              'mod_a::hash_a' => {
                                'a' => 'value mod_a::hash_a.a (from mod_a)',
                                'b' => 'value mod_a::hash_a.b (from mod_a)'
                              },
                              'mod_a::hash_b' => {
                                'a' => 'value mod_a::hash_b.a (from mod_a)',
                                'b' => 'value mod_a::hash_b.b (from mod_a)'
                              },
                              'mod_a::interpolated' => "-- %{lookup('mod_a::a')} --",
                              'mod_a::really_interpolated' => "-- %{lookup('mod_a::a')} --",
                              'mod_a::a_a' => "-- %{lookup('mod_a::hash_a.a')} --",
                              'mod_a::a_b' => "-- %{lookup('mod_a::hash_a.b')} --",
                              'mod_a::b_a' => "-- %{lookup('mod_a::hash_b.a')} --",
                              'mod_a::b_b' => "-- %{lookup('mod_a::hash_b.b')} --",
                              'mod_a::bad_type' => :oops,
                              'mod_a::bad_type_in_hash' => { 'a' => :oops },
                            }
                            end
                          context.not_found unless hash.include?(root_key)
                          value = sub_segments.reduce(hash[root_key]) do |memo, segment|
                            context.not_found unless memo.is_a?(Hash) && memo.include?(segment)
                            memo[segment]
                          end
                          root_key == 'mod_a::really_interpolated' ? context.interpolate(value) : value
                        end
                      end
                    RUBY
                    }
                  }
                }
              },
              'hiera.yaml' => <<-YAML.unindent,
              ---
              version: 5
              defaults:
                options:
                  option_b:
                    z: Default option value b.z

              hierarchy:
                - name: "Common"
                  data_dig: mod_a::ruby_dig
                  uri: "http://www.example.com/passed/as/option"
                  options:
                    option_a: Option value a
                    option_b:
                      x: Option value b.x
                      y: Option value b.y
                - name: "Extra"
                  data_dig: mod_a::ruby_dig
           YAML
            }
          }
        end

        it 'finds data in the module' do
          expect(lookup('mod_a::b')).to eql('value mod_a::b (from mod_a)')
        end

        it 'environment data has higher priority than module data' do
          expect(lookup('mod_a::a')).to eql('value mod_a::a (from environment)')
        end

        it 'will not resolve interpolated expressions' do
          expect(lookup('mod_a::interpolated')).to eql("-- %{lookup('mod_a::a')} --")
        end

        it 'resolves interpolated expressions using Context#interpolate' do
          expect(lookup('mod_a::really_interpolated')).to eql("-- value mod_a::a (from environment) --")
        end

        it 'does not accept return of runtime type from function' do
          # Message is produced by the called function, not by the lookup framework
          expect(explain('mod_a::bad_type')).to include("value returned from function 'ruby_dig' has wrong type")
        end

        it 'does not accept return of runtime type embedded in hash from function' do
          # Message is produced by the called function, not by the lookup framework
          expect(explain('mod_a::bad_type_in_hash')).to include("value returned from function 'ruby_dig' has wrong type")
        end

        it 'will not merge hashes from environment and module unless strategy hash is used' do
          expect(lookup('mod_a::hash_a')).to eql({'a' => 'value mod_a::hash_a.a (from environment)'})
        end

        it 'hierarchy entry options are passed to the function' do
          expect(lookup('mod_a::options.option_b.x')).to eql('Option value b.x')
        end

        it 'default options are passed to the function' do
          expect(lookup('mod_a::options.option_b.z')).to eql('Default option value b.z')
        end

        it 'default options are not merged with hierarchy options' do
          expect(lookup('mod_a::options')).to eql(
            {
              'option_a' => 'Option value a',
              'option_b' => {
                'y' => 'Option value b.y',
                'x' => 'Option value b.x'
              },
              'uri' => 'http://www.example.com/passed/as/option'
            })
        end

        it 'hierarchy entry "uri" is passed as location option to the function' do
          expect(lookup('mod_a::options.uri')).to eql('http://www.example.com/passed/as/option')
        end

        it 'recursive lookup is trapped' do
          expect(explain('mod_a::lookup.mod_a::lookup')).to include('Recursive lookup detected')
        end

        context 'with merge strategy hash' do
          it 'merges hashes from environment and module' do
            expect(lookup('mod_a::hash_a', :merge => 'hash')).to eql({'a' => 'value mod_a::hash_a.a (from environment)', 'b' => 'value mod_a::hash_a.b (from mod_a)'})
          end

          it 'will "undig" value from data_dig function, merge root hashes, and then dig to get values by subkey' do
            expect(lookup(['mod_a::hash_a.a', 'mod_a::hash_a.b'], :merge => 'hash')).to eql(
              ['value mod_a::hash_a.a (from environment)', 'value mod_a::hash_a.b (from mod_a)'])
          end
        end
      end

      context 'that has a default_hierarchy' do
        let(:mod_a_hiera_yaml) { <<-YAML.unindent }
          version: 5
          hierarchy:
            - name: "Common"
              path: common.yaml
            - name: "Common 2"
              path: common2.yaml

          default_hierarchy:
            - name: "Default"
              path: defaults.yaml
            - name: "Default 2"
              path: defaults2.yaml
          YAML

        let(:mod_a_common) { <<-YAML.unindent }
          mod_a::a: value mod_a::a (from module)
          mod_a::d:
            a: value mod_a::d.a (from module)
          mod_a::f:
            a:
              a: value mod_a::f.a.a (from module)
          mod_a::to_array1: 'hello'
          mod_a::to_array2: 'hello'
          mod_a::to_int: 'bananas'
          mod_a::to_bad_type: 'pyjamas'
          mod_a::undef_value: null
          lookup_options:
            mod_a::e:
              merge: deep
            mod_a::to_array1:
              merge: deep
              convert_to: "Array"
            mod_a::to_array2:
              convert_to:
                - "Array"
                - true
            mod_a::to_int:
              convert_to: "Integer"
            mod_a::to_bad_type:
              convert_to: "ComicSans"
            mod_a::undef_value:
              convert_to:
                - "Array"
                - true
          YAML


        let(:mod_a_common2) { <<-YAML.unindent }
          mod_a::b: value mod_a::b (from module)
          mod_a::d:
            c: value mod_a::d.c (from module)
          mod_a::f:
            a:
              b: value mod_a::f.a.b (from module)
          YAML

        let(:mod_a_defaults) { <<-YAML.unindent }
          mod_a::a: value mod_a::a (from module defaults)
          mod_a::b: value mod_a::b (from module defaults)
          mod_a::c: value mod_a::c (from module defaults)
          mod_a::d:
            b: value mod_a::d.b (from module defaults)
          mod_a::e:
            a:
              a: value mod_a::e.a.a (from module defaults)
          mod_a::g:
            a:
              a: value mod_a::g.a.a (from module defaults)
          lookup_options:
            mod_a::d:
              merge: hash
            mod_a::g:
              merge: deep
          YAML

        let(:mod_a_defaults2) { <<-YAML.unindent }
          mod_a::e:
            a:
              b: value mod_a::e.a.b (from module defaults)
          mod_a::g:
            a:
              b: value mod_a::g.a.b (from module defaults)
          YAML

        let(:mod_a_files) do
          {
            'mod_a' => {
              'data' => {
                'common.yaml' => mod_a_common,
                'common2.yaml' => mod_a_common2,
                'defaults.yaml' => mod_a_defaults,
                'defaults2.yaml' => mod_a_defaults2
              },
              'hiera.yaml' => mod_a_hiera_yaml
            }
          }
        end

        it 'the default hierarchy does not interfere with environment hierarchy' do
          expect(lookup('mod_a::a')).to eql('value mod_a::a (from environment)')
        end

        it 'the default hierarchy does not interfere with regular hierarchy in module' do
          expect(lookup('mod_a::b')).to eql('value mod_a::b (from module)')
        end

        it 'the default hierarchy is consulted when no value is found elsewhere' do
          expect(lookup('mod_a::c')).to eql('value mod_a::c (from module defaults)')
        end

        it 'the default hierarchy does not participate in a merge' do
          expect(lookup('mod_a::d', 'merge' => 'hash')).to eql('a' => 'value mod_a::d.a (from module)', 'c' => 'value mod_a::d.c (from module)')
        end

        it 'lookup_options from regular hierarchy does not effect values found in the default hierarchy' do
          expect(lookup('mod_a::e')).to eql('a' => { 'a' => 'value mod_a::e.a.a (from module defaults)' })
        end

        it 'lookup_options from default hierarchy affects values found in the default hierarchy' do
          expect(lookup('mod_a::g')).to eql('a' => { 'a' => 'value mod_a::g.a.a (from module defaults)', 'b' => 'value mod_a::g.a.b (from module defaults)'})
        end

        it 'merge parameter does not override lookup_options defined in the default hierarchy' do
          expect(lookup('mod_a::g', 'merge' => 'hash')).to eql(
            'a' => { 'a' => 'value mod_a::g.a.a (from module defaults)', 'b' => 'value mod_a::g.a.b (from module defaults)'})
        end

        it 'lookup_options from default hierarchy does not effect values found in the regular hierarchy' do
          expect(lookup('mod_a::d')).to eql('a' => 'value mod_a::d.a (from module)')
        end

        context "and conversion via convert_to" do
          it 'converts with a single data type value' do
            expect(lookup('mod_a::to_array1')).to eql(['h', 'e', 'l', 'l', 'o'])
          end

          it 'converts with an array of arguments to the convert_to call' do
            expect(lookup('mod_a::to_array2')).to eql(['hello'])
          end

          it 'converts an undef/nil value that has convert_to option' do
            expect(lookup('mod_a::undef_value')).to eql([nil])
          end

          it 'errors if a convert_to lookup_option cannot be performed because value does not match type' do
            expect{lookup('mod_a::to_int')}.to raise_error(/The convert_to lookup_option for key 'mod_a::to_int' raised error.*The string 'bananas' cannot be converted to Integer/)
          end

          it 'errors if a convert_to lookup_option cannot be performed because type does not exist' do
            expect{lookup('mod_a::to_bad_type')}.to raise_error(/The convert_to lookup_option for key 'mod_a::to_bad_type' raised error.*Creation of new instance of type 'TypeReference\['ComicSans'\]' is not supported/)
          end

          it 'adds explanation that conversion took place with a type' do
            explanation = explain('mod_a::to_array1')
            expect(explanation).to include('Applying convert_to lookup_option with arguments [Array]')
          end

          it 'adds explanation that conversion took place with a type and arguments' do
            explanation = explain('mod_a::to_array2')
            expect(explanation).to include('Applying convert_to lookup_option with arguments [Array, true]')
          end
        end

        it 'the default hierarchy lookup is included in the explain output' do
          explanation = explain('mod_a::c')
          expect(explanation).to match(/Searching default_hierarchy of module "mod_a".+Original path: "defaults.yaml"/m)
        end
      end
    end

    context 'and an eyaml lookup_key function' do
      let(:private_key_name) { 'private_key.pkcs7.pem' }
      let(:public_key_name) { 'public_key.pkcs7.pem' }

      let(:private_key) do
        <<-PKCS7.unindent
          -----BEGIN RSA PRIVATE KEY-----
          MIIEogIBAAKCAQEAwHB3GvImq59em4LV9DMfP0Zjs21eW3Jd5I9fuY0jLJhIkH6f
          CR7tyOpYV6xUj+TF8giq9WLxZI7sourMJMWjEWhVjgUr5lqp1RLv4lwfDv3Wk4XC
          2LUuqj1IAErUXKeRz8i3lUSZW1Pf4CaMpnIiPdWbz6f0KkaJSFi9bqexONBx4fKQ
          NlgZwm2/aYjjrYng788I0QhWDKUqsQOi5mZKlHNRsDlk7J3Afhsx/jTLrCX/G8+2
          tPtLsHyRN39kluM5vYHbKXDsCG/a88Z2yUE2+r4Clp0FUKffiEDBPm0/H0sQ4Q1o
          EfQFDQRKaIkhpsm0nOnLYTy3/xJc5uqDNkLiawIDAQABAoIBAE98pNXOe8ab93oI
          mtNZYmjCbGAqprTjEoFb71A3SfYbmK2Gf65GxjUdBwx/tBYTiuekSOk+yzKcDoZk
          sZnmwKpqDByzaiSmAkxunANFxdZtZvpcX9UfUX0j/t+QCROUa5gF8j6HrUiZ5nkx
          sxr1PcuItekaGLJ1nDLz5JsWTQ+H4M+GXQw7/t96x8v8g9el4exTiAHGk6Fv16kD
          017T02M9qTTmV3Ab/enDIBmKVD42Ta36K/wc4l1aoUQNiRbIGVh96Cgd1CFXLF3x
          CsaNbYT4SmRXaYqoj6MKq+QFEGxadFmJy48NoSd4joirIn2lUjHxJebw3lLbNLDR
          uvQnQ2ECgYEA/nD94wEMr6078uMv6nKxPpNGq7fihwSKf0G/PQDqrRmjUCewuW+k
          /iXMe1Y/y0PjFeNlSbUsUvKQ5xF7F/1AnpuPHIrn3cjGVLb71W+zen1m8SnhsW/f
          7dPgtcb4SCvfhmLgoov+P34YcNfGi6qgPUu6319IqoB3BIi7PvfEomkCgYEAwZ4+
          V0bMjFdDn2hnYzjTNcF2aUQ1jPvtuETizGwyCbbMLl9522lrjC2DrH41vvqX35ct
          CBJkhQFbtHM8Gnmozv0vxhI2jP+u14mzfePZsaXuYrEgWRj+BCsYUHodXryxnEWj
          yVrTNskab1B5jFm2SCJDmKcycBOYpRBLCMx6W7MCgYBA99z7/6KboOIzzKrJdGup
          jLV410UyMIikoccQ7pD9jhRTPS80yjsY4dHqlEVJw5XSWvPb9DTTITi6p44EvBep
          6BKMuTMnQELUEr0O7KypVCfa4FTOl8BX28f+4kU3OGykxc6R8qkC0VGwTohV1UWB
          ITsgGhZV4uOA9uDI3T8KMQKBgEnQY2HwmuDSD/TA39GDA3qV8+ez2lqSXRGIKZLX
          mMf9SaBQQ+uzKA4799wWDbVuYeIbB07xfCL83pJP8FUDlqi6+7Celu9wNp7zX1ua
          Nw8z/ErhzjxJe+Xo7A8aTwIkG+5A2m1UU/up9YsEeiJYvVaIwY58B42U2vfq20BS
          fD9jAoGAX2MscBzIsmN+U9R0ptL4SXcPiVnOl8mqvQWr1B4OLgxX7ghht5Fs956W
          bHipxOWMFCPJA/AhNB8q1DvYiD1viZbIALSCJVUkzs4AEFIjiPsCBKxerl7jF6Xp
          1WYSaCmfvoCVEpFNt8cKp4Gq+zEBYAV4Q6TkcD2lDtEW49MuN8A=
          -----END RSA PRIVATE KEY-----
          PKCS7
      end

      let(:public_key) do
        <<-PKCS7.unindent
          -----BEGIN CERTIFICATE-----
          MIIC2TCCAcGgAwIBAgIBATANBgkqhkiG9w0BAQUFADAAMCAXDTE3MDExMzA5MTY1
          MloYDzIwNjcwMTAxMDkxNjUyWjAAMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
          CgKCAQEAwHB3GvImq59em4LV9DMfP0Zjs21eW3Jd5I9fuY0jLJhIkH6fCR7tyOpY
          V6xUj+TF8giq9WLxZI7sourMJMWjEWhVjgUr5lqp1RLv4lwfDv3Wk4XC2LUuqj1I
          AErUXKeRz8i3lUSZW1Pf4CaMpnIiPdWbz6f0KkaJSFi9bqexONBx4fKQNlgZwm2/
          aYjjrYng788I0QhWDKUqsQOi5mZKlHNRsDlk7J3Afhsx/jTLrCX/G8+2tPtLsHyR
          N39kluM5vYHbKXDsCG/a88Z2yUE2+r4Clp0FUKffiEDBPm0/H0sQ4Q1oEfQFDQRK
          aIkhpsm0nOnLYTy3/xJc5uqDNkLiawIDAQABo1wwWjAPBgNVHRMBAf8EBTADAQH/
          MB0GA1UdDgQWBBSejWrVnw7QaBjNFCHMNFi+doSOcTAoBgNVHSMEITAfgBSejWrV
          nw7QaBjNFCHMNFi+doSOcaEEpAIwAIIBATANBgkqhkiG9w0BAQUFAAOCAQEAAe85
          BQ1ydAHFqo0ib38VRPOwf5xPHGbYGhvQi4/sU6aTuR7pxaOJPYz05jLhS+utEmy1
          sknBq60G67yhQE7IHcfwrl1arirG2WmKGvAbjeYL2K1UiU0pVD3D+Klkv/pK6jIQ
          eOJRGb3qNUn0Sq9EoYIOXiGXQ641F0bZZ0+5H92kT1lmnF5oLfCb84ImD9T3snH6
          pIr5RKRx/0YmJIcv3WdpoPT903rOJiRIEgIj/hDk9QZTBpm222Ul5yQQ5pBywpSp
          xh0bmJKAQWhQm7QlybKfyaQmg5ot1jEzWAvD2I5FjHQxmAlchjb6RreaRhExj+JE
          5O117dMBdzDBjcNMOA==
          -----END CERTIFICATE-----
          PKCS7
      end

      let(:keys_dir) do
        keys = tmpdir('keys')
        dir_contained_in(keys, {
          private_key_name => private_key,
          public_key_name => public_key
        })
        keys
      end

      let(:private_key_path) { File.join(keys_dir, private_key_name) }
      let(:public_key_path) { File.join(keys_dir, public_key_name) }

      let(:env_hiera_yaml) do
        <<-YAML.unindent
          version: 5
          hierarchy:
            - name: EYaml
              path: common.eyaml
              lookup_key: eyaml_lookup_key
              options:
                pkcs7_private_key: #{private_key_path}
                pkcs7_public_key: #{public_key_path}
          YAML
      end

      let(:scope_additions) { { 'ipl_suffix' => 'aa' } }
      let(:data_files) do
        {
          'common.eyaml' => <<-YAML.unindent
            # a: Encrypted value 'a' (from environment)
            a: >
              ENC[PKCS7,MIIBmQYJKoZIhvcNAQcDoIIBijCCAYYCAQAxggEhMIIBHQIBADAFMAACAQEw
              DQYJKoZIhvcNAQEBBQAEggEAUwwNRA5ZKM87SLnjnJfzDFRQbeheSYMTOhcr
              sgTPCGtzEAzvRBrkdIRAvDZVRfadV9OB+bJsYrhWIkU1bYiOn1m78ginh96M
              44RuspnIZYnL9Dhs+JyC8VvB5nlvlEph2RGt+KYg9iU4JYhwZ2+8+yxB6/UK
              H5HGKDCjBbEc8o9MbCckLsciIh11hKKgT6K0yhKB/nBxxM78nrX0BxmAHX2u
              bejKDRa9S/0uS7Y91nvnbIkaQpZ4KteSQ+J4/lQBMlMAeE+2F9ncM8jFKnQC
              rzzdbn1O/zwsEt5J5CRP1Sc+8hM644+IqkLs+17segxArHVGOsEqyDcHbXEK
              9jspfzBcBgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBCIq/L5HeJgA9XQm67j
              JHUngDDS5s52FsuSIMin7Z/pV+XuaJGFkL80ia4bXnCWilmtM8oUa/DZuBje
              dCILO7I8QqU=]
            hash_a:
              "hash_%{ipl_suffix}":
                # aaa: Encrypted value hash_a.hash_aa.aaa (from environment)
                aaa: >
                  ENC[PKCS7,MIIBqQYJKoZIhvcNAQcDoIIBmjCCAZYCAQAxggEhMIIBHQIBADAFMAACAQEw
                  DQYJKoZIhvcNAQEBBQAEggEAhvGXL5RxVUs9wdqJvpCyXtfCHrm2HbG/u30L
                  n8EuRD9ravlsgIISAnd27JPtrxA+0rZq4EQRGz6OcovnH9vTg86/lVBhhPnz
                  b83ArptGJhRvTYUJ19GZI3AYjJbhWj/Jo5NL56oQJaPBccqHxMApm/U0wlus
                  QtASL94cLuh4toVIBQCQzD5/Bx51p2wQobm9p4WKSl1zJhDceurmoLZXqhuN
                  JwwEBwXopJvgid3ZDPbdX8nI6vHhb/8wDq9yb5DOsrkgqDqQgwPU9sUUioQj
                  Hr1pGyeOWnbEe99iEb2+m7TWsC0NN7OBo06mAgFNbBLjvn2k4PiCxrOOgJ8S
                  LI5eXjBsBgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBCWNS6j3m/Xvrp5RFaN
                  ovm/gEB4oPlYJswoXuWqcEBfwZzbpy96x3b2Le/yoa72ylbPAUc5GfLENvFQ
                  zXpTtSmQE0fixY4JMaBTke65ZRvoiOQO]
            array_a:
              # - "array_a[0]"
              - >
                ENC[PKCS7,MIIBeQYJKoZIhvcNAQcDoIIBajCCAWYCAQAxggEhMIIBHQIBADAFMAACAQEw
                DQYJKoZIhvcNAQEBBQAEggEAmXZfyfU77vVCZqHpR10qhD0Jy9DpMGBgal97
                vUO2VHX7KlCgagK0kz8/uLRIthkYzcpn8ISmw/+CIAny3jOjxOsylJiujqyu
                hx/JEFl8bOKOg40Bd0UuBaw/qZ+CoAtOorhiIW7x6t7DpknItC6gkH/cSJ4/
                p3MdhoARRuwj2fvuaChVsD39l2rXjgJj0OJOaDXdbuisG75VRZf5l8IH6+44
                Q7m6W7BU69LX+ozn+W3filQoiJ5MPf8w/KXAObMSbKYIDsrZUyIWyyNUbpW0
                MieIkHj93bX3gIEcenECLdWaEzcPa7MHgl6zevQKg4H0JVmcvKYyfHYqcrVE
                PqizKDA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBDf259KZEay1widVSFy
                I9zGgBAICjm0x2GeqoCnHdiAA+jt]
              # - "array_a[1]"
              - >
                ENC[PKCS7,MIIBeQYJKoZIhvcNAQcDoIIBajCCAWYCAQAxggEhMIIBHQIBADAFMAACAQEw
                DQYJKoZIhvcNAQEBBQAEggEATVy4hHG356INFKOswAhoravh66iJljp+Vn3o
                UVD1kyRiqY5tz3UVSptzUmzD+YssX/f73AKCjUI3HrPNL7kAxsk6fWS7nDEj
                AuxtCqGYeBha6oYJYziSGIHfAdY3MiJUI1C9g/OQB4TTvKdrlDArPiY8THJi
                bzLLMbVQYJ6ixSldwkdKD75vtikyamx+1LSyVBSg8maVyPvLHtLZJuT71rln
                WON3Ious9PIbd+izbcCzaoqh5UnTfDCjOuAYliXalBxamIIwNzSV1sdR8/qf
                t22zpYK4J8lgCBV2gKfrOWSi9MAs6JhCeOb8wNLMmAUTbc0WrFJxoCwAPX0z
                MAjsNjA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBC4v4bNE4gFlbLmVY+9
                BtSLgBBm7U0wu6d6s9wF9Ek9IHPe]
            # ref_a: "A resolved = '%{hiera('a')}'"
            ref_a: >
                ENC[PKCS7,MIIBiQYJKoZIhvcNAQcDoIIBejCCAXYCAQAxggEhMIIBHQIBADAFMAACAQEw
                DQYJKoZIhvcNAQEBBQAEggEAFSuUp+yk+oaA7b5ekT0u360CQ9Q2sIQ/bTcM
                jT3XLjm8HIGYPcysOEnuo8WcAxJFY5iya4yQ7Y/UhMWXaTi7Vzv/6BmyPDwz
                +7Z2Mf0r0PvS5+ylue6aem/3bXPOmXTKTf68OCehTRXlDUs8/av9gnsDzojp
                yiUTBZvKxhIP2n//GyoHgyATveHT0lxPVpdMycB347DtWS7IduCxx0+KiOOw
                DXYFlYbIVxVInwgERxtsfYSr+Fu0/mkjtRsQm+dPzMQOATE9Val2gGKsV6bi
                kdm1OM9HrwVsFj6Lma6FYmr89Bcm/1uEc8fiOMtNK3z2+nwunWBMNCGneMYD
                C5IJejBMBgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBAeiZDGQyXHkZlV5ceT
                iCxpgCDDatuVvbPEEi8rKOC7xhPHZ22zLEEV//l7C9jxq+DZcA==]
            YAML
        }
      end

      let(:env_data) { data_files }

      context 'and a module using eyaml with different options' do

        let(:private_module_key) do
          <<-PKCS7.unindent
          -----BEGIN RSA PRIVATE KEY-----
          MIIEogIBAAKCAQEAuqVpctipK4OMWM+RwKcd/mR4pg6qE3+ItPVC9TlvBrmDaN/y
          YZRjQR+XovXSGuy/CneSQ9Qss0Ff3FKAmEeH0qN0V47a81hgLpjhLCX1n+Ov7r1Q
          DC1ciTpVzHE4krN3rJ/RmDohitIqT1IYYhdcEdaMG9E26HIzn1QIwaDiYU3mfqWM
          8CZExa0CeIsEzHRLSxuMi/xX0ENImCRUzY9GH88Cu2gUhpKlbVzJmVqGPgp94pJY
          YM+SUb0XP1yRySpJMnVg98oCUrQO2OoE/Gax/djAi6hrJUzejPsEKdZ1yxM6OyJW
          NjWZYs8izAxBqm7pv1hx5+X7AIPqwZTMVrB7TQIDAQABAoIBAHIex13QOYeAlGSM
          7bpUtBMiTV6DItxvIyA5wen8ZvU+oqmSHDorp5BfB7E9Cm0qChkVSRot9fLYawtk
          anoxakuRY4ZRs3AMvipfkXYT854CckTP/cykQ6soPuOU6plQIEEtKtMf3/hoTjRX
          ps77J3FEtEAh6Kexg/zMPdpeS2xgULhk0P9ZQEg+JhLA5dq0p0nz3SBkuzcxei79
          +Za/Tg1osD0AINOajdvPnKxvlmWJN0+LpGwVjFNhkoUXPeDyvq0z2V/Uqwz4HP2I
          UGv4tz3SbzFc3Ie4lzgUZzCQgUK3u60pq1uyA6BRtxwdEmpn5v++jGXBGJZpWwcW
          UNblESUCgYEA4aTH9+LHsNjLPs2FmSc7hNjwHG1rAHcDXTX2ccySjRcQvH4Z7xBL
          di+SzZ2Tf8gSLycPRgRVCbrgCODpjoV2D5wWnyUHfWm4+GQxHURYa4UDx69tsSKE
          OTRASJo7/Mz0M1a6YzgCzVRM/TO676ucmawzKUY5OUm1oehtODAiZOcCgYEA08GM
          AMBOznys02xREJI5nLR6AveuTbIjF2efEidoxoW+1RrMOkcqaDTrJQ5PLM+oDDwD
          iPzVjnroSbwJzFB71atIg7b7TwltgkXy7wNTedO2cm5u/I0q8tY2Jaa4Mz8JUnbe
          yafvtS0/mY6A5k+8/2UIMFin2rqU9NC9EUPIo6sCgYBhOvAwELibq89osIbxB8bN
          5+0PUtbYzG/WqnoXb193DIlZr7zdFththPJtR4lXdo7fYqViNluuZahEKyZ5E2lc
          MJZO3VXs5LGf1wyS3/B55EdMtHs/6O+w9qL8pflTZb2UobqPJoOOltTWBoR24iwI
          y/r/vhLKbMini9AEdjlb4QKBgGdYsax4Lr4GCQ8ScSnmQ6ngRyAFo5MV2pyEnRTu
          GOuywKUe9AeJTgAXu5+VMT0Mh9aYv5zu0Ic+IvpBhIKr0RRCCR0Hg/VaA5Et9FeE
          RwxRMFz+2rn1Z72moDyV9pZEMJeHnknK5WmGEOEvtGczCWmX9Hwr+Jf+sc4dxfiU
          HWsLAoGAXWSX73p/6R4eRfF5zU2UFJPvDzhmwObAuvU4zKs9x7PMxZfvyt/eBCO1
          fj2+hIR72RxVuHbLApF1BT6gPVLtNdvaNuCs8YlHcnx/Oi088F0ni7fL/xYBUvaB
          7wTf188UJxP1ofVMZW00P4I9mR6BrOulv455gCwsmg2X7WtJU48=
          -----END RSA PRIVATE KEY-----
          PKCS7
        end

        let(:public_module_key) do
          <<-PKCS7.unindent
          -----BEGIN CERTIFICATE-----
          MIIC2TCCAcGgAwIBAgIBATANBgkqhkiG9w0BAQUFADAAMCAXDTE3MDUzMTE2Mjc0
          M1oYDzIwNjcwNTE5MTYyNzQzWjAAMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
          CgKCAQEAuqVpctipK4OMWM+RwKcd/mR4pg6qE3+ItPVC9TlvBrmDaN/yYZRjQR+X
          ovXSGuy/CneSQ9Qss0Ff3FKAmEeH0qN0V47a81hgLpjhLCX1n+Ov7r1QDC1ciTpV
          zHE4krN3rJ/RmDohitIqT1IYYhdcEdaMG9E26HIzn1QIwaDiYU3mfqWM8CZExa0C
          eIsEzHRLSxuMi/xX0ENImCRUzY9GH88Cu2gUhpKlbVzJmVqGPgp94pJYYM+SUb0X
          P1yRySpJMnVg98oCUrQO2OoE/Gax/djAi6hrJUzejPsEKdZ1yxM6OyJWNjWZYs8i
          zAxBqm7pv1hx5+X7AIPqwZTMVrB7TQIDAQABo1wwWjAPBgNVHRMBAf8EBTADAQH/
          MB0GA1UdDgQWBBQkhoMgOyPzEe7tOOimNH2//PYF2TAoBgNVHSMEITAfgBQkhoMg
          OyPzEe7tOOimNH2//PYF2aEEpAIwAIIBATANBgkqhkiG9w0BAQUFAAOCAQEAhRWc
          Nz3PcUJllao5G/v4AyvjLgwB2JgjJgh6D3ILoOe9TrDSXD7ZV3F30vFae+Eztk86
          pmM8x57E0HsuuY+Owf6/hvELtwbzf9N/lc9ySZSogGFoQeJ8rnCJAQ0FaPjqb7AN
          xTaY9HTzr4dZG1f+sw32RUu2fDe7Deqgf85uMSZ1mtRTt9zvo8lMQxVA2nVOfwz2
          Nxf+qSNYSCtf0/6iwfzHy0qPjaJnywgBCi3Lg2IMSqGUatxzH+9HWrBgD+ZYxmDz
          2gW+EIU1Y/We/tbjIWaR1PD+IzeRJi5fHq60RKHPSdp7TGtV48bQRvyZXC7sVCRa
          yxfX1IGYhCDzbFRQNg==
          -----END CERTIFICATE-----
          PKCS7
        end

        let(:module_keys_dir) do
          keys = tmpdir('keys')
          dir_contained_in(keys, {
            private_key_name => private_module_key,
            public_key_name => public_module_key
          })
          keys
        end

        let(:private_module_key_path) { File.join(module_keys_dir, private_key_name) }
        let(:public_module_key_path) { File.join(module_keys_dir, public_key_name) }

        let(:mod_a_files) do
          {
            'mod_a' => {
              'hiera.yaml' => <<-YAML.unindent,
                version: 5
                hierarchy:
                  - name: EYaml
                    path: common.eyaml
                    lookup_key: eyaml_lookup_key
                    options:
                      pkcs7_private_key: #{private_module_key_path}
                      pkcs7_public_key: #{public_module_key_path}
                YAML
              'data' => {
                'common.eyaml' => <<-YAML.unindent
                ---
                # "%{lookup('a')} (from module)"
                mod_a::a: >
                  ENC[PKCS7,MIIBiQYJKoZIhvcNAQcDoIIBejCCAXYCAQAxggEhMIIBHQIBADAFMAACAQEw
                  DQYJKoZIhvcNAQEBBQAEggEAC+lvda8mX6XkgCBstNw4IQUDyFcS6M0mS9gZ
                  ev4VBDeUK4AUNVnzzdbW0Mnj9LbqlpzFx96VGqSxsRBpe7BVD0kVo5jQsEMn
                  nbrWOD1lvXYrXZMXBeD9xJbMbH5EiiFhbaXcEKRAVGaLVQKjXDENDQ/On+it
                  1+wmmVwJynDJR0lsCz6dcSKvw6wnxBcv32qFyePvJuIf04CHMhaS4ykedYHK
                  vagUn5uVXOv/8G0JPlZnQLyxjE0v0heb0Zj0mvcP2+Y5BSW50AQVrMWJNtdW
                  aFEg6H5hpjduQfQh3iWVuDLnWhbP0sY2Grn5dTOxQP8aTDSsiTUcSeIAmjr/
                  K8YRCjBMBgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBAjL7InlBjRuohLLcBx
                  686ogCDkhCan8bCE7aX2nr75QtLF3q89pFIR4/NGl5+oGEO+qQ==]
                YAML
              }
            }
          }
        end

        let(:populated_env_dir) do
          dir_contained_in(env_dir, DeepMerge.deep_merge!(environment_files, env_name => { 'modules' => mod_a_files }))
          env_dir
        end

        it 'repeatedly finds data in environment and module' do
          expect(lookup(['array_a', 'mod_a::a', 'hash_a'])).to eql([
            ['array_a[0]', 'array_a[1]'],
            "Encrypted value 'a' (from environment) (from module)",
            {'hash_aa'=>{'aaa'=>'Encrypted value hash_a.hash_aa.aaa (from environment)'}}])
        end
      end

      it 'finds data in the environment' do
        expect(lookup('a')).to eql("Encrypted value 'a' (from environment)")
      end

      it 'evaluates interpolated keys' do
        expect(lookup('hash_a')).to include('hash_aa')
      end

      it 'evaluates interpolations in encrypted values' do
        expect(lookup('ref_a')).to eql("A resolved = 'Encrypted value 'a' (from environment)'")
      end

      it 'can read encrypted values inside a hash' do
        expect(lookup('hash_a.hash_aa.aaa')).to eql('Encrypted value hash_a.hash_aa.aaa (from environment)')
      end

      it 'can read encrypted values inside an array' do
        expect(lookup('array_a')).to eql(['array_a[0]', 'array_a[1]'])
      end

      context 'declared in global scope as a Hiera v3 backend' do
        let(:environment_files) { {} }
        let(:data_file_content) { <<-YAML.unindent }
          a: >
            ENC[PKCS7,MIIBmQYJKoZIhvcNAQcDoIIBijCCAYYCAQAxggEhMIIBHQIBADAFMAACAQEw
            DQYJKoZIhvcNAQEBBQAEggEAH457bsfL8kYw9O50roE3dcE21nCnmPnQ2XSX
            LYRJ2C78LarbfFonKz0gvDW7tyhsLWASFCFaiU8T1QPBd2b3hoQK8E4B2Ual
            xga/K7r9y3OSgRomTm9tpTltC6re0Ubh3Dy71H61obwxEdNVTqjPe95+m2b8
            6zWZVnzZzXXsTG1S17yJn1zaB/LXHbWNy4KyLLKCGAml+Gfl6ZMjmaplTmUA
            QIC5rI8abzbPP3TDMmbLOGNkrmLqI+3uS8tSueTMoJmWaMF6c+H/cA7oRxmV
            QCeEUVXjyFvCHcmbA+keS/RK9XF+vc07/XS4XkYSPs/I5hLQji1y9bkkGAs0
            tehxQjBcBgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBDHpA6Fcl/R16aIYcow
            oiO4gDAvfFH6jLUwXkcYtagnwdmhkd9TQJtxNWcIwMpvmk036MqIoGwwhQdg
            gV4beiCFtLU=]
          YAML

        let(:hiera_yaml) do
          <<-YAML.unindent
          :backends: eyaml
          :eyaml:
            :datadir: #{code_dir}/hieradata
            :pkcs7_private_key: #{private_key_path}
            :pkcs7_public_key: #{public_key_path}
          :hierarchy:
            - common
          YAML
        end

        let(:data_files) do
          {
            'common.eyaml' => data_file_content
          }
        end

        let(:code_dir_files) do
          {
            'hiera.yaml' => hiera_yaml,
            'hieradata' => data_files
          }
        end

        before(:each) do
          Puppet.settings[:hiera_config] = File.join(code_dir, 'hiera.yaml')
        end

        it 'finds data in the global layer' do
          expect(lookup('a')).to eql("Encrypted value 'a' (from global)")
        end

        it 'delegates configured eyaml backend to eyaml_lookup_key function' do
          expect(explain('a')).to match(/Hierarchy entry "eyaml"\n.*\n.*\n.*"common"\n\s*Found key: "a"/m)
        end

        context 'using intepolated paths to the key pair' do
          let(:scope_additions) { { 'priv_path' => private_key_path, 'pub_path' => public_key_path } }

          let(:hiera_yaml) do
            <<-YAML.unindent
          :backends: eyaml
          :eyaml:
            :datadir: #{code_dir}/hieradata
            :pkcs7_private_key: "%{priv_path}"
            :pkcs7_public_key: "%{pub_path}"
          :hierarchy:
            - common
            YAML
          end

          it 'finds data in the global layer' do
            expect(lookup('a')).to eql("Encrypted value 'a' (from global)")
          end
        end

        context 'with special extension declared in options' do
          let(:environment_files) { {} }
          let(:hiera_yaml) do
            <<-YAML.unindent
            :backends: eyaml
            :eyaml:
              :extension: xyaml
              :datadir: #{code_dir}/hieradata
              :pkcs7_private_key: #{private_key_path}
              :pkcs7_public_key: #{public_key_path}
            :hierarchy:
              - common
            YAML
          end

          let(:data_files) do
            {
              'common.xyaml' => data_file_content
            }
          end

          it 'finds data in the global layer' do
            expect(lookup('a')).to eql("Encrypted value 'a' (from global)")
          end

          it 'delegates configured eyaml backend to eyaml_lookup_key function' do
            expect(explain('a')).to match(/Hierarchy entry "eyaml"\n.*\n.*\n.*"common"\n\s*Found key: "a"/m)
          end
        end
      end
    end
  end
end