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
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
|
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/EnvironmentTests.py 2014/07/05 09:42:21 garyo"
import SCons.compat
import copy
import io
import os
import sys
import unittest
from collections import UserDict as UD, UserList as UL
import TestCmd
import TestUnit
from SCons.Environment import *
import SCons.Warnings
def diff_env(env1, env2):
s1 = "env1 = {\n"
s2 = "env2 = {\n"
d = {}
for k in list(env1._dict.keys()) + list(env2._dict.keys()):
d[k] = None
for k in sorted(d.keys()):
if k in env1:
if k in env2:
if env1[k] != env2[k]:
s1 = s1 + " " + repr(k) + " : " + repr(env1[k]) + "\n"
s2 = s2 + " " + repr(k) + " : " + repr(env2[k]) + "\n"
else:
s1 = s1 + " " + repr(k) + " : " + repr(env1[k]) + "\n"
elif k in env2:
s2 = s2 + " " + repr(k) + " : " + repr(env2[k]) + "\n"
s1 = s1 + "}\n"
s2 = s2 + "}\n"
return s1 + s2
def diff_dict(d1, d2):
s1 = "d1 = {\n"
s2 = "d2 = {\n"
d = {}
for k in list(d1.keys()) + list(d2.keys()):
d[k] = None
for k in sorted(d.keys()):
if k in d1:
if k in d2:
if d1[k] != d2[k]:
s1 = s1 + " " + repr(k) + " : " + repr(d1[k]) + "\n"
s2 = s2 + " " + repr(k) + " : " + repr(d2[k]) + "\n"
else:
s1 = s1 + " " + repr(k) + " : " + repr(d1[k]) + "\n"
elif k in env2:
s2 = s2 + " " + repr(k) + " : " + repr(d2[k]) + "\n"
s1 = s1 + "}\n"
s2 = s2 + "}\n"
return s1 + s2
called_it = {}
built_it = {}
class Builder(SCons.Builder.BuilderBase):
"""A dummy Builder class for testing purposes. "Building"
a target is simply setting a value in the dictionary.
"""
def __init__(self, name = None):
self.name = name
def __call__(self, env, target=None, source=None, **kw):
global called_it
called_it['target'] = target
called_it['source'] = source
called_it.update(kw)
def execute(self, target = None, **kw):
global built_it
built_it[target] = 1
scanned_it = {}
class Scanner(object):
"""A dummy Scanner class for testing purposes. "Scanning"
a target is simply setting a value in the dictionary.
"""
def __init__(self, name, skeys=[]):
self.name = name
self.skeys = skeys
def __call__(self, filename):
global scanned_it
scanned_it[filename] = 1
def __cmp__(self, other):
try:
return cmp(self.__dict__, other.__dict__)
except AttributeError:
return 1
def get_skeys(self, env):
return self.skeys
def __str__(self):
return self.name
class CLVar(UL):
def __init__(self, seq):
if isinstance(seq, str):
seq = seq.split()
UL.__init__(self, seq)
def __add__(self, other):
return UL.__add__(self, CLVar(other))
def __radd__(self, other):
return UL.__radd__(self, CLVar(other))
def __coerce__(self, other):
return (self, CLVar(other))
class DummyNode(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def rfile(self):
return self
def get_subst_proxy(self):
return self
def test_tool( env ):
env['_F77INCFLAGS'] = '$( ${_concat(INCPREFIX, F77PATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
class TestEnvironmentFixture(object):
def TestEnvironment(self, *args, **kw):
if not kw or 'tools' not in kw:
kw['tools'] = [test_tool]
default_keys = { 'CC' : 'cc',
'CCFLAGS' : '-DNDEBUG',
'ENV' : { 'TMP' : '/tmp' } }
for key, value in default_keys.items():
if key not in kw:
kw[key] = value
if 'BUILDERS' not in kw:
static_obj = SCons.Builder.Builder(action = {},
emitter = {},
suffix = '.o',
single_source = 1)
kw['BUILDERS'] = {'Object' : static_obj}
static_obj.add_action('.cpp', 'fake action')
env = Environment(*args, **kw)
return env
class SubstitutionTestCase(unittest.TestCase):
def test___init__(self):
"""Test initializing a SubstitutionEnvironment
"""
env = SubstitutionEnvironment()
assert '__env__' not in env
def test___cmp__(self):
"""Test comparing SubstitutionEnvironments
"""
env1 = SubstitutionEnvironment(XXX = 'x')
env2 = SubstitutionEnvironment(XXX = 'x')
env3 = SubstitutionEnvironment(XXX = 'xxx')
env4 = SubstitutionEnvironment(XXX = 'x', YYY = 'x')
assert env1 == env2
assert env1 != env3
assert env1 != env4
def test___delitem__(self):
"""Test deleting a variable from a SubstitutionEnvironment
"""
env1 = SubstitutionEnvironment(XXX = 'x', YYY = 'y')
env2 = SubstitutionEnvironment(XXX = 'x')
del env1['YYY']
assert env1 == env2
def test___getitem__(self):
"""Test fetching a variable from a SubstitutionEnvironment
"""
env = SubstitutionEnvironment(XXX = 'x')
assert env['XXX'] == 'x', env['XXX']
def test___setitem__(self):
"""Test setting a variable in a SubstitutionEnvironment
"""
env1 = SubstitutionEnvironment(XXX = 'x')
env2 = SubstitutionEnvironment(XXX = 'x', YYY = 'y')
env1['YYY'] = 'y'
assert env1 == env2
def test_get(self):
"""Test the SubstitutionEnvironment get() method
"""
env = SubstitutionEnvironment(XXX = 'x')
assert env.get('XXX') == 'x', env.get('XXX')
assert env.get('YYY') is None, env.get('YYY')
def test_has_key(self):
"""Test the SubstitutionEnvironment has_key() method
"""
env = SubstitutionEnvironment(XXX = 'x')
assert 'XXX' in env
assert 'YYY' not in env
def test_contains(self):
"""Test the SubstitutionEnvironment __contains__() method
"""
env = SubstitutionEnvironment(XXX = 'x')
assert 'XXX' in env
assert not 'YYY' in env
def test_items(self):
"""Test the SubstitutionEnvironment items() method
"""
env = SubstitutionEnvironment(XXX = 'x', YYY = 'y')
items = list(env.items())
assert items == [('XXX','x'), ('YYY','y')], items
def test_arg2nodes(self):
"""Test the arg2nodes method
"""
env = SubstitutionEnvironment()
dict = {}
class X(SCons.Node.Node):
pass
def Factory(name, directory = None, create = 1, dict=dict, X=X):
if name not in dict:
dict[name] = X()
dict[name].name = name
return dict[name]
nodes = env.arg2nodes("Util.py UtilTests.py", Factory)
assert len(nodes) == 1, nodes
assert isinstance(nodes[0], X)
assert nodes[0].name == "Util.py UtilTests.py"
try: unicode
except NameError: pass
else:
code = """if 1:
nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory)
assert len(nodes) == 1, nodes
assert isinstance(nodes[0], X)
assert nodes[0].name == u"Util.py UtilTests.py"
\n"""
exec code in globals(), locals()
nodes = env.arg2nodes(["Util.py", "UtilTests.py"], Factory)
assert len(nodes) == 2, nodes
assert isinstance(nodes[0], X)
assert isinstance(nodes[1], X)
assert nodes[0].name == "Util.py"
assert nodes[1].name == "UtilTests.py"
n1 = Factory("Util.py")
nodes = env.arg2nodes([n1, "UtilTests.py"], Factory)
assert len(nodes) == 2, nodes
assert isinstance(nodes[0], X)
assert isinstance(nodes[1], X)
assert nodes[0].name == "Util.py"
assert nodes[1].name == "UtilTests.py"
class SConsNode(SCons.Node.Node):
pass
nodes = env.arg2nodes(SConsNode())
assert len(nodes) == 1, nodes
assert isinstance(nodes[0], SConsNode), node
class OtherNode(object):
pass
nodes = env.arg2nodes(OtherNode())
assert len(nodes) == 1, nodes
assert isinstance(nodes[0], OtherNode), node
def lookup_a(str, F=Factory):
if str[0] == 'a':
n = F(str)
n.a = 1
return n
else:
return None
def lookup_b(str, F=Factory):
if str[0] == 'b':
n = F(str)
n.b = 1
return n
else:
return None
env_ll = SubstitutionEnvironment()
env_ll.lookup_list = [lookup_a, lookup_b]
nodes = env_ll.arg2nodes(['aaa', 'bbb', 'ccc'], Factory)
assert len(nodes) == 3, nodes
assert nodes[0].name == 'aaa', nodes[0]
assert nodes[0].a == 1, nodes[0]
assert not hasattr(nodes[0], 'b'), nodes[0]
assert nodes[1].name == 'bbb'
assert not hasattr(nodes[1], 'a'), nodes[1]
assert nodes[1].b == 1, nodes[1]
assert nodes[2].name == 'ccc'
assert not hasattr(nodes[2], 'a'), nodes[1]
assert not hasattr(nodes[2], 'b'), nodes[1]
def lookup_bbbb(str, F=Factory):
if str == 'bbbb':
n = F(str)
n.bbbb = 1
return n
else:
return None
def lookup_c(str, F=Factory):
if str[0] == 'c':
n = F(str)
n.c = 1
return n
else:
return None
nodes = env.arg2nodes(['bbbb', 'ccc'], Factory,
[lookup_c, lookup_bbbb, lookup_b])
assert len(nodes) == 2, nodes
assert nodes[0].name == 'bbbb'
assert not hasattr(nodes[0], 'a'), nodes[1]
assert not hasattr(nodes[0], 'b'), nodes[1]
assert nodes[0].bbbb == 1, nodes[1]
assert not hasattr(nodes[0], 'c'), nodes[0]
assert nodes[1].name == 'ccc'
assert not hasattr(nodes[1], 'a'), nodes[1]
assert not hasattr(nodes[1], 'b'), nodes[1]
assert not hasattr(nodes[1], 'bbbb'), nodes[0]
assert nodes[1].c == 1, nodes[1]
def test_arg2nodes_target_source(self):
"""Test the arg2nodes method with target= and source= keywords
"""
targets = [DummyNode('t1'), DummyNode('t2')]
sources = [DummyNode('s1'), DummyNode('s2')]
env = SubstitutionEnvironment()
nodes = env.arg2nodes(['${TARGET}-a',
'${SOURCE}-b',
'${TARGETS[1]}-c',
'${SOURCES[1]}-d'],
DummyNode,
target=targets,
source=sources)
names = [n.name for n in nodes]
assert names == ['t1-a', 's1-b', 't2-c', 's2-d'], names
def test_gvars(self):
"""Test the base class gvars() method"""
env = SubstitutionEnvironment()
gvars = env.gvars()
assert gvars == {}, gvars
def test_lvars(self):
"""Test the base class lvars() method"""
env = SubstitutionEnvironment()
lvars = env.lvars()
assert lvars == {}, lvars
def test_subst(self):
"""Test substituting construction variables within strings
Check various combinations, including recursive expansion
of variables into other variables.
"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
mystr = env.subst("$AAA ${AAA}A $BBBB $BBB")
assert mystr == "a aA b", mystr
# Changed the tests below to reflect a bug fix in
# subst()
env = SubstitutionEnvironment(AAA = '$BBB', BBB = 'b', BBBA = 'foo')
mystr = env.subst("$AAA ${AAA}A ${AAA}B $BBB")
assert mystr == "b bA bB b", mystr
env = SubstitutionEnvironment(AAA = '$BBB', BBB = '$CCC', CCC = 'c')
mystr = env.subst("$AAA ${AAA}A ${AAA}B $BBB")
assert mystr == "c cA cB c", mystr
# Lists:
env = SubstitutionEnvironment(AAA = ['a', 'aa', 'aaa'])
mystr = env.subst("$AAA")
assert mystr == "a aa aaa", mystr
# Tuples:
env = SubstitutionEnvironment(AAA = ('a', 'aa', 'aaa'))
mystr = env.subst("$AAA")
assert mystr == "a aa aaa", mystr
t1 = DummyNode('t1')
t2 = DummyNode('t2')
s1 = DummyNode('s1')
s2 = DummyNode('s2')
env = SubstitutionEnvironment(AAA = 'aaa')
s = env.subst('$AAA $TARGET $SOURCES', target=[t1, t2], source=[s1, s2])
assert s == "aaa t1 s1 s2", s
s = env.subst('$AAA $TARGETS $SOURCE', target=[t1, t2], source=[s1, s2])
assert s == "aaa t1 t2 s1", s
# Test callables in the SubstitutionEnvironment
def foo(target, source, env, for_signature):
assert str(target) == 't', target
assert str(source) == 's', source
return env["FOO"]
env = SubstitutionEnvironment(BAR=foo, FOO='baz')
t = DummyNode('t')
s = DummyNode('s')
subst = env.subst('test $BAR', target=t, source=s)
assert subst == 'test baz', subst
# Test not calling callables in the SubstitutionEnvironment
if 0:
# This will take some serious surgery to subst() and
# subst_list(), so just leave these tests out until we can
# do that.
def bar(arg):
pass
env = SubstitutionEnvironment(BAR=bar, FOO='$BAR')
subst = env.subst('$BAR', call=None)
assert subst is bar, subst
subst = env.subst('$FOO', call=None)
assert subst is bar, subst
def test_subst_kw(self):
"""Test substituting construction variables within dictionaries"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
kw = env.subst_kw({'$AAA' : 'aaa', 'bbb' : '$BBB'})
assert len(kw) == 2, kw
assert kw['a'] == 'aaa', kw['a']
assert kw['bbb'] == 'b', kw['bbb']
def test_subst_list(self):
"""Test substituting construction variables in command lists
"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
l = env.subst_list("$AAA ${AAA}A $BBBB $BBB")
assert l == [["a", "aA", "b"]], l
# Changed the tests below to reflect a bug fix in
# subst()
env = SubstitutionEnvironment(AAA = '$BBB', BBB = 'b', BBBA = 'foo')
l = env.subst_list("$AAA ${AAA}A ${AAA}B $BBB")
assert l == [["b", "bA", "bB", "b"]], l
env = SubstitutionEnvironment(AAA = '$BBB', BBB = '$CCC', CCC = 'c')
l = env.subst_list("$AAA ${AAA}A ${AAA}B $BBB")
assert l == [["c", "cA", "cB", "c"]], mystr
env = SubstitutionEnvironment(AAA = '$BBB', BBB = '$CCC', CCC = [ 'a', 'b\nc' ])
lst = env.subst_list([ "$AAA", "B $CCC" ])
assert lst == [[ "a", "b"], ["c", "B a", "b"], ["c"]], lst
t1 = DummyNode('t1')
t2 = DummyNode('t2')
s1 = DummyNode('s1')
s2 = DummyNode('s2')
env = SubstitutionEnvironment(AAA = 'aaa')
s = env.subst_list('$AAA $TARGET $SOURCES', target=[t1, t2], source=[s1, s2])
assert s == [["aaa", "t1", "s1", "s2"]], s
s = env.subst_list('$AAA $TARGETS $SOURCE', target=[t1, t2], source=[s1, s2])
assert s == [["aaa", "t1", "t2", "s1"]], s
# Test callables in the SubstitutionEnvironment
def foo(target, source, env, for_signature):
assert str(target) == 't', target
assert str(source) == 's', source
return env["FOO"]
env = SubstitutionEnvironment(BAR=foo, FOO='baz')
t = DummyNode('t')
s = DummyNode('s')
lst = env.subst_list('test $BAR', target=t, source=s)
assert lst == [['test', 'baz']], lst
# Test not calling callables in the SubstitutionEnvironment
if 0:
# This will take some serious surgery to subst() and
# subst_list(), so just leave these tests out until we can
# do that.
def bar(arg):
pass
env = SubstitutionEnvironment(BAR=bar, FOO='$BAR')
subst = env.subst_list('$BAR', call=None)
assert subst is bar, subst
subst = env.subst_list('$FOO', call=None)
assert subst is bar, subst
def test_subst_path(self):
"""Test substituting a path list
"""
class MyProxy(object):
def __init__(self, val):
self.val = val
def get(self):
return self.val + '-proxy'
class MyNode(object):
def __init__(self, val):
self.val = val
def get_subst_proxy(self):
return self
def __str__(self):
return self.val
class MyObj(object):
def get(self):
return self
env = SubstitutionEnvironment(FOO='foo',
BAR='bar',
LIST=['one', 'two'],
PROXY=MyProxy('my1'))
r = env.subst_path('$FOO')
assert r == ['foo'], r
r = env.subst_path(['$FOO', 'xxx', '$BAR'])
assert r == ['foo', 'xxx', 'bar'], r
r = env.subst_path(['$FOO', '$LIST', '$BAR'])
assert list(map(str, r)) == ['foo', 'one two', 'bar'], r
r = env.subst_path(['$FOO', '$TARGET', '$SOURCE', '$BAR'])
assert r == ['foo', '', '', 'bar'], r
r = env.subst_path(['$FOO', '$TARGET', '$BAR'], target=MyNode('ttt'))
assert list(map(str, r)) == ['foo', 'ttt', 'bar'], r
r = env.subst_path(['$FOO', '$SOURCE', '$BAR'], source=MyNode('sss'))
assert list(map(str, r)) == ['foo', 'sss', 'bar'], r
n = MyObj()
r = env.subst_path(['$PROXY', MyProxy('my2'), n])
assert r == ['my1-proxy', 'my2-proxy', n], r
class StringableObj(object):
def __init__(self, s):
self.s = s
def __str__(self):
return self.s
env = SubstitutionEnvironment(FOO=StringableObj("foo"),
BAR=StringableObj("bar"))
r = env.subst_path([ "${FOO}/bar", "${BAR}/baz" ])
assert r == [ "foo/bar", "bar/baz" ], r
r = env.subst_path([ "bar/${FOO}", "baz/${BAR}" ])
assert r == [ "bar/foo", "baz/bar" ], r
r = env.subst_path([ "bar/${FOO}/bar", "baz/${BAR}/baz" ])
assert r == [ "bar/foo/bar", "baz/bar/baz" ], r
def test_subst_target_source(self):
"""Test the base environment subst_target_source() method"""
env = SubstitutionEnvironment(AAA = 'a', BBB = 'b')
mystr = env.subst_target_source("$AAA ${AAA}A $BBBB $BBB")
assert mystr == "a aA b", mystr
def test_backtick(self):
"""Test the backtick() method for capturing command output"""
env = SubstitutionEnvironment()
test = TestCmd.TestCmd(workdir = '')
test.write('stdout.py', """\
import sys
sys.stdout.write('this came from stdout.py\\n')
sys.exit(0)
""")
test.write('stderr.py', """\
import sys
sys.stderr.write('this came from stderr.py\\n')
sys.exit(0)
""")
test.write('fail.py', """\
import sys
sys.exit(1)
""")
test.write('echo.py', """\
import os, sys
sys.stdout.write(os.environ['ECHO'] + '\\n')
sys.exit(0)
""")
save_stderr = sys.stderr
python = '"' + sys.executable + '"'
try:
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('stdout.py'))
output = env.backtick(cmd)
errout = sys.stderr.getvalue()
assert output == 'this came from stdout.py\n', output
assert errout == '', errout
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('stderr.py'))
output = env.backtick(cmd)
errout = sys.stderr.getvalue()
assert output == '', output
assert errout == 'this came from stderr.py\n', errout
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('fail.py'))
try:
env.backtick(cmd)
except OSError, e:
assert str(e) == "'%s' exited 1" % cmd, str(e)
else:
self.fail("did not catch expected OSError")
sys.stderr = io.StringIO()
cmd = '%s %s' % (python, test.workpath('echo.py'))
env['ENV'] = os.environ.copy()
env['ENV']['ECHO'] = 'this came from ECHO'
output = env.backtick(cmd)
errout = sys.stderr.getvalue()
assert output == 'this came from ECHO\n', output
assert errout == '', errout
finally:
sys.stderr = save_stderr
def test_AddMethod(self):
"""Test the AddMethod() method"""
env = SubstitutionEnvironment(FOO = 'foo')
def func(self):
return 'func-' + self['FOO']
assert not hasattr(env, 'func')
env.AddMethod(func)
r = env.func()
assert r == 'func-foo', r
assert not hasattr(env, 'bar')
env.AddMethod(func, 'bar')
r = env.bar()
assert r == 'func-foo', r
def func2(self, arg=''):
return 'func2-' + self['FOO'] + arg
env.AddMethod(func2)
r = env.func2()
assert r == 'func2-foo', r
r = env.func2('-xxx')
assert r == 'func2-foo-xxx', r
env.AddMethod(func2, 'func')
r = env.func()
assert r == 'func2-foo', r
r = env.func('-yyy')
assert r == 'func2-foo-yyy', r
# Test that clones of clones correctly re-bind added methods.
env1 = Environment(FOO = '1')
env1.AddMethod(func2)
env2 = env1.Clone(FOO = '2')
env3 = env2.Clone(FOO = '3')
env4 = env3.Clone(FOO = '4')
r = env1.func2()
assert r == 'func2-1', r
r = env2.func2()
assert r == 'func2-2', r
r = env3.func2()
assert r == 'func2-3', r
r = env4.func2()
assert r == 'func2-4', r
# Test that clones don't re-bind an attribute that the user
env1 = Environment(FOO = '1')
env1.AddMethod(func2)
def replace_func2():
return 'replace_func2'
env1.func2 = replace_func2
env2 = env1.Clone(FOO = '2')
r = env2.func2()
assert r == 'replace_func2', r
def test_Override(self):
"Test overriding construction variables"
env = SubstitutionEnvironment(ONE=1, TWO=2, THREE=3, FOUR=4)
assert env['ONE'] == 1, env['ONE']
assert env['TWO'] == 2, env['TWO']
assert env['THREE'] == 3, env['THREE']
assert env['FOUR'] == 4, env['FOUR']
env2 = env.Override({'TWO' : '10',
'THREE' :'x $THREE y',
'FOUR' : ['x', '$FOUR', 'y']})
assert env2['ONE'] == 1, env2['ONE']
assert env2['TWO'] == '10', env2['TWO']
assert env2['THREE'] == 'x 3 y', env2['THREE']
assert env2['FOUR'] == ['x', 4, 'y'], env2['FOUR']
assert env['ONE'] == 1, env['ONE']
assert env['TWO'] == 2, env['TWO']
assert env['THREE'] == 3, env['THREE']
assert env['FOUR'] == 4, env['FOUR']
env2.Replace(ONE = "won")
assert env2['ONE'] == "won", env2['ONE']
assert env['ONE'] == 1, env['ONE']
def test_ParseFlags(self):
"""Test the ParseFlags() method
"""
env = SubstitutionEnvironment()
empty = {
'ASFLAGS' : [],
'CFLAGS' : [],
'CCFLAGS' : [],
'CXXFLAGS' : [],
'CPPDEFINES' : [],
'CPPFLAGS' : [],
'CPPPATH' : [],
'FRAMEWORKPATH' : [],
'FRAMEWORKS' : [],
'LIBPATH' : [],
'LIBS' : [],
'LINKFLAGS' : [],
'RPATH' : [],
}
d = env.ParseFlags(None)
assert d == empty, d
d = env.ParseFlags('')
assert d == empty, d
d = env.ParseFlags([])
assert d == empty, d
s = "-I/usr/include/fum -I bar -X\n" + \
'-I"C:\\Program Files\\ASCEND\\include" ' + \
"-L/usr/fax -L foo -lxxx -l yyy " + \
'-L"C:\\Program Files\\ASCEND" -lascend ' + \
"-Wa,-as -Wl,-link " + \
"-Wl,-rpath=rpath1 " + \
"-Wl,-R,rpath2 " + \
"-Wl,-Rrpath3 " + \
"-Wp,-cpp " + \
"-std=c99 " + \
"-std=c++0x " + \
"-framework Carbon " + \
"-frameworkdir=fwd1 " + \
"-Ffwd2 " + \
"-F fwd3 " + \
"-dylib_file foo-dylib " + \
"-pthread " + \
"-fopenmp " + \
"-mno-cygwin -mwindows " + \
"-arch i386 -isysroot /tmp +DD64 " + \
"-DFOO -DBAR=value -D BAZ "
d = env.ParseFlags(s)
assert d['ASFLAGS'] == ['-as'], d['ASFLAGS']
assert d['CFLAGS'] == ['-std=c99']
assert d['CCFLAGS'] == ['-X', '-Wa,-as',
'-pthread', '-fopenmp', '-mno-cygwin',
('-arch', 'i386'), ('-isysroot', '/tmp'),
'+DD64'], repr(d['CCFLAGS'])
assert d['CXXFLAGS'] == ['-std=c++0x'], repr(d['CXXFLAGS'])
assert d['CPPDEFINES'] == ['FOO', ['BAR', 'value'], 'BAZ'], d['CPPDEFINES']
assert d['CPPFLAGS'] == ['-Wp,-cpp'], d['CPPFLAGS']
assert d['CPPPATH'] == ['/usr/include/fum',
'bar',
'C:\\Program Files\\ASCEND\\include'], d['CPPPATH']
assert d['FRAMEWORKPATH'] == ['fwd1', 'fwd2', 'fwd3'], d['FRAMEWORKPATH']
assert d['FRAMEWORKS'] == ['Carbon'], d['FRAMEWORKS']
assert d['LIBPATH'] == ['/usr/fax',
'foo',
'C:\\Program Files\\ASCEND'], d['LIBPATH']
LIBS = list(map(str, d['LIBS']))
assert LIBS == ['xxx', 'yyy', 'ascend'], (d['LIBS'], LIBS)
assert d['LINKFLAGS'] == ['-Wl,-link',
'-dylib_file', 'foo-dylib',
'-pthread', '-fopenmp',
'-mno-cygwin', '-mwindows',
('-arch', 'i386'),
('-isysroot', '/tmp'),
'+DD64'], repr(d['LINKFLAGS'])
assert d['RPATH'] == ['rpath1', 'rpath2', 'rpath3'], d['RPATH']
def test_MergeFlags(self):
"""Test the MergeFlags() method
"""
env = SubstitutionEnvironment()
env.MergeFlags('')
assert 'CCFLAGS' not in env, env['CCFLAGS']
env.MergeFlags('-X')
assert env['CCFLAGS'] == ['-X'], env['CCFLAGS']
env.MergeFlags('-X')
assert env['CCFLAGS'] == ['-X'], env['CCFLAGS']
env = SubstitutionEnvironment(CCFLAGS=None)
env.MergeFlags('-Y')
assert env['CCFLAGS'] == ['-Y'], env['CCFLAGS']
env = SubstitutionEnvironment()
env.MergeFlags({'A':['aaa'], 'B':['bbb']})
assert env['A'] == ['aaa'], env['A']
assert env['B'] == ['bbb'], env['B']
# def test_MergeShellPaths(self):
# """Test the MergeShellPaths() method
# """
# env = Environment()
# env.MergeShellPaths({})
# assert not env['ENV'].has_key('INCLUDE'), env['INCLUDE']
# env.MergeShellPaths({'INCLUDE': r'c:\Program Files\Stuff'})
# assert env['ENV']['INCLUDE'] == r'c:\Program Files\Stuff', env['ENV']['INCLUDE']
# env.MergeShellPaths({'INCLUDE': r'c:\Program Files\Stuff'})
# assert env['ENV']['INCLUDE'] == r'c:\Program Files\Stuff', env['ENV']['INCLUDE']
# env.MergeShellPaths({'INCLUDE': r'xyz'})
# assert env['ENV']['INCLUDE'] == r'xyz%sc:\Program Files\Stuff'%os.pathsep, env['ENV']['INCLUDE']
# env = Environment()
# env['ENV']['INCLUDE'] = 'xyz'
# env.MergeShellPaths({'INCLUDE':['c:/inc1', 'c:/inc2']} )
# assert env['ENV']['INCLUDE'] == r'c:/inc1%sc:/inc2%sxyz'%(os.pathsep, os.pathsep), env['ENV']['INCLUDE']
# # test prepend=0
# env = Environment()
# env.MergeShellPaths({'INCLUDE': r'c:\Program Files\Stuff'}, prepend=0)
# assert env['ENV']['INCLUDE'] == r'c:\Program Files\Stuff', env['ENV']['INCLUDE']
# env.MergeShellPaths({'INCLUDE': r'xyz'}, prepend=0)
# assert env['ENV']['INCLUDE'] == r'c:\Program Files\Stuff%sxyz'%os.pathsep, env['ENV']['INCLUDE']
class BaseTestCase(unittest.TestCase,TestEnvironmentFixture):
reserved_variables = [
'CHANGED_SOURCES',
'CHANGED_TARGETS',
'SOURCE',
'SOURCES',
'TARGET',
'TARGETS',
'UNCHANGED_SOURCES',
'UNCHANGED_TARGETS',
]
def test___init__(self):
"""Test construction Environment creation
Create two with identical arguments and check that
they compare the same.
"""
env1 = self.TestEnvironment(XXX = 'x', YYY = 'y')
env2 = self.TestEnvironment(XXX = 'x', YYY = 'y')
assert env1 == env2, diff_env(env1, env2)
assert '__env__' not in env1
assert '__env__' not in env2
def test_variables(self):
"""Test that variables only get applied once."""
class FakeOptions(object):
def __init__(self, key, val):
self.calls = 0
self.key = key
self.val = val
def keys(self):
return [self.key]
def Update(self, env):
env[self.key] = self.val
self.calls = self.calls + 1
o = FakeOptions('AAA', 'fake_opt')
env = Environment(variables=o, AAA='keyword_arg')
assert o.calls == 1, o.calls
assert env['AAA'] == 'fake_opt', env['AAA']
def test_get(self):
"""Test the get() method."""
env = self.TestEnvironment(aaa = 'AAA')
x = env.get('aaa')
assert x == 'AAA', x
x = env.get('aaa', 'XXX')
assert x == 'AAA', x
x = env.get('bbb')
assert x is None, x
x = env.get('bbb', 'XXX')
assert x == 'XXX', x
def test_Builder_calls(self):
"""Test Builder calls through different environments
"""
global called_it
b1 = Builder()
b2 = Builder()
env = Environment()
env.Replace(BUILDERS = { 'builder1' : b1,
'builder2' : b2 })
called_it = {}
env.builder1('in1')
assert called_it['target'] is None, called_it
assert called_it['source'] == ['in1'], called_it
called_it = {}
env.builder2(source = 'in2', xyzzy = 1)
assert called_it['target'] is None, called_it
assert called_it['source'] == ['in2'], called_it
assert called_it['xyzzy'] == 1, called_it
called_it = {}
env.builder1(foo = 'bar')
assert called_it['foo'] == 'bar', called_it
assert called_it['target'] is None, called_it
assert called_it['source'] is None, called_it
def test_BuilderWrapper_attributes(self):
"""Test getting and setting of BuilderWrapper attributes
"""
b1 = Builder()
b2 = Builder()
e1 = Environment()
e2 = Environment()
e1.Replace(BUILDERS = {'b' : b1})
bw = e1.b
assert bw.env is e1
bw.env = e2
assert bw.env is e2
assert bw.builder is b1
bw.builder = b2
assert bw.builder is b2
self.assertRaises(AttributeError, getattr, bw, 'foobar')
bw.foobar = 42
assert bw.foobar is 42
# This unit test is currently disabled because we don't think the
# underlying method it tests (Environment.BuilderWrapper.execute())
# is necessary, but we're leaving the code here for now in case
# that's mistaken.
def _DO_NOT_test_Builder_execs(self):
"""Test Builder execution through different environments
One environment is initialized with a single
Builder object, one with a list of a single Builder
object, and one with a list of two Builder objects.
"""
global built_it
b1 = Builder()
b2 = Builder()
built_it = {}
env3 = Environment()
env3.Replace(BUILDERS = { 'builder1' : b1,
'builder2' : b2 })
env3.builder1.execute(target = 'out1')
env3.builder2.execute(target = 'out2')
env3.builder1.execute(target = 'out3')
assert built_it['out1']
assert built_it['out2']
assert built_it['out3']
env4 = env3.Clone()
assert env4.builder1.env is env4, "builder1.env (%s) == env3 (%s)?" % (
env4.builder1.env, env3)
assert env4.builder2.env is env4, "builder2.env (%s) == env3 (%s)?" % (
env4.builder1.env, env3)
# Now test BUILDERS as a dictionary.
built_it = {}
env5 = self.TestEnvironment(BUILDERS={ 'foo' : b1 })
env5['BUILDERS']['bar'] = b2
env5.foo.execute(target='out1')
env5.bar.execute(target='out2')
assert built_it['out1']
assert built_it['out2']
built_it = {}
env6 = Environment()
env6['BUILDERS'] = { 'foo' : b1,
'bar' : b2 }
env6.foo.execute(target='out1')
env6.bar.execute(target='out2')
assert built_it['out1']
assert built_it['out2']
def test_Scanners(self):
"""Test setting SCANNERS in various ways
One environment is initialized with a single
Scanner object, one with a list of a single Scanner
object, and one with a list of two Scanner objects.
"""
global scanned_it
s1 = Scanner(name = 'scanner1', skeys = [".c", ".cc"])
s2 = Scanner(name = 'scanner2', skeys = [".m4"])
s3 = Scanner(name = 'scanner3', skeys = [".m4", ".m5"])
s4 = Scanner(name = 'scanner4', skeys = [None])
# XXX Tests for scanner execution through different environments,
# XXX if we ever want to do that some day
# scanned_it = {}
# env1 = self.TestEnvironment(SCANNERS = s1)
# env1.scanner1(filename = 'out1')
# assert scanned_it['out1']
#
# scanned_it = {}
# env2 = self.TestEnvironment(SCANNERS = [s1])
# env1.scanner1(filename = 'out1')
# assert scanned_it['out1']
#
# scanned_it = {}
# env3 = Environment()
# env3.Replace(SCANNERS = [s1])
# env3.scanner1(filename = 'out1')
# env3.scanner2(filename = 'out2')
# env3.scanner1(filename = 'out3')
# assert scanned_it['out1']
# assert scanned_it['out2']
# assert scanned_it['out3']
suffixes = [".c", ".cc", ".cxx", ".m4", ".m5"]
env = Environment()
try: del env['SCANNERS']
except KeyError: pass
s = list(map(env.get_scanner, suffixes))
assert s == [None, None, None, None, None], s
env = self.TestEnvironment(SCANNERS = [])
s = list(map(env.get_scanner, suffixes))
assert s == [None, None, None, None, None], s
env.Replace(SCANNERS = [s1])
s = list(map(env.get_scanner, suffixes))
assert s == [s1, s1, None, None, None], s
env.Append(SCANNERS = [s2])
s = list(map(env.get_scanner, suffixes))
assert s == [s1, s1, None, s2, None], s
env.AppendUnique(SCANNERS = [s3])
s = list(map(env.get_scanner, suffixes))
assert s == [s1, s1, None, s2, s3], s
env = env.Clone(SCANNERS = [s2])
s = list(map(env.get_scanner, suffixes))
assert s == [None, None, None, s2, None], s
env['SCANNERS'] = [s1]
s = list(map(env.get_scanner, suffixes))
assert s == [s1, s1, None, None, None], s
env.PrependUnique(SCANNERS = [s2, s1])
s = list(map(env.get_scanner, suffixes))
assert s == [s1, s1, None, s2, None], s
env.Prepend(SCANNERS = [s3])
s = list(map(env.get_scanner, suffixes))
assert s == [s1, s1, None, s3, s3], s
# Verify behavior of case-insensitive suffix matches on Windows.
uc_suffixes = [_.upper() for _ in suffixes]
env = Environment(SCANNERS = [s1, s2, s3],
PLATFORM = 'linux')
s = list(map(env.get_scanner, suffixes))
assert s == [s1, s1, None, s2, s3], s
s = list(map(env.get_scanner, uc_suffixes))
assert s == [None, None, None, None, None], s
env['PLATFORM'] = 'win32'
s = list(map(env.get_scanner, uc_suffixes))
assert s == [s1, s1, None, s2, s3], s
# Verify behavior for a scanner returning None (on Windows
# where we might try to perform case manipulation on None).
env.Replace(SCANNERS = [s4])
s = list(map(env.get_scanner, suffixes))
assert s == [None, None, None, None, None], s
def test_ENV(self):
"""Test setting the external ENV in Environments
"""
env = Environment()
assert 'ENV' in env.Dictionary()
env = self.TestEnvironment(ENV = { 'PATH' : '/foo:/bar' })
assert env.Dictionary('ENV')['PATH'] == '/foo:/bar'
def test_ReservedVariables(self):
"""Test warning generation when reserved variable names are set"""
reserved_variables = [
'CHANGED_SOURCES',
'CHANGED_TARGETS',
'SOURCE',
'SOURCES',
'TARGET',
'TARGETS',
'UNCHANGED_SOURCES',
'UNCHANGED_TARGETS',
]
warning = SCons.Warnings.ReservedVariableWarning
SCons.Warnings.enableWarningClass(warning)
old = SCons.Warnings.warningAsException(1)
try:
env4 = Environment()
for kw in self.reserved_variables:
exc_caught = None
try:
env4[kw] = 'xyzzy'
except warning:
exc_caught = 1
assert exc_caught, "Did not catch ReservedVariableWarning for `%s'" % kw
assert kw not in env4, "`%s' variable was incorrectly set" % kw
finally:
SCons.Warnings.warningAsException(old)
def test_FutureReservedVariables(self):
"""Test warning generation when future reserved variable names are set"""
future_reserved_variables = []
warning = SCons.Warnings.FutureReservedVariableWarning
SCons.Warnings.enableWarningClass(warning)
old = SCons.Warnings.warningAsException(1)
try:
env4 = Environment()
for kw in future_reserved_variables:
exc_caught = None
try:
env4[kw] = 'xyzzy'
except warning:
exc_caught = 1
assert exc_caught, "Did not catch FutureReservedVariableWarning for `%s'" % kw
assert kw in env4, "`%s' variable was not set" % kw
finally:
SCons.Warnings.warningAsException(old)
def test_IllegalVariables(self):
"""Test that use of illegal variables raises an exception"""
env = Environment()
def test_it(var, env=env):
exc_caught = None
try:
env[var] = 1
except SCons.Errors.UserError:
exc_caught = 1
assert exc_caught, "did not catch UserError for '%s'" % var
env['aaa'] = 1
assert env['aaa'] == 1, env['aaa']
test_it('foo/bar')
test_it('foo.bar')
test_it('foo-bar')
def test_autogenerate(dict):
"""Test autogenerating variables in a dictionary."""
drive, p = os.path.splitdrive(os.getcwd())
def normalize_path(path, drive=drive):
if path[0] in '\\/':
path = drive + path
path = os.path.normpath(path)
drive, path = os.path.splitdrive(path)
return drive.lower() + path
env = dict.TestEnvironment(LIBS = [ 'foo', 'bar', 'baz' ],
LIBLINKPREFIX = 'foo',
LIBLINKSUFFIX = 'bar')
def RDirs(pathlist, fs=env.fs):
return fs.Dir('xx').Rfindalldirs(pathlist)
env['RDirs'] = RDirs
flags = env.subst_list('$_LIBFLAGS', 1)[0]
assert flags == ['foobar', 'foobar', 'foobazbar'], flags
blat = env.fs.Dir('blat')
env.Replace(CPPPATH = [ 'foo', '$FOO/bar', blat ],
INCPREFIX = 'foo ',
INCSUFFIX = 'bar',
FOO = 'baz')
flags = env.subst_list('$_CPPINCFLAGS', 1)[0]
expect = [ '$(',
normalize_path('foo'),
normalize_path('xx/foobar'),
normalize_path('foo'),
normalize_path('xx/baz/bar'),
normalize_path('foo'),
normalize_path('blatbar'),
'$)',
]
assert flags == expect, flags
env.Replace(F77PATH = [ 'foo', '$FOO/bar', blat ],
INCPREFIX = 'foo ',
INCSUFFIX = 'bar',
FOO = 'baz')
flags = env.subst_list('$_F77INCFLAGS', 1)[0]
expect = [ '$(',
normalize_path('foo'),
normalize_path('xx/foobar'),
normalize_path('foo'),
normalize_path('xx/baz/bar'),
normalize_path('foo'),
normalize_path('blatbar'),
'$)',
]
assert flags == expect, flags
env.Replace(CPPPATH = '', F77PATH = '', LIBPATH = '')
l = env.subst_list('$_CPPINCFLAGS')
assert l == [[]], l
l = env.subst_list('$_F77INCFLAGS')
assert l == [[]], l
l = env.subst_list('$_LIBDIRFLAGS')
assert l == [[]], l
env.fs.Repository('/rep1')
env.fs.Repository('/rep2')
env.Replace(CPPPATH = [ 'foo', '/__a__/b', '$FOO/bar', blat],
INCPREFIX = '-I ',
INCSUFFIX = 'XXX',
FOO = 'baz')
flags = env.subst_list('$_CPPINCFLAGS', 1)[0]
expect = [ '$(',
'-I', normalize_path('xx/fooXXX'),
'-I', normalize_path('/rep1/xx/fooXXX'),
'-I', normalize_path('/rep2/xx/fooXXX'),
'-I', normalize_path('/__a__/bXXX'),
'-I', normalize_path('xx/baz/barXXX'),
'-I', normalize_path('/rep1/xx/baz/barXXX'),
'-I', normalize_path('/rep2/xx/baz/barXXX'),
'-I', normalize_path('blatXXX'),
'$)'
]
def normalize_if_path(arg, np=normalize_path):
if arg not in ('$(','$)','-I'):
return np(str(arg))
return arg
flags = list(map(normalize_if_path, flags))
assert flags == expect, flags
def test_platform(self):
"""Test specifying a platform callable when instantiating."""
class platform(object):
def __str__(self): return "TestPlatform"
def __call__(self, env): env['XYZZY'] = 777
def tool(env):
env['SET_TOOL'] = 'initialized'
assert env['PLATFORM'] == "TestPlatform"
env = self.TestEnvironment(platform = platform(), tools = [tool])
assert env['XYZZY'] == 777, env
assert env['PLATFORM'] == "TestPlatform"
assert env['SET_TOOL'] == "initialized"
def test_Default_PLATFORM(self):
"""Test overriding the default PLATFORM variable"""
class platform(object):
def __str__(self): return "DefaultTestPlatform"
def __call__(self, env): env['XYZZY'] = 888
def tool(env):
env['SET_TOOL'] = 'abcde'
assert env['PLATFORM'] == "DefaultTestPlatform"
import SCons.Defaults
save = SCons.Defaults.ConstructionEnvironment.copy()
try:
import SCons.Defaults
SCons.Defaults.ConstructionEnvironment.update({
'PLATFORM' : platform(),
})
env = self.TestEnvironment(tools = [tool])
assert env['XYZZY'] == 888, env
assert env['PLATFORM'] == "DefaultTestPlatform"
assert env['SET_TOOL'] == "abcde"
finally:
SCons.Defaults.ConstructionEnvironment = save
def test_tools(self):
"""Test specifying a tool callable when instantiating."""
def t1(env):
env['TOOL1'] = 111
def t2(env):
env['TOOL2'] = 222
def t3(env):
env['AAA'] = env['XYZ']
def t4(env):
env['TOOL4'] = 444
env = self.TestEnvironment(tools = [t1, t2, t3], XYZ = 'aaa')
assert env['TOOL1'] == 111, env['TOOL1']
assert env['TOOL2'] == 222, env
assert env['AAA'] == 'aaa', env
t4(env)
assert env['TOOL4'] == 444, env
test = TestCmd.TestCmd(workdir = '')
test.write('faketool.py', """\
def generate(env, **kw):
for k, v in kw.items():
env[k] = v
def exists(env):
return 1
""")
env = self.TestEnvironment(tools = [('faketool', {'a':1, 'b':2, 'c':3})],
toolpath = [test.workpath('')])
assert env['a'] == 1, env['a']
assert env['b'] == 2, env['b']
assert env['c'] == 3, env['c']
def test_Default_TOOLS(self):
"""Test overriding the default TOOLS variable"""
def t5(env):
env['TOOL5'] = 555
def t6(env):
env['TOOL6'] = 666
def t7(env):
env['BBB'] = env['XYZ']
def t8(env):
env['TOOL8'] = 888
import SCons.Defaults
save = SCons.Defaults.ConstructionEnvironment.copy()
try:
SCons.Defaults.ConstructionEnvironment.update({
'TOOLS' : [t5, t6, t7],
})
env = Environment(XYZ = 'bbb')
assert env['TOOL5'] == 555, env['TOOL5']
assert env['TOOL6'] == 666, env
assert env['BBB'] == 'bbb', env
t8(env)
assert env['TOOL8'] == 888, env
finally:
SCons.Defaults.ConstructionEnvironment = save
def test_null_tools(self):
"""Test specifying a tool of None is OK."""
def t1(env):
env['TOOL1'] = 111
def t2(env):
env['TOOL2'] = 222
env = self.TestEnvironment(tools = [t1, None, t2], XYZ = 'aaa')
assert env['TOOL1'] == 111, env['TOOL1']
assert env['TOOL2'] == 222, env
assert env['XYZ'] == 'aaa', env
env = self.TestEnvironment(tools = [None], XYZ = 'xyz')
assert env['XYZ'] == 'xyz', env
env = self.TestEnvironment(tools = [t1, '', t2], XYZ = 'ddd')
assert env['TOOL1'] == 111, env['TOOL1']
assert env['TOOL2'] == 222, env
assert env['XYZ'] == 'ddd', env
def test_concat(self):
"Test _concat()"
e1 = self.TestEnvironment(PRE='pre', SUF='suf', STR='a b', LIST=['a', 'b'])
s = e1.subst
x = s("${_concat('', '', '', __env__)}")
assert x == '', x
x = s("${_concat('', [], '', __env__)}")
assert x == '', x
x = s("${_concat(PRE, '', SUF, __env__)}")
assert x == '', x
x = s("${_concat(PRE, STR, SUF, __env__)}")
assert x == 'prea bsuf', x
x = s("${_concat(PRE, LIST, SUF, __env__)}")
assert x == 'preasuf prebsuf', x
def test_concat_nested(self):
"Test _concat() on a nested substitution strings."
e = self.TestEnvironment(PRE='pre', SUF='suf',
L1=['a', 'b'],
L2=['c', 'd'],
L3=['$L2'])
x = e.subst('$( ${_concat(PRE, L1, SUF, __env__)} $)')
assert x == 'preasuf prebsuf', x
e.AppendUnique(L1 = ['$L2'])
x = e.subst('$( ${_concat(PRE, L1, SUF, __env__)} $)')
assert x == 'preasuf prebsuf precsuf predsuf', x
e.AppendUnique(L1 = ['$L3'])
x = e.subst('$( ${_concat(PRE, L1, SUF, __env__)} $)')
assert x == 'preasuf prebsuf precsuf predsuf precsuf predsuf', x
def test_gvars(self):
"""Test the Environment gvars() method"""
env = self.TestEnvironment(XXX = 'x', YYY = 'y', ZZZ = 'z')
gvars = env.gvars()
assert gvars['XXX'] == 'x', gvars['XXX']
assert gvars['YYY'] == 'y', gvars['YYY']
assert gvars['ZZZ'] == 'z', gvars['ZZZ']
def test__update(self):
"""Test the _update() method"""
env = self.TestEnvironment(X = 'x', Y = 'y', Z = 'z')
assert env['X'] == 'x', env['X']
assert env['Y'] == 'y', env['Y']
assert env['Z'] == 'z', env['Z']
env._update({'X' : 'xxx',
'TARGET' : 't',
'TARGETS' : 'ttt',
'SOURCE' : 's',
'SOURCES' : 'sss',
'Z' : 'zzz'})
assert env['X'] == 'xxx', env['X']
assert env['Y'] == 'y', env['Y']
assert env['Z'] == 'zzz', env['Z']
assert env['TARGET'] == 't', env['TARGET']
assert env['TARGETS'] == 'ttt', env['TARGETS']
assert env['SOURCE'] == 's', env['SOURCE']
assert env['SOURCES'] == 'sss', env['SOURCES']
def test_Append(self):
"""Test appending to construction variables in an Environment
"""
b1 = Environment()['BUILDERS']
b2 = Environment()['BUILDERS']
assert b1 == b2, diff_dict(b1, b2)
cases = [
'a1', 'A1', 'a1A1',
'a2', ['A2'], ['a2', 'A2'],
'a3', UL(['A3']), UL(['a', '3', 'A3']),
'a4', '', 'a4',
'a5', [], ['a5'],
'a6', UL([]), UL(['a', '6']),
'a7', [''], ['a7', ''],
'a8', UL(['']), UL(['a', '8', '']),
['e1'], 'E1', ['e1', 'E1'],
['e2'], ['E2'], ['e2', 'E2'],
['e3'], UL(['E3']), UL(['e3', 'E3']),
['e4'], '', ['e4'],
['e5'], [], ['e5'],
['e6'], UL([]), UL(['e6']),
['e7'], [''], ['e7', ''],
['e8'], UL(['']), UL(['e8', '']),
UL(['i1']), 'I1', UL(['i1', 'I', '1']),
UL(['i2']), ['I2'], UL(['i2', 'I2']),
UL(['i3']), UL(['I3']), UL(['i3', 'I3']),
UL(['i4']), '', UL(['i4']),
UL(['i5']), [], UL(['i5']),
UL(['i6']), UL([]), UL(['i6']),
UL(['i7']), [''], UL(['i7', '']),
UL(['i8']), UL(['']), UL(['i8', '']),
{'d1':1}, 'D1', {'d1':1, 'D1':None},
{'d2':1}, ['D2'], {'d2':1, 'D2':None},
{'d3':1}, UL(['D3']), {'d3':1, 'D3':None},
{'d4':1}, {'D4':1}, {'d4':1, 'D4':1},
{'d5':1}, UD({'D5':1}), UD({'d5':1, 'D5':1}),
UD({'u1':1}), 'U1', UD({'u1':1, 'U1':None}),
UD({'u2':1}), ['U2'], UD({'u2':1, 'U2':None}),
UD({'u3':1}), UL(['U3']), UD({'u3':1, 'U3':None}),
UD({'u4':1}), {'U4':1}, UD({'u4':1, 'U4':1}),
UD({'u5':1}), UD({'U5':1}), UD({'u5':1, 'U5':1}),
'', 'M1', 'M1',
'', ['M2'], ['M2'],
'', UL(['M3']), UL(['M3']),
'', '', '',
'', [], [],
'', UL([]), UL([]),
'', [''], [''],
'', UL(['']), UL(['']),
[], 'N1', ['N1'],
[], ['N2'], ['N2'],
[], UL(['N3']), UL(['N3']),
[], '', [],
[], [], [],
[], UL([]), UL([]),
[], [''], [''],
[], UL(['']), UL(['']),
UL([]), 'O1', ['O', '1'],
UL([]), ['O2'], ['O2'],
UL([]), UL(['O3']), UL(['O3']),
UL([]), '', UL([]),
UL([]), [], UL([]),
UL([]), UL([]), UL([]),
UL([]), [''], UL(['']),
UL([]), UL(['']), UL(['']),
[''], 'P1', ['', 'P1'],
[''], ['P2'], ['', 'P2'],
[''], UL(['P3']), UL(['', 'P3']),
[''], '', [''],
[''], [], [''],
[''], UL([]), UL(['']),
[''], [''], ['', ''],
[''], UL(['']), UL(['', '']),
UL(['']), 'Q1', ['', 'Q', '1'],
UL(['']), ['Q2'], ['', 'Q2'],
UL(['']), UL(['Q3']), UL(['', 'Q3']),
UL(['']), '', UL(['']),
UL(['']), [], UL(['']),
UL(['']), UL([]), UL(['']),
UL(['']), [''], UL(['', '']),
UL(['']), UL(['']), UL(['', '']),
]
env = Environment()
failed = 0
while cases:
input, append, expect = cases[:3]
env['XXX'] = copy.copy(input)
try:
env.Append(XXX = append)
except Exception, e:
if failed == 0: print
print " %s Append %s exception: %s" % \
(repr(input), repr(append), e)
failed = failed + 1
else:
result = env['XXX']
if result != expect:
if failed == 0: print
print " %s Append %s => %s did not match %s" % \
(repr(input), repr(append), repr(result), repr(expect))
failed = failed + 1
del cases[:3]
assert failed == 0, "%d Append() cases failed" % failed
env['UL'] = UL(['foo'])
env.Append(UL = 'bar')
result = env['UL']
assert isinstance(result, UL), repr(result)
assert result == ['foo', 'b', 'a', 'r'], result
env['CLVar'] = CLVar(['foo'])
env.Append(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['foo', 'bar'], result
class C(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __cmp__(self, other):
raise Exception("should not compare")
ccc = C('ccc')
env2 = self.TestEnvironment(CCC1 = ['c1'], CCC2 = ccc)
env2.Append(CCC1 = ccc, CCC2 = ['c2'])
assert env2['CCC1'][0] == 'c1', env2['CCC1']
assert env2['CCC1'][1] is ccc, env2['CCC1']
assert env2['CCC2'][0] is ccc, env2['CCC2']
assert env2['CCC2'][1] == 'c2', env2['CCC2']
env3 = self.TestEnvironment(X = {'x1' : 7})
env3.Append(X = {'x1' : 8, 'x2' : 9}, Y = {'y1' : 10})
assert env3['X'] == {'x1': 8, 'x2': 9}, env3['X']
assert env3['Y'] == {'y1': 10}, env3['Y']
z1 = Builder()
z2 = Builder()
env4 = self.TestEnvironment(BUILDERS = {'z1' : z1})
env4.Append(BUILDERS = {'z2' : z2})
assert env4['BUILDERS'] == {'z1' : z1, 'z2' : z2}, env4['BUILDERS']
assert hasattr(env4, 'z1')
assert hasattr(env4, 'z2')
def test_AppendENVPath(self):
"""Test appending to an ENV path."""
env1 = self.TestEnvironment(ENV = {'PATH': r'C:\dir\num\one;C:\dir\num\two'},
MYENV = {'MYPATH': r'C:\mydir\num\one;C:\mydir\num\two'})
# have to include the pathsep here so that the test will work on UNIX too.
env1.AppendENVPath('PATH',r'C:\dir\num\two', sep = ';')
env1.AppendENVPath('PATH',r'C:\dir\num\three', sep = ';')
env1.AppendENVPath('MYPATH',r'C:\mydir\num\three','MYENV', sep = ';')
env1.AppendENVPath('MYPATH',r'C:\mydir\num\one','MYENV', sep = ';')
# this should do nothing since delete_existing is 0
env1.AppendENVPath('MYPATH',r'C:\mydir\num\three','MYENV', sep = ';', delete_existing=0)
assert(env1['ENV']['PATH'] == r'C:\dir\num\one;C:\dir\num\two;C:\dir\num\three')
assert(env1['MYENV']['MYPATH'] == r'C:\mydir\num\two;C:\mydir\num\three;C:\mydir\num\one')
test = TestCmd.TestCmd(workdir = '')
test.subdir('sub1', 'sub2')
p=env1['ENV']['PATH']
env1.AppendENVPath('PATH','#sub1', sep = ';')
env1.AppendENVPath('PATH',env1.fs.Dir('sub2'), sep = ';')
assert env1['ENV']['PATH'] == p + ';sub1;sub2', env1['ENV']['PATH']
def test_AppendUnique(self):
"""Test appending to unique values to construction variables
This strips values that are already present when lists are
involved."""
env = self.TestEnvironment(AAA1 = 'a1',
AAA2 = 'a2',
AAA3 = 'a3',
AAA4 = 'a4',
AAA5 = 'a5',
BBB1 = ['b1'],
BBB2 = ['b2'],
BBB3 = ['b3'],
BBB4 = ['b4'],
BBB5 = ['b5'],
CCC1 = '',
CCC2 = '',
DDD1 = ['a', 'b', 'c'])
env['LL1'] = [env.Literal('a literal'), env.Literal('b literal')]
env['LL2'] = [env.Literal('c literal'), env.Literal('b literal')]
env.AppendUnique(AAA1 = 'a1',
AAA2 = ['a2'],
AAA3 = ['a3', 'b', 'c', 'c', 'b', 'a3'], # ignore dups
AAA4 = 'a4.new',
AAA5 = ['a5.new'],
BBB1 = 'b1',
BBB2 = ['b2'],
BBB3 = ['b3', 'c', 'd', 'c', 'b3'],
BBB4 = 'b4.new',
BBB5 = ['b5.new'],
CCC1 = 'c1',
CCC2 = ['c2'],
DDD1 = 'b',
LL1 = env.Literal('a literal'),
LL2 = env.Literal('a literal'))
assert env['AAA1'] == 'a1a1', env['AAA1']
assert env['AAA2'] == ['a2'], env['AAA2']
assert env['AAA3'] == ['a3', 'b', 'c'], env['AAA3']
assert env['AAA4'] == 'a4a4.new', env['AAA4']
assert env['AAA5'] == ['a5', 'a5.new'], env['AAA5']
assert env['BBB1'] == ['b1'], env['BBB1']
assert env['BBB2'] == ['b2'], env['BBB2']
assert env['BBB3'] == ['b3', 'c', 'd'], env['BBB3']
assert env['BBB4'] == ['b4', 'b4.new'], env['BBB4']
assert env['BBB5'] == ['b5', 'b5.new'], env['BBB5']
assert env['CCC1'] == 'c1', env['CCC1']
assert env['CCC2'] == ['c2'], env['CCC2']
assert env['DDD1'] == ['a', 'b', 'c'], env['DDD1']
assert env['LL1'] == [env.Literal('a literal'), env.Literal('b literal')], env['LL1']
assert env['LL2'] == [env.Literal('c literal'), env.Literal('b literal'), env.Literal('a literal')], [str(x) for x in env['LL2']]
env.AppendUnique(DDD1 = 'b', delete_existing=1)
assert env['DDD1'] == ['a', 'c', 'b'], env['DDD1'] # b moves to end
env.AppendUnique(DDD1 = ['a','b'], delete_existing=1)
assert env['DDD1'] == ['c', 'a', 'b'], env['DDD1'] # a & b move to end
env.AppendUnique(DDD1 = ['e','f', 'e'], delete_existing=1)
assert env['DDD1'] == ['c', 'a', 'b', 'f', 'e'], env['DDD1'] # add last
env['CLVar'] = CLVar([])
env.AppendUnique(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['bar'], result
env['CLVar'] = CLVar(['abc'])
env.AppendUnique(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['abc', 'bar'], result
env['CLVar'] = CLVar(['bar'])
env.AppendUnique(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['bar'], result
def test_Clone(self):
"""Test construction environment copying
Update the copy independently afterwards and check that
the original remains intact (that is, no dangling
references point to objects in the copied environment).
Clone the original with some construction variable
updates and check that the original remains intact
and the copy has the updated values.
"""
env1 = self.TestEnvironment(XXX = 'x', YYY = 'y')
env2 = env1.Clone()
env1copy = env1.Clone()
assert env1copy == env1copy
assert env2 == env2
env2.Replace(YYY = 'yyy')
assert env2 == env2
assert env1 != env2
assert env1 == env1copy
env3 = env1.Clone(XXX = 'x3', ZZZ = 'z3')
assert env3 == env3
assert env3.Dictionary('XXX') == 'x3'
assert env3.Dictionary('YYY') == 'y'
assert env3.Dictionary('ZZZ') == 'z3'
assert env1 == env1copy
# Ensure that lists and dictionaries are
# deep copied, but not instances.
class TestA(object):
pass
env1 = self.TestEnvironment(XXX=TestA(), YYY = [ 1, 2, 3 ],
ZZZ = { 1:2, 3:4 })
env2=env1.Clone()
env2.Dictionary('YYY').append(4)
env2.Dictionary('ZZZ')[5] = 6
assert env1.Dictionary('XXX') is env2.Dictionary('XXX')
assert 4 in env2.Dictionary('YYY')
assert not 4 in env1.Dictionary('YYY')
assert 5 in env2.Dictionary('ZZZ')
assert 5 not in env1.Dictionary('ZZZ')
#
env1 = self.TestEnvironment(BUILDERS = {'b1' : Builder()})
assert hasattr(env1, 'b1'), "env1.b1 was not set"
assert env1.b1.object == env1, "b1.object doesn't point to env1"
env2 = env1.Clone(BUILDERS = {'b2' : Builder()})
assert env2 is env2
assert env2 == env2
assert hasattr(env1, 'b1'), "b1 was mistakenly cleared from env1"
assert env1.b1.object == env1, "b1.object was changed"
assert not hasattr(env2, 'b1'), "b1 was not cleared from env2"
assert hasattr(env2, 'b2'), "env2.b2 was not set"
assert env2.b2.object == env2, "b2.object doesn't point to env2"
# Ensure that specifying new tools in a copied environment
# works.
def foo(env): env['FOO'] = 1
def bar(env): env['BAR'] = 2
def baz(env): env['BAZ'] = 3
env1 = self.TestEnvironment(tools=[foo])
env2 = env1.Clone()
env3 = env1.Clone(tools=[bar, baz])
assert env1.get('FOO') is 1
assert env1.get('BAR') is None
assert env1.get('BAZ') is None
assert env2.get('FOO') is 1
assert env2.get('BAR') is None
assert env2.get('BAZ') is None
assert env3.get('FOO') is 1
assert env3.get('BAR') is 2
assert env3.get('BAZ') is 3
# Ensure that recursive variable substitution when copying
# environments works properly.
env1 = self.TestEnvironment(CCFLAGS = '-DFOO', XYZ = '-DXYZ')
env2 = env1.Clone(CCFLAGS = '$CCFLAGS -DBAR',
XYZ = ['-DABC', 'x $XYZ y', '-DDEF'])
x = env2.get('CCFLAGS')
assert x == '-DFOO -DBAR', x
x = env2.get('XYZ')
assert x == ['-DABC', 'x -DXYZ y', '-DDEF'], x
# Ensure that special properties of a class don't get
# lost on copying.
env1 = self.TestEnvironment(FLAGS = CLVar('flag1 flag2'))
x = env1.get('FLAGS')
assert x == ['flag1', 'flag2'], x
env2 = env1.Clone()
env2.Append(FLAGS = 'flag3 flag4')
x = env2.get('FLAGS')
assert x == ['flag1', 'flag2', 'flag3', 'flag4'], x
x = env1.get('FLAGS')
assert x == ['flag1', 'flag2'], x
# Ensure that appending directly to a copied CLVar
# doesn't modify the original.
env1 = self.TestEnvironment(FLAGS = CLVar('flag1 flag2'))
x = env1.get('FLAGS')
assert x == ['flag1', 'flag2'], x
env2 = env1.Clone()
env2['FLAGS'] += ['flag3', 'flag4']
x = env2.get('FLAGS')
assert x == ['flag1', 'flag2', 'flag3', 'flag4'], x
x = env1.get('FLAGS')
assert x == ['flag1', 'flag2'], x
# Test that the environment stores the toolpath and
# re-uses it for copies.
test = TestCmd.TestCmd(workdir = '')
test.write('xxx.py', """\
def exists(env):
1
def generate(env):
env['XXX'] = 'one'
""")
test.write('yyy.py', """\
def exists(env):
1
def generate(env):
env['YYY'] = 'two'
""")
env = self.TestEnvironment(tools=['xxx'], toolpath=[test.workpath('')])
assert env['XXX'] == 'one', env['XXX']
env = env.Clone(tools=['yyy'])
assert env['YYY'] == 'two', env['YYY']
# Test that
real_value = [4]
def my_tool(env, rv=real_value):
assert env['KEY_THAT_I_WANT'] == rv[0]
env['KEY_THAT_I_WANT'] = rv[0] + 1
env = self.TestEnvironment()
real_value[0] = 5
env = env.Clone(KEY_THAT_I_WANT=5, tools=[my_tool])
assert env['KEY_THAT_I_WANT'] == real_value[0], env['KEY_THAT_I_WANT']
real_value[0] = 6
env = env.Clone(KEY_THAT_I_WANT=6, tools=[my_tool])
assert env['KEY_THAT_I_WANT'] == real_value[0], env['KEY_THAT_I_WANT']
def test_Copy(self):
"""Test copying using the old env.Copy() method"""
env1 = self.TestEnvironment(XXX = 'x', YYY = 'y')
env2 = env1.Copy()
env1copy = env1.Copy()
assert env1copy == env1copy
assert env2 == env2
env2.Replace(YYY = 'yyy')
assert env2 == env2
assert env1 != env2
assert env1 == env1copy
def test_Detect(self):
"""Test Detect()ing tools"""
test = TestCmd.TestCmd(workdir = '')
test.subdir('sub1', 'sub2')
sub1 = test.workpath('sub1')
sub2 = test.workpath('sub2')
if sys.platform == 'win32':
test.write(['sub1', 'xxx'], "sub1/xxx\n")
test.write(['sub2', 'xxx'], "sub2/xxx\n")
env = self.TestEnvironment(ENV = { 'PATH' : [sub1, sub2] })
x = env.Detect('xxx.exe')
assert x is None, x
test.write(['sub2', 'xxx.exe'], "sub2/xxx.exe\n")
env = self.TestEnvironment(ENV = { 'PATH' : [sub1, sub2] })
x = env.Detect('xxx.exe')
assert x == 'xxx.exe', x
test.write(['sub1', 'xxx.exe'], "sub1/xxx.exe\n")
x = env.Detect('xxx.exe')
assert x == 'xxx.exe', x
else:
test.write(['sub1', 'xxx.exe'], "sub1/xxx.exe\n")
test.write(['sub2', 'xxx.exe'], "sub2/xxx.exe\n")
env = self.TestEnvironment(ENV = { 'PATH' : [sub1, sub2] })
x = env.Detect('xxx.exe')
assert x is None, x
sub2_xxx_exe = test.workpath('sub2', 'xxx.exe')
os.chmod(sub2_xxx_exe, 0755)
env = self.TestEnvironment(ENV = { 'PATH' : [sub1, sub2] })
x = env.Detect('xxx.exe')
assert x == 'xxx.exe', x
sub1_xxx_exe = test.workpath('sub1', 'xxx.exe')
os.chmod(sub1_xxx_exe, 0755)
x = env.Detect('xxx.exe')
assert x == 'xxx.exe', x
env = self.TestEnvironment(ENV = { 'PATH' : [] })
x = env.Detect('xxx.exe')
assert x is None, x
def test_Dictionary(self):
"""Test retrieval of known construction variables
Fetch them from the Dictionary and check for well-known
defaults that get inserted.
"""
env = self.TestEnvironment(XXX = 'x', YYY = 'y', ZZZ = 'z')
assert env.Dictionary('XXX') == 'x'
assert env.Dictionary('YYY') == 'y'
assert env.Dictionary('XXX', 'ZZZ') == ['x', 'z']
xxx, zzz = env.Dictionary('XXX', 'ZZZ')
assert xxx == 'x'
assert zzz == 'z'
assert 'BUILDERS' in env.Dictionary()
assert 'CC' in env.Dictionary()
assert 'CCFLAGS' in env.Dictionary()
assert 'ENV' in env.Dictionary()
assert env['XXX'] == 'x'
env['XXX'] = 'foo'
assert env.Dictionary('XXX') == 'foo'
del env['XXX']
assert 'XXX' not in env.Dictionary()
def test_FindIxes(self):
"Test FindIxes()"
env = self.TestEnvironment(LIBPREFIX='lib',
LIBSUFFIX='.a',
SHLIBPREFIX='lib',
SHLIBSUFFIX='.so',
PREFIX='pre',
SUFFIX='post')
paths = [os.path.join('dir', 'libfoo.a'),
os.path.join('dir', 'libfoo.so')]
assert paths[0] == env.FindIxes(paths, 'LIBPREFIX', 'LIBSUFFIX')
assert paths[1] == env.FindIxes(paths, 'SHLIBPREFIX', 'SHLIBSUFFIX')
assert None is env.FindIxes(paths, 'PREFIX', 'POST')
paths = ['libfoo.a', 'prefoopost']
assert paths[0] == env.FindIxes(paths, 'LIBPREFIX', 'LIBSUFFIX')
assert None is env.FindIxes(paths, 'SHLIBPREFIX', 'SHLIBSUFFIX')
assert paths[1] == env.FindIxes(paths, 'PREFIX', 'SUFFIX')
def test_ParseConfig(self):
"""Test the ParseConfig() method"""
env = self.TestEnvironment(COMMAND='command',
ASFLAGS='assembler',
CCFLAGS=[''],
CPPDEFINES=[],
CPPFLAGS=[''],
CPPPATH='string',
FRAMEWORKPATH=[],
FRAMEWORKS=[],
LIBPATH=['list'],
LIBS='',
LINKFLAGS=[''],
RPATH=[])
orig_backtick = env.backtick
class my_backtick(object):
def __init__(self, save_command, output):
self.save_command = save_command
self.output = output
def __call__(self, command):
self.save_command.append(command)
return self.output
try:
save_command = []
env.backtick = my_backtick(save_command,
"-I/usr/include/fum -I bar -X\n" + \
"-L/usr/fax -L foo -lxxx -l yyy " + \
"-Wa,-as -Wl,-link " + \
"-Wl,-rpath=rpath1 " + \
"-Wl,-R,rpath2 " + \
"-Wl,-Rrpath3 " + \
"-Wp,-cpp abc " + \
"-framework Carbon " + \
"-frameworkdir=fwd1 " + \
"-Ffwd2 " + \
"-F fwd3 " + \
"-pthread " + \
"-mno-cygwin -mwindows " + \
"-arch i386 -isysroot /tmp +DD64 " + \
"-DFOO -DBAR=value")
env.ParseConfig("fake $COMMAND")
assert save_command == ['fake command'], save_command
assert env['ASFLAGS'] == ['assembler', '-as'], env['ASFLAGS']
assert env['CCFLAGS'] == ['', '-X', '-Wa,-as',
'-pthread', '-mno-cygwin',
('-arch', 'i386'), ('-isysroot', '/tmp'),
'+DD64'], env['CCFLAGS']
assert env['CPPDEFINES'] == ['FOO', ['BAR', 'value']], env['CPPDEFINES']
assert env['CPPFLAGS'] == ['', '-Wp,-cpp'], env['CPPFLAGS']
assert env['CPPPATH'] == ['string', '/usr/include/fum', 'bar'], env['CPPPATH']
assert env['FRAMEWORKPATH'] == ['fwd1', 'fwd2', 'fwd3'], env['FRAMEWORKPATH']
assert env['FRAMEWORKS'] == ['Carbon'], env['FRAMEWORKS']
assert env['LIBPATH'] == ['list', '/usr/fax', 'foo'], env['LIBPATH']
assert env['LIBS'] == ['xxx', 'yyy', env.File('abc')], env['LIBS']
assert env['LINKFLAGS'] == ['', '-Wl,-link', '-pthread',
'-mno-cygwin', '-mwindows',
('-arch', 'i386'),
('-isysroot', '/tmp'),
'+DD64'], env['LINKFLAGS']
assert env['RPATH'] == ['rpath1', 'rpath2', 'rpath3'], env['RPATH']
env.backtick = my_backtick([], "-Ibar")
env.ParseConfig("fake2")
assert env['CPPPATH'] == ['string', '/usr/include/fum', 'bar'], env['CPPPATH']
env.ParseConfig("fake2", unique=0)
assert env['CPPPATH'] == ['string', '/usr/include/fum', 'bar', 'bar'], env['CPPPATH']
finally:
env.backtick = orig_backtick
def test_ParseDepends(self):
"""Test the ParseDepends() method"""
test = TestCmd.TestCmd(workdir = '')
test.write('single', """
#file: dependency
f0: \
d1 \
d2 \
d3 \
""")
test.write('multiple', """
f1: foo
f2 f3: bar
f4: abc def
#file: dependency
f5: \
ghi \
jkl \
mno \
""")
env = self.TestEnvironment(SINGLE = test.workpath('single'))
tlist = []
dlist = []
def my_depends(target, dependency, tlist=tlist, dlist=dlist):
tlist.extend(target)
dlist.extend(dependency)
env.Depends = my_depends
env.ParseDepends(test.workpath('does_not_exist'))
exc_caught = None
try:
env.ParseDepends(test.workpath('does_not_exist'), must_exist=1)
except IOError:
exc_caught = 1
assert exc_caught, "did not catch expected IOError"
del tlist[:]
del dlist[:]
env.ParseDepends('$SINGLE', only_one=1)
t = list(map(str, tlist))
d = list(map(str, dlist))
assert t == ['f0'], t
assert d == ['d1', 'd2', 'd3'], d
del tlist[:]
del dlist[:]
env.ParseDepends(test.workpath('multiple'))
t = list(map(str, tlist))
d = list(map(str, dlist))
assert t == ['f1', 'f2', 'f3', 'f4', 'f5'], t
assert d == ['foo', 'bar', 'abc', 'def', 'ghi', 'jkl', 'mno'], d
exc_caught = None
try:
env.ParseDepends(test.workpath('multiple'), only_one=1)
except SCons.Errors.UserError:
exc_caught = 1
assert exc_caught, "did not catch expected UserError"
def test_Platform(self):
"""Test the Platform() method"""
env = self.TestEnvironment(WIN32='win32', NONE='no-such-platform')
exc_caught = None
try:
env.Platform('does_not_exist')
except SCons.Errors.UserError:
exc_caught = 1
assert exc_caught, "did not catch expected UserError"
exc_caught = None
try:
env.Platform('$NONE')
except SCons.Errors.UserError:
exc_caught = 1
assert exc_caught, "did not catch expected UserError"
env.Platform('posix')
assert env['OBJSUFFIX'] == '.o', env['OBJSUFFIX']
env.Platform('$WIN32')
assert env['OBJSUFFIX'] == '.obj', env['OBJSUFFIX']
def test_Prepend(self):
"""Test prepending to construction variables in an Environment
"""
cases = [
'a1', 'A1', 'A1a1',
'a2', ['A2'], ['A2', 'a2'],
'a3', UL(['A3']), UL(['A3', 'a', '3']),
'a4', '', 'a4',
'a5', [], ['a5'],
'a6', UL([]), UL(['a', '6']),
'a7', [''], ['', 'a7'],
'a8', UL(['']), UL(['', 'a', '8']),
['e1'], 'E1', ['E1', 'e1'],
['e2'], ['E2'], ['E2', 'e2'],
['e3'], UL(['E3']), UL(['E3', 'e3']),
['e4'], '', ['e4'],
['e5'], [], ['e5'],
['e6'], UL([]), UL(['e6']),
['e7'], [''], ['', 'e7'],
['e8'], UL(['']), UL(['', 'e8']),
UL(['i1']), 'I1', UL(['I', '1', 'i1']),
UL(['i2']), ['I2'], UL(['I2', 'i2']),
UL(['i3']), UL(['I3']), UL(['I3', 'i3']),
UL(['i4']), '', UL(['i4']),
UL(['i5']), [], UL(['i5']),
UL(['i6']), UL([]), UL(['i6']),
UL(['i7']), [''], UL(['', 'i7']),
UL(['i8']), UL(['']), UL(['', 'i8']),
{'d1':1}, 'D1', {'d1':1, 'D1':None},
{'d2':1}, ['D2'], {'d2':1, 'D2':None},
{'d3':1}, UL(['D3']), {'d3':1, 'D3':None},
{'d4':1}, {'D4':1}, {'d4':1, 'D4':1},
{'d5':1}, UD({'D5':1}), UD({'d5':1, 'D5':1}),
UD({'u1':1}), 'U1', UD({'u1':1, 'U1':None}),
UD({'u2':1}), ['U2'], UD({'u2':1, 'U2':None}),
UD({'u3':1}), UL(['U3']), UD({'u3':1, 'U3':None}),
UD({'u4':1}), {'U4':1}, UD({'u4':1, 'U4':1}),
UD({'u5':1}), UD({'U5':1}), UD({'u5':1, 'U5':1}),
'', 'M1', 'M1',
'', ['M2'], ['M2'],
'', UL(['M3']), UL(['M3']),
'', '', '',
'', [], [],
'', UL([]), UL([]),
'', [''], [''],
'', UL(['']), UL(['']),
[], 'N1', ['N1'],
[], ['N2'], ['N2'],
[], UL(['N3']), UL(['N3']),
[], '', [],
[], [], [],
[], UL([]), UL([]),
[], [''], [''],
[], UL(['']), UL(['']),
UL([]), 'O1', UL(['O', '1']),
UL([]), ['O2'], UL(['O2']),
UL([]), UL(['O3']), UL(['O3']),
UL([]), '', UL([]),
UL([]), [], UL([]),
UL([]), UL([]), UL([]),
UL([]), [''], UL(['']),
UL([]), UL(['']), UL(['']),
[''], 'P1', ['P1', ''],
[''], ['P2'], ['P2', ''],
[''], UL(['P3']), UL(['P3', '']),
[''], '', [''],
[''], [], [''],
[''], UL([]), UL(['']),
[''], [''], ['', ''],
[''], UL(['']), UL(['', '']),
UL(['']), 'Q1', UL(['Q', '1', '']),
UL(['']), ['Q2'], UL(['Q2', '']),
UL(['']), UL(['Q3']), UL(['Q3', '']),
UL(['']), '', UL(['']),
UL(['']), [], UL(['']),
UL(['']), UL([]), UL(['']),
UL(['']), [''], UL(['', '']),
UL(['']), UL(['']), UL(['', '']),
]
env = Environment()
failed = 0
while cases:
input, prepend, expect = cases[:3]
env['XXX'] = copy.copy(input)
try:
env.Prepend(XXX = prepend)
except Exception, e:
if failed == 0: print
print " %s Prepend %s exception: %s" % \
(repr(input), repr(prepend), e)
failed = failed + 1
else:
result = env['XXX']
if result != expect:
if failed == 0: print
print " %s Prepend %s => %s did not match %s" % \
(repr(input), repr(prepend), repr(result), repr(expect))
failed = failed + 1
del cases[:3]
assert failed == 0, "%d Prepend() cases failed" % failed
env['UL'] = UL(['foo'])
env.Prepend(UL = 'bar')
result = env['UL']
assert isinstance(result, UL), repr(result)
assert result == ['b', 'a', 'r', 'foo'], result
env['CLVar'] = CLVar(['foo'])
env.Prepend(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['bar', 'foo'], result
env3 = self.TestEnvironment(X = {'x1' : 7})
env3.Prepend(X = {'x1' : 8, 'x2' : 9}, Y = {'y1' : 10})
assert env3['X'] == {'x1': 8, 'x2' : 9}, env3['X']
assert env3['Y'] == {'y1': 10}, env3['Y']
z1 = Builder()
z2 = Builder()
env4 = self.TestEnvironment(BUILDERS = {'z1' : z1})
env4.Prepend(BUILDERS = {'z2' : z2})
assert env4['BUILDERS'] == {'z1' : z1, 'z2' : z2}, env4['BUILDERS']
assert hasattr(env4, 'z1')
assert hasattr(env4, 'z2')
def test_PrependENVPath(self):
"""Test prepending to an ENV path."""
env1 = self.TestEnvironment(ENV = {'PATH': r'C:\dir\num\one;C:\dir\num\two'},
MYENV = {'MYPATH': r'C:\mydir\num\one;C:\mydir\num\two'})
# have to include the pathsep here so that the test will work on UNIX too.
env1.PrependENVPath('PATH',r'C:\dir\num\two',sep = ';')
env1.PrependENVPath('PATH',r'C:\dir\num\three',sep = ';')
env1.PrependENVPath('MYPATH',r'C:\mydir\num\three','MYENV',sep = ';')
env1.PrependENVPath('MYPATH',r'C:\mydir\num\one','MYENV',sep = ';')
# this should do nothing since delete_existing is 0
env1.PrependENVPath('MYPATH',r'C:\mydir\num\three','MYENV', sep = ';', delete_existing=0)
assert(env1['ENV']['PATH'] == r'C:\dir\num\three;C:\dir\num\two;C:\dir\num\one')
assert(env1['MYENV']['MYPATH'] == r'C:\mydir\num\one;C:\mydir\num\three;C:\mydir\num\two')
test = TestCmd.TestCmd(workdir = '')
test.subdir('sub1', 'sub2')
p=env1['ENV']['PATH']
env1.PrependENVPath('PATH','#sub1', sep = ';')
env1.PrependENVPath('PATH',env1.fs.Dir('sub2'), sep = ';')
assert env1['ENV']['PATH'] == 'sub2;sub1;' + p, env1['ENV']['PATH']
def test_PrependUnique(self):
"""Test prepending unique values to construction variables
This strips values that are already present when lists are
involved."""
env = self.TestEnvironment(AAA1 = 'a1',
AAA2 = 'a2',
AAA3 = 'a3',
AAA4 = 'a4',
AAA5 = 'a5',
BBB1 = ['b1'],
BBB2 = ['b2'],
BBB3 = ['b3'],
BBB4 = ['b4'],
BBB5 = ['b5'],
CCC1 = '',
CCC2 = '',
DDD1 = ['a', 'b', 'c'])
env.PrependUnique(AAA1 = 'a1',
AAA2 = ['a2'],
AAA3 = ['a3', 'b', 'c', 'b', 'a3'], # ignore dups
AAA4 = 'a4.new',
AAA5 = ['a5.new'],
BBB1 = 'b1',
BBB2 = ['b2'],
BBB3 = ['b3', 'b', 'c', 'b3'],
BBB4 = 'b4.new',
BBB5 = ['b5.new'],
CCC1 = 'c1',
CCC2 = ['c2'],
DDD1 = 'b')
assert env['AAA1'] == 'a1a1', env['AAA1']
assert env['AAA2'] == ['a2'], env['AAA2']
assert env['AAA3'] == ['c', 'b', 'a3'], env['AAA3']
assert env['AAA4'] == 'a4.newa4', env['AAA4']
assert env['AAA5'] == ['a5.new', 'a5'], env['AAA5']
assert env['BBB1'] == ['b1'], env['BBB1']
assert env['BBB2'] == ['b2'], env['BBB2']
assert env['BBB3'] == ['b', 'c', 'b3'], env['BBB3']
assert env['BBB4'] == ['b4.new', 'b4'], env['BBB4']
assert env['BBB5'] == ['b5.new', 'b5'], env['BBB5']
assert env['CCC1'] == 'c1', env['CCC1']
assert env['CCC2'] == ['c2'], env['CCC2']
assert env['DDD1'] == ['a', 'b', 'c'], env['DDD1']
env.PrependUnique(DDD1 = 'b', delete_existing=1)
assert env['DDD1'] == ['b', 'a', 'c'], env['DDD1'] # b moves to front
env.PrependUnique(DDD1 = ['a','c'], delete_existing=1)
assert env['DDD1'] == ['a', 'c', 'b'], env['DDD1'] # a & c move to front
env.PrependUnique(DDD1 = ['d','e','d'], delete_existing=1)
assert env['DDD1'] == ['d', 'e', 'a', 'c', 'b'], env['DDD1']
env['CLVar'] = CLVar([])
env.PrependUnique(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['bar'], result
env['CLVar'] = CLVar(['abc'])
env.PrependUnique(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['bar', 'abc'], result
env['CLVar'] = CLVar(['bar'])
env.PrependUnique(CLVar = 'bar')
result = env['CLVar']
assert isinstance(result, CLVar), repr(result)
assert result == ['bar'], result
def test_Replace(self):
"""Test replacing construction variables in an Environment
After creation of the Environment, of course.
"""
env1 = self.TestEnvironment(AAA = 'a', BBB = 'b')
env1.Replace(BBB = 'bbb', CCC = 'ccc')
env2 = self.TestEnvironment(AAA = 'a', BBB = 'bbb', CCC = 'ccc')
assert env1 == env2, diff_env(env1, env2)
b1 = Builder()
b2 = Builder()
env3 = self.TestEnvironment(BUILDERS = {'b1' : b1})
assert hasattr(env3, 'b1'), "b1 was not set"
env3.Replace(BUILDERS = {'b2' : b2})
assert not hasattr(env3, 'b1'), "b1 was not cleared"
assert hasattr(env3, 'b2'), "b2 was not set"
def test_ReplaceIxes(self):
"Test ReplaceIxes()"
env = self.TestEnvironment(LIBPREFIX='lib',
LIBSUFFIX='.a',
SHLIBPREFIX='lib',
SHLIBSUFFIX='.so',
PREFIX='pre',
SUFFIX='post')
assert 'libfoo.a' == env.ReplaceIxes('libfoo.so',
'SHLIBPREFIX', 'SHLIBSUFFIX',
'LIBPREFIX', 'LIBSUFFIX')
assert os.path.join('dir', 'libfoo.a') == env.ReplaceIxes(os.path.join('dir', 'libfoo.so'),
'SHLIBPREFIX', 'SHLIBSUFFIX',
'LIBPREFIX', 'LIBSUFFIX')
assert 'libfoo.a' == env.ReplaceIxes('prefoopost',
'PREFIX', 'SUFFIX',
'LIBPREFIX', 'LIBSUFFIX')
def test_SetDefault(self):
"""Test the SetDefault method"""
env = self.TestEnvironment(tools = [])
env.SetDefault(V1 = 1)
env.SetDefault(V1 = 2)
assert env['V1'] == 1
env['V2'] = 2
env.SetDefault(V2 = 1)
assert env['V2'] == 2
def test_Tool(self):
"""Test the Tool() method"""
env = self.TestEnvironment(LINK='link', NONE='no-such-tool')
exc_caught = None
try:
env.Tool('does_not_exist')
except SCons.Errors.EnvironmentError:
exc_caught = 1
assert exc_caught, "did not catch expected EnvironmentError"
exc_caught = None
try:
env.Tool('$NONE')
except SCons.Errors.EnvironmentError:
exc_caught = 1
assert exc_caught, "did not catch expected EnvironmentError"
# Use a non-existent toolpath directory just to make sure we
# can call Tool() with the keyword argument.
env.Tool('cc', toolpath=['/no/such/directory'])
assert env['CC'] == 'cc', env['CC']
env.Tool('$LINK')
assert env['LINK'] == '$SMARTLINK', env['LINK']
# Test that the environment stores the toolpath and
# re-uses it for later calls.
test = TestCmd.TestCmd(workdir = '')
test.write('xxx.py', """\
def exists(env):
1
def generate(env):
env['XXX'] = 'one'
""")
test.write('yyy.py', """\
def exists(env):
1
def generate(env):
env['YYY'] = 'two'
""")
env = self.TestEnvironment(tools=['xxx'], toolpath=[test.workpath('')])
assert env['XXX'] == 'one', env['XXX']
env.Tool('yyy')
assert env['YYY'] == 'two', env['YYY']
def test_WhereIs(self):
"""Test the WhereIs() method"""
test = TestCmd.TestCmd(workdir = '')
sub1_xxx_exe = test.workpath('sub1', 'xxx.exe')
sub2_xxx_exe = test.workpath('sub2', 'xxx.exe')
sub3_xxx_exe = test.workpath('sub3', 'xxx.exe')
sub4_xxx_exe = test.workpath('sub4', 'xxx.exe')
test.subdir('subdir', 'sub1', 'sub2', 'sub3', 'sub4')
if sys.platform != 'win32':
test.write(sub1_xxx_exe, "\n")
os.mkdir(sub2_xxx_exe)
test.write(sub3_xxx_exe, "\n")
os.chmod(sub3_xxx_exe, 0777)
test.write(sub4_xxx_exe, "\n")
os.chmod(sub4_xxx_exe, 0777)
env_path = os.environ['PATH']
pathdirs_1234 = [ test.workpath('sub1'),
test.workpath('sub2'),
test.workpath('sub3'),
test.workpath('sub4'),
] + env_path.split(os.pathsep)
pathdirs_1243 = [ test.workpath('sub1'),
test.workpath('sub2'),
test.workpath('sub4'),
test.workpath('sub3'),
] + env_path.split(os.pathsep)
path = os.pathsep.join(pathdirs_1234)
env = self.TestEnvironment(ENV = {'PATH' : path})
wi = env.WhereIs('xxx.exe')
assert wi == test.workpath(sub3_xxx_exe), wi
wi = env.WhereIs('xxx.exe', pathdirs_1243)
assert wi == test.workpath(sub4_xxx_exe), wi
wi = env.WhereIs('xxx.exe', os.pathsep.join(pathdirs_1243))
assert wi == test.workpath(sub4_xxx_exe), wi
wi = env.WhereIs('xxx.exe', reject = sub3_xxx_exe)
assert wi == test.workpath(sub4_xxx_exe), wi
wi = env.WhereIs('xxx.exe', pathdirs_1243, reject = sub3_xxx_exe)
assert wi == test.workpath(sub4_xxx_exe), wi
path = os.pathsep.join(pathdirs_1243)
env = self.TestEnvironment(ENV = {'PATH' : path})
wi = env.WhereIs('xxx.exe')
assert wi == test.workpath(sub4_xxx_exe), wi
wi = env.WhereIs('xxx.exe', pathdirs_1234)
assert wi == test.workpath(sub3_xxx_exe), wi
wi = env.WhereIs('xxx.exe', os.pathsep.join(pathdirs_1234))
assert wi == test.workpath(sub3_xxx_exe), wi
if sys.platform == 'win32':
wi = env.WhereIs('xxx', pathext = '')
assert wi is None, wi
wi = env.WhereIs('xxx', pathext = '.exe')
assert wi == test.workpath(sub4_xxx_exe), wi
wi = env.WhereIs('xxx', path = pathdirs_1234, pathext = '.BAT;.EXE')
assert wi.lower() == test.workpath(sub3_xxx_exe).lower(), wi
# Test that we return a normalized path even when
# the path contains forward slashes.
forward_slash = test.workpath('') + '/sub3'
wi = env.WhereIs('xxx', path = forward_slash, pathext = '.EXE')
assert wi.lower() == test.workpath(sub3_xxx_exe).lower(), wi
def test_Action(self):
"""Test the Action() method"""
import SCons.Action
env = self.TestEnvironment(FOO = 'xyzzy')
a = env.Action('foo')
assert a, a
assert a.__class__ is SCons.Action.CommandAction, a.__class__
a = env.Action('$FOO')
assert a, a
assert a.__class__ is SCons.Action.CommandAction, a.__class__
a = env.Action('$$FOO')
assert a, a
assert a.__class__ is SCons.Action.LazyAction, a.__class__
a = env.Action(['$FOO', 'foo'])
assert a, a
assert a.__class__ is SCons.Action.ListAction, a.__class__
def func(arg):
pass
a = env.Action(func)
assert a, a
assert a.__class__ is SCons.Action.FunctionAction, a.__class__
def test_AddPostAction(self):
"""Test the AddPostAction() method"""
env = self.TestEnvironment(FOO='fff', BAR='bbb')
n = env.AddPostAction('$FOO', lambda x: x)
assert str(n[0]) == 'fff', n[0]
n = env.AddPostAction(['ggg', '$BAR'], lambda x: x)
assert str(n[0]) == 'ggg', n[0]
assert str(n[1]) == 'bbb', n[1]
def test_AddPreAction(self):
"""Test the AddPreAction() method"""
env = self.TestEnvironment(FOO='fff', BAR='bbb')
n = env.AddPreAction('$FOO', lambda x: x)
assert str(n[0]) == 'fff', n[0]
n = env.AddPreAction(['ggg', '$BAR'], lambda x: x)
assert str(n[0]) == 'ggg', n[0]
assert str(n[1]) == 'bbb', n[1]
def test_Alias(self):
"""Test the Alias() method"""
env = self.TestEnvironment(FOO='kkk', BAR='lll', EA='export_alias')
tgt = env.Alias('new_alias')[0]
assert str(tgt) == 'new_alias', tgt
assert tgt.sources == [], tgt.sources
assert not hasattr(tgt, 'builder'), tgt.builder
tgt = env.Alias('None_alias', None)[0]
assert str(tgt) == 'None_alias', tgt
assert tgt.sources == [], tgt.sources
tgt = env.Alias('empty_list', [])[0]
assert str(tgt) == 'empty_list', tgt
assert tgt.sources == [], tgt.sources
tgt = env.Alias('export_alias', [ 'asrc1', '$FOO' ])[0]
assert str(tgt) == 'export_alias', tgt
assert len(tgt.sources) == 2, list(map(str, tgt.sources))
assert str(tgt.sources[0]) == 'asrc1', list(map(str, tgt.sources))
assert str(tgt.sources[1]) == 'kkk', list(map(str, tgt.sources))
n = env.Alias(tgt, source = ['$BAR', 'asrc4'])[0]
assert n is tgt, n
assert len(tgt.sources) == 4, list(map(str, tgt.sources))
assert str(tgt.sources[2]) == 'lll', list(map(str, tgt.sources))
assert str(tgt.sources[3]) == 'asrc4', list(map(str, tgt.sources))
n = env.Alias('$EA', 'asrc5')[0]
assert n is tgt, n
assert len(tgt.sources) == 5, list(map(str, tgt.sources))
assert str(tgt.sources[4]) == 'asrc5', list(map(str, tgt.sources))
t1, t2 = env.Alias(['t1', 't2'], ['asrc6', 'asrc7'])
assert str(t1) == 't1', t1
assert str(t2) == 't2', t2
assert len(t1.sources) == 2, list(map(str, t1.sources))
assert str(t1.sources[0]) == 'asrc6', list(map(str, t1.sources))
assert str(t1.sources[1]) == 'asrc7', list(map(str, t1.sources))
assert len(t2.sources) == 2, list(map(str, t2.sources))
assert str(t2.sources[0]) == 'asrc6', list(map(str, t2.sources))
assert str(t2.sources[1]) == 'asrc7', list(map(str, t2.sources))
tgt = env.Alias('add', 's1')
tgt = env.Alias('add', 's2')[0]
s = list(map(str, tgt.sources))
assert s == ['s1', 's2'], s
tgt = env.Alias(tgt, 's3')[0]
s = list(map(str, tgt.sources))
assert s == ['s1', 's2', 's3'], s
tgt = env.Alias('act', None, "action1")[0]
s = str(tgt.builder.action)
assert s == "action1", s
tgt = env.Alias('act', None, "action2")[0]
s = str(tgt.builder.action)
assert s == "action1\naction2", s
tgt = env.Alias(tgt, None, "action3")[0]
s = str(tgt.builder.action)
assert s == "action1\naction2\naction3", s
def test_AlwaysBuild(self):
"""Test the AlwaysBuild() method"""
env = self.TestEnvironment(FOO='fff', BAR='bbb')
t = env.AlwaysBuild('a', 'b$FOO', ['c', 'd'], '$BAR',
env.fs.Dir('dir'), env.fs.File('file'))
assert t[0].__class__.__name__ == 'Entry'
assert t[0].path == 'a'
assert t[0].always_build
assert t[1].__class__.__name__ == 'Entry'
assert t[1].path == 'bfff'
assert t[1].always_build
assert t[2].__class__.__name__ == 'Entry'
assert t[2].path == 'c'
assert t[2].always_build
assert t[3].__class__.__name__ == 'Entry'
assert t[3].path == 'd'
assert t[3].always_build
assert t[4].__class__.__name__ == 'Entry'
assert t[4].path == 'bbb'
assert t[4].always_build
assert t[5].__class__.__name__ == 'Dir'
assert t[5].path == 'dir'
assert t[5].always_build
assert t[6].__class__.__name__ == 'File'
assert t[6].path == 'file'
assert t[6].always_build
def test_VariantDir(self):
"""Test the VariantDir() method"""
class MyFS(object):
def Dir(self, name):
return name
def VariantDir(self, variant_dir, src_dir, duplicate):
self.variant_dir = variant_dir
self.src_dir = src_dir
self.duplicate = duplicate
env = self.TestEnvironment(FOO = 'fff', BAR = 'bbb')
env.fs = MyFS()
env.VariantDir('build', 'src')
assert env.fs.variant_dir == 'build', env.fs.variant_dir
assert env.fs.src_dir == 'src', env.fs.src_dir
assert env.fs.duplicate == 1, env.fs.duplicate
env.VariantDir('build${FOO}', '${BAR}src', 0)
assert env.fs.variant_dir == 'buildfff', env.fs.variant_dir
assert env.fs.src_dir == 'bbbsrc', env.fs.src_dir
assert env.fs.duplicate == 0, env.fs.duplicate
def test_Builder(self):
"""Test the Builder() method"""
env = self.TestEnvironment(FOO = 'xyzzy')
b = env.Builder(action = 'foo')
assert b is not None, b
b = env.Builder(action = '$FOO')
assert b is not None, b
b = env.Builder(action = ['$FOO', 'foo'])
assert b is not None, b
def func(arg):
pass
b = env.Builder(action = func)
assert b is not None, b
b = env.Builder(generator = func)
assert b is not None, b
def test_CacheDir(self):
"""Test the CacheDir() method"""
env = self.TestEnvironment(CD = 'CacheDir')
env.CacheDir('foo')
assert env._CacheDir_path == 'foo', env._CacheDir_path
env.CacheDir('$CD')
assert env._CacheDir_path == 'CacheDir', env._CacheDir_path
def test_Clean(self):
"""Test the Clean() method"""
env = self.TestEnvironment(FOO = 'fff', BAR = 'bbb')
CT = SCons.Environment.CleanTargets
foo = env.arg2nodes('foo')[0]
fff = env.arg2nodes('fff')[0]
t = env.Clean('foo', 'aaa')
l = list(map(str, CT[foo]))
assert l == ['aaa'], l
t = env.Clean(foo, ['$BAR', 'ccc'])
l = list(map(str, CT[foo]))
assert l == ['aaa', 'bbb', 'ccc'], l
eee = env.arg2nodes('eee')[0]
t = env.Clean('$FOO', 'ddd')
l = list(map(str, CT[fff]))
assert l == ['ddd'], l
t = env.Clean(fff, [eee, 'fff'])
l = list(map(str, CT[fff]))
assert l == ['ddd', 'eee', 'fff'], l
def test_Command(self):
"""Test the Command() method."""
env = Environment()
t = env.Command(target='foo.out', source=['foo1.in', 'foo2.in'],
action='buildfoo $target $source')[0]
assert t.builder is not None
assert t.builder.action.__class__.__name__ == 'CommandAction'
assert t.builder.action.cmd_list == 'buildfoo $target $source'
assert 'foo1.in' in [x.path for x in t.sources]
assert 'foo2.in' in [x.path for x in t.sources]
sub = env.fs.Dir('sub')
t = env.Command(target='bar.out', source='sub',
action='buildbar $target $source')[0]
assert 'sub' in [x.path for x in t.sources]
def testFunc(env, target, source):
assert str(target[0]) == 'foo.out'
assert 'foo1.in' in list(map(str, source)) and 'foo2.in' in list(map(str, source)), list(map(str, source))
return 0
t = env.Command(target='foo.out', source=['foo1.in','foo2.in'],
action=testFunc)[0]
assert t.builder is not None
assert t.builder.action.__class__.__name__ == 'FunctionAction'
t.build()
assert 'foo1.in' in [x.path for x in t.sources]
assert 'foo2.in' in [x.path for x in t.sources]
x = []
def test2(baz, x=x):
x.append(baz)
env = self.TestEnvironment(TEST2 = test2)
t = env.Command(target='baz.out', source='baz.in',
action='${TEST2(XYZ)}',
XYZ='magic word')[0]
assert t.builder is not None
t.build()
assert x[0] == 'magic word', x
t = env.Command(target='${X}.out', source='${X}.in',
action = 'foo',
X = 'xxx')[0]
assert str(t) == 'xxx.out', str(t)
assert 'xxx.in' in [x.path for x in t.sources]
env = self.TestEnvironment(source_scanner = 'should_not_find_this')
t = env.Command(target='file.out', source='file.in',
action = 'foo',
source_scanner = 'fake')[0]
assert t.builder.source_scanner == 'fake', t.builder.source_scanner
def test_Configure(self):
"""Test the Configure() method"""
# Configure() will write to a local temporary file.
test = TestCmd.TestCmd(workdir = '')
save = os.getcwd()
try:
os.chdir(test.workpath())
env = self.TestEnvironment(FOO = 'xyzzy')
def func(arg):
pass
c = env.Configure()
assert c is not None, c
c.Finish()
c = env.Configure(custom_tests = {'foo' : func, '$FOO' : func})
assert c is not None, c
assert hasattr(c, 'foo')
assert hasattr(c, 'xyzzy')
c.Finish()
finally:
os.chdir(save)
def test_Depends(self):
"""Test the explicit Depends method."""
env = self.TestEnvironment(FOO = 'xxx', BAR='yyy')
env.Dir('dir1')
env.Dir('dir2')
env.File('xxx.py')
env.File('yyy.py')
t = env.Depends(target='EnvironmentTest.py',
dependency='Environment.py')[0]
assert t.__class__.__name__ == 'Entry', t.__class__.__name__
assert t.path == 'EnvironmentTest.py'
assert len(t.depends) == 1
d = t.depends[0]
assert d.__class__.__name__ == 'Entry', d.__class__.__name__
assert d.path == 'Environment.py'
t = env.Depends(target='${FOO}.py', dependency='${BAR}.py')[0]
assert t.__class__.__name__ == 'File', t.__class__.__name__
assert t.path == 'xxx.py'
assert len(t.depends) == 1
d = t.depends[0]
assert d.__class__.__name__ == 'File', d.__class__.__name__
assert d.path == 'yyy.py'
t = env.Depends(target='dir1', dependency='dir2')[0]
assert t.__class__.__name__ == 'Dir', t.__class__.__name__
assert t.path == 'dir1'
assert len(t.depends) == 1
d = t.depends[0]
assert d.__class__.__name__ == 'Dir', d.__class__.__name__
assert d.path == 'dir2'
def test_Dir(self):
"""Test the Dir() method"""
class MyFS(object):
def Dir(self, name):
return 'Dir(%s)' % name
env = self.TestEnvironment(FOO = 'foodir', BAR = 'bardir')
env.fs = MyFS()
d = env.Dir('d')
assert d == 'Dir(d)', d
d = env.Dir('$FOO')
assert d == 'Dir(foodir)', d
d = env.Dir('${BAR}_$BAR')
assert d == 'Dir(bardir_bardir)', d
d = env.Dir(['dir1'])
assert d == ['Dir(dir1)'], d
d = env.Dir(['dir1', 'dir2'])
assert d == ['Dir(dir1)', 'Dir(dir2)'], d
def test_NoClean(self):
"""Test the NoClean() method"""
env = self.TestEnvironment(FOO='ggg', BAR='hhh')
env.Dir('p_hhhb')
env.File('p_d')
t = env.NoClean('p_a', 'p_${BAR}b', ['p_c', 'p_d'], 'p_$FOO')
assert t[0].__class__.__name__ == 'Entry', t[0].__class__.__name__
assert t[0].path == 'p_a'
assert t[0].noclean
assert t[1].__class__.__name__ == 'Dir', t[1].__class__.__name__
assert t[1].path == 'p_hhhb'
assert t[1].noclean
assert t[2].__class__.__name__ == 'Entry', t[2].__class__.__name__
assert t[2].path == 'p_c'
assert t[2].noclean
assert t[3].__class__.__name__ == 'File', t[3].__class__.__name__
assert t[3].path == 'p_d'
assert t[3].noclean
assert t[4].__class__.__name__ == 'Entry', t[4].__class__.__name__
assert t[4].path == 'p_ggg'
assert t[4].noclean
def test_Dump(self):
"""Test the Dump() method"""
env = self.TestEnvironment(FOO = 'foo')
assert env.Dump('FOO') == "'foo'", env.Dump('FOO')
assert len(env.Dump()) > 200, env.Dump() # no args version
def test_Environment(self):
"""Test the Environment() method"""
env = self.TestEnvironment(FOO = 'xxx', BAR = 'yyy')
e2 = env.Environment(X = '$FOO', Y = '$BAR')
assert e2['X'] == 'xxx', e2['X']
assert e2['Y'] == 'yyy', e2['Y']
def test_Execute(self):
"""Test the Execute() method"""
class MyAction(object):
def __init__(self, *args, **kw):
self.args = args
def __call__(self, target, source, env):
return "%s executed" % self.args
env = Environment()
env.Action = MyAction
result = env.Execute("foo")
assert result == "foo executed", result
def test_Entry(self):
"""Test the Entry() method"""
class MyFS(object):
def Entry(self, name):
return 'Entry(%s)' % name
env = self.TestEnvironment(FOO = 'fooentry', BAR = 'barentry')
env.fs = MyFS()
e = env.Entry('e')
assert e == 'Entry(e)', e
e = env.Entry('$FOO')
assert e == 'Entry(fooentry)', e
e = env.Entry('${BAR}_$BAR')
assert e == 'Entry(barentry_barentry)', e
e = env.Entry(['entry1'])
assert e == ['Entry(entry1)'], e
e = env.Entry(['entry1', 'entry2'])
assert e == ['Entry(entry1)', 'Entry(entry2)'], e
def test_File(self):
"""Test the File() method"""
class MyFS(object):
def File(self, name):
return 'File(%s)' % name
env = self.TestEnvironment(FOO = 'foofile', BAR = 'barfile')
env.fs = MyFS()
f = env.File('f')
assert f == 'File(f)', f
f = env.File('$FOO')
assert f == 'File(foofile)', f
f = env.File('${BAR}_$BAR')
assert f == 'File(barfile_barfile)', f
f = env.File(['file1'])
assert f == ['File(file1)'], f
f = env.File(['file1', 'file2'])
assert f == ['File(file1)', 'File(file2)'], f
def test_FindFile(self):
"""Test the FindFile() method"""
env = self.TestEnvironment(FOO = 'fff', BAR = 'bbb')
r = env.FindFile('foo', ['no_such_directory'])
assert r is None, r
# XXX
def test_Flatten(self):
"""Test the Flatten() method"""
env = Environment()
l = env.Flatten([1])
assert l == [1]
l = env.Flatten([1, [2, [3, [4]]]])
assert l == [1, 2, 3, 4], l
def test_GetBuildPath(self):
"""Test the GetBuildPath() method."""
env = self.TestEnvironment(MAGIC = 'xyzzy')
p = env.GetBuildPath('foo')
assert p == 'foo', p
p = env.GetBuildPath('$MAGIC')
assert p == 'xyzzy', p
def test_Ignore(self):
"""Test the explicit Ignore method."""
env = self.TestEnvironment(FOO='yyy', BAR='zzz')
env.Dir('dir1')
env.Dir('dir2')
env.File('yyyzzz')
env.File('zzzyyy')
t = env.Ignore(target='targ.py', dependency='dep.py')[0]
assert t.__class__.__name__ == 'Entry', t.__class__.__name__
assert t.path == 'targ.py'
assert len(t.ignore) == 1
i = t.ignore[0]
assert i.__class__.__name__ == 'Entry', i.__class__.__name__
assert i.path == 'dep.py'
t = env.Ignore(target='$FOO$BAR', dependency='$BAR$FOO')[0]
assert t.__class__.__name__ == 'File', t.__class__.__name__
assert t.path == 'yyyzzz'
assert len(t.ignore) == 1
i = t.ignore[0]
assert i.__class__.__name__ == 'File', i.__class__.__name__
assert i.path == 'zzzyyy'
t = env.Ignore(target='dir1', dependency='dir2')[0]
assert t.__class__.__name__ == 'Dir', t.__class__.__name__
assert t.path == 'dir1'
assert len(t.ignore) == 1
i = t.ignore[0]
assert i.__class__.__name__ == 'Dir', i.__class__.__name__
assert i.path == 'dir2'
def test_Literal(self):
"""Test the Literal() method"""
env = self.TestEnvironment(FOO='fff', BAR='bbb')
list = env.subst_list([env.Literal('$FOO'), '$BAR'])[0]
assert list == ['$FOO', 'bbb'], list
list = env.subst_list(['$FOO', env.Literal('$BAR')])[0]
assert list == ['fff', '$BAR'], list
def test_Local(self):
"""Test the Local() method."""
env = self.TestEnvironment(FOO='lll')
l = env.Local(env.fs.File('fff'))
assert str(l[0]) == 'fff', l[0]
l = env.Local('ggg', '$FOO')
assert str(l[0]) == 'ggg', l[0]
assert str(l[1]) == 'lll', l[1]
def test_Precious(self):
"""Test the Precious() method"""
env = self.TestEnvironment(FOO='ggg', BAR='hhh')
env.Dir('p_hhhb')
env.File('p_d')
t = env.Precious('p_a', 'p_${BAR}b', ['p_c', 'p_d'], 'p_$FOO')
assert t[0].__class__.__name__ == 'Entry', t[0].__class__.__name__
assert t[0].path == 'p_a'
assert t[0].precious
assert t[1].__class__.__name__ == 'Dir', t[1].__class__.__name__
assert t[1].path == 'p_hhhb'
assert t[1].precious
assert t[2].__class__.__name__ == 'Entry', t[2].__class__.__name__
assert t[2].path == 'p_c'
assert t[2].precious
assert t[3].__class__.__name__ == 'File', t[3].__class__.__name__
assert t[3].path == 'p_d'
assert t[3].precious
assert t[4].__class__.__name__ == 'Entry', t[4].__class__.__name__
assert t[4].path == 'p_ggg'
assert t[4].precious
def test_Pseudo(self):
"""Test the Pseudo() method"""
env = self.TestEnvironment(FOO='ggg', BAR='hhh')
env.Dir('p_hhhb')
env.File('p_d')
t = env.Pseudo('p_a', 'p_${BAR}b', ['p_c', 'p_d'], 'p_$FOO')
assert t[0].__class__.__name__ == 'Entry', t[0].__class__.__name__
assert t[0].path == 'p_a'
assert t[0].pseudo
assert t[1].__class__.__name__ == 'Dir', t[1].__class__.__name__
assert t[1].path == 'p_hhhb'
assert t[1].pseudo
assert t[2].__class__.__name__ == 'Entry', t[2].__class__.__name__
assert t[2].path == 'p_c'
assert t[2].pseudo
assert t[3].__class__.__name__ == 'File', t[3].__class__.__name__
assert t[3].path == 'p_d'
assert t[3].pseudo
assert t[4].__class__.__name__ == 'Entry', t[4].__class__.__name__
assert t[4].path == 'p_ggg'
assert t[4].pseudo
def test_Repository(self):
"""Test the Repository() method."""
class MyFS(object):
def __init__(self):
self.list = []
def Repository(self, *dirs):
self.list.extend(list(dirs))
def Dir(self, name):
return name
env = self.TestEnvironment(FOO='rrr', BAR='sss')
env.fs = MyFS()
env.Repository('/tmp/foo')
env.Repository('/tmp/$FOO', '/tmp/$BAR/foo')
expect = ['/tmp/foo', '/tmp/rrr', '/tmp/sss/foo']
assert env.fs.list == expect, env.fs.list
def test_Scanner(self):
"""Test the Scanner() method"""
def scan(node, env, target, arg):
pass
env = self.TestEnvironment(FOO = scan)
s = env.Scanner('foo')
assert s is not None, s
s = env.Scanner(function = 'foo')
assert s is not None, s
if 0:
s = env.Scanner('$FOO')
assert s is not None, s
s = env.Scanner(function = '$FOO')
assert s is not None, s
def test_SConsignFile(self):
"""Test the SConsignFile() method"""
import SCons.SConsign
class MyFS(object):
SConstruct_dir = os.sep + 'dir'
env = self.TestEnvironment(FOO = 'SConsign',
BAR = os.path.join(os.sep, 'File'))
env.fs = MyFS()
env.Execute = lambda action: None
try:
fnames = []
dbms = []
def capture(name, dbm_module, fnames=fnames, dbms=dbms):
fnames.append(name)
dbms.append(dbm_module)
save_SConsign_File = SCons.SConsign.File
SCons.SConsign.File = capture
env.SConsignFile('foo')
assert fnames[-1] == os.path.join(os.sep, 'dir', 'foo'), fnames
assert dbms[-1] is None, dbms
env.SConsignFile('$FOO')
assert fnames[-1] == os.path.join(os.sep, 'dir', 'SConsign'), fnames
assert dbms[-1] is None, dbms
env.SConsignFile('/$FOO')
assert fnames[-1] == os.sep + 'SConsign', fnames
assert dbms[-1] is None, dbms
env.SConsignFile(os.sep + '$FOO')
assert fnames[-1] == os.sep + 'SConsign', fnames
assert dbms[-1] is None, dbms
env.SConsignFile('$BAR', 'x')
assert fnames[-1] == os.path.join(os.sep, 'File'), fnames
assert dbms[-1] == 'x', dbms
env.SConsignFile('__$BAR', 7)
assert fnames[-1] == os.path.join(os.sep, 'dir', '__', 'File'), fnames
assert dbms[-1] == 7, dbms
env.SConsignFile()
assert fnames[-1] == os.path.join(os.sep, 'dir', '.sconsign'), fnames
assert dbms[-1] is None, dbms
env.SConsignFile(None)
assert fnames[-1] is None, fnames
assert dbms[-1] is None, dbms
finally:
SCons.SConsign.File = save_SConsign_File
def test_SideEffect(self):
"""Test the SideEffect() method"""
env = self.TestEnvironment(LIB='lll', FOO='fff', BAR='bbb')
env.File('mylll.pdb')
env.Dir('mymmm.pdb')
foo = env.Object('foo.obj', 'foo.cpp')[0]
bar = env.Object('bar.obj', 'bar.cpp')[0]
s = env.SideEffect('mylib.pdb', ['foo.obj', 'bar.obj'])[0]
assert s.__class__.__name__ == 'Entry', s.__class__.__name__
assert s.path == 'mylib.pdb'
assert s.side_effect
assert foo.side_effects == [s]
assert bar.side_effects == [s]
fff = env.Object('fff.obj', 'fff.cpp')[0]
bbb = env.Object('bbb.obj', 'bbb.cpp')[0]
s = env.SideEffect('my${LIB}.pdb', ['${FOO}.obj', '${BAR}.obj'])[0]
assert s.__class__.__name__ == 'File', s.__class__.__name__
assert s.path == 'mylll.pdb'
assert s.side_effect
assert fff.side_effects == [s], fff.side_effects
assert bbb.side_effects == [s], bbb.side_effects
ggg = env.Object('ggg.obj', 'ggg.cpp')[0]
ccc = env.Object('ccc.obj', 'ccc.cpp')[0]
s = env.SideEffect('mymmm.pdb', ['ggg.obj', 'ccc.obj'])[0]
assert s.__class__.__name__ == 'Dir', s.__class__.__name__
assert s.path == 'mymmm.pdb'
assert s.side_effect
assert ggg.side_effects == [s], ggg.side_effects
assert ccc.side_effects == [s], ccc.side_effects
def test_SourceCode(self):
"""Test the SourceCode() method."""
env = self.TestEnvironment(FOO='mmm', BAR='nnn')
e = env.SourceCode('foo', None)[0]
assert e.path == 'foo'
s = e.src_builder()
assert s is None, s
b = Builder()
e = env.SourceCode(e, b)[0]
assert e.path == 'foo'
s = e.src_builder()
assert s is b, s
e = env.SourceCode('$BAR$FOO', None)[0]
assert e.path == 'nnnmmm'
s = e.src_builder()
assert s is None, s
def test_SourceSignatures(type):
"""Test the SourceSignatures() method"""
import SCons.Errors
env = type.TestEnvironment(M = 'MD5', T = 'timestamp')
exc_caught = None
try:
env.SourceSignatures('invalid_type')
except SCons.Errors.UserError:
exc_caught = 1
assert exc_caught, "did not catch expected UserError"
env.SourceSignatures('MD5')
assert env.src_sig_type == 'MD5', env.src_sig_type
env.SourceSignatures('$M')
assert env.src_sig_type == 'MD5', env.src_sig_type
env.SourceSignatures('timestamp')
assert env.src_sig_type == 'timestamp', env.src_sig_type
env.SourceSignatures('$T')
assert env.src_sig_type == 'timestamp', env.src_sig_type
try:
import SCons.Util
save_md5 = SCons.Util.md5
SCons.Util.md5 = None
try:
env.SourceSignatures('MD5')
except SCons.Errors.UserError:
pass
else:
self.fail('Did not catch expected UserError')
finally:
SCons.Util.md5 = save_md5
def test_Split(self):
"""Test the Split() method"""
env = self.TestEnvironment(FOO='fff', BAR='bbb')
s = env.Split("foo bar")
assert s == ["foo", "bar"], s
s = env.Split("$FOO bar")
assert s == ["fff", "bar"], s
s = env.Split(["foo", "bar"])
assert s == ["foo", "bar"], s
s = env.Split(["foo", "${BAR}-bbb"])
assert s == ["foo", "bbb-bbb"], s
s = env.Split("foo")
assert s == ["foo"], s
s = env.Split("$FOO$BAR")
assert s == ["fffbbb"], s
def test_TargetSignatures(type):
"""Test the TargetSignatures() method"""
import SCons.Errors
env = type.TestEnvironment(B = 'build', C = 'content')
exc_caught = None
try:
env.TargetSignatures('invalid_type')
except SCons.Errors.UserError:
exc_caught = 1
assert exc_caught, "did not catch expected UserError"
assert not hasattr(env, '_build_signature')
env.TargetSignatures('build')
assert env.tgt_sig_type == 'build', env.tgt_sig_type
env.TargetSignatures('$B')
assert env.tgt_sig_type == 'build', env.tgt_sig_type
env.TargetSignatures('content')
assert env.tgt_sig_type == 'content', env.tgt_sig_type
env.TargetSignatures('$C')
assert env.tgt_sig_type == 'content', env.tgt_sig_type
env.TargetSignatures('MD5')
assert env.tgt_sig_type == 'MD5', env.tgt_sig_type
env.TargetSignatures('timestamp')
assert env.tgt_sig_type == 'timestamp', env.tgt_sig_type
try:
import SCons.Util
save_md5 = SCons.Util.md5
SCons.Util.md5 = None
try:
env.TargetSignatures('MD5')
except SCons.Errors.UserError:
pass
else:
self.fail('Did not catch expected UserError')
try:
env.TargetSignatures('content')
except SCons.Errors.UserError:
pass
else:
self.fail('Did not catch expected UserError')
finally:
SCons.Util.md5 = save_md5
def test_Value(self):
"""Test creating a Value() object
"""
env = Environment()
v1 = env.Value('a')
assert v1.value == 'a', v1.value
value2 = 'a'
v2 = env.Value(value2)
assert v2.value == value2, v2.value
assert v2.value is value2, v2.value
assert not v1 is v2
assert v1.value == v2.value
v3 = env.Value('c', 'build-c')
assert v3.value == 'c', v3.value
def test_Environment_global_variable(type):
"""Test setting Environment variable to an Environment.Base subclass"""
class MyEnv(SCons.Environment.Base):
def xxx(self, string):
return self.subst(string)
SCons.Environment.Environment = MyEnv
env = SCons.Environment.Environment(FOO = 'foo')
f = env.subst('$FOO')
assert f == 'foo', f
f = env.xxx('$FOO')
assert f == 'foo', f
def test_bad_keywords(self):
"""Test trying to use reserved keywords in an Environment"""
added = []
env = self.TestEnvironment(TARGETS = 'targets',
SOURCES = 'sources',
SOURCE = 'source',
TARGET = 'target',
CHANGED_SOURCES = 'changed_sources',
CHANGED_TARGETS = 'changed_targets',
UNCHANGED_SOURCES = 'unchanged_sources',
UNCHANGED_TARGETS = 'unchanged_targets',
INIT = 'init')
bad_msg = '%s is not reserved, but got omitted; see Environment.construction_var_name_ok'
added.append('INIT')
for x in self.reserved_variables:
assert x not in env, env[x]
for x in added:
assert x in env, bad_msg % x
env.Append(TARGETS = 'targets',
SOURCES = 'sources',
SOURCE = 'source',
TARGET = 'target',
CHANGED_SOURCES = 'changed_sources',
CHANGED_TARGETS = 'changed_targets',
UNCHANGED_SOURCES = 'unchanged_sources',
UNCHANGED_TARGETS = 'unchanged_targets',
APPEND = 'append')
added.append('APPEND')
for x in self.reserved_variables:
assert x not in env, env[x]
for x in added:
assert x in env, bad_msg % x
env.AppendUnique(TARGETS = 'targets',
SOURCES = 'sources',
SOURCE = 'source',
TARGET = 'target',
CHANGED_SOURCES = 'changed_sources',
CHANGED_TARGETS = 'changed_targets',
UNCHANGED_SOURCES = 'unchanged_sources',
UNCHANGED_TARGETS = 'unchanged_targets',
APPENDUNIQUE = 'appendunique')
added.append('APPENDUNIQUE')
for x in self.reserved_variables:
assert x not in env, env[x]
for x in added:
assert x in env, bad_msg % x
env.Prepend(TARGETS = 'targets',
SOURCES = 'sources',
SOURCE = 'source',
TARGET = 'target',
CHANGED_SOURCES = 'changed_sources',
CHANGED_TARGETS = 'changed_targets',
UNCHANGED_SOURCES = 'unchanged_sources',
UNCHANGED_TARGETS = 'unchanged_targets',
PREPEND = 'prepend')
added.append('PREPEND')
for x in self.reserved_variables:
assert x not in env, env[x]
for x in added:
assert x in env, bad_msg % x
env.Prepend(TARGETS = 'targets',
SOURCES = 'sources',
SOURCE = 'source',
TARGET = 'target',
CHANGED_SOURCES = 'changed_sources',
CHANGED_TARGETS = 'changed_targets',
UNCHANGED_SOURCES = 'unchanged_sources',
UNCHANGED_TARGETS = 'unchanged_targets',
PREPENDUNIQUE = 'prependunique')
added.append('PREPENDUNIQUE')
for x in self.reserved_variables:
assert x not in env, env[x]
for x in added:
assert x in env, bad_msg % x
env.Replace(TARGETS = 'targets',
SOURCES = 'sources',
SOURCE = 'source',
TARGET = 'target',
CHANGED_SOURCES = 'changed_sources',
CHANGED_TARGETS = 'changed_targets',
UNCHANGED_SOURCES = 'unchanged_sources',
UNCHANGED_TARGETS = 'unchanged_targets',
REPLACE = 'replace')
added.append('REPLACE')
for x in self.reserved_variables:
assert x not in env, env[x]
for x in added:
assert x in env, bad_msg % x
copy = env.Clone(TARGETS = 'targets',
SOURCES = 'sources',
SOURCE = 'source',
TARGET = 'target',
CHANGED_SOURCES = 'changed_sources',
CHANGED_TARGETS = 'changed_targets',
UNCHANGED_SOURCES = 'unchanged_sources',
UNCHANGED_TARGETS = 'unchanged_targets',
COPY = 'copy')
for x in self.reserved_variables:
assert x not in copy, env[x]
for x in added + ['COPY']:
assert x in copy, bad_msg % x
over = env.Override({'TARGETS' : 'targets',
'SOURCES' : 'sources',
'SOURCE' : 'source',
'TARGET' : 'target',
'CHANGED_SOURCES' : 'changed_sources',
'CHANGED_TARGETS' : 'changed_targets',
'UNCHANGED_SOURCES' : 'unchanged_sources',
'UNCHANGED_TARGETS' : 'unchanged_targets',
'OVERRIDE' : 'override'})
for x in self.reserved_variables:
assert x not in over, over[x]
for x in added + ['OVERRIDE']:
assert x in over, bad_msg % x
def test_parse_flags(self):
'''Test the Base class parse_flags argument'''
# all we have to show is that it gets to MergeFlags internally
env = Environment(tools=[], parse_flags = '-X')
assert env['CCFLAGS'] == ['-X'], env['CCFLAGS']
env = Environment(tools=[], CCFLAGS=None, parse_flags = '-Y')
assert env['CCFLAGS'] == ['-Y'], env['CCFLAGS']
env = Environment(tools=[], CPPDEFINES = 'FOO', parse_flags = '-std=c99 -X -DBAR')
assert env['CFLAGS'] == ['-std=c99'], env['CFLAGS']
assert env['CCFLAGS'] == ['-X'], env['CCFLAGS']
assert env['CPPDEFINES'] == ['FOO', 'BAR'], env['CPPDEFINES']
def test_clone_parse_flags(self):
'''Test the env.Clone() parse_flags argument'''
# all we have to show is that it gets to MergeFlags internally
env = Environment(tools = [])
env2 = env.Clone(parse_flags = '-X')
assert 'CCFLAGS' not in env
assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS']
env = Environment(tools = [], CCFLAGS=None)
env2 = env.Clone(parse_flags = '-Y')
assert env['CCFLAGS'] is None, env['CCFLAGS']
assert env2['CCFLAGS'] == ['-Y'], env2['CCFLAGS']
env = Environment(tools = [], CPPDEFINES = 'FOO')
env2 = env.Clone(parse_flags = '-std=c99 -X -DBAR')
assert 'CFLAGS' not in env
assert env2['CFLAGS'] == ['-std=c99'], env2['CFLAGS']
assert 'CCFLAGS' not in env
assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS']
assert env['CPPDEFINES'] == 'FOO', env['CPPDEFINES']
assert env2['CPPDEFINES'] == ['FOO','BAR'], env2['CPPDEFINES']
class OverrideEnvironmentTestCase(unittest.TestCase,TestEnvironmentFixture):
def setUp(self):
env = Environment()
env._dict = {'XXX' : 'x', 'YYY' : 'y'}
env2 = OverrideEnvironment(env, {'XXX' : 'x2'})
env3 = OverrideEnvironment(env2, {'XXX' : 'x3', 'YYY' : 'y3', 'ZZZ' : 'z3'})
self.envs = [ env, env2, env3 ]
def checkpath(self, node, expect):
return str(node) == os.path.normpath(expect)
def test___init__(self):
"""Test OverrideEnvironment initialization"""
env, env2, env3 = self.envs
assert env['XXX'] == 'x', env['XXX']
assert env2['XXX'] == 'x2', env2['XXX']
assert env3['XXX'] == 'x3', env3['XXX']
assert env['YYY'] == 'y', env['YYY']
assert env2['YYY'] == 'y', env2['YYY']
assert env3['YYY'] == 'y3', env3['YYY']
def test___delitem__(self):
"""Test deleting variables from an OverrideEnvironment"""
env, env2, env3 = self.envs
del env3['XXX']
assert 'XXX' not in env, "env has XXX?"
assert 'XXX' not in env2, "env2 has XXX?"
assert 'XXX' not in env3, "env3 has XXX?"
del env3['YYY']
assert 'YYY' not in env, "env has YYY?"
assert 'YYY' not in env2, "env2 has YYY?"
assert 'YYY' not in env3, "env3 has YYY?"
del env3['ZZZ']
assert 'ZZZ' not in env, "env has ZZZ?"
assert 'ZZZ' not in env2, "env2 has ZZZ?"
assert 'ZZZ' not in env3, "env3 has ZZZ?"
def test_get(self):
"""Test the OverrideEnvironment get() method"""
env, env2, env3 = self.envs
assert env.get('XXX') == 'x', env.get('XXX')
assert env2.get('XXX') == 'x2', env2.get('XXX')
assert env3.get('XXX') == 'x3', env3.get('XXX')
assert env.get('YYY') == 'y', env.get('YYY')
assert env2.get('YYY') == 'y', env2.get('YYY')
assert env3.get('YYY') == 'y3', env3.get('YYY')
assert env.get('ZZZ') is None, env.get('ZZZ')
assert env2.get('ZZZ') is None, env2.get('ZZZ')
assert env3.get('ZZZ') == 'z3', env3.get('ZZZ')
def test_has_key(self):
"""Test the OverrideEnvironment has_key() method"""
env, env2, env3 = self.envs
assert 'XXX' in env, 'XXX' in env
assert 'XXX' in env2, 'XXX' in env2
assert 'XXX' in env3, 'XXX' in env3
assert 'YYY' in env, 'YYY' in env
assert 'YYY' in env2, 'YYY' in env2
assert 'YYY' in env3, 'YYY' in env3
assert 'ZZZ' not in env, 'ZZZ' in env
assert 'ZZZ' not in env2, 'ZZZ' in env2
assert 'ZZZ' in env3, 'ZZZ' in env3
def test_contains(self):
"""Test the OverrideEnvironment __contains__() method"""
env, env2, env3 = self.envs
assert 'XXX' in env
assert 'XXX' in env2
assert 'XXX' in env3
assert 'YYY' in env
assert 'YYY' in env2
assert 'YYY' in env3
assert not 'ZZZ' in env
assert not 'ZZZ' in env2
assert 'ZZZ' in env3
def test_items(self):
"""Test the OverrideEnvironment Dictionary() method"""
env, env2, env3 = self.envs
items = env.Dictionary()
assert items == {'XXX' : 'x', 'YYY' : 'y'}, items
items = env2.Dictionary()
assert items == {'XXX' : 'x2', 'YYY' : 'y'}, items
items = env3.Dictionary()
assert items == {'XXX' : 'x3', 'YYY' : 'y3', 'ZZZ' : 'z3'}, items
def test_items(self):
"""Test the OverrideEnvironment items() method"""
env, env2, env3 = self.envs
items = sorted(env.items())
assert items == [('XXX', 'x'), ('YYY', 'y')], items
items = sorted(env2.items())
assert items == [('XXX', 'x2'), ('YYY', 'y')], items
items = sorted(env3.items())
assert items == [('XXX', 'x3'), ('YYY', 'y3'), ('ZZZ', 'z3')], items
def test_gvars(self):
"""Test the OverrideEnvironment gvars() method"""
env, env2, env3 = self.envs
gvars = env.gvars()
assert gvars == {'XXX' : 'x', 'YYY' : 'y'}, gvars
gvars = env2.gvars()
assert gvars == {'XXX' : 'x', 'YYY' : 'y'}, gvars
gvars = env3.gvars()
assert gvars == {'XXX' : 'x', 'YYY' : 'y'}, gvars
def test_lvars(self):
"""Test the OverrideEnvironment lvars() method"""
env, env2, env3 = self.envs
lvars = env.lvars()
assert lvars == {}, lvars
lvars = env2.lvars()
assert lvars == {'XXX' : 'x2'}, lvars
lvars = env3.lvars()
assert lvars == {'XXX' : 'x3', 'YYY' : 'y3', 'ZZZ' : 'z3'}, lvars
def test_Replace(self):
"""Test the OverrideEnvironment Replace() method"""
env, env2, env3 = self.envs
assert env['XXX'] == 'x', env['XXX']
assert env2['XXX'] == 'x2', env2['XXX']
assert env3['XXX'] == 'x3', env3['XXX']
assert env['YYY'] == 'y', env['YYY']
assert env2['YYY'] == 'y', env2['YYY']
assert env3['YYY'] == 'y3', env3['YYY']
env.Replace(YYY = 'y4')
assert env['XXX'] == 'x', env['XXX']
assert env2['XXX'] == 'x2', env2['XXX']
assert env3['XXX'] == 'x3', env3['XXX']
assert env['YYY'] == 'y4', env['YYY']
assert env2['YYY'] == 'y4', env2['YYY']
assert env3['YYY'] == 'y3', env3['YYY']
# Tests a number of Base methods through an OverrideEnvironment to
# make sure they handle overridden constructionv variables properly.
#
# The following Base methods also call self.subst(), and so could
# theoretically be subject to problems with evaluating overridden
# variables, but they're never really called that way in the rest
# of our code, so we won't worry about them (at least for now):
#
# ParseConfig()
# ParseDepends()
# Platform()
# Tool()
#
# Action()
# Alias()
# Builder()
# CacheDir()
# Configure()
# Environment()
# FindFile()
# Scanner()
# SourceSignatures()
# TargetSignatures()
# It's unlikely Clone() will ever be called this way, so let the
# other methods test that handling overridden values works.
#def test_Clone(self):
# """Test the OverrideEnvironment Clone() method"""
# pass
def test_FindIxes(self):
"""Test the OverrideEnvironment FindIxes() method"""
env, env2, env3 = self.envs
x = env.FindIxes(['xaaay'], 'XXX', 'YYY')
assert x == 'xaaay', x
x = env2.FindIxes(['x2aaay'], 'XXX', 'YYY')
assert x == 'x2aaay', x
x = env3.FindIxes(['x3aaay3'], 'XXX', 'YYY')
assert x == 'x3aaay3', x
def test_ReplaceIxes(self):
"""Test the OverrideEnvironment ReplaceIxes() method"""
env, env2, env3 = self.envs
x = env.ReplaceIxes('xaaay', 'XXX', 'YYY', 'YYY', 'XXX')
assert x == 'yaaax', x
x = env2.ReplaceIxes('x2aaay', 'XXX', 'YYY', 'YYY', 'XXX')
assert x == 'yaaax2', x
x = env3.ReplaceIxes('x3aaay3', 'XXX', 'YYY', 'YYY', 'XXX')
assert x == 'y3aaax3', x
# It's unlikely WhereIs() will ever be called this way, so let the
# other methods test that handling overridden values works.
#def test_WhereIs(self):
# """Test the OverrideEnvironment WhereIs() method"""
# pass
def test_Dir(self):
"""Test the OverrideEnvironment Dir() method"""
env, env2, env3 = self.envs
x = env.Dir('ddir/$XXX')
assert self.checkpath(x, 'ddir/x'), str(x)
x = env2.Dir('ddir/$XXX')
assert self.checkpath(x, 'ddir/x2'), str(x)
x = env3.Dir('ddir/$XXX')
assert self.checkpath(x, 'ddir/x3'), str(x)
def test_Entry(self):
"""Test the OverrideEnvironment Entry() method"""
env, env2, env3 = self.envs
x = env.Entry('edir/$XXX')
assert self.checkpath(x, 'edir/x'), str(x)
x = env2.Entry('edir/$XXX')
assert self.checkpath(x, 'edir/x2'), str(x)
x = env3.Entry('edir/$XXX')
assert self.checkpath(x, 'edir/x3'), str(x)
def test_File(self):
"""Test the OverrideEnvironment File() method"""
env, env2, env3 = self.envs
x = env.File('fdir/$XXX')
assert self.checkpath(x, 'fdir/x'), str(x)
x = env2.File('fdir/$XXX')
assert self.checkpath(x, 'fdir/x2'), str(x)
x = env3.File('fdir/$XXX')
assert self.checkpath(x, 'fdir/x3'), str(x)
def test_Split(self):
"""Test the OverrideEnvironment Split() method"""
env, env2, env3 = self.envs
env['AAA'] = '$XXX $YYY $ZZZ'
x = env.Split('$AAA')
assert x == ['x', 'y'], x
x = env2.Split('$AAA')
assert x == ['x2', 'y'], x
x = env3.Split('$AAA')
assert x == ['x3', 'y3', 'z3'], x
def test_parse_flags(self):
'''Test the OverrideEnvironment parse_flags argument'''
# all we have to show is that it gets to MergeFlags internally
env = SubstitutionEnvironment()
env2 = env.Override({'parse_flags' : '-X'})
assert 'CCFLAGS' not in env
assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS']
env = SubstitutionEnvironment(CCFLAGS=None)
env2 = env.Override({'parse_flags' : '-Y'})
assert env['CCFLAGS'] is None, env['CCFLAGS']
assert env2['CCFLAGS'] == ['-Y'], env2['CCFLAGS']
env = SubstitutionEnvironment(CPPDEFINES = 'FOO')
env2 = env.Override({'parse_flags' : '-std=c99 -X -DBAR'})
assert 'CFLAGS' not in env
assert env2['CFLAGS'] == ['-std=c99'], env2['CFLAGS']
assert 'CCFLAGS' not in env
assert env2['CCFLAGS'] == ['-X'], env2['CCFLAGS']
assert env['CPPDEFINES'] == 'FOO', env['CPPDEFINES']
assert env2['CPPDEFINES'] == ['FOO','BAR'], env2['CPPDEFINES']
class NoSubstitutionProxyTestCase(unittest.TestCase,TestEnvironmentFixture):
def test___init__(self):
"""Test NoSubstitutionProxy initialization"""
env = self.TestEnvironment(XXX = 'x', YYY = 'y')
assert env['XXX'] == 'x', env['XXX']
assert env['YYY'] == 'y', env['YYY']
proxy = NoSubstitutionProxy(env)
assert proxy['XXX'] == 'x', proxy['XXX']
assert proxy['YYY'] == 'y', proxy['YYY']
def test_attributes(self):
"""Test getting and setting NoSubstitutionProxy attributes"""
env = Environment()
setattr(env, 'env_attr', 'value1')
proxy = NoSubstitutionProxy(env)
setattr(proxy, 'proxy_attr', 'value2')
x = getattr(env, 'env_attr')
assert x == 'value1', x
x = getattr(proxy, 'env_attr')
assert x == 'value1', x
x = getattr(env, 'proxy_attr')
assert x == 'value2', x
x = getattr(proxy, 'proxy_attr')
assert x == 'value2', x
def test_subst(self):
"""Test the NoSubstitutionProxy.subst() method"""
env = self.TestEnvironment(XXX = 'x', YYY = 'y')
assert env['XXX'] == 'x', env['XXX']
assert env['YYY'] == 'y', env['YYY']
proxy = NoSubstitutionProxy(env)
assert proxy['XXX'] == 'x', proxy['XXX']
assert proxy['YYY'] == 'y', proxy['YYY']
x = env.subst('$XXX')
assert x == 'x', x
x = proxy.subst('$XXX')
assert x == '$XXX', x
x = proxy.subst('$YYY', raw=7, target=None, source=None,
conv=None,
extra_meaningless_keyword_argument=None)
assert x == '$YYY', x
def test_subst_kw(self):
"""Test the NoSubstitutionProxy.subst_kw() method"""
env = self.TestEnvironment(XXX = 'x', YYY = 'y')
assert env['XXX'] == 'x', env['XXX']
assert env['YYY'] == 'y', env['YYY']
proxy = NoSubstitutionProxy(env)
assert proxy['XXX'] == 'x', proxy['XXX']
assert proxy['YYY'] == 'y', proxy['YYY']
x = env.subst_kw({'$XXX':'$YYY'})
assert x == {'x':'y'}, x
x = proxy.subst_kw({'$XXX':'$YYY'})
assert x == {'$XXX':'$YYY'}, x
def test_subst_list(self):
"""Test the NoSubstitutionProxy.subst_list() method"""
env = self.TestEnvironment(XXX = 'x', YYY = 'y')
assert env['XXX'] == 'x', env['XXX']
assert env['YYY'] == 'y', env['YYY']
proxy = NoSubstitutionProxy(env)
assert proxy['XXX'] == 'x', proxy['XXX']
assert proxy['YYY'] == 'y', proxy['YYY']
x = env.subst_list('$XXX')
assert x == [['x']], x
x = proxy.subst_list('$XXX')
assert x == [[]], x
x = proxy.subst_list('$YYY', raw=0, target=None, source=None, conv=None)
assert x == [[]], x
def test_subst_target_source(self):
"""Test the NoSubstitutionProxy.subst_target_source() method"""
env = self.TestEnvironment(XXX = 'x', YYY = 'y')
assert env['XXX'] == 'x', env['XXX']
assert env['YYY'] == 'y', env['YYY']
proxy = NoSubstitutionProxy(env)
assert proxy['XXX'] == 'x', proxy['XXX']
assert proxy['YYY'] == 'y', proxy['YYY']
args = ('$XXX $TARGET $SOURCE $YYY',)
kw = {'target' : DummyNode('ttt'), 'source' : DummyNode('sss')}
x = env.subst_target_source(*args, **kw)
assert x == 'x ttt sss y', x
x = proxy.subst_target_source(*args, **kw)
assert x == ' ttt sss ', x
class EnvironmentVariableTestCase(unittest.TestCase):
def test_is_valid_construction_var(self):
"""Testing is_valid_construction_var()"""
r = is_valid_construction_var("_a")
assert r is not None, r
r = is_valid_construction_var("z_")
assert r is not None, r
r = is_valid_construction_var("X_")
assert r is not None, r
r = is_valid_construction_var("2a")
assert r is None, r
r = is_valid_construction_var("a2_")
assert r is not None, r
r = is_valid_construction_var("/")
assert r is None, r
r = is_valid_construction_var("_/")
assert r is None, r
r = is_valid_construction_var("a/")
assert r is None, r
r = is_valid_construction_var(".b")
assert r is None, r
r = is_valid_construction_var("_.b")
assert r is None, r
r = is_valid_construction_var("b1._")
assert r is None, r
r = is_valid_construction_var("-b")
assert r is None, r
r = is_valid_construction_var("_-b")
assert r is None, r
r = is_valid_construction_var("b1-_")
assert r is None, r
if __name__ == "__main__":
suite = unittest.TestSuite()
tclasses = [ SubstitutionTestCase,
BaseTestCase,
OverrideEnvironmentTestCase,
NoSubstitutionProxyTestCase,
EnvironmentVariableTestCase ]
for tclass in tclasses:
names = unittest.getTestCaseNames(tclass, 'test_')
suite.addTests(list(map(tclass, names)))
TestUnit.run(suite)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|