summaryrefslogtreecommitdiffstats
path: root/src/engine/SCons/ActionTests.py
blob: 011cc0df88522e44b4e2aea34eec91f2c8a80bec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
#
# __COPYRIGHT__
#
# 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__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

# Define a null function and a null class for use as builder actions.
# Where these are defined in the file seems to affect their byte-code
# contents, so try to minimize changes by defining them here, before we
# even import anything.
def GlobalFunc():
    pass

class GlobalActFunc:
    def __call__(self):
        pass

import os
import re
import StringIO
import string
import sys
import types
import unittest
import UserDict

import SCons.Action
import SCons.Environment
import SCons.Errors

import TestCmd

# Initial setup of the common environment for all tests,
# a temporary working directory containing a
# script for writing arguments to an output file.
#
# We don't do this as a setUp() method because it's
# unnecessary to create a separate directory and script
# for each test, they can just use the one.
test = TestCmd.TestCmd(workdir = '')

test.write('act.py', """\
import os, string, sys
f = open(sys.argv[1], 'w')
f.write("act.py: '" + string.join(sys.argv[2:], "' '") + "'\\n")
try:
    if sys.argv[3]:
        f.write("act.py: '" + os.environ[sys.argv[3]] + "'\\n")
except:
    pass
f.close()
if os.environ.has_key( 'ACTPY_PIPE' ):
    if os.environ.has_key( 'PIPE_STDOUT_FILE' ):
         stdout_msg = open(os.environ['PIPE_STDOUT_FILE'], 'r').read()
    else:
         stdout_msg = "act.py: stdout: executed act.py %s\\n" % string.join(sys.argv[1:])
    sys.stdout.write( stdout_msg )
    if os.environ.has_key( 'PIPE_STDERR_FILE' ):
         stderr_msg = open(os.environ['PIPE_STDERR_FILE'], 'r').read()
    else:
         stderr_msg = "act.py: stderr: executed act.py %s\\n" % string.join(sys.argv[1:])
    sys.stderr.write( stderr_msg )
sys.exit(0)
""")

test.write('exit.py', """\
import sys
sys.exit(int(sys.argv[1]))
""")

act_py = test.workpath('act.py')
exit_py = test.workpath('exit.py')

outfile = test.workpath('outfile')
outfile2 = test.workpath('outfile2')
pipe_file = test.workpath('pipe.out')

scons_env = SCons.Environment.Environment()

# Capture all the stuff the Actions will print,
# so it doesn't clutter the output.
sys.stdout = StringIO.StringIO()

class CmdStringHolder:
    def __init__(self, cmd, literal=None):
        self.data = str(cmd)
        self.literal = literal

    def is_literal(self):
        return self.literal

    def escape(self, escape_func):
        """Escape the string with the supplied function.  The
        function is expected to take an arbitrary string, then
        return it with all special characters escaped and ready
        for passing to the command interpreter.

        After calling this function, the next call to str() will
        return the escaped string.
        """

        if self.is_literal():
            return escape_func(self.data)
        elif ' ' in self.data or '\t' in self.data:
            return '"%s"' % self.data
        else:
            return self.data

class Environment:
    def __init__(self, **kw):
        self.d = {}
        self.d['SHELL'] = scons_env['SHELL']
        self.d['SPAWN'] = scons_env['SPAWN']
        self.d['PSPAWN'] = scons_env['PSPAWN']
        self.d['ESCAPE'] = scons_env['ESCAPE']
        for k, v in kw.items():
            self.d[k] = v
    # Just use the underlying scons_subst*() utility methods.
    def subst(self, strSubst, raw=0, target=[], source=[]):
        return SCons.Subst.scons_subst(strSubst, self, raw, target, source, self.d)
    subst_target_source = subst
    def subst_list(self, strSubst, raw=0, target=[], source=[]):
        return SCons.Subst.scons_subst_list(strSubst, self, raw, target, source, self.d)
    def __getitem__(self, item):
        return self.d[item]
    def __setitem__(self, item, value):
        self.d[item] = value
    def has_key(self, item):
        return self.d.has_key(item)
    def get(self, key, value=None):
        return self.d.get(key, value)
    def items(self):
        return self.d.items()
    def Dictionary(self):
        return self.d
    def Copy(self, **kw):
        res = Environment()
        res.d = SCons.Environment.our_deepcopy(self.d)
        for k, v in kw.items():
            res.d[k] = v
        return res
    def sig_dict(self):
        d = {}
        for k,v in self.items(): d[k] = v
        d['TARGETS'] = ['__t1__', '__t2__', '__t3__', '__t4__', '__t5__', '__t6__']
        d['TARGET'] = d['TARGETS'][0]
        d['SOURCES'] = ['__s1__', '__s2__', '__s3__', '__s4__', '__s5__', '__s6__']
        d['SOURCE'] = d['SOURCES'][0]
        return d

class DummyNode:
    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

if os.name == 'java':
    python = os.path.join(sys.prefix, 'jython')
else:
    python = sys.executable

