2 # Copyright (c) 2001, 2002 Steven Knight
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 *
38 class UtilTestCase(unittest.TestCase):
40 """Test the subst function."""
42 loc['TARGETS'] = PathList(map(os.path.normpath, [ "./foo/bar.exe",
45 loc['TARGET'] = loc['TARGETS'][0]
46 loc['SOURCES'] = PathList(map(os.path.normpath, [ "./foo/blah.cpp",
49 loc['SOURCE'] = loc['SOURCES'][0]
59 return string.replace(str, '/', os.sep)
61 newcom = scons_subst("test $TARGETS $SOURCES", loc, {})
62 assert newcom == cvt("test foo/bar.exe /bar/baz.obj ../foo/baz.obj foo/blah.cpp /bar/ack.cpp ../foo/ack.c")
64 newcom = scons_subst("test ${TARGETS[:]} ${SOURCES[0]}", loc, {})
65 assert newcom == cvt("test foo/bar.exe /bar/baz.obj ../foo/baz.obj foo/blah.cpp")
67 newcom = scons_subst("test ${TARGETS[1:]}v", loc, {})
68 assert newcom == cvt("test /bar/baz.obj ../foo/baz.objv")
70 newcom = scons_subst("test $TARGET", loc, {})
71 assert newcom == cvt("test foo/bar.exe")
73 newcom = scons_subst("test $TARGET$FOO[0]", loc, {})
74 assert newcom == cvt("test foo/bar.exe[0]")
76 newcom = scons_subst("test ${TARGET.file}", loc, {})
77 assert newcom == cvt("test bar.exe")
79 newcom = scons_subst("test ${TARGET.filebase}", loc, {})
80 assert newcom == cvt("test bar")
82 newcom = scons_subst("test ${TARGET.suffix}", loc, {})
83 assert newcom == cvt("test .exe")
85 newcom = scons_subst("test ${TARGET.base}", loc, {})
86 assert newcom == cvt("test foo/bar")
88 newcom = scons_subst("test ${TARGET.dir}", loc, {})
89 assert newcom == cvt("test foo")
91 newcom = scons_subst("test ${TARGET.abspath}", loc, {})
92 assert newcom == cvt("test %s/foo/bar.exe"%SCons.Util.updrive(os.getcwd())), newcom
94 newcom = scons_subst("test ${SOURCES.abspath}", loc, {})
95 assert newcom == cvt("test %s/foo/blah.cpp %s %s/foo/ack.c"%(SCons.Util.updrive(os.getcwd()),
96 SCons.Util.updrive(os.path.abspath(os.path.normpath("/bar/ack.cpp"))),
97 SCons.Util.updrive(os.path.normpath(os.getcwd()+"/..")))), newcom
99 newcom = scons_subst("test ${SOURCE.abspath}", loc, {})
100 assert newcom == cvt("test %s/foo/blah.cpp"%SCons.Util.updrive(os.getcwd())), newcom
102 newcom = scons_subst("test $xxx", loc, {})
103 assert newcom == cvt("test"), newcom
105 newcom = scons_subst("test $($xxx$)", loc, {})
106 assert newcom == cvt("test $($)"), newcom
108 newcom = scons_subst("test $( $xxx $)", loc, {})
109 assert newcom == cvt("test $( $)"), newcom
111 newcom = scons_subst("test $($xxx$)", loc, {}, re.compile('\$[()]'))
112 assert newcom == cvt("test"), newcom
114 newcom = scons_subst("test $( $xxx $)", loc, {}, re.compile('\$[()]'))
115 assert newcom == cvt("test"), newcom
117 newcom = scons_subst("test $zero", loc, {})
118 assert newcom == cvt("test 0"), newcom
120 newcom = scons_subst("test $one", loc, {})
121 assert newcom == cvt("test 1"), newcom
123 newcom = scons_subst("test aXbXcXd", loc, {}, re.compile('X'))
124 assert newcom == cvt("test abcd"), newcom
126 glob = { 'a' : 1, 'b' : 2 }
127 loc = {'a' : 3, 'c' : 4 }
128 newcom = scons_subst("test $a $b $c $d test", glob, loc)
129 assert newcom == "test 3 2 4 test", newcom
131 # Test against a former bug in scons_subst_list()
132 glob = { "FOO" : "$BAR",
135 "BARXYX" : "BADNEWS" }
136 newcom = scons_subst("$FOO$BLAT", glob, {})
137 assert newcom == "BAZXYX", newcom
139 # Test for double-dollar-sign behavior
140 glob = { "FOO" : "BAR",
142 newcom = scons_subst("$$FOO$BAZ", glob, {})
143 assert newcom == "$FOOBLAT", newcom
145 def test_splitext(self):
146 assert splitext('foo') == ('foo','')
147 assert splitext('foo.bar') == ('foo','.bar')
148 assert splitext(os.path.join('foo.bar', 'blat')) == (os.path.join('foo.bar', 'blat'),'')
150 def test_subst_list(self):
151 """Testing the scons_subst_list() method..."""
154 def __init__(self, name):
158 def is_literal(self):
162 loc['TARGETS'] = PathList(map(os.path.normpath, [ "./foo/bar.exe",
163 "/bar/baz with spaces.obj",
165 loc['TARGET'] = loc['TARGETS'][0]
166 loc['SOURCES'] = PathList(map(os.path.normpath, [ "./foo/blah with spaces.cpp",
170 loc['NEWLINE'] = 'before\nafter'
172 loc['DO'] = Node('do something')
173 loc['FOO'] = Node('foo.in')
174 loc['BAR'] = Node('bar with spaces.out')
175 loc['CRAZY'] = Node('crazy\nfile.in')
182 return string.replace(str, '/', os.sep)
184 cmd_list = scons_subst_list("$TARGETS", loc, {})
185 assert cmd_list[0][1] == cvt("/bar/baz with spaces.obj"), cmd_list[0][1]
187 cmd_list = scons_subst_list("$SOURCES $NEWLINE $TARGETS", loc, {})
188 assert len(cmd_list) == 2, cmd_list
189 assert cmd_list[0][0] == cvt('foo/blah with spaces.cpp'), cmd_list[0][0]
190 assert cmd_list[1][2] == cvt("/bar/baz with spaces.obj"), cmd_list[1]
192 cmd_list = scons_subst_list("$SOURCES$NEWLINE", loc, {})
193 assert len(cmd_list) == 2, cmd_list
194 assert cmd_list[1][0] == 'after', cmd_list[1][0]
195 assert cmd_list[0][2] == cvt('../foo/ack.cbefore'), cmd_list[0][2]
197 cmd_list = scons_subst_list("$DO --in=$FOO --out=$BAR", loc, {})
198 assert len(cmd_list) == 1, cmd_list
199 assert len(cmd_list[0]) == 3, cmd_list
200 assert cmd_list[0][0] == 'do something', cmd_list[0][0]
201 assert cmd_list[0][1] == '--in=foo.in', cmd_list[0][1]
202 assert cmd_list[0][2] == '--out=bar with spaces.out', cmd_list[0][2]
204 # This test is now fixed, and works like it should.
205 cmd_list = scons_subst_list("$DO --in=$CRAZY --out=$BAR", loc, {})
206 assert len(cmd_list) == 1, map(str, cmd_list[0])
207 assert len(cmd_list[0]) == 3, cmd_list
208 assert cmd_list[0][0] == 'do something', cmd_list[0][0]
209 assert cmd_list[0][1] == '--in=crazy\nfile.in', cmd_list[0][1]
210 assert cmd_list[0][2] == '--out=bar with spaces.out', cmd_list[0][2]
212 # Test inputting a list to scons_subst_list()
213 cmd_list = scons_subst_list([ "$SOURCES$NEWLINE", "$TARGETS",
216 assert len(cmd_list) == 2, len(cmd_list)
217 assert cmd_list[0][0] == cvt('foo/blah with spaces.cpp'), cmd_list[0][0]
218 assert cmd_list[1][0] == cvt("after"), cmd_list[1]
219 assert cmd_list[1][4] == "This is a test", cmd_list[1]
221 glob = { 'a' : 1, 'b' : 2 }
222 loc = {'a' : 3, 'c' : 4 }
223 cmd_list = scons_subst_list("test $a $b $c $d test", glob, loc)
224 assert len(cmd_list) == 1, cmd_list
225 assert map(str, cmd_list[0]) == ['test', '3', '2', '4', 'test'], map(str, cmd_list[0])
227 # Test against a former bug in scons_subst_list()
228 glob = { "FOO" : "$BAR",
231 "BARXYX" : "BADNEWS" }
232 cmd_list = scons_subst_list("$FOO$BLAT", glob, {})
233 assert cmd_list[0][0] == "BAZXYX", cmd_list[0][0]
235 # Test for double-dollar-sign behavior
236 glob = { "FOO" : "BAR",
238 cmd_list = scons_subst_list("$$FOO$BAZ", glob, {})
239 assert cmd_list[0][0] == "$FOOBLAT", cmd_list[0][0]
241 # Now test escape functionality
242 def escape_func(foo):
243 return '**' + foo + '**'
246 glob = { "FOO" : PathList([ 'foo\nwith\nnewlines',
247 'bar\nwith\nnewlines' ]) }
248 cmd_list = scons_subst_list("$FOO", glob, {})
249 assert cmd_list[0][0] == 'foo\nwith\nnewlines', cmd_list[0][0]
250 cmd_list[0][0].escape(escape_func)
251 assert cmd_list[0][0] == '**foo\nwith\nnewlines**', cmd_list[0][0]
252 assert cmd_list[0][1] == 'bar\nwith\nnewlines', cmd_list[0][0]
253 cmd_list[0][1].escape(escape_func)
254 assert cmd_list[0][1] == '**bar\nwith\nnewlines**', cmd_list[0][0]
256 def test_quote_spaces(self):
257 """Testing the quote_spaces() method..."""
258 q = quote_spaces('x')
261 q = quote_spaces('x x')
262 assert q == '"x x"', q
264 q = quote_spaces('x\tx')
265 assert q == '"x\tx"', q
267 def test_render_tree(self):
269 def __init__(self, name, children=[]):
270 self.children = children
275 def get_children(node):
278 windows_h = Node("windows.h")
279 stdlib_h = Node("stdlib.h")
280 stdio_h = Node("stdio.h")
281 bar_c = Node("bar.c", [stdlib_h, windows_h])
282 bar_o = Node("bar.o", [bar_c])
283 foo_c = Node("foo.c", [stdio_h])
284 foo_o = Node("foo.o", [foo_c])
285 foo = Node("foo", [foo_o, bar_o])
298 actual = render_tree(foo, get_children)
299 assert expect == actual, (expect, actual)
301 def test_is_Dict(self):
304 assert is_Dict(UserDict.UserDict())
305 assert not is_Dict([])
306 assert not is_Dict("")
307 if hasattr(types, 'UnicodeType'):
308 exec "assert not is_Dict(u'')"
310 def test_is_List(self):
313 assert is_List(UserList.UserList())
314 assert not is_List({})
315 assert not is_List("")
316 if hasattr(types, 'UnicodeType'):
317 exec "assert not is_List(u'')"
319 def test_Split(self):
320 assert Split("foo bar") == ["foo", "bar"]
321 assert Split(["foo", "bar"]) == ["foo", "bar"]
322 assert Split("foo") == ["foo"]
324 def test_is_String(self):
326 if hasattr(types, 'UnicodeType'):
327 exec "assert is_String(u'')"
333 assert is_String(UserString.UserString(''))
334 assert not is_String({})
335 assert not is_String([])
337 def test_to_String(self):
338 """Test the to_String() method."""
339 assert to_String(1) == "1", to_String(1)
340 assert to_String([ 1, 2, 3]) == str([1, 2, 3]), to_String([1,2,3])
341 assert to_String("foo") == "foo", to_String("foo")
346 s1=UserString.UserString('blah')
347 assert to_String(s1) == s1, s1
348 assert to_String(s1) == 'blah', s1
350 class Derived(UserString.UserString):
353 assert to_String(s2) == s2, s2
354 assert to_String(s2) == 'foo', s2
356 if hasattr(types, 'UnicodeType'):
357 s3=UserString.UserString(unicode('bar'))
358 assert to_String(s3) == s3, s3
359 assert to_String(s3) == unicode('bar'), s3
360 assert type(to_String(s3)) is types.UnicodeType, \
365 if hasattr(types, 'UnicodeType'):
367 assert to_String(s4) == unicode('baz'), to_String(s4)
368 assert type(to_String(s4)) is types.UnicodeType, \
371 def test_WhereIs(self):
372 test = TestCmd.TestCmd(workdir = '')
374 sub1_xxx_exe = test.workpath('sub1', 'xxx.exe')
375 sub2_xxx_exe = test.workpath('sub2', 'xxx.exe')
376 sub3_xxx_exe = test.workpath('sub3', 'xxx.exe')
377 sub4_xxx_exe = test.workpath('sub4', 'xxx.exe')
379 test.subdir('subdir', 'sub1', 'sub2', 'sub3', 'sub4')
381 if sys.platform != 'win32':
382 test.write(sub1_xxx_exe, "\n")
384 os.mkdir(sub2_xxx_exe)
386 test.write(sub3_xxx_exe, "\n")
387 os.chmod(sub3_xxx_exe, 0777)
389 test.write(sub4_xxx_exe, "\n")
390 os.chmod(sub4_xxx_exe, 0777)
392 env_path = os.environ['PATH']
394 pathdirs_1234 = [ test.workpath('sub1'),
395 test.workpath('sub2'),
396 test.workpath('sub3'),
397 test.workpath('sub4'),
398 ] + string.split(env_path, os.pathsep)
400 pathdirs_1243 = [ test.workpath('sub1'),
401 test.workpath('sub2'),
402 test.workpath('sub4'),
403 test.workpath('sub3'),
404 ] + string.split(env_path, os.pathsep)
406 os.environ['PATH'] = string.join(pathdirs_1234, os.pathsep)
407 wi = WhereIs('xxx.exe')
408 assert wi == test.workpath(sub3_xxx_exe), wi
409 wi = WhereIs('xxx.exe', pathdirs_1243)
410 assert wi == test.workpath(sub4_xxx_exe), wi
411 wi = WhereIs('xxx.exe', string.join(pathdirs_1243, os.pathsep))
412 assert wi == test.workpath(sub4_xxx_exe), wi
414 os.environ['PATH'] = string.join(pathdirs_1243, os.pathsep)
415 wi = WhereIs('xxx.exe')
416 assert wi == test.workpath(sub4_xxx_exe), wi
417 wi = WhereIs('xxx.exe', pathdirs_1234)
418 assert wi == test.workpath(sub3_xxx_exe), wi
419 wi = WhereIs('xxx.exe', string.join(pathdirs_1234, os.pathsep))
420 assert wi == test.workpath(sub3_xxx_exe), wi
422 if sys.platform == 'win32':
423 wi = WhereIs('xxx', pathext = '')
424 assert wi is None, wi
426 wi = WhereIs('xxx', pathext = '.exe')
427 assert wi == test.workpath(sub4_xxx_exe), wi
429 wi = WhereIs('xxx', path = pathdirs_1234, pathext = '.BAT;.EXE')
430 assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi
432 def test_get_env_var(self):
433 """Testing get_environment_var()."""
434 assert get_environment_var("$FOO") == "FOO", get_environment_var("$FOO")
435 assert get_environment_var("${BAR}") == "BAR", get_environment_var("${BAR}")
436 assert get_environment_var("${BAR}FOO") == None, get_environment_var("${BAR}FOO")
437 assert get_environment_var("$BAR ") == None, get_environment_var("$BAR ")
438 assert get_environment_var("FOO$BAR") == None, get_environment_var("FOO$BAR")
440 def test_Proxy(self):
441 """Test generic Proxy class."""
451 class ProxyTest(Proxy):
457 assert p.foo() == 1, p.foo()
458 assert p.bar() == 4, p.bar()
459 assert p.baz == 3, p.baz
464 assert p.baz == 5, p.baz
466 def test_Literal(self):
467 """Test the Literal() function."""
468 cmd_list = [ '$FOO', Literal('$BAR') ]
469 cmd_list = scons_subst_list(cmd_list,
471 'BAR' : 'BLAT' }, {})
472 def escape_func(cmd):
473 return '**' + cmd + '**'
475 map(lambda x, e=escape_func: x.escape(e), cmd_list[0])
476 cmd_list = map(str, cmd_list[0])
477 assert cmd_list[0] == 'BAZ', cmd_list[0]
478 assert cmd_list[1] == '**$BAR**', cmd_list[1]
480 def test_mapPaths(self):
481 """Test the mapPaths function"""
482 fs = SCons.Node.FS.FS()
484 file=fs.File('bar/file')
487 def subst(self, arg):
490 res = mapPaths([ file, 'baz', 'blat/boo', '#test' ], dir)
491 assert res[0] == file, res[0]
492 assert res[1] == os.path.normpath('foo/baz'), res[1]
493 assert res[2] == os.path.normpath('foo/blat/boo'), res[2]
494 assert res[3] == '#test', res[3]
497 res=mapPaths('bleh', dir, env)
498 assert res[0] == os.path.normpath('foo/bar'), res[1]
501 if __name__ == "__main__":
502 suite = unittest.makeSuite(UtilTestCase, 'test_')
503 if not unittest.TextTestRunner().run(suite).wasSuccessful():