Cygwin fixes: use -fPIC and .dll for shared libraries, 'rm' to remove files. (Chad...
[scons.git] / src / engine / SCons / UtilTests.py
1 #
2 # __COPYRIGHT__
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and associated documentation files (the
6 # "Software"), to deal in the Software without restriction, including
7 # without limitation the rights to use, copy, modify, merge, publish,
8 # distribute, sublicense, and/or sell copies of the Software, and to
9 # permit persons to whom the Software is furnished to do so, subject to
10 # the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included
13 # in all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
16 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
17 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 #
23
24 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
25
26 import os
27 import os.path
28 import re
29 import string
30 import sys
31 import types
32 import unittest
33 import SCons.Node
34 import SCons.Node.FS
35 from SCons.Util import *
36 import TestCmd
37
38
39 class OutBuffer:
40     def __init__(self):
41         self.buffer = ""
42
43     def write(self, str):
44         self.buffer = self.buffer + str
45
46 class DummyEnv:
47     def __init__(self, dict={}):
48         self.dict = dict
49
50     def Dictionary(self, key = None):
51         if not key:
52             return self.dict
53         return self.dict[key]
54
55     def sig_dict(self):
56         dict = self.dict.copy()
57         dict["TARGETS"] = 'tsig'
58         dict["SOURCES"] = 'ssig'
59         return dict
60
61 def CmdGen1(target, source, env):
62     # Nifty trick...since Environment references are interpolated,
63     # instantiate an instance of a callable class with this one,
64     # which will then get evaluated.
65     assert target == 't', target
66     assert source == 's', source
67     return "${CMDGEN2('foo')}"
68
69 class CmdGen2:
70     def __init__(self, mystr):
71         self.mystr = mystr
72
73     def __call__(self, target, source, env):
74         assert target == 't', target
75         assert source == 's', source
76         return [ self.mystr, env.Dictionary('BAR') ]
77
78 class UtilTestCase(unittest.TestCase):
79     def test_subst(self):
80         """Test the subst function"""
81         loc = {}
82         target = [ "./foo/bar.exe",
83                    "/bar/baz.obj",
84                    "../foo/baz.obj" ]
85         source = [ "./foo/blah.cpp",
86                    "/bar/ack.cpp",
87                    "../foo/ack.c" ]
88         loc['xxx'] = None
89         loc['zero'] = 0
90         loc['one'] = 1
91         loc['BAR'] = 'baz'
92
93         loc['CMDGEN1'] = CmdGen1
94         loc['CMDGEN2'] = CmdGen2
95
96         env = DummyEnv(loc)
97
98         if os.sep == '/':
99             def cvt(str):
100                 return str
101         else:
102             def cvt(str):
103                 return string.replace(str, '/', os.sep)
104
105         newcom = scons_subst("test $TARGETS $SOURCES", env,
106                              target=target, source=source)
107         assert newcom == cvt("test foo/bar.exe /bar/baz.obj ../foo/baz.obj foo/blah.cpp /bar/ack.cpp ../foo/ack.c")
108
109         newcom = scons_subst("test ${TARGETS[:]} ${SOURCES[0]}", env,
110                              target=target, source=source)
111         assert newcom == cvt("test foo/bar.exe /bar/baz.obj ../foo/baz.obj foo/blah.cpp")
112
113         newcom = scons_subst("test ${TARGETS[1:]}v", env,
114                              target=target, source=source)
115         assert newcom == cvt("test /bar/baz.obj ../foo/baz.objv")
116
117         newcom = scons_subst("test $TARGET", env,
118                              target=target, source=source)
119         assert newcom == cvt("test foo/bar.exe")
120
121         newcom = scons_subst("test $TARGET$FOO[0]", env,
122                              target=target, source=source)
123         assert newcom == cvt("test foo/bar.exe[0]")
124
125         newcom = scons_subst("test ${TARGET.file}", env,
126                              target=target, source=source)
127         assert newcom == cvt("test bar.exe")
128
129         newcom = scons_subst("test ${TARGET.filebase}", env,
130                              target=target, source=source)
131         assert newcom == cvt("test bar")
132
133         newcom = scons_subst("test ${TARGET.suffix}", env,
134                              target=target, source=source)
135         assert newcom == cvt("test .exe")
136
137         newcom = scons_subst("test ${TARGET.base}", env,
138                              target=target, source=source)
139         assert newcom == cvt("test foo/bar")
140
141         newcom = scons_subst("test ${TARGET.dir}", env,
142                              target=target, source=source)
143         assert newcom == cvt("test foo")
144
145         newcom = scons_subst("test ${TARGET.abspath}", env,
146                              target=target, source=source)
147         assert newcom == cvt("test %s/foo/bar.exe"%SCons.Util.updrive(os.getcwd())), newcom
148
149         newcom = scons_subst("test ${SOURCES.abspath}", env,
150                              target=target, source=source)
151         assert newcom == cvt("test %s/foo/blah.cpp %s %s/foo/ack.c"%(SCons.Util.updrive(os.getcwd()),
152                                                                      SCons.Util.updrive(os.path.abspath(os.path.normpath("/bar/ack.cpp"))),
153                                                                      SCons.Util.updrive(os.path.normpath(os.getcwd()+"/..")))), newcom
154
155         newcom = scons_subst("test ${SOURCE.abspath}", env,
156                              target=target, source=source)
157         assert newcom == cvt("test %s/foo/blah.cpp"%SCons.Util.updrive(os.getcwd())), newcom
158
159         # Note that we don't use the cvt() helper function here,
160         # because we're testing that the .posix attribute does its own
161         # conversion of the path name backslashes to slashes.
162         newcom = scons_subst("test ${TARGET.posix} ${SOURCE.posix}", env,
163                              target=target, source=source)
164         assert newcom == "test foo/bar.exe foo/blah.cpp", newcom
165
166         newcom = scons_subst("test $xxx", env)
167         assert newcom == cvt("test"), newcom
168
169         newcom = scons_subst("test $($xxx$)", env)
170         assert newcom == cvt("test $($)"), newcom
171
172         newcom = scons_subst("test $( $xxx $)", env)
173         assert newcom == cvt("test $( $)"), newcom
174
175         newcom = scons_subst("test $($xxx$)", env, re.compile('\$[()]'))
176         assert newcom == cvt("test"), newcom
177
178         newcom = scons_subst("test $( $xxx $)", env, re.compile('\$[()]'))
179         assert newcom == cvt("test"), newcom
180
181         newcom = scons_subst("test $zero", env)
182         assert newcom == cvt("test 0"), newcom
183
184         newcom = scons_subst("test $one", env)
185         assert newcom == cvt("test 1"), newcom
186
187         newcom = scons_subst("test aXbXcXd", env, re.compile('X'))
188         assert newcom == cvt("test abcd"), newcom
189
190         newcom = scons_subst("test $CMDGEN1 $SOURCES $TARGETS",
191                              env, target='t', source='s')
192         assert newcom == cvt("test foo baz s t"), newcom
193
194         # Test against a former bug in scons_subst_list()
195         glob = { "FOO" : "$BAR",
196                  "BAR" : "BAZ",
197                  "BLAT" : "XYX",
198                  "BARXYX" : "BADNEWS" }
199         newcom = scons_subst("$FOO$BLAT", DummyEnv(glob))
200         assert newcom == "BAZXYX", newcom
201
202         # Test for double-dollar-sign behavior
203         glob = { "FOO" : "BAR",
204                  "BAZ" : "BLAT" }
205         newcom = scons_subst("$$FOO$BAZ", DummyEnv(glob))
206         assert newcom == "$FOOBLAT", newcom
207
208     def test_splitext(self):
209         assert splitext('foo') == ('foo','')
210         assert splitext('foo.bar') == ('foo','.bar')
211         assert splitext(os.path.join('foo.bar', 'blat')) == (os.path.join('foo.bar', 'blat'),'')
212
213     def test_subst_list(self):
214         """Testing the scons_subst_list() method..."""
215
216         class Node:
217             def __init__(self, name):
218                 self.name = name
219             def __str__(self):
220                 return self.name
221             def is_literal(self):
222                 return 1
223         
224         loc = {}
225         target = [ "./foo/bar.exe",
226                    "/bar/baz with spaces.obj",
227                    "../foo/baz.obj" ]
228         source = [ "./foo/blah with spaces.cpp",
229                    "/bar/ack.cpp",
230                    "../foo/ack.c" ]
231         loc['xxx'] = None
232         loc['NEWLINE'] = 'before\nafter'
233
234         loc['DO'] = Node('do something')
235         loc['FOO'] = Node('foo.in')
236         loc['BAR'] = Node('bar with spaces.out')
237         loc['CRAZY'] = Node('crazy\nfile.in')
238
239         loc['CMDGEN1'] = CmdGen1
240         loc['CMDGEN2'] = CmdGen2
241
242         env = DummyEnv(loc)
243
244         if os.sep == '/':
245             def cvt(str):
246                 return str
247         else:
248             def cvt(str):
249                 return string.replace(str, '/', os.sep)
250
251         cmd_list = scons_subst_list("$TARGETS", env,
252                                     target=target,
253                                     source=source)
254         assert cmd_list[0][1] == cvt("/bar/baz with spaces.obj"), cmd_list[0][1]
255
256         cmd_list = scons_subst_list("$SOURCES $NEWLINE $TARGETS", env,
257                                     target=target,
258                                     source=source)
259         assert len(cmd_list) == 2, cmd_list
260         assert cmd_list[0][0] == cvt('foo/blah with spaces.cpp'), cmd_list[0][0]
261         assert cmd_list[1][2] == cvt("/bar/baz with spaces.obj"), cmd_list[1]
262
263         cmd_list = scons_subst_list("$SOURCES$NEWLINE", env,
264                                     target=target,
265                                     source=source)
266         assert len(cmd_list) == 2, cmd_list
267         assert cmd_list[1][0] == 'after', cmd_list[1][0]
268         assert cmd_list[0][2] == cvt('../foo/ack.cbefore'), cmd_list[0][2]
269
270         cmd_list = scons_subst_list("$DO --in=$FOO --out=$BAR", env)
271         assert len(cmd_list) == 1, cmd_list
272         assert len(cmd_list[0]) == 3, cmd_list
273         assert cmd_list[0][0] == 'do something', cmd_list[0][0]
274         assert cmd_list[0][1] == '--in=foo.in', cmd_list[0][1]
275         assert cmd_list[0][2] == '--out=bar with spaces.out', cmd_list[0][2]
276
277         # This test is now fixed, and works like it should.
278         cmd_list = scons_subst_list("$DO --in=$CRAZY --out=$BAR", env)
279         assert len(cmd_list) == 1, map(str, cmd_list[0])
280         assert len(cmd_list[0]) == 3, cmd_list
281         assert cmd_list[0][0] == 'do something', cmd_list[0][0]
282         assert cmd_list[0][1] == '--in=crazy\nfile.in', cmd_list[0][1]
283         assert cmd_list[0][2] == '--out=bar with spaces.out', cmd_list[0][2]
284         
285         # Test inputting a list to scons_subst_list()
286         cmd_list = scons_subst_list([ "$SOURCES$NEWLINE", "$TARGETS",
287                                         "This is a test" ],
288                                     env,
289                                     target=target,
290                                     source=source)
291         assert len(cmd_list) == 2, len(cmd_list)
292         assert cmd_list[0][0] == cvt('foo/blah with spaces.cpp'), cmd_list[0][0]
293         assert cmd_list[1][0] == cvt("after"), cmd_list[1]
294         assert cmd_list[1][4] == "This is a test", cmd_list[1]
295
296         # Test interpolating a callable.
297         cmd_list = scons_subst_list("testing $CMDGEN1 $TARGETS $SOURCES", env,
298                                     target='t', source='s')
299         assert len(cmd_list) == 1, len(cmd_list)
300         assert cmd_list[0][0] == 'testing', cmd_list[0][0]
301         assert cmd_list[0][1] == 'foo', cmd_list[0][1]
302         assert cmd_list[0][2] == 'bar with spaces.out', cmd_list[0][2]
303         assert cmd_list[0][3] == 't', cmd_list[0][3]
304         assert cmd_list[0][4] == 's', cmd_list[0][4]
305
306
307         # Test against a former bug in scons_subst_list()
308         glob = { "FOO" : "$BAR",
309                  "BAR" : "BAZ",
310                  "BLAT" : "XYX",
311                  "BARXYX" : "BADNEWS" }
312         cmd_list = scons_subst_list("$FOO$BLAT", DummyEnv(glob))
313         assert cmd_list[0][0] == "BAZXYX", cmd_list[0][0]
314
315         # Test for double-dollar-sign behavior
316         glob = { "FOO" : "BAR",
317                  "BAZ" : "BLAT" }
318         cmd_list = scons_subst_list("$$FOO$BAZ", DummyEnv(glob))
319         assert cmd_list[0][0] == "$FOOBLAT", cmd_list[0][0]
320
321         # Now test escape functionality
322         def escape_func(foo):
323             return '**' + foo + '**'
324         def quote_func(foo):
325             return foo
326         glob = { "FOO" : PathList([ 'foo\nwith\nnewlines',
327                                     'bar\nwith\nnewlines' ]) }
328         cmd_list = scons_subst_list("$FOO", DummyEnv(glob))
329         assert cmd_list[0][0] == 'foo\nwith\nnewlines', cmd_list[0][0]
330         cmd_list[0][0].escape(escape_func)
331         assert cmd_list[0][0] == '**foo\nwith\nnewlines**', cmd_list[0][0]
332         assert cmd_list[0][1] == 'bar\nwith\nnewlines', cmd_list[0][0]
333         cmd_list[0][1].escape(escape_func)
334         assert cmd_list[0][1] == '**bar\nwith\nnewlines**', cmd_list[0][0]
335
336     def test_quote_spaces(self):
337         """Testing the quote_spaces() method..."""
338         q = quote_spaces('x')
339         assert q == 'x', q
340
341         q = quote_spaces('x x')
342         assert q == '"x x"', q
343
344         q = quote_spaces('x\tx')
345         assert q == '"x\tx"', q
346
347     def test_render_tree(self):
348         class Node:
349             def __init__(self, name, children=[]):
350                 self.children = children
351                 self.name = name
352             def __str__(self):
353                 return self.name
354
355         def get_children(node):
356             return node.children
357
358         windows_h = Node("windows.h")
359         stdlib_h = Node("stdlib.h")
360         stdio_h = Node("stdio.h")
361         bar_c = Node("bar.c", [stdlib_h, windows_h])
362         bar_o = Node("bar.o", [bar_c])
363         foo_c = Node("foo.c", [stdio_h])
364         foo_o = Node("foo.o", [foo_c])
365         foo = Node("foo", [foo_o, bar_o])
366
367         expect = """\
368 +-foo
369   +-foo.o
370   | +-foo.c
371   |   +-stdio.h
372   +-bar.o
373     +-bar.c
374       +-stdlib.h
375       +-windows.h
376 """
377
378         actual = render_tree(foo, get_children)
379         assert expect == actual, (expect, actual)
380         
381         bar_h = Node('bar.h', [stdlib_h])
382         blat_h = Node('blat.h', [stdlib_h])
383         blat_c = Node('blat.c', [blat_h, bar_h])
384         blat_o = Node('blat.o', [blat_c])
385
386         expect = """\
387 +-blat.o
388   +-blat.c
389     +-blat.h
390     | +-stdlib.h
391     +-bar.h
392 """
393
394         actual = render_tree(blat_o, get_children, 1)
395         assert expect == actual, (expect, actual)        
396
397     def test_is_Dict(self):
398         assert is_Dict({})
399         import UserDict
400         assert is_Dict(UserDict.UserDict())
401         assert not is_Dict([])
402         assert not is_Dict("")
403         if hasattr(types, 'UnicodeType'):
404             exec "assert not is_Dict(u'')"
405
406     def test_is_List(self):
407         assert is_List([])
408         import UserList
409         assert is_List(UserList.UserList())
410         assert not is_List({})
411         assert not is_List("")
412         if hasattr(types, 'UnicodeType'):
413             exec "assert not is_List(u'')"
414
415     def test_Split(self):
416         assert Split("foo bar") == ["foo", "bar"]
417         assert Split(["foo", "bar"]) == ["foo", "bar"]
418         assert Split("foo") == ["foo"]
419
420     def test_is_String(self):
421         assert is_String("")
422         if hasattr(types, 'UnicodeType'):
423             exec "assert is_String(u'')"
424         try:
425             import UserString
426         except:
427             pass
428         else:
429             assert is_String(UserString.UserString(''))
430         assert not is_String({})
431         assert not is_String([])
432
433     def test_to_String(self):
434         """Test the to_String() method."""
435         assert to_String(1) == "1", to_String(1)
436         assert to_String([ 1, 2, 3]) == str([1, 2, 3]), to_String([1,2,3])
437         assert to_String("foo") == "foo", to_String("foo")
438
439         try:
440             import UserString
441
442             s1=UserString.UserString('blah')
443             assert to_String(s1) == s1, s1
444             assert to_String(s1) == 'blah', s1
445
446             class Derived(UserString.UserString):
447                 pass
448             s2 = Derived('foo')
449             assert to_String(s2) == s2, s2
450             assert to_String(s2) == 'foo', s2
451
452             if hasattr(types, 'UnicodeType'):
453                 s3=UserString.UserString(unicode('bar'))
454                 assert to_String(s3) == s3, s3
455                 assert to_String(s3) == unicode('bar'), s3
456                 assert type(to_String(s3)) is types.UnicodeType, \
457                        type(to_String(s3))
458         except ImportError:
459             pass
460
461         if hasattr(types, 'UnicodeType'):
462             s4 = unicode('baz')
463             assert to_String(s4) == unicode('baz'), to_String(s4)
464             assert type(to_String(s4)) is types.UnicodeType, \
465                    type(to_String(s4))
466
467     def test_WhereIs(self):
468         test = TestCmd.TestCmd(workdir = '')
469
470         sub1_xxx_exe = test.workpath('sub1', 'xxx.exe')
471         sub2_xxx_exe = test.workpath('sub2', 'xxx.exe')
472         sub3_xxx_exe = test.workpath('sub3', 'xxx.exe')
473         sub4_xxx_exe = test.workpath('sub4', 'xxx.exe')
474
475         test.subdir('subdir', 'sub1', 'sub2', 'sub3', 'sub4')
476
477         if sys.platform != 'win32':
478             test.write(sub1_xxx_exe, "\n")
479
480         os.mkdir(sub2_xxx_exe)
481
482         test.write(sub3_xxx_exe, "\n")
483         os.chmod(sub3_xxx_exe, 0777)
484
485         test.write(sub4_xxx_exe, "\n")
486         os.chmod(sub4_xxx_exe, 0777)
487
488         env_path = os.environ['PATH']
489
490         pathdirs_1234 = [ test.workpath('sub1'),
491                           test.workpath('sub2'),
492                           test.workpath('sub3'),
493                           test.workpath('sub4'),
494                         ] + string.split(env_path, os.pathsep)
495
496         pathdirs_1243 = [ test.workpath('sub1'),
497                           test.workpath('sub2'),
498                           test.workpath('sub4'),
499                           test.workpath('sub3'),
500                         ] + string.split(env_path, os.pathsep)
501
502         os.environ['PATH'] = string.join(pathdirs_1234, os.pathsep)
503         wi = WhereIs('xxx.exe')
504         assert wi == test.workpath(sub3_xxx_exe), wi
505         wi = WhereIs('xxx.exe', pathdirs_1243)
506         assert wi == test.workpath(sub4_xxx_exe), wi
507         wi = WhereIs('xxx.exe', string.join(pathdirs_1243, os.pathsep))
508         assert wi == test.workpath(sub4_xxx_exe), wi
509
510         os.environ['PATH'] = string.join(pathdirs_1243, os.pathsep)
511         wi = WhereIs('xxx.exe')
512         assert wi == test.workpath(sub4_xxx_exe), wi
513         wi = WhereIs('xxx.exe', pathdirs_1234)
514         assert wi == test.workpath(sub3_xxx_exe), wi
515         wi = WhereIs('xxx.exe', string.join(pathdirs_1234, os.pathsep))
516         assert wi == test.workpath(sub3_xxx_exe), wi
517
518         if sys.platform == 'win32':
519             wi = WhereIs('xxx', pathext = '')
520             assert wi is None, wi
521
522             wi = WhereIs('xxx', pathext = '.exe')
523             assert wi == test.workpath(sub4_xxx_exe), wi
524
525             wi = WhereIs('xxx', path = pathdirs_1234, pathext = '.BAT;.EXE')
526             assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi
527
528             # Test that we return a normalized path even when
529             # the path contains forward slashes.
530             forward_slash = test.workpath('') + '/sub3'
531             wi = WhereIs('xxx', path = forward_slash, pathext = '.EXE')
532             assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi
533
534     def test_get_env_var(self):
535         """Testing get_environment_var()."""
536         assert get_environment_var("$FOO") == "FOO", get_environment_var("$FOO")
537         assert get_environment_var("${BAR}") == "BAR", get_environment_var("${BAR}")
538         assert get_environment_var("$FOO_BAR1234") == "FOO_BAR1234", get_environment_var("$FOO_BAR1234")
539         assert get_environment_var("${BAR_FOO1234}") == "BAR_FOO1234", get_environment_var("${BAR_FOO1234}")
540         assert get_environment_var("${BAR}FOO") == None, get_environment_var("${BAR}FOO")
541         assert get_environment_var("$BAR ") == None, get_environment_var("$BAR ")
542         assert get_environment_var("FOO$BAR") == None, get_environment_var("FOO$BAR")
543         assert get_environment_var("$FOO[0]") == None, get_environment_var("$FOO[0]")
544         assert get_environment_var("${some('complex expression')}") == None, get_environment_var("${some('complex expression')}")
545
546     def test_Proxy(self):
547         """Test generic Proxy class."""
548         class Subject:
549             def foo(self):
550                 return 1
551             def bar(self):
552                 return 2
553
554         s=Subject()
555         s.baz = 3
556
557         class ProxyTest(Proxy):
558             def bar(self):
559                 return 4
560
561         p=ProxyTest(s)
562
563         assert p.foo() == 1, p.foo()
564         assert p.bar() == 4, p.bar()
565         assert p.baz == 3, p.baz
566
567         p.baz = 5
568         s.baz = 6
569
570         assert p.baz == 5, p.baz
571
572     def test_Literal(self):
573         """Test the Literal() function."""
574         cmd_list = [ '$FOO', Literal('$BAR') ]
575         cmd_list = scons_subst_list(cmd_list,
576                                     DummyEnv({ 'FOO' : 'BAZ',
577                                                'BAR' : 'BLAT' }))
578         def escape_func(cmd):
579             return '**' + cmd + '**'
580
581         map(lambda x, e=escape_func: x.escape(e), cmd_list[0])
582         cmd_list = map(str, cmd_list[0])
583         assert cmd_list[0] == 'BAZ', cmd_list[0]
584         assert cmd_list[1] == '**$BAR**', cmd_list[1]
585
586     def test_mapPaths(self):
587         """Test the mapPaths function"""
588         fs = SCons.Node.FS.FS()
589         dir=fs.Dir('foo')
590         file=fs.File('bar/file')
591         
592         class DummyEnv:
593             def subst(self, arg):
594                 return 'bar'
595
596         res = mapPaths([ file, 'baz', 'blat/boo', '#test' ], dir)
597         assert res[0] == file, res[0]
598         assert res[1] == os.path.join('foo', 'baz'), res[1]
599         assert res[2] == os.path.join('foo', 'blat/boo'), res[2]
600         assert res[3] == '#test', res[3]
601
602         env=DummyEnv()
603         res=mapPaths('bleh', dir, env)
604         assert res[0] == os.path.normpath('foo/bar'), res[1]
605
606     def test_display(self):
607         old_stdout = sys.stdout
608         sys.stdout = OutBuffer()
609         SCons.Util.display("line1")
610         display.set_mode(0)
611         SCons.Util.display("line2")
612         display.set_mode(1)
613         SCons.Util.display("line3")
614
615         assert sys.stdout.buffer == "line1\nline3\n"
616         sys.stdout = old_stdout
617
618     def test_fs_delete(self):
619         test = TestCmd.TestCmd(workdir = '')
620         base = test.workpath('')
621         xxx = test.workpath('xxx.xxx')
622         sub1_yyy = test.workpath('sub1', 'yyy.yyy')
623         test.subdir('sub1')
624         test.write(xxx, "\n")
625         test.write(sub1_yyy, "\n")
626
627         old_stdout = sys.stdout
628         sys.stdout = OutBuffer()
629
630         exp = "Removed " + os.path.join(base, sub1_yyy) + '\n' + \
631               "Removed directory " + os.path.join(base, 'sub1') + '\n' + \
632               "Removed " + os.path.join(base, xxx) + '\n' + \
633               "Removed directory " + base + '\n'
634
635         SCons.Util.fs_delete(base, remove=0)
636         assert sys.stdout.buffer == exp
637         assert os.path.exists(sub1_yyy)
638
639         sys.stdout.buffer = ""
640         SCons.Util.fs_delete(base, remove=1)
641         assert sys.stdout.buffer == exp
642         assert not os.path.exists(base)
643
644         test._dirlist = None
645         sys.stdout = old_stdout
646
647     def test_get_native_path(self):
648         """Test the get_native_path() function."""
649         import tempfile
650         filename = tempfile.mktemp()
651         str = '1234567890 ' + filename
652         open(filename, 'w').write(str)
653         assert open(SCons.Util.get_native_path(filename)).read() == str
654
655     def test_subst_dict(self):
656         """Test substituting dictionary values in an Action
657         """
658         d = subst_dict([], [], DummyEnv({'a' : 'A', 'b' : 'B'}))
659         assert d['a'] == 'A', d
660         assert d['b'] == 'B', d
661
662         d = subst_dict(target = 't', source = 's', env=DummyEnv())
663         assert str(d['TARGETS']) == 't', d['TARGETS']
664         assert str(d['TARGET']) == 't', d['TARGET']
665         assert str(d['SOURCES']) == 's', d['SOURCES']
666         assert str(d['SOURCE']) == 's', d['SOURCE']
667
668         d = subst_dict(target = ['t1', 't2'],
669                        source = ['s1', 's2'],
670                        env = DummyEnv())
671         TARGETS = map(lambda x: str(x), d['TARGETS'])
672         TARGETS.sort()
673         assert TARGETS == ['t1', 't2'], d['TARGETS']
674         assert str(d['TARGET']) == 't1', d['TARGET']
675         SOURCES = map(lambda x: str(x), d['SOURCES'])
676         SOURCES.sort()
677         assert SOURCES == ['s1', 's2'], d['SOURCES']
678         assert str(d['SOURCE']) == 's1', d['SOURCE']
679
680         class N:
681             def __init__(self, name):
682                 self.name = name
683             def __str__(self):
684                 return self.name
685             def rstr(self):
686                 return 'rstr-' + self.name
687
688         d = subst_dict(target = [N('t3'), 't4'],
689                        source = ['s3', N('s4')],
690                        env = DummyEnv())
691         TARGETS = map(lambda x: str(x), d['TARGETS'])
692         TARGETS.sort()
693         assert TARGETS == ['t3', 't4'], d['TARGETS']
694         SOURCES = map(lambda x: str(x), d['SOURCES'])
695         SOURCES.sort()
696         assert SOURCES == ['rstr-s4', 's3'], d['SOURCES']
697
698
699 if __name__ == "__main__":
700     suite = unittest.makeSuite(UtilTestCase, 'test_')
701     if not unittest.TextTestRunner().run(suite).wasSuccessful():
702         sys.exit(1)