class ActionTestCase(unittest.TestCase):
    """Test the Action() factory function"""

    def test_FunctionAction(self):
        """Test the Action() factory's creation of FunctionAction objects
        """
        def foo():
            pass
        def bar():
            pass
        a1 = SCons.Action.Action(foo)
        assert isinstance(a1, SCons.Action.FunctionAction), a1
        assert a1.execfunction == foo, a1.execfunction

        a11 = SCons.Action.Action(foo, strfunction=bar)
        assert isinstance(a11, SCons.Action.FunctionAction), a11
        assert a11.execfunction == foo, a11.execfunction
        assert a11.strfunction == bar, a11.strfunction

    def test_CommandAction(self):
        """Test the Action() factory's creation of CommandAction objects
        """
        a1 = SCons.Action.Action("string")
        assert isinstance(a1, SCons.Action.CommandAction), a1
        assert a1.cmd_list == "string", a1.cmd_list

        if hasattr(types, 'UnicodeType'):
            exec "a2 = SCons.Action.Action(u'string')"
            exec "assert isinstance(a2, SCons.Action.CommandAction), a2"

        a3 = SCons.Action.Action(["a3"])
        assert isinstance(a3, SCons.Action.CommandAction), a3
        assert a3.cmd_list == "a3", a3.cmd_list

        a4 = SCons.Action.Action([[ "explicit", "command", "line" ]])
        assert isinstance(a4, SCons.Action.CommandAction), a4
        assert a4.cmd_list == [ "explicit", "command", "line" ], a4.cmd_list

        def foo():
            pass

        a5 = SCons.Action.Action("string", strfunction=foo)
        assert isinstance(a5, SCons.Action.CommandAction), a5
        assert a5.cmd_list == "string", a5.cmd_list
        assert a5.strfunction == foo, a5.strfunction

    def test_ListAction(self):
        """Test the Action() factory's creation of ListAction objects
        """
        a1 = SCons.Action.Action(["x", "y", "z", [ "a", "b", "c"]])
        assert isinstance(a1, SCons.Action.ListAction), a1
        assert isinstance(a1.list[0], SCons.Action.CommandAction), a1.list[0]
        assert a1.list[0].cmd_list == "x", a1.list[0].cmd_list
        assert isinstance(a1.list[1], SCons.Action.CommandAction), a1.list[1]
        assert a1.list[1].cmd_list == "y", a1.list[1].cmd_list
        assert isinstance(a1.list[2], SCons.Action.CommandAction), a1.list[2]
        assert a1.list[2].cmd_list == "z", a1.list[2].cmd_list
        assert isinstance(a1.list[3], SCons.Action.CommandAction), a1.list[3]
        assert a1.list[3].cmd_list == [ "a", "b", "c" ], a1.list[3].cmd_list

        a2 = SCons.Action.Action("x\ny\nz")
        assert isinstance(a2, SCons.Action.ListAction), a2
        assert isinstance(a2.list[0], SCons.Action.CommandAction), a2.list[0]
        assert a2.list[0].cmd_list == "x", a2.list[0].cmd_list
        assert isinstance(a2.list[1], SCons.Action.CommandAction), a2.list[1]
        assert a2.list[1].cmd_list == "y", a2.list[1].cmd_list
        assert isinstance(a2.list[2], SCons.Action.CommandAction), a2.list[2]
        assert a2.list[2].cmd_list == "z", a2.list[2].cmd_list

        def foo():
            pass

        a3 = SCons.Action.Action(["x", foo, "z"])
        assert isinstance(a3, SCons.Action.ListAction), a3
        assert isinstance(a3.list[0], SCons.Action.CommandAction), a3.list[0]
        assert a3.list[0].cmd_list == "x", a3.list[0].cmd_list
        assert isinstance(a3.list[1], SCons.Action.FunctionAction), a3.list[1]
        assert a3.list[1].execfunction == foo, a3.list[1].execfunction
        assert isinstance(a3.list[2], SCons.Action.CommandAction), a3.list[2]
        assert a3.list[2].cmd_list == "z", a3.list[2].cmd_list

        a4 = SCons.Action.Action(["x", "y"], strfunction=foo)
        assert isinstance(a4, SCons.Action.ListAction), a4
        assert isinstance(a4.list[0], SCons.Action.CommandAction), a4.list[0]
        assert a4.list[0].cmd_list == "x", a4.list[0].cmd_list
        assert a4.list[0].strfunction == foo, a4.list[0].strfunction
        assert isinstance(a4.list[1], SCons.Action.CommandAction), a4.list[1]
        assert a4.list[1].cmd_list == "y", a4.list[1].cmd_list
        assert a4.list[1].strfunction == foo, a4.list[1].strfunction

        a5 = SCons.Action.Action("x\ny", strfunction=foo)
        assert isinstance(a5, SCons.Action.ListAction), a5
        assert isinstance(a5.list[0], SCons.Action.CommandAction), a5.list[0]
        assert a5.list[0].cmd_list == "x", a5.list[0].cmd_list
        assert a5.list[0].strfunction == foo, a5.list[0].strfunction
        assert isinstance(a5.list[1], SCons.Action.CommandAction), a5.list[1]
        assert a5.list[1].cmd_list == "y", a5.list[1].cmd_list
        assert a5.list[1].strfunction == foo, a5.list[1].strfunction

    def test_CommandGeneratorAction(self):
        """Test the Action() factory's creation of CommandGeneratorAction objects
        """
        def foo():
            pass
        def bar():
            pass
        a1 = SCons.Action.Action(foo, generator=1)
        assert isinstance(a1, SCons.Action.CommandGeneratorAction), a1
        assert a1.generator is foo, a1.generator

        a2 = SCons.Action.Action(foo, strfunction=bar, generator=1)
        assert isinstance(a2, SCons.Action.CommandGeneratorAction), a2
        assert a2.generator is foo, a2.generator

    def test_LazyCmdGeneratorAction(self):
        """Test the Action() factory's creation of lazy CommandGeneratorAction objects
        """
        def foo():
            pass

        a1 = SCons.Action.Action("$FOO")
        assert isinstance(a1, SCons.Action.LazyAction), a1

        a2 = SCons.Action.Action("$FOO", strfunction=foo)
        assert isinstance(a2, SCons.Action.LazyAction), a2

    def test_no_action(self):
        """Test when the Action() factory can't create an action object
        """
        a5 = SCons.Action.Action(1)
        assert a5 is None, a5

    def test_reentrance(self):
        """Test the Action() factory when the action is already an Action object
        """
        a1 = SCons.Action.Action("foo")
        a2 = SCons.Action.Action(a1)
        assert a2 is a1, a2

class ActionBaseTestCase(unittest.TestCase):
    def test_get_executor(self):
        """Test the ActionBase.get_executor() method"""
        a = SCons.Action.Action('foo')
        x = a.get_executor({}, {}, [], [], {})
        assert not x is None, x
 
