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:
12 # The above copyright notice and this permission notice shall be included
13 # in all copies or substantial portions of the Software.
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.
24 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
35 from SCons.Util import *
44 self.buffer = self.buffer + str
47 def __init__(self, dict={}):
50 def Dictionary(self, key = None):
56 dict = self.dict.copy()
57 dict["TARGETS"] = 'tsig'
58 dict["SOURCES"] = 'ssig'
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')}"
70 def __init__(self, mystr):
73 def __call__(self, target, source, env):
74 assert target == 't', target
75 assert source == 's', source
76 return [ self.mystr, env.Dictionary('BAR') ]
78 class UtilTestCase(unittest.TestCase):
80 """Test the subst function"""
82 target = [ "./foo/bar.exe",
85 source = [ "./foo/blah.cpp",
93 loc['CMDGEN1'] = CmdGen1
94 loc['CMDGEN2'] = CmdGen2
103 return string.replace(str, '/', os.sep)
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")
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")
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")
117 newcom = scons_subst("test $TARGET", env,
118 target=target, source=source)
119 assert newcom == cvt("test foo/bar.exe")
121 newcom = scons_subst("test $TARGET$FOO[0]", env,
122 target=target, source=source)
123 assert newcom == cvt("test foo/bar.exe[0]")
125 newcom = scons_subst("test ${TARGET.file}", env,
126 target=target, source=source)
127 assert newcom == cvt("test bar.exe")
129 newcom = scons_subst("test ${TARGET.filebase}", env,
130 target=target, source=source)
131 assert newcom == cvt("test bar")
133 newcom = scons_subst("test ${TARGET.suffix}", env,
134 target=target, source=source)
135 assert newcom == cvt("test .exe")
137 newcom = scons_subst("test ${TARGET.base}", env,
138 target=target, source=source)
139 assert newcom == cvt("test foo/bar")
141 newcom = scons_subst("test ${TARGET.dir}", env,
142 target=target, source=source)
143 assert newcom == cvt("test foo")
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
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
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
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
166 newcom = scons_subst("test $xxx", env)
167 assert newcom == cvt("test"), newcom
169 newcom = scons_subst("test $($xxx$)", env)
170 assert newcom == cvt("test $($)"), newcom
172 newcom = scons_subst("test $( $xxx $)", env)
173 assert newcom == cvt("test $( $)"), newcom
175 newcom = scons_subst("test $($xxx$)", env, re.compile('\$[()]'))
176 assert newcom == cvt("test"), newcom
178 newcom = scons_subst("test $( $xxx $)", env, re.compile('\$[()]'))
179 assert newcom == cvt("test"), newcom
181 newcom = scons_subst("test $zero", env)
182 assert newcom == cvt("test 0"), newcom
184 newcom = scons_subst("test $one", env)
185 assert newcom == cvt("test 1"), newcom
187 newcom = scons_subst("test aXbXcXd", env, re.compile('X'))
188 assert newcom == cvt("test abcd"), newcom
190 newcom = scons_subst("test $CMDGEN1 $SOURCES $TARGETS",
191 env, target='t', source='s')
192 assert newcom == cvt("test foo baz s t"), newcom
194 # Test against a former bug in scons_subst_list()
195 glob = { "FOO" : "$BAR",
198 "BARXYX" : "BADNEWS" }
199 newcom = scons_subst("$FOO$BLAT", DummyEnv(glob))
200 assert newcom == "BAZXYX", newcom
202 # Test for double-dollar-sign behavior
203 glob = { "FOO" : "BAR",
205 newcom = scons_subst("$$FOO$BAZ", DummyEnv(glob))
206 assert newcom == "$FOOBLAT", newcom
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'),'')
213 def test_subst_list(self):
214 """Testing the scons_subst_list() method..."""
217 def __init__(self, name):
221 def is_literal(self):
225 target = [ "./foo/bar.exe",
226 "/bar/baz with spaces.obj",
228 source = [ "./foo/blah with spaces.cpp",
232 loc['NEWLINE'] = 'before\nafter'
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')
239 loc['CMDGEN1'] = CmdGen1
240 loc['CMDGEN2'] = CmdGen2
249 return string.replace(str, '/', os.sep)
251 cmd_list = scons_subst_list("$TARGETS", env,
254 assert cmd_list[0][1] == cvt("/bar/baz with spaces.obj"), cmd_list[0][1]
256 cmd_list = scons_subst_list("$SOURCES $NEWLINE $TARGETS", env,
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]
263 cmd_list = scons_subst_list("$SOURCES$NEWLINE", env,
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]
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]
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]
285 # Test inputting a list to scons_subst_list()
286 cmd_list = scons_subst_list([ "$SOURCES$NEWLINE", "$TARGETS",
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]
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]
307 # Test against a former bug in scons_subst_list()
308 glob = { "FOO" : "$BAR",
311 "BARXYX" : "BADNEWS" }
312 cmd_list = scons_subst_list("$FOO$BLAT", DummyEnv(glob))
313 assert cmd_list[0][0] == "BAZXYX", cmd_list[0][0]
315 # Test for double-dollar-sign behavior
316 glob = { "FOO" : "BAR",
318 cmd_list = scons_subst_list("$$FOO$BAZ", DummyEnv(glob))
319 assert cmd_list[0][0] == "$FOOBLAT", cmd_list[0][0]
321 # Now test escape functionality
322 def escape_func(foo):
323 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]
336 def test_quote_spaces(self):
337 """Testing the quote_spaces() method..."""
338 q = quote_spaces('x')
341 q = quote_spaces('x x')
342 assert q == '"x x"', q
344 q = quote_spaces('x\tx')
345 assert q == '"x\tx"', q
347 def test_render_tree(self):
349 def __init__(self, name, children=[]):
350 self.children = children
355 def get_children(node):
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])
378 actual = render_tree(foo, get_children)
379 assert expect == actual, (expect, actual)
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])
394 actual = render_tree(blat_o, get_children, 1)
395 assert expect == actual, (expect, actual)
397 def test_is_Dict(self):
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'')"
406 def test_is_List(self):
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'')"
415 def test_Split(self):
416 assert Split("foo bar") == ["foo", "bar"]
417 assert Split(["foo", "bar"]) == ["foo", "bar"]
418 assert Split("foo") == ["foo"]
420 def test_is_String(self):
422 if hasattr(types, 'UnicodeType'):
423 exec "assert is_String(u'')"
429 assert is_String(UserString.UserString(''))
430 assert not is_String({})
431 assert not is_String([])
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")
442 s1=UserString.UserString('blah')
443 assert to_String(s1) == s1, s1
444 assert to_String(s1) == 'blah', s1
446 class Derived(UserString.UserString):
449 assert to_String(s2) == s2, s2
450 assert to_String(s2) == 'foo', s2
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, \
461 if hasattr(types, 'UnicodeType'):
463 assert to_String(s4) == unicode('baz'), to_String(s4)
464 assert type(to_String(s4)) is types.UnicodeType, \
467 def test_WhereIs(self):
468 test = TestCmd.TestCmd(workdir = '')
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')
475 test.subdir('subdir', 'sub1', 'sub2', 'sub3', 'sub4')
477 if sys.platform != 'win32':
478 test.write(sub1_xxx_exe, "\n")
480 os.mkdir(sub2_xxx_exe)
482 test.write(sub3_xxx_exe, "\n")
483 os.chmod(sub3_xxx_exe, 0777)
485 test.write(sub4_xxx_exe, "\n")
486 os.chmod(sub4_xxx_exe, 0777)
488 env_path = os.environ['PATH']
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)
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)
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
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
518 if sys.platform == 'win32':
519 wi = WhereIs('xxx', pathext = '')
520 assert wi is None, wi
522 wi = WhereIs('xxx', pathext = '.exe')
523 assert wi == test.workpath(sub4_xxx_exe), wi
525 wi = WhereIs('xxx', path = pathdirs_1234, pathext = '.BAT;.EXE')
526 assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi
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
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')}")
546 def test_Proxy(self):
547 """Test generic Proxy class."""
557 class ProxyTest(Proxy):
563 assert p.foo() == 1, p.foo()
564 assert p.bar() == 4, p.bar()
565 assert p.baz == 3, p.baz
570 assert p.baz == 5, p.baz
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',
578 def escape_func(cmd):
579 return '**' + cmd + '**'
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]
586 def test_mapPaths(self):
587 """Test the mapPaths function"""
588 fs = SCons.Node.FS.FS()
590 file=fs.File('bar/file')
593 def subst(self, arg):
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]
603 res=mapPaths('bleh', dir, env)
604 assert res[0] == os.path.normpath('foo/bar'), res[1]
606 def test_display(self):
607 old_stdout = sys.stdout
608 sys.stdout = OutBuffer()
609 SCons.Util.display("line1")
611 SCons.Util.display("line2")
613 SCons.Util.display("line3")
615 assert sys.stdout.buffer == "line1\nline3\n"
616 sys.stdout = old_stdout
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')
624 test.write(xxx, "\n")
625 test.write(sub1_yyy, "\n")
627 old_stdout = sys.stdout
628 sys.stdout = OutBuffer()
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'
635 SCons.Util.fs_delete(base, remove=0)
636 assert sys.stdout.buffer == exp
637 assert os.path.exists(sub1_yyy)
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)
645 sys.stdout = old_stdout
647 def test_get_native_path(self):
648 """Test the get_native_path() function."""
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
655 def test_subst_dict(self):
656 """Test substituting dictionary values in an Action
658 d = subst_dict([], [], DummyEnv({'a' : 'A', 'b' : 'B'}))
659 assert d['a'] == 'A', d
660 assert d['b'] == 'B', d
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']
668 d = subst_dict(target = ['t1', 't2'],
669 source = ['s1', 's2'],
671 TARGETS = map(lambda x: str(x), d['TARGETS'])
673 assert TARGETS == ['t1', 't2'], d['TARGETS']
674 assert str(d['TARGET']) == 't1', d['TARGET']
675 SOURCES = map(lambda x: str(x), d['SOURCES'])
677 assert SOURCES == ['s1', 's2'], d['SOURCES']
678 assert str(d['SOURCE']) == 's1', d['SOURCE']
681 def __init__(self, name):
686 return 'rstr-' + self.name
688 d = subst_dict(target = [N('t3'), 't4'],
689 source = ['s3', N('s4')],
691 TARGETS = map(lambda x: str(x), d['TARGETS'])
693 assert TARGETS == ['t3', 't4'], d['TARGETS']
694 SOURCES = map(lambda x: str(x), d['SOURCES'])
696 assert SOURCES == ['rstr-s4', 's3'], d['SOURCES']
699 if __name__ == "__main__":
700 suite = unittest.makeSuite(UtilTestCase, 'test_')
701 if not unittest.TextTestRunner().run(suite).wasSuccessful():