class _ActionActionTestCase(unittest.TestCase):

    def test__init__(self):
        """Test creation of _ActionAction objects
        """

        def func1():
            pass

        def func2():
            pass

        a = SCons.Action._ActionAction()
        assert not hasattr(a, 'strfunction')

        assert SCons.Action._ActionAction(kwarg = 1)
        assert not hasattr(a, 'strfunction')
        assert not hasattr(a, 'kwarg')

        a = SCons.Action._ActionAction(strfunction=func1)
        assert a.strfunction is func1, a.strfunction

        a = SCons.Action._ActionAction(presub=func1)
        assert a.presub is func1, a.presub

        a = SCons.Action._ActionAction(chdir=1)
        assert a.chdir is 1, a.chdir

        a = SCons.Action._ActionAction(func1, func2, 'x')
        assert a.strfunction is func1, a.strfunction
        assert a.presub is func2, a.presub
        assert a.chdir is 'x', a.chdir

    def test___cmp__(self):
        """Test Action comparison
        """
        a1 = SCons.Action.Action("x")
        a2 = SCons.Action.Action("x")
        assert a1 == a2
        a3 = SCons.Action.Action("y")
        assert a1 != a3
        assert a2 != a3

    def test_print_cmd_lines(self):
        """Test the print_cmd_lines() method
        """
        save_stdout = sys.stdout

        try:
            def execfunc(target, source, env):
                pass
            a = SCons.Action.Action(execfunc)

            sio = StringIO.StringIO()
            sys.stdout = sio
            a.print_cmd_line("foo bar", None, None, None)
            s = sio.getvalue()
            assert s == "foo bar\n", s

        finally:
            sys.stdout = save_stdout

    def test___call__(self):
        """Test calling an Action
        """
        save_stdout = sys.stdout

        save_print_actions = SCons.Action.print_actions
        save_print_actions_presub = SCons.Action.print_actions_presub
        save_execute_actions = SCons.Action.execute_actions
        #SCons.Action.print_actions = 0

        test = TestCmd.TestCmd(workdir = '')
        test.subdir('sub', 'xyz')
        os.chdir(test.workpath())

        try:
            env = Environment()

            def execfunc(target, source, env):
                assert type(target) is type([]), type(target)
                assert type(source) is type([]), type(source)
                return 7
            a = SCons.Action.Action(execfunc)

            def firstfunc(target, source, env):
                assert type(target) is type([]), type(target)
                assert type(source) is type([]), type(source)
                return 0
            def lastfunc(target, source, env):
                assert type(target) is type([]), type(target)
                assert type(source) is type([]), type(source)
                return 9
            b = SCons.Action.Action([firstfunc, execfunc, lastfunc])
            
            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a("out", "in", env)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'execfunc(["out"], ["in"])\n', s

            a.chdir = 'xyz'
            expect = 'os.chdir(%s)\nexecfunc(["out"], ["in"])\nos.chdir(%s)\n'

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a("out", "in", env)
            assert result == 7, result
            s = sio.getvalue()
            assert s == expect % (repr('xyz'), repr(test.workpath())), s

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a("out", "in", env, chdir='sub')
            assert result == 7, result
            s = sio.getvalue()
            assert s == expect % (repr('sub'), repr(test.workpath())), s

            a.chdir = None

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = b("out", "in", env)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'firstfunc(["out"], ["in"])\nexecfunc(["out"], ["in"])\n', s

            SCons.Action.execute_actions = 0

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a("out", "in", env)
            assert result == 0, result
            s = sio.getvalue()
            assert s == 'execfunc(["out"], ["in"])\n', s

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = b("out", "in", env)
            assert result == 0, result
            s = sio.getvalue()
            assert s == 'firstfunc(["out"], ["in"])\nexecfunc(["out"], ["in"])\nlastfunc(["out"], ["in"])\n', s

            SCons.Action.print_actions_presub = 1
            SCons.Action.execute_actions = 1

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a("out", "in", env)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'execfunc(["out"], ["in"])\n', s

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a("out", "in", env, presub=1)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'Building out with action:\n  execfunc(target, source, env)\nexecfunc(["out"], ["in"])\n', s

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = b(["out"], "in", env, presub=1)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'Building out with action:\n  firstfunc(target, source, env)\nfirstfunc(["out"], ["in"])\nBuilding out with action:\n  execfunc(target, source, env)\nexecfunc(["out"], ["in"])\n', s

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = b(["out", "list"], "in", env, presub=1)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'Building out and list with action:\n  firstfunc(target, source, env)\nfirstfunc(["out", "list"], ["in"])\nBuilding out and list with action:\n  execfunc(target, source, env)\nexecfunc(["out", "list"], ["in"])\n', s

            a2 = SCons.Action.Action(execfunc)

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a2("out", "in", env)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'Building out with action:\n  execfunc(target, source, env)\nexecfunc(["out"], ["in"])\n', s

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a2("out", "in", env, presub=0)
            assert result == 7, result
            s = sio.getvalue()
            assert s == 'execfunc(["out"], ["in"])\n', s

            SCons.Action.execute_actions = 0

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a2("out", "in", env, presub=0)
            assert result == 0, result
            s = sio.getvalue()
            assert s == 'execfunc(["out"], ["in"])\n', s

            sio = StringIO.StringIO()
            sys.stdout = sio
            result = a("out", "in", env, presub=0, execute=1, show=0)
            assert result == 7, result
            s = sio.getvalue()
            assert s == '', s

            sys.stdout = save_stdout
            exitstatfunc_result = []

            def exitstatfunc(stat, result=exitstatfunc_result):
                result.append(stat)
                return stat

            result = a("out", "in", env, exitstatfunc=exitstatfunc)
            assert result == 0, result
            assert exitstatfunc_result == [], exitstatfunc_result

            result = a("out", "in", env, execute=1, exitstatfunc=exitstatfunc)
            assert result == 7, result
            assert exitstatfunc_result == [7], exitstatfunc_result

            SCons.Action.execute_actions = 1

            result = []
            def my_print_cmd_line(s, target, source, env, result=result):
                result.append(s)
            env['PRINT_CMD_LINE_FUNC'] = my_print_cmd_line
            a("output", "input", env)
            assert result == ['execfunc(["output"], ["input"])'], result
            

        finally:
            sys.stdout = save_stdout
            SCons.Action.print_actions = save_print_actions
            SCons.Action.print_actions_presub = save_print_actions_presub
            SCons.Action.execute_actions = save_execute_actions

    def test_presub_lines(self):
        """Test the presub_lines() method
        """
        env = Environment()
        a = SCons.Action.Action("x")
        s = a.presub_lines(env)
        assert s == ['x'], s

        a = SCons.Action.Action(["y", "z"])
        s = a.presub_lines(env)
        assert s == ['y', 'z'], s

        def func():
            pass
        a = SCons.Action.Action(func)
        s = a.presub_lines(env)
        assert s == ["func(target, source, env)"], s

        def gen(target, source, env, for_signature):
            return 'generat' + env.get('GEN', 'or')
        a = SCons.Action.Action(gen, generator=1)
        s = a.presub_lines(env)
        assert s == ["generator"], s
        s = a.presub_lines(Environment(GEN = 'ed'))
        assert s == ["generated"], s

        a = SCons.Action.Action("$ACT")
        s = a.presub_lines(env)
        assert s == [''], s
        s = a.presub_lines(Environment(ACT = 'expanded action'))
        assert s == ['expanded action'], s

    def test_add(self):
        """Test adding Actions to stuff."""
        # Adding actions to other Actions or to stuff that can
        # be converted into an Action should produce a ListAction
        # containing all the Actions.
        def bar():
            return None
        baz = SCons.Action.Action(bar, generator=1)
        act1 = SCons.Action.Action('foo bar')
        act2 = SCons.Action.Action([ 'foo', bar ])

        sum = act1 + act2
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 3, len(sum.list)
        assert map(lambda x: isinstance(x, SCons.Action.ActionBase),
                   sum.list) == [ 1, 1, 1 ]

        sum = act1 + act1
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 2, len(sum.list)

        sum = act2 + act2
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 4, len(sum.list)

        # Should also be able to add command generators to each other
        # or to actions
        sum = baz + baz
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 2, len(sum.list)

        sum = baz + act1
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 2, len(sum.list)

        sum = act2 + baz
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 3, len(sum.list)

        # Also should be able to add Actions to anything that can
        # be converted into an action.
        sum = act1 + bar
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 2, len(sum.list)
        assert isinstance(sum.list[1], SCons.Action.FunctionAction)

        sum = 'foo bar' + act2
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 3, len(sum.list)
        assert isinstance(sum.list[0], SCons.Action.CommandAction)

        sum = [ 'foo', 'bar' ] + act1
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 3, sum.list
        assert isinstance(sum.list[0], SCons.Action.CommandAction)
        assert isinstance(sum.list[1], SCons.Action.CommandAction)

        sum = act2 + [ baz, bar ]
        assert isinstance(sum, SCons.Action.ListAction), str(sum)
        assert len(sum.list) == 4, len(sum.list)
        assert isinstance(sum.list[2], SCons.Action.CommandGeneratorAction)
        assert isinstance(sum.list[3], SCons.Action.FunctionAction)

        try:
            sum = act2 + 1
        except TypeError:
            pass
        else:
            assert 0, "Should have thrown a TypeError adding to an int."

        try:
            sum = 1 + act2
        except TypeError:
            pass
        else:
            assert 0, "Should have thrown a TypeError adding to an int."

class CommandActionTestCase(unittest.TestCase):

    def test___init__(self):
        """Test creation of a command Action
        """
        a = SCons.Action.CommandAction(["xyzzy"])
        assert a.cmd_list == [ "xyzzy" ], a.cmd_list
        assert a.cmdstr is None, a.cmdstr

        a = SCons.Action.CommandAction(["abra"], "cadabra")
        assert a.cmd_list == [ "abra" ], a.cmd_list
        assert a.cmdstr == "cadabra", a.cmdstr

    def test___str__(self):
        """Test fetching the pre-substitution string for command Actions
        """
        env = Environment()
        act = SCons.Action.CommandAction('xyzzy $TARGET $SOURCE')
        s = str(act)
        assert s == 'xyzzy $TARGET $SOURCE', s

        act = SCons.Action.CommandAction(['xyzzy',
                                          '$TARGET', '$SOURCE',
                                          '$TARGETS', '$SOURCES'])
        s = str(act)
        assert s == "xyzzy $TARGET $SOURCE $TARGETS $SOURCES", s

    def test_genstring(self):
        """Test the genstring() method for command Actions
        """

        env = Environment()
        t1 = DummyNode('t1')
        t2 = DummyNode('t2')
        s1 = DummyNode('s1')
        s2 = DummyNode('s2')
        act = SCons.Action.CommandAction('xyzzy $TARGET $SOURCE')
        expect = 'xyzzy $TARGET $SOURCE'
        s = act.genstring([], [], env)
        assert s == expect, s
        s = act.genstring([t1], [s1], env)
        assert s == expect, s
        s = act.genstring([t1, t2], [s1, s2], env)
        assert s == expect, s

        act = SCons.Action.CommandAction('xyzzy $TARGETS $SOURCES')
        expect = 'xyzzy $TARGETS $SOURCES'
        s = act.genstring([], [], env)
        assert s == expect, s
        s = act.genstring([t1], [s1], env)
        assert s == expect, s
        s = act.genstring([t1, t2], [s1, s2], env)
        assert s == expect, s

        act = SCons.Action.CommandAction(['xyzzy',
                                          '$TARGET', '$SOURCE',
                                          '$TARGETS', '$SOURCES'])
        expect = "xyzzy $TARGET $SOURCE $TARGETS $SOURCES"
        s = act.genstring([], [], env)
        assert s == expect, s
        s = act.genstring([t1], [s1], env)
        assert s == expect, s
        s = act.genstring([t1, t2], [s1, s2], env)
        assert s == expect, s

    def test_strfunction(self):
        """Test fetching the string representation of command Actions
        """

        env = Environment()
        t1 = DummyNode('t1')
        t2 = DummyNode('t2')
        s1 = DummyNode('s1')
        s2 = DummyNode('s2')
        act = SCons.Action.CommandAction('xyzzy $TARGET $SOURCE')
        s = act.strfunction([], [], env)
        assert s == 'xyzzy', s
        s = act.strfunction([t1], [s1], env)
        assert s == 'xyzzy t1 s1', s
        s = act.strfunction([t1, t2], [s1, s2], env)
        assert s == 'xyzzy t1 s1', s

        act = SCons.Action.CommandAction('xyzzy $TARGET $SOURCE',
                                         'cmdstr - $SOURCE - $TARGET -')
        s = act.strfunction([], [], env)
        assert s == 'cmdstr - - -', s
        s = act.strfunction([t1], [s1], env)
        assert s == 'cmdstr - s1 - t1 -', s
        s = act.strfunction([t1, t2], [s1, s2], env)
        assert s == 'cmdstr - s1 - t1 -', s

        act = SCons.Action.CommandAction('xyzzy $TARGETS $SOURCES')
        s = act.strfunction([], [], env)
        assert s == 'xyzzy', s
        s = act.strfunction([t1], [s1], env)
        assert s == 'xyzzy t1 s1', s
        s = act.strfunction([t1, t2], [s1, s2], env)
        assert s == 'xyzzy t1 t2 s1 s2', s

        act = SCons.Action.CommandAction('xyzzy $TARGETS $SOURCES',
                                         'cmdstr = $SOURCES = $TARGETS =')
        s = act.strfunction([], [], env)
        assert s == 'cmdstr = = =', s
        s = act.strfunction([t1], [s1], env)
        assert s == 'cmdstr = s1 = t1 =', s
        s = act.strfunction([t1, t2], [s1, s2], env)
        assert s == 'cmdstr = s1 s2 = t1 t2 =', s

        act = SCons.Action.CommandAction(['xyzzy',
                                          '$TARGET', '$SOURCE',
                                          '$TARGETS', '$SOURCES'])
        s = act.strfunction([], [], env)
        assert s == 'xyzzy', s
        s = act.strfunction([t1], [s1], env)
        assert s == 'xyzzy t1 s1 t1 s1', s
        s = act.strfunction([t1, t2], [s1, s2], env)
        assert s == 'xyzzy t1 s1 t1 t2 s1 s2', s

        def sf(target, source, env):
            return "sf was called"
        act = SCons.Action.CommandAction('foo', strfunction=sf)
        s = act.strfunction([], [], env)
        assert s == "sf was called", s

        class actclass1:
            def __init__(self, targets, sources, env):
                pass
            def __call__(self):
                return 1
        class actclass2:
            def __init__(self, targets, sources, env):
                self.strfunction = 5
            def __call__(self):
                return 2
        class actclass3:
            def __init__(self, targets, sources, env):
                pass
            def __call__(self):
                return 3
            def strfunction(self, targets, sources, env):
                return 'actclass3 on %s to get %s'%(str(sources[0]),
                                                    str(targets[0]))
        class actclass4:
            def __init__(self, targets, sources, env):
                pass
            def __call__(self):
                return 4
            strfunction = None

        act1 = SCons.Action.Action(actclass1([t1], [s1], env))
        s = act1.strfunction([t1], [s1], env)
        assert s == 'actclass1(["t1"], ["s1"])', s

        act2 = SCons.Action.Action(actclass2([t1], [s1], env))
        s = act2.strfunction([t1], [s1], env)
        assert s == 'actclass2(["t1"], ["s1"])', s

        act3 = SCons.Action.Action(actclass3([t1], [s1], env))
        s = act3.strfunction([t1], [s1], env)
        assert s == 'actclass3 on s1 to get t1', s

        act4 = SCons.Action.Action(actclass4([t1], [s1], env))
        s = act4.strfunction([t1], [s1], env)
        assert s is None, s

        act = SCons.Action.CommandAction("@foo bar")
        s = act.strfunction([], [], env)
        assert s == "", s

        act = SCons.Action.CommandAction("@-foo bar")
        s = act.strfunction([], [], env)
        assert s == "", s

        act = SCons.Action.CommandAction("-@foo bar")
        s = act.strfunction([], [], env)
        assert s == "", s

        act = SCons.Action.CommandAction("-foo bar")
        s = act.strfunction([], [], env)
        assert s == "foo bar", s

        act = SCons.Action.CommandAction("@ foo bar")
        s = act.strfunction([], [], env)
        assert s == "", s

        act = SCons.Action.CommandAction("@- foo bar")
        s = act.strfunction([], [], env)
        assert s == "", s

        act = SCons.Action.CommandAction("-@ foo bar")
        s = act.strfunction([], [], env)
        assert s == "", s

        act = SCons.Action.CommandAction("- foo bar")
        s = act.strfunction([], [], env)
        assert s == "foo bar", s

    def test_execute(self):
        """Test execution of command Actions

        """
        try:
            env = self.env
        except AttributeError:
            env = Environment()

        cmd1 = r'%s %s %s xyzzy' % (python, act_py, outfile)

        act = SCons.Action.CommandAction(cmd1)
        r = act([], [], env.Copy())
        assert r == 0
        c = test.read(outfile, 'r')
        assert c == "act.py: 'xyzzy'\n", c

        cmd2 = r'%s %s %s $TARGET' % (python, act_py, outfile)

        act = SCons.Action.CommandAction(cmd2)
        r = act(DummyNode('foo'), [], env.Copy())
        assert r == 0
        c = test.read(outfile, 'r')
        assert c == "act.py: 'foo'\n", c

        cmd3 = r'%s %s %s ${TARGETS}' % (python, act_py, outfile)

        act = SCons.Action.CommandAction(cmd3)
        r = act(map(DummyNode, ['aaa', 'bbb']), [], env.Copy())
        assert r == 0
        c = test.read(outfile, 'r')
        assert c == "act.py: 'aaa' 'bbb'\n", c

        cmd4 = r'%s %s %s $SOURCES' % (python, act_py, outfile)

        act = SCons.Action.CommandAction(cmd4)
        r = act([], [DummyNode('one'), DummyNode('two')], env.Copy())
        assert r == 0
        c = test.read(outfile, 'r')
        assert c == "act.py: 'one' 'two'\n", c

        cmd4 = r'%s %s %s ${SOURCES[:2]}' % (python, act_py, outfile)

        act = SCons.Action.CommandAction(cmd4)
        sources = [DummyNode('three'), DummyNode('four'), DummyNode('five')]
        env2 = env.Copy()
        r = act([], source = sources, env = env2)
        assert r == 0
        c = test.read(outfile, 'r')
        assert c == "act.py: 'three' 'four'\n", c

        cmd5 = r'%s %s %s $TARGET XYZZY' % (python, act_py, outfile)

        act = SCons.Action.CommandAction(cmd5)
        env5 = Environment()
        if scons_env.has_key('ENV'):
            env5['ENV'] = scons_env['ENV']
            PATH = scons_env['ENV'].get('PATH', '')
        else:
            env5['ENV'] = {}
            PATH = ''

        env5['ENV']['XYZZY'] = 'xyzzy'
        r = act(target = DummyNode('out5'), source = [], env = env5)

        act = SCons.Action.CommandAction(cmd5)
        r = act(target = DummyNode('out5'),
                source = [],
                env = env.Copy(ENV = {'XYZZY' : 'xyzzy5',
                                      'PATH' : PATH}))
        assert r == 0
        c = test.read(outfile, 'r')
        assert c == "act.py: 'out5' 'XYZZY'\nact.py: 'xyzzy5'\n", c

        class Obj:
            def __init__(self, str):
                self._str = str
            def __str__(self):
                return self._str
            def rfile(self):
                return self
            def get_subst_proxy(self):
                return self

        cmd6 = r'%s %s %s ${TARGETS[1]} $TARGET ${SOURCES[:2]}' % (python, act_py, outfile)

        act = SCons.Action.CommandAction(cmd6)
        r = act(target = [Obj('111'), Obj('222')],
                        source = [Obj('333'), Obj('444'), Obj('555')],
                        env = env.Copy())
        assert r == 0
        c = test.read(outfile, 'r')
        assert c == "act.py: '222' '111' '333' '444'\n", c

        if os.name == 'nt':
            # NT treats execs of directories and non-executable files
            # as "file not found" errors
            expect_nonexistent = 1
            expect_nonexecutable = 1
        elif sys.platform == 'cygwin':
            expect_nonexistent = 127
            expect_nonexecutable = 127
        else:
            expect_nonexistent = 127
            expect_nonexecutable = 126

        # Test that a nonexistent command returns 127
        act = SCons.Action.CommandAction(python + "_no_such_command_")
        r = act([], [], env.Copy(out = outfile))
        assert r == expect_nonexistent, "r == %d" % r

        # Test that trying to execute a directory returns 126
        dir, tail = os.path.split(python)
        act = SCons.Action.CommandAction(dir)
        r = act([], [], env.Copy(out = outfile))
        assert r == expect_nonexecutable, "r == %d" % r

        # Test that trying to execute a non-executable file returns 126
        act = SCons.Action.CommandAction(outfile)
        r = act([], [], env.Copy(out = outfile))
        assert r == expect_nonexecutable, "r == %d" % r

        act = SCons.Action.CommandAction('%s %s 1' % (python, exit_py))
        r = act([], [], env)
        assert r == 1, r

        act = SCons.Action.CommandAction('@%s %s 1' % (python, exit_py))
        r = act([], [], env)
        assert r == 1, r

        act = SCons.Action.CommandAction('@-%s %s 1' % (python, exit_py))
        r = act([], [], env)
        assert r == 0, r

        act = SCons.Action.CommandAction('-%s %s 1' % (python, exit_py))
        r = act([], [], env)
        assert r == 0, r

        act = SCons.Action.CommandAction('@ %s %s 1' % (python, exit_py))
        r = act([], [], env)
        assert r == 1, r

        act = SCons.Action.CommandAction('@- %s %s 1' % (python, exit_py))
        r = act([], [], env)
        assert r == 0, r

        act = SCons.Action.CommandAction('- %s %s 1' % (python, exit_py))
        r = act([], [], env)
        assert r == 0, r

    def _DO_NOT_EXECUTE_test_pipe_execute(self):
        """Test capturing piped output from an action

        We used to have PIPE_BUILD support built right into
        Action.execute() for the benefit of the SConf subsystem, but we've
        moved that logic back into SConf itself.  We'll leave this code
        here, just in case we ever want to resurrect this functionality
        in the future, but change the name of the test so it doesn't
        get executed as part of the normal test suite.
        """
        pipe = open( pipe_file, "w" )
        self.env = Environment(ENV = {'ACTPY_PIPE' : '1'}, PIPE_BUILD = 1,
                               PSTDOUT = pipe, PSTDERR = pipe)
        # everything should also work when piping output
        self.test_execute()
        self.env['PSTDOUT'].close()
        pipe_out = test.read( pipe_file )

        act_out = "act.py: stdout: executed act.py"
        act_err = "act.py: stderr: executed act.py"

        # Since we are now using select(), stdout and stderr can be
        # intermixed, so count the lines separately.
        outlines = re.findall(act_out, pipe_out)
        errlines = re.findall(act_err, pipe_out)
        assert len(outlines) == 6, pipe_out + repr(outlines)
        assert len(errlines) == 6, pipe_out + repr(errlines)

        # test redirection operators
        def test_redirect(self, redir, stdout_msg, stderr_msg):
            cmd = r'%s %s %s xyzzy %s' % (python, act_py, outfile, redir)
            # Write the output and error messages to files because Win32
            # can't handle strings that are too big in its external
            # environment (os.spawnve() returns EINVAL, "Invalid
            # argument").
            stdout_file = test.workpath('stdout_msg')
            stderr_file = test.workpath('stderr_msg')
            open(stdout_file, 'w').write(stdout_msg)
            open(stderr_file, 'w').write(stderr_msg)
            pipe = open( pipe_file, "w" )
            act = SCons.Action.CommandAction(cmd)
            env = Environment( ENV = {'ACTPY_PIPE' : '1',
                                      'PIPE_STDOUT_FILE' : stdout_file,
                                      'PIPE_STDERR_FILE' : stderr_file},
                               PIPE_BUILD = 1,
                               PSTDOUT = pipe, PSTDERR = pipe )
            r = act([], [], env)
            pipe.close()
            assert r == 0
            return (test.read(outfile2, 'r'), test.read(pipe_file, 'r'))

        (redirected, pipe_out) = test_redirect(self,'> %s' % outfile2,
                                               act_out, act_err)
        assert redirected == act_out
        assert pipe_out == act_err

        (redirected, pipe_out) = test_redirect(self,'2> %s' % outfile2,
                                               act_out, act_err)
        assert redirected == act_err
        assert pipe_out == act_out

        (redirected, pipe_out) = test_redirect(self,'> %s 2>&1' % outfile2,
                                               act_out, act_err)
        assert (redirected == act_out + act_err or
                redirected == act_err + act_out)
        assert pipe_out == ""

        act_err = "Long Command Output\n"*3000
        # the size of the string should exceed the system's default block size
        act_out = ""
        (redirected, pipe_out) = test_redirect(self,'> %s' % outfile2,
                                               act_out, act_err)
        assert (redirected == act_out)
        assert (pipe_out == act_err)

    def test_set_handler(self):
        """Test setting the command handler...
        """
        class Test:
            def __init__(self):
                self.executed = 0
        t=Test()
        def func(sh, escape, cmd, args, env, test=t):
            test.executed = args
            test.shell = sh
            return 0
        def escape_func(cmd):
            return '**' + cmd + '**'

        class LiteralStr:
            def __init__(self, x):
                self.data = x
            def __str__(self):
                return self.data
            def escape(self, escape_func):
                return escape_func(self.data)
            def is_literal(self):
                return 1

        a = SCons.Action.CommandAction(["xyzzy"])
        e = Environment(SPAWN = func)
        a([], [], e)
        assert t.executed == [ 'xyzzy' ], t.executed

        a = SCons.Action.CommandAction(["xyzzy"])
        e = Environment(SPAWN = func, SHELL = 'fake shell')
        a([], [], e)
        assert t.executed == [ 'xyzzy' ], t.executed
        assert t.shell == 'fake shell', t.shell

        a = SCons.Action.CommandAction([ LiteralStr("xyzzy") ])
        e = Environment(SPAWN = func, ESCAPE = escape_func)
        a([], [], e)
        assert t.executed == [ '**xyzzy**' ], t.executed

    def test_get_contents(self):
        """Test fetching the contents of a command Action
        """
        def CmdGen(target, source, env, for_signature):
            assert for_signature
            return "%s %s" % \
                   (env["foo"], env["bar"])

        # The number 1 is there to make sure all args get converted to strings.
        a = SCons.Action.CommandAction(["|", "$(", "$foo", "|", "$bar",
                                        "$)", "|", "$baz", 1])
        c = a.get_contents(target=[], source=[],
                           env=Environment(foo = 'FFF', bar = 'BBB',
                                           baz = CmdGen))
        assert c == "| | FFF BBB 1", c

        # Make sure that CommandActions use an Environment's
        # subst_target_source() method for substitution.
        class SpecialEnvironment(Environment):
            def subst_target_source(self, strSubst, raw=0, target=[], source=[]):
                return 'subst_target_source: ' + strSubst

        c = a.get_contents(target=DummyNode('ttt'), source = DummyNode('sss'),
                           env=SpecialEnvironment(foo = 'GGG', bar = 'CCC',
                                                  baz = 'ZZZ'))
        assert c == 'subst_target_source: | $( $foo | $bar $) | $baz 1', c

        # We've discussed using the real target and source names in a
        # CommandAction's signature contents.  This would have have the
        # advantage of recompiling when a file's name changes (keeping
        # debug info current), but it would currently break repository
        # logic that will change the file name based on whether the
        # files come from a repository or locally.  If we ever move to
        # that scheme, then all of the '__t1__' and '__s6__' file names
        # in the asserts below would change to 't1' and 's6' and the
        # like.
        t = map(DummyNode, ['t1', 't2', 't3', 't4', 't5', 't6'])
        s = map(DummyNode, ['s1', 's2', 's3', 's4', 's5', 's6'])
        env = Environment()

        a = SCons.Action.CommandAction(["$TARGET"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "t1", c

        a = SCons.Action.CommandAction(["$TARGETS"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "t1 t2 t3 t4 t5 t6", c

        a = SCons.Action.CommandAction(["${TARGETS[2]}"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "t3", c

        a = SCons.Action.CommandAction(["${TARGETS[3:5]}"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "t4 t5", c

        a = SCons.Action.CommandAction(["$SOURCE"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "s1", c

        a = SCons.Action.CommandAction(["$SOURCES"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "s1 s2 s3 s4 s5 s6", c

        a = SCons.Action.CommandAction(["${SOURCES[2]}"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "s3", c

        a = SCons.Action.CommandAction(["${SOURCES[3:5]}"])
        c = a.get_contents(target=t, source=s, env=env)
        assert c == "s4 s5", c

class CommandGeneratorActionTestCase(unittest.TestCase):

    def test___init__(self):
        """Test creation of a command generator Action
        """
        def f(target, source, env):
            pass
        a = SCons.Action.CommandGeneratorAction(f)
        assert a.generator == f

    def test___str__(self):
        """Test the pre-substitution strings for command generator Actions
        """
        def f(target, source, env, for_signature, self=self):
            return "FOO"
        a = SCons.Action.CommandGeneratorAction(f)
        s = str(a)
        assert s == 'FOO', s

    def test_genstring(self):
        """Test the command generator Action genstring() method
        """
        def f(target, source, env, for_signature, self=self):
            dummy = env['dummy']
            self.dummy = dummy
            return "$FOO $TARGET $SOURCE $TARGETS $SOURCES"
        a = SCons.Action.CommandGeneratorAction(f)
        self.dummy = 0
        s = a.genstring([], [], env=Environment(FOO='xyzzy', dummy=1))
        assert self.dummy == 1, self.dummy
        assert s == "$FOO $TARGET $SOURCE $TARGETS $SOURCES", s

    def test_execute(self):
        """Test executing a command generator Action
        """

        def f(target, source, env, for_signature, self=self):
            dummy = env['dummy']
            self.dummy = dummy
            s = env.subst("$FOO")
            assert s == 'foo baz\nbar ack', s
            return "$FOO"
        def func_action(target, source, env, self=self):
            dummy=env['dummy']
            s = env.subst('$foo')
            assert s == 'bar', s
            self.dummy=dummy
        def f2(target, source, env, for_signature, f=func_action):
            return f
        def ch(sh, escape, cmd, args, env, self=self):
            self.cmd.append(cmd)
            self.args.append(args)

        a = SCons.Action.CommandGeneratorAction(f)
        self.dummy = 0
        self.cmd = []
        self.args = []
        a([], [], env=Environment(FOO = 'foo baz\nbar ack',
                                          dummy = 1,
                                          SPAWN = ch))
        assert self.dummy == 1, self.dummy
        assert self.cmd == ['foo', 'bar'], self.cmd
        assert self.args == [[ 'foo', 'baz' ], [ 'bar', 'ack' ]], self.args

        b = SCons.Action.CommandGeneratorAction(f2)
        self.dummy = 0
        b(target=[], source=[], env=Environment(foo =  'bar',
                                                        dummy =  2 ))
        assert self.dummy==2, self.dummy
        del self.dummy

        class DummyFile:
            def __init__(self, t):
                self.t = t
            def rfile(self):
                self.t.rfile_called = 1
                return self
            def get_subst_proxy(self):
                return self
        def f3(target, source, env, for_signature):
            return ''
        c = SCons.Action.CommandGeneratorAction(f3)
        c(target=[], source=DummyFile(self), env=Environment())
        assert self.rfile_called

    def test_get_contents(self):
        """Test fetching the contents of a command generator Action
        """
        def f(target, source, env, for_signature):
            foo = env['foo']
            bar = env['bar']
            assert for_signature, for_signature
            return [["guux", foo, "$(", "$ignore", "$)", bar,
                     '${test("$( foo $bar $)")}' ]]

        def test(mystr):
            assert mystr == "$( foo $bar $)", mystr
            return "test"

        env = Environment(foo = 'FFF', bar =  'BBB',
                          ignore = 'foo', test=test)
        a = SCons.Action.CommandGeneratorAction(f)
        c = a.get_contents(target=[], source=[], env=env)
        assert c == "guux FFF BBB test", c


class FunctionActionTestCase(unittest.TestCase):

    def test___init__(self):
        """Test creation of a function Action
        """
        def func1():
            pass
        def func2():
            pass
        def func3():
            pass
        def func4():
            pass

        a = SCons.Action.FunctionAction(func1)
        assert a.execfunction == func1, a.execfunction
        assert isinstance(a.strfunction, types.MethodType), type(a.strfunction)

        a = SCons.Action.FunctionAction(func2, strfunction=func3)
        assert a.execfunction == func2, a.execfunction
        assert a.strfunction == func3, a.strfunction

    def test___str__(self):
        """Test the __str__() method for function Actions
        """
        def func1():
            pass
        a = SCons.Action.FunctionAction(func1)
        s = str(a)
        assert s == "func1(target, source, env)", s

        class class1:
            def __call__(self):
                pass
        a = SCons.Action.FunctionAction(class1())
        s = str(a)
        assert s == "class1(target, source, env)", s

    def test_execute(self):
        """Test executing a function Action
        """
        self.inc = 0
        def f(target, source, env):
            s = env['s']
            s.inc = s.inc + 1
            s.target = target
            s.source=source
            assert env.subst("$BAR") == 'foo bar', env.subst("$BAR")
            return 0
        a = SCons.Action.FunctionAction(f)
        a(target=1, source=2, env=Environment(BAR = 'foo bar',
                                                      s = self))
        assert self.inc == 1, self.inc
        assert self.source == [2], self.source
        assert self.target == [1], self.target

        global count
        count = 0
        def function1(target, source, env):
            global count
            count = count + 1
            for t in target:
                open(t, 'w').write("function1\n")
            return 1

        act = SCons.Action.FunctionAction(function1)
        r = None
        try:
            r = act(target = [outfile, outfile2], source=[], env=Environment())
        except SCons.Errors.BuildError:
            pass
        assert r == 1
        assert count == 1
        c = test.read(outfile, 'r')
        assert c == "function1\n", c
        c = test.read(outfile2, 'r')
        assert c == "function1\n", c

        class class1a:
            def __init__(self, target, source, env):
                open(env['out'], 'w').write("class1a\n")

        act = SCons.Action.FunctionAction(class1a)
        r = act([], [], Environment(out = outfile))
        assert r.__class__ == class1a
        c = test.read(outfile, 'r')
        assert c == "class1a\n", c

        class class1b:
            def __call__(self, target, source, env):
                open(env['out'], 'w').write("class1b\n")
                return 2

        act = SCons.Action.FunctionAction(class1b())
        r = act([], [], Environment(out = outfile))
        assert r == 2
        c = test.read(outfile, 'r')
        assert c == "class1b\n", c

        def build_it(target, source, env, self=self):
            self.build_it = 1
            return 0
        def string_it(target, source, env, self=self):
            self.string_it = 1
            return None
        act = SCons.Action.FunctionAction(build_it, strfunction=string_it)
        r = act([], [], Environment())
        assert r == 0, r
        assert self.build_it
        assert self.string_it

    def test_get_contents(self):
        """Test fetching the contents of a function Action
        """

        def LocalFunc():
            pass

        matches = [
            "d\000\000S",
            "d\x00\x00S",
        ]

        a = SCons.Action.FunctionAction(GlobalFunc)
        c = a.get_contents(target=[], source=[], env=Environment())
        assert c in matches, repr(c)

        a = SCons.Action.FunctionAction(LocalFunc)
        c = a.get_contents(target=[], source=[], env=Environment())
        assert c in matches, repr(c)

        a = SCons.Action.FunctionAction(GlobalFunc, varlist=['XYZ'])

        matches_foo = map(lambda x: x + "foo", matches)

        c = a.get_contents(target=[], source=[], env=Environment())
        assert c in matches, repr(c)
        c = a.get_contents(target=[], source=[], env=Environment(XYZ = 'foo'))
        assert c in matches_foo, repr(c)

        class Foo:
            def get_contents(self, target, source, env):
                return 'xyzzy'
        a = SCons.Action.FunctionAction(Foo())
        c = a.get_contents(target=[], source=[], env=Environment())
        assert c == 'xyzzy', repr(c)

class ListActionTestCase(unittest.TestCase):

    def test___init__(self):
        """Test creation of a list of subsidiary Actions
        """
        def func():
            pass
        a = SCons.Action.ListAction(["x", func, ["y", "z"]])
        assert isinstance(a.list[0], SCons.Action.CommandAction)
        assert isinstance(a.list[1], SCons.Action.FunctionAction)
        assert isinstance(a.list[2], SCons.Action.ListAction)
        assert a.list[2].list[0].cmd_list == 'y'

    def test___str__(self):
        """Test the __str__() method for a list of subsidiary Actions
        """
        def f(target,source,env):
            pass
        def g(target,source,env):
            pass
        a = SCons.Action.ListAction([f, g, "XXX", f])
        s = str(a)
        assert s == "f(target, source, env)\ng(target, source, env)\nXXX\nf(target, source, env)", s

    def test_genstring(self):
        """Test the genstring() method for a list of subsidiary Actions
        """
        def f(target,source,env):
            pass
        def g(target,source,env,for_signature):
            return 'generated %s %s' % (target[0], source[0])
        g = SCons.Action.Action(g, generator=1)
        a = SCons.Action.ListAction([f, g, "XXX", f])
        s = a.genstring(['foo.x'], ['bar.y'], Environment())
        assert s == "f(target, source, env)\ngenerated foo.x bar.y\nXXX\nf(target, source, env)", s

    def test_execute(self):
        """Test executing a list of subsidiary Actions
        """
        self.inc = 0
        def f(target,source,env):
            s = env['s']
            s.inc = s.inc + 1
        a = SCons.Action.ListAction([f, f, f])
        a([], [], Environment(s = self))
        assert self.inc == 3, self.inc

        cmd2 = r'%s %s %s syzygy' % (python, act_py, outfile)

        def function2(target, source, env):
            open(env['out'], 'a').write("function2\n")
            return 0

        class class2a:
            def __call__(self, target, source, env):
                open(env['out'], 'a').write("class2a\n")
                return 0

        class class2b:
            def __init__(self, target, source, env):
                open(env['out'], 'a').write("class2b\n")
        act = SCons.Action.ListAction([cmd2, function2, class2a(), class2b])
        r = act([], [], Environment(out = outfile))
        assert r.__class__ == class2b
        c = test.read(outfile, 'r')
        assert c == "act.py: 'syzygy'\nfunction2\nclass2a\nclass2b\n", c

    def test_get_contents(self):
        """Test fetching the contents of a list of subsidiary Actions
        """
        self.foo=0
        def gen(target, source, env, for_signature):
            s = env['s']
            s.foo=1
            return "y"
        a = SCons.Action.ListAction(["x",
                                     SCons.Action.Action(gen, generator=1),
                                     "z"])
        c = a.get_contents(target=[], source=[], env=Environment(s = self))
        assert self.foo==1, self.foo
        assert c == "xyz", c

class LazyActionTestCase(unittest.TestCase):
    def test___init__(self):
        """Test creation of a lazy-evaluation Action
        """
        # Environment variable references should create a special type
        # of LazyAction that lazily evaluates the variable for whether
        # it's a string or something else before doing anything.
        a9 = SCons.Action.Action('$FOO')
        assert isinstance(a9, SCons.Action.LazyAction), a9
        assert a9.var == 'FOO', a9.var

        a10 = SCons.Action.Action('${FOO}')
        assert isinstance(a10, SCons.Action.LazyAction), a10
        assert a10.var == 'FOO', a10.var

    def test_genstring(self):
        """Test the lazy-evaluation Action genstring() method
        """
        def f(target, source, env):
            pass
        a = SCons.Action.Action('$BAR')
        env1 = Environment(BAR=f, s=self)
        env2 = Environment(BAR='xxx', s=self)
        s = a.genstring([], [], env=env1)
        assert s == "f(target, source, env)", s
        s = a.genstring([], [], env=env2)
        assert s == 'xxx', s

    def test_execute(self):
        """Test executing a lazy-evaluation Action
        """
        def f(target, source, env):
            s = env['s']
            s.test=1
            return 0
        a = SCons.Action.Action('$BAR')
        a([], [], env=Environment(BAR = f, s = self))
        assert self.test == 1, self.test
        cmd = r'%s %s %s lazy' % (python, act_py, outfile)
        a([], [], env=Environment(BAR = cmd, s = self))
        c = test.read(outfile, 'r')
        assert c == "act.py: 'lazy'\n", c

    def test_get_contents(self):
        """Test fetching the contents of a lazy-evaluation Action
        """
        a = SCons.Action.Action("${FOO}")
        env = Environment(FOO = [["This", "is", "a", "test"]])
        c = a.get_contents(target=[], source=[], env=env)
        assert c == "This is a test", c

class ActionCallerTestCase(unittest.TestCase):
    def test___init__(self):
        """Test creation of an ActionCaller"""
        ac = SCons.Action.ActionCaller(1, [2, 3], {'FOO' : 4, 'BAR' : 5})
        assert ac.parent == 1, ac.parent
        assert ac.args == [2, 3], ac.args
        assert ac.kw == {'FOO' : 4, 'BAR' : 5}, ac.kw

    def test_get_contents(self):
        """Test fetching the contents of an ActionCaller"""
        def strfunc():
            pass

        def LocalFunc():
            pass

        matches = [
            "d\000\000S",
            "d\x00\x00S"
        ]

        af = SCons.Action.ActionFactory(GlobalFunc, strfunc)
        ac = SCons.Action.ActionCaller(af, [], {})
        c = ac.get_contents([], [], Environment())
        assert c in matches, repr(c)

        af = SCons.Action.ActionFactory(LocalFunc, strfunc)
        ac = SCons.Action.ActionCaller(af, [], {})
        c = ac.get_contents([], [], Environment())
        assert c in matches, repr(c)

        matches = [
            'd\000\000S',
            "d\x00\x00S"
        ]

        class LocalActFunc:
            def __call__(self):
                pass

        af = SCons.Action.ActionFactory(GlobalActFunc(), strfunc)
        ac = SCons.Action.ActionCaller(af, [], {})
        c = ac.get_contents([], [], Environment())
        assert c in matches, repr(c)

        af = SCons.Action.ActionFactory(LocalActFunc(), strfunc)
        ac = SCons.Action.ActionCaller(af, [], {})
        c = ac.get_contents([], [], Environment())
        assert c in matches, repr(c)

        matches = [
            "<built-in function str>",
            "<type 'str'>",
        ]

        af = SCons.Action.ActionFactory(str, strfunc)
        ac = SCons.Action.ActionCaller(af, [], {})
        c = ac.get_contents([], [], Environment())
        assert c == "<built-in function str>" or \
               c == "<type 'str'>", repr(c)

    def test___call__(self):
        """Test calling an ActionCaller"""
        actfunc_args = []
        def actfunc(a1, a2, a3, args=actfunc_args):
            args.extend([a1, a2, a3])
        def strfunc(a1, a2, a3):
            pass

        e = Environment(FOO = 2, BAR = 5)

        af = SCons.Action.ActionFactory(actfunc, strfunc)
        ac = SCons.Action.ActionCaller(af, ['$__env__', '$FOO', 3], {})
        ac([], [], e)
        assert actfunc_args[0] is e, actfunc_args
        assert actfunc_args[1] == '2', actfunc_args
        assert actfunc_args[2] == 3, actfunc_args
        del actfunc_args[:]

        ac = SCons.Action.ActionCaller(af, [], {'a3' : '$__env__', 'a2' : '$BAR', 'a1' : 4})
        ac([], [], e)
        assert actfunc_args[0] == 4, actfunc_args
        assert actfunc_args[1] == '5', actfunc_args
        assert actfunc_args[2] is e, actfunc_args
        del actfunc_args[:]

    def test_strfunction(self):
        """Test calling the ActionCaller strfunction() method"""
        strfunc_args = []
        def actfunc(a1, a2, a3):
            pass
        def strfunc(a1, a2, a3, args=strfunc_args):
            args.extend([a1, a2, a3])

        af = SCons.Action.ActionFactory(actfunc, strfunc)
        ac = SCons.Action.ActionCaller(af, [1, '$FOO', 3], {})
        ac.strfunction([], [], Environment(FOO = 2))
        assert strfunc_args == [1, '2', 3], strfunc_args

        del strfunc_args[:]
        ac = SCons.Action.ActionCaller(af, [], {'a3' : 6, 'a2' : '$BAR', 'a1' : 4})
        ac.strfunction([], [], Environment(BAR = 5))
        assert strfunc_args == [4, '5', 6], strfunc_args

class ActionFactoryTestCase(unittest.TestCase):
    def test___init__(self):
        """Test creation of an ActionFactory"""
        def actfunc():
            pass
        def strfunc():
            pass
        ac = SCons.Action.ActionFactory(actfunc, strfunc)
        assert ac.actfunc is actfunc, ac.actfunc
        assert ac.strfunc is strfunc, ac.strfunc

    def test___call__(self):
        """Test calling whatever's returned from an ActionFactory"""
        actfunc_args = []
        strfunc_args = []
        def actfunc(a1, a2, a3, args=actfunc_args):
            args.extend([a1, a2, a3])
        def strfunc(a1, a2, a3, args=strfunc_args):
            args.extend([a1, a2, a3])
        af = SCons.Action.ActionFactory(actfunc, strfunc)
        af(3, 6, 9)([], [], Environment())
        assert actfunc_args == [3, 6, 9], actfunc_args
        assert strfunc_args == [3, 6, 9], strfunc_args


class ActionCompareTestCase(unittest.TestCase):

    def test_1_solo_name(self):
        """Test Lazy Cmd Generator Action get_name alone.

        Basically ensures we can locate the builder, comparing it to
        itself along the way."""
        bar = SCons.Builder.Builder(action = {})
        env = Environment( BUILDERS = {'BAR' : bar} )
        name = bar.get_name(env)
        assert name == 'BAR', name

    def test_2_multi_name(self):
        """Test LazyCmdGenerator Action get_name multi builders.

        Ensure that we can compare builders (and thereby actions) to
        each other safely."""
        foo = SCons.Builder.Builder(action = '$FOO', suffix = '.foo')
        bar = SCons.Builder.Builder(action = {})
        assert foo != bar
        assert foo.action != bar.action
        env = Environment( BUILDERS = {'FOO' : foo,
                                       'BAR' : bar} )
        name = foo.get_name(env)
        assert name == 'FOO', name
        name = bar.get_name(env)
        assert name == 'BAR', name

    def test_3_dict_names(self):
        """Test Action/Suffix dicts with get_name.

        Verifies that Action/Suffix dictionaries work correctly,
        especially two builders that can generate the same suffix,
        where one of the builders has a suffix dictionary with a None
        key."""
        
        foo = SCons.Builder.Builder(action = '$FOO', suffix = '.foo')
        bar = SCons.Builder.Builder(action = {}, suffix={None:'.bar'})
        bar.add_action('.cow', "$MOO")
        dog = SCons.Builder.Builder(suffix = '.bar')
        
        env = Environment( BUILDERS = {'FOO' : foo,
                                       'BAR' : bar,
                                       'DOG' : dog} )
        
        assert foo.get_name(env) == 'FOO', foo.get_name(env)
        assert bar.get_name(env) == 'BAR', bar.get_name(env)
        assert dog.get_name(env) == 'DOG', dog.get_name(env)


if __name__ == "__main__":
    suite = unittest.TestSuite()
    tclasses = [ ActionTestCase,
                 ActionBaseTestCase,
                 _ActionActionTestCase,
                 CommandActionTestCase,
                 CommandGeneratorActionTestCase,
                 FunctionActionTestCase,
                 ListActionTestCase,
                 LazyActionTestCase,
                 ActionCallerTestCase,
                 ActionFactoryTestCase,
                 ActionCompareTestCase ]
    for tclass in tclasses:
        names = unittest.getTestCaseNames(tclass, 'test_')
        suite.addTests(map(tclass, names))
    if not unittest.TextTestRunner().run(suite).wasSuccessful():
        sys.exit(1)