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__"
32 from SCons.Util import *
42 self.buffer = self.buffer + str
45 """Simple node work-alike."""
46 def __init__(self, name):
47 self.name = os.path.normpath(name)
54 def get_subst_proxy(self):
58 def __init__(self, dict={}):
61 def Dictionary(self, key = None):
66 def __getitem__(self, key):
70 dict = self.dict.copy()
71 dict["TARGETS"] = 'tsig'
72 dict["SOURCES"] = 'ssig'
75 def cs(target=None, source=None, env=None, for_signature=None):
78 def cl(target=None, source=None, env=None, for_signature=None):
81 def CmdGen1(target, source, env, for_signature):
82 # Nifty trick...since Environment references are interpolated,
83 # instantiate an instance of a callable class with this one,
84 # which will then get evaluated.
85 assert str(target) == 't', target
86 assert str(source) == 's', source
87 return "${CMDGEN2('foo', %d)}" % for_signature
90 def __init__(self, mystr, forsig):
92 self.expect_for_signature = forsig
94 def __call__(self, target, source, env, for_signature):
95 assert str(target) == 't', target
96 assert str(source) == 's', source
97 assert for_signature == self.expect_for_signature, for_signature
98 return [ self.mystr, env.Dictionary('BAR') ]
105 return string.replace(str, '/', os.sep)
107 class UtilTestCase(unittest.TestCase):
108 def test_subst(self):
109 """Test the subst() function"""
110 class MyNode(DummyNode):
111 """Simple node work-alike with some extra stuff for testing."""
112 def __init__(self, name):
113 DummyNode.__init__(self, name)
116 self.attribute = Attribute()
117 self.attribute.attr1 = 'attr$1-' + os.path.basename(name)
118 self.attribute.attr2 = 'attr$2-' + os.path.basename(name)
119 def get_stuff(self, extra):
120 return self.name + extra
124 def __init__(self, literal):
125 self.literal = literal
128 def is_literal(self):
131 def function_foo(arg):
134 target = [ MyNode("./foo/bar.exe"),
135 MyNode("/bar/baz.obj"),
136 MyNode("../foo/baz.obj") ]
137 source = [ MyNode("./foo/blah.cpp"),
138 MyNode("/bar/ack.cpp"),
139 MyNode("../foo/ack.c") ]
155 # $XXX$HHH should expand to GGGIII, not BADNEWS.
159 'FFFIII' : 'BADNEWS',
161 'LITERAL' : TestLiteral("$XXX"),
163 # Test that we can expand to and return a function.
164 #'FUNCTION' : function_foo,
172 # Test various combinations of strings, lists and functions.
183 # Test function calls within ${}.
184 'FUNCCALL' : '${FUNC1("$AAA $FUNC2 $BBB")}',
185 'FUNC1' : lambda x: x,
186 'FUNC2' : lambda target, source, env, for_signature: ['x$CCC'],
188 # Various tests refactored from ActionTests.py.
189 'LIST' : [["This", "is", "$(", "$a", "$)", "test"]],
192 'RECURSE' : 'foo $RECURSE bar',
193 'RRR' : 'foo $SSS bar',
199 # Basic tests of substitution functionality.
201 # Basics: strings without expansions are left alone, and
202 # the simplest possible expansion to a null-string value.
206 # Test expansion of integer values.
207 "test $zero", "test 0",
208 "test $one", "test 1",
210 # Test multiple re-expansion of values.
211 "test $ONE", "test four",
213 # Test a whole bunch of $TARGET[S] and $SOURCE[S] expansions.
214 "test $TARGETS $SOURCES",
215 "test foo/bar.exe /bar/baz.obj ../foo/baz.obj foo/blah.cpp /bar/ack.cpp ../foo/ack.c",
217 "test ${TARGETS[:]} ${SOURCES[0]}",
218 "test foo/bar.exe /bar/baz.obj ../foo/baz.obj foo/blah.cpp",
220 "test ${TARGETS[1:]}v",
221 "test /bar/baz.obj ../foo/baz.objv",
226 "test $TARGET$FOO[0]",
227 "test foo/bar.exe[0]",
232 "test ${SOURCES[0:2].foo}",
238 "test ${TARGET.get_stuff('blah')}",
239 "test foo/bar.exeblah",
241 "test ${SOURCES.get_stuff('blah')}",
242 "test foo/blah.cppblah /bar/ack.cppblah ../foo/ack.cblah",
244 "test ${SOURCES[0:2].get_stuff('blah')}",
245 "test foo/blah.cppblah /bar/ack.cppblah",
247 "test ${SOURCES[0:2].get_stuff('blah')}",
248 "test foo/blah.cppblah /bar/ack.cppblah",
250 "test ${SOURCES.attribute.attr1}",
251 "test attr$1-blah.cpp attr$1-ack.cpp attr$1-ack.c",
253 "test ${SOURCES.attribute.attr2}",
254 "test attr$2-blah.cpp attr$2-ack.cpp attr$2-ack.c",
256 # Test adjacent expansions.
263 # Test that adjacent expansions don't get re-interpreted
264 # together. The correct disambiguated expansion should be:
265 # $XXX$HHH => ${FFF}III => GGGIII
267 # $XXX$HHH => ${FFFIII} => BADNEWS
268 "$XXX$HHH", "GGGIII",
270 # Test double-dollar-sign behavior.
271 "$$FFF$HHH", "$FFFIII",
273 # Test that a Literal will stop dollar-sign substitution.
274 "$XXX $LITERAL $FFF", "GGG $XXX GGG",
276 # Test that we don't blow up even if they subscript
277 # something in ways they "can't."
283 # Test various combinations of strings and lists.
303 # Test function calls within ${}.
304 '$FUNCCALL', 'a xc b',
306 # Bug reported by Christoph Wiedemann.
307 cvt('$xxx/bin'), '/bin',
310 kwargs = {'target' : target, 'source' : source}
314 input, expect = cases[:2]
316 result = apply(scons_subst, (input, env), kwargs)
318 if failed == 0: print
319 print " input %s => %s did not match %s" % (repr(input), repr(result), repr(expect))
322 assert failed == 0, "%d subst() cases failed" % failed
324 # Tests of the various SUBST_* modes of substitution.
341 "$AAA ${AAA}A $BBBB $BBB",
356 # Verify what happens with no target or source nodes.
367 # Various tests refactored from ActionTests.py.
369 "This is $( $) test",
373 ["|", "$(", "$AAA", "|", "$BBB", "$)", "|", "$CCC", 1],
374 "| $( a | b $) | c 1",
381 input, eraw, ecmd, esig = subst_cases[:4]
382 result = scons_subst(input, env, mode=SUBST_RAW)
384 if failed == 0: print
385 print " input %s => RAW %s did not match %s" % (repr(input), repr(result), repr(eraw))
387 result = scons_subst(input, env, mode=SUBST_CMD)
389 if failed == 0: print
390 print " input %s => CMD %s did not match %s" % (repr(input), repr(result), repr(ecmd))
392 result = scons_subst(input, env, mode=SUBST_SIG)
394 if failed == 0: print
395 print " input %s => SIG %s did not match %s" % (repr(input), repr(result), repr(esig))
398 assert failed == 0, "%d subst() mode cases failed" % failed
404 result = scons_subst("$TARGET $SOURCES", env,
407 assert result == "t1 s1 s2", result
408 result = scons_subst("$TARGET $SOURCES", env,
412 assert result == " ", result
414 result = scons_subst("$TARGET $SOURCES", env, target=[], source=[])
415 assert result == " ", result
416 result = scons_subst("$TARGETS $SOURCE", env, target=[], source=[])
417 assert result == " ", result
419 # Test interpolating a callable.
420 newcom = scons_subst("test $CMDGEN1 $SOURCES $TARGETS",
421 env, target=MyNode('t'), source=MyNode('s'))
422 assert newcom == "test foo baz s t", newcom
424 # Test that we handle syntax errors during expansion as expected.
426 scons_subst('$foo.bar.3.0', env)
427 except SCons.Errors.UserError, e:
428 expect1 = "Syntax error `invalid syntax' trying to evaluate `$foo.bar.3.0'"
429 expect2 = "Syntax error `invalid syntax (line 1)' trying to evaluate `$foo.bar.3.0'"
430 assert str(e) in [expect1, expect2], e
432 raise AssertionError, "did not catch expected UserError"
434 # Test how we handle overriding the internal conversion routines.
439 env = DummyEnv({'NODE' : n1})
440 node = scons_subst("$NODE", env, mode=SUBST_RAW, conv=s)
441 assert node == [n1], node
442 node = scons_subst("$NODE", env, mode=SUBST_CMD, conv=s)
443 assert node == [n1], node
444 node = scons_subst("$NODE", env, mode=SUBST_SIG, conv=s)
445 assert node == [n1], node
447 # Test returning a function.
448 #env = DummyEnv({'FUNCTION' : foo})
449 #func = scons_subst("$FUNCTION", env, mode=SUBST_RAW, call=None)
450 #assert func is function_foo, func
451 #func = scons_subst("$FUNCTION", env, mode=SUBST_CMD, call=None)
452 #assert func is function_foo, func
453 #func = scons_subst("$FUNCTION", env, mode=SUBST_SIG, call=None)
454 #assert func is function_foo, func
456 # Test supplying an overriding gvars dictionary.
457 env = DummyEnv({'XXX' : 'xxx'})
458 result = scons_subst('$XXX', env)
459 assert result == 'xxx', result
460 result = scons_subst('$XXX', env, gvars={'XXX' : 'yyy'})
461 assert result == 'yyy', result
463 def test_subst_list(self):
464 """Testing the scons_subst_list() method..."""
465 class MyNode(DummyNode):
466 """Simple node work-alike with some extra stuff for testing."""
467 def __init__(self, name):
468 DummyNode.__init__(self, name)
471 self.attribute = Attribute()
472 self.attribute.attr1 = 'attr$1-' + os.path.basename(name)
473 self.attribute.attr2 = 'attr$2-' + os.path.basename(name)
475 target = [ MyNode("./foo/bar.exe"),
476 MyNode("/bar/baz with spaces.obj"),
477 MyNode("../foo/baz.obj") ]
478 source = [ MyNode("./foo/blah with spaces.cpp"),
479 MyNode("/bar/ack.cpp"),
480 MyNode("../foo/ack.c") ]
484 'NEWLINE' : 'before\nafter',
490 'DO' : DummyNode('do something'),
491 'FOO' : DummyNode('foo.in'),
492 'BAR' : DummyNode('bar with spaces.out'),
493 'CRAZY' : DummyNode('crazy\nfile.in'),
495 # $XXX$HHH should expand to GGGIII, not BADNEWS.
499 'FFFIII' : 'BADNEWS',
504 'LITERALS' : [ Literal('foo\nwith\nnewlines'),
505 Literal('bar\nwith\nnewlines') ],
507 # Test various combinations of strings, lists and functions.
518 # Test function calls within ${}.
519 'FUNCCALL' : '${FUNC1("$AAA $FUNC2 $BBB")}',
520 'FUNC1' : lambda x: x,
521 'FUNC2' : lambda target, source, env, for_signature: ['x$CCC'],
523 # Various tests refactored from ActionTests.py.
524 'LIST' : [["This", "is", "$(", "$a", "$)", "test"]],
527 'RECURSE' : 'foo $RECURSE bar',
528 'RRR' : 'foo $SSS bar',
537 ["foo/bar.exe", "/bar/baz with spaces.obj", "../foo/baz.obj"],
540 "$SOURCES $NEWLINE $TARGETS",
542 ["foo/blah with spaces.cpp", "/bar/ack.cpp", "../foo/ack.c", "before"],
543 ["after", "foo/bar.exe", "/bar/baz with spaces.obj", "../foo/baz.obj"],
548 ["foo/blah with spaces.cpp", "/bar/ack.cpp", "../foo/ack.cbefore"],
562 "test ${SOURCES.attribute.attr1}",
564 ["test", "attr$1-blah with spaces.cpp", "attr$1-ack.cpp", "attr$1-ack.c"],
567 "test ${SOURCES.attribute.attr2}",
569 ["test", "attr$2-blah with spaces.cpp", "attr$2-ack.cpp", "attr$2-ack.c"],
572 "$DO --in=$FOO --out=$BAR",
574 ["do something", "--in=foo.in", "--out=bar with spaces.out"],
577 # This test is now fixed, and works like it should.
578 "$DO --in=$CRAZY --out=$BAR",
580 ["do something", "--in=crazy\nfile.in", "--out=bar with spaces.out"],
583 # Try passing a list to scons_subst_list().
584 [ "$SOURCES$NEWLINE", "$TARGETS", "This is a test"],
586 ["foo/blah with spaces.cpp", "/bar/ack.cpp", "../foo/ack.cbefore"],
587 ["after", "foo/bar.exe", "/bar/baz with spaces.obj", "../foo/baz.obj", "This is a test"],
590 # Test against a former bug in scons_subst_list().
596 # Test double-dollar-sign behavior.
602 # Test various combinations of strings, lists and functions.
611 ['x', 'y'], [['x', 'y']],
621 '$S z', [['x', 'y', 'z']],
622 ['$S'], [['x', 'y']],
623 ['$S z'], [['x', 'y z']], # XXX - IS THIS BEST?
624 ['$S', 'z'], [['x', 'y', 'z']],
626 '$LS z', [['x y', 'z']],
628 ['$LS z'], [['x y z']],
629 ['$LS', 'z'], [['x y', 'z']],
631 '$L z', [['x', 'y', 'z']],
632 ['$L'], [['x', 'y']],
633 ['$L z'], [['x', 'y z']], # XXX - IS THIS BEST?
634 ['$L', 'z'], [['x', 'y', 'z']],
644 # Test function calls within ${}.
645 '$FUNCCALL', [['a', 'xc', 'b']],
647 # Test handling of newlines in white space.
648 'foo\nbar', [['foo'], ['bar']],
649 'foo\n\nbar', [['foo'], ['bar']],
650 'foo \n \n bar', [['foo'], ['bar']],
651 'foo \nmiddle\n bar', [['foo'], ['middle'], ['bar']],
653 # Bug reported by Christoph Wiedemann.
654 cvt('$xxx/bin'), [['/bin']],
656 # Test variables smooshed together with different prefixes.
657 'foo$AAA', [['fooa']],
658 '<$AAA', [['<', 'a']],
659 '>$AAA', [['>', 'a']],
660 '|$AAA', [['|', 'a']],
663 kwargs = {'target' : target, 'source' : source}
667 input, expect = cases[:2]
668 expect = map(lambda l: map(cvt, l), expect)
669 result = apply(scons_subst_list, (input, env), kwargs)
671 if failed == 0: print
672 print " input %s => %s did not match %s" % (repr(input), result, repr(expect))
675 assert failed == 0, "%d subst_list() cases failed" % failed
681 result = scons_subst_list("$TARGET $SOURCES", env,
684 assert result == [['t1', 's1', 's2']], result
685 result = scons_subst_list("$TARGET $SOURCES", env,
689 assert result == [[]], result
691 # Test interpolating a callable.
694 cmd_list = scons_subst_list("testing $CMDGEN1 $TARGETS $SOURCES",
695 env, target=_t, source=_s)
696 assert cmd_list == [['testing', 'foo', 'bar with spaces.out', 't', 's']], cmd_list
698 # Test escape functionality.
699 def escape_func(foo):
700 return '**' + foo + '**'
701 cmd_list = scons_subst_list("abc $LITERALS xyz", env)
702 assert cmd_list == [['abc',
703 'foo\nwith\nnewlines',
704 'bar\nwith\nnewlines',
706 c = cmd_list[0][0].escape(escape_func)
708 c = cmd_list[0][1].escape(escape_func)
709 assert c == '**foo\nwith\nnewlines**', c
710 c = cmd_list[0][2].escape(escape_func)
711 assert c == '**bar\nwith\nnewlines**', c
712 c = cmd_list[0][3].escape(escape_func)
715 cmd_list = scons_subst_list("abc${LITERALS}xyz", env)
716 c = cmd_list[0][0].escape(escape_func)
717 assert c == '**abcfoo\nwith\nnewlines**', c
718 c = cmd_list[0][1].escape(escape_func)
719 assert c == '**bar\nwith\nnewlinesxyz**', c
721 # Tests of the various SUBST_* modes of substitution.
734 [["test", "$(", "$)"]],
738 "$AAA ${AAA}A $BBBB $BBB",
753 # Verify what happens with no target or source nodes.
764 # Various test refactored from ActionTests.py
766 [['This', 'is', '$(', '$)', 'test']],
767 [['This', 'is', 'test']],
768 [['This', 'is', 'test']],
770 ["|", "$(", "$AAA", "|", "$BBB", "$)", "|", "$CCC", 1],
771 [["|", "$(", "a", "|", "b", "$)", "|", "c", "1"]],
772 [["|", "a", "|", "b", "|", "c", "1"]],
773 [["|", "|", "c", "1"]],
776 r = scons_subst_list("$TARGET $SOURCES", env, mode=SUBST_RAW)
780 while subst_list_cases:
781 input, eraw, ecmd, esig = subst_list_cases[:4]
782 result = scons_subst_list(input, env, mode=SUBST_RAW)
784 if failed == 0: print
785 print " input %s => RAW %s did not match %s" % (repr(input), repr(result), repr(eraw))
787 result = scons_subst_list(input, env, mode=SUBST_CMD)
789 if failed == 0: print
790 print " input %s => CMD %s did not match %s" % (repr(input), repr(result), repr(ecmd))
792 result = scons_subst_list(input, env, mode=SUBST_SIG)
794 if failed == 0: print
795 print " input %s => SIG %s did not match %s" % (repr(input), repr(result), repr(esig))
797 del subst_list_cases[:4]
798 assert failed == 0, "%d subst() mode cases failed" % failed
800 # Test that we handle syntax errors during expansion as expected.
802 scons_subst_list('$foo.bar.3.0', env)
803 except SCons.Errors.UserError, e:
804 expect1 = "Syntax error `invalid syntax' trying to evaluate `$foo.bar.3.0'"
805 expect2 = "Syntax error `invalid syntax (line 1)' trying to evaluate `$foo.bar.3.0'"
806 assert str(e) in [expect1, expect2], e
808 raise AssertionError, "did not catch expected SyntaxError"
810 # Test we handle overriding the internal conversion routines.
815 env = DummyEnv({'NODE' : n1})
816 node = scons_subst_list("$NODE", env, mode=SUBST_RAW, conv=s)
817 assert node == [[n1]], node
818 node = scons_subst_list("$NODE", env, mode=SUBST_CMD, conv=s)
819 assert node == [[n1]], node
820 node = scons_subst_list("$NODE", env, mode=SUBST_SIG, conv=s)
821 assert node == [[n1]], node
823 # Test supplying an overriding gvars dictionary.
824 env = DummyEnv({'XXX' : 'xxx'})
825 result = scons_subst_list('$XXX', env)
826 assert result == [['xxx']], result
827 result = scons_subst_list('$XXX', env, gvars={'XXX' : 'yyy'})
828 assert result == [['yyy']], result
830 def test_subst_once(self):
831 """Testing the scons_subst_once() method"""
836 'RECURSE' : 'r $RECURSE r',
837 'LIST' : ['a', 'b', 'c'],
869 ['x', 'a', 'b', 'c', 'y'],
871 ['x', 'x $LIST y', 'y'],
873 ['x', 'x a b c y', 'y'],
875 ['x', 'x $CCFLAGS y', 'y'],
877 ['x', 'x $CCFLAGS y', 'y'],
879 ['x', 'x $RECURSE y', 'y'],
881 ['x', 'x $RECURSE y', 'y'],
886 input, key, expect = cases[:3]
887 result = scons_subst_once(input, env, key)
889 if failed == 0: print
890 print " input %s (%s) => %s did not match %s" % (repr(input), repr(key), repr(result), repr(expect))
893 assert failed == 0, "%d subst() cases failed" % failed
895 def test_splitext(self):
896 assert splitext('foo') == ('foo','')
897 assert splitext('foo.bar') == ('foo','.bar')
898 assert splitext(os.path.join('foo.bar', 'blat')) == (os.path.join('foo.bar', 'blat'),'')
900 def test_quote_spaces(self):
901 """Testing the quote_spaces() method..."""
902 q = quote_spaces('x')
905 q = quote_spaces('x x')
906 assert q == '"x x"', q
908 q = quote_spaces('x\tx')
909 assert q == '"x\tx"', q
911 def test_render_tree(self):
913 def __init__(self, name, children=[]):
914 self.children = children
919 def get_children(node):
922 windows_h = Node("windows.h")
923 stdlib_h = Node("stdlib.h")
924 stdio_h = Node("stdio.h")
925 bar_c = Node("bar.c", [stdlib_h, windows_h])
926 bar_o = Node("bar.o", [bar_c])
927 foo_c = Node("foo.c", [stdio_h])
928 foo_o = Node("foo.o", [foo_c])
929 foo = Node("foo", [foo_o, bar_o])
942 actual = render_tree(foo, get_children)
943 assert expect == actual, (expect, actual)
945 bar_h = Node('bar.h', [stdlib_h])
946 blat_h = Node('blat.h', [stdlib_h])
947 blat_c = Node('blat.c', [blat_h, bar_h])
948 blat_o = Node('blat.o', [blat_c])
958 actual = render_tree(blat_o, get_children, 1)
959 assert expect == actual, (expect, actual)
961 def test_is_Dict(self):
964 assert is_Dict(UserDict.UserDict())
965 assert not is_Dict([])
966 assert not is_Dict("")
967 if hasattr(types, 'UnicodeType'):
968 exec "assert not is_Dict(u'')"
970 def test_is_List(self):
973 assert is_List(UserList.UserList())
974 assert not is_List({})
975 assert not is_List("")
976 if hasattr(types, 'UnicodeType'):
977 exec "assert not is_List(u'')"
979 def test_is_String(self):
981 if hasattr(types, 'UnicodeType'):
982 exec "assert is_String(u'')"
988 assert is_String(UserString.UserString(''))
989 assert not is_String({})
990 assert not is_String([])
992 def test_to_String(self):
993 """Test the to_String() method."""
994 assert to_String(1) == "1", to_String(1)
995 assert to_String([ 1, 2, 3]) == str([1, 2, 3]), to_String([1,2,3])
996 assert to_String("foo") == "foo", to_String("foo")
1001 s1=UserString.UserString('blah')
1002 assert to_String(s1) == s1, s1
1003 assert to_String(s1) == 'blah', s1
1005 class Derived(UserString.UserString):
1008 assert to_String(s2) == s2, s2
1009 assert to_String(s2) == 'foo', s2
1011 if hasattr(types, 'UnicodeType'):
1012 s3=UserString.UserString(unicode('bar'))
1013 assert to_String(s3) == s3, s3
1014 assert to_String(s3) == unicode('bar'), s3
1015 assert type(to_String(s3)) is types.UnicodeType, \
1020 if hasattr(types, 'UnicodeType'):
1022 assert to_String(s4) == unicode('baz'), to_String(s4)
1023 assert type(to_String(s4)) is types.UnicodeType, \
1026 def test_WhereIs(self):
1027 test = TestCmd.TestCmd(workdir = '')
1029 sub1_xxx_exe = test.workpath('sub1', 'xxx.exe')
1030 sub2_xxx_exe = test.workpath('sub2', 'xxx.exe')
1031 sub3_xxx_exe = test.workpath('sub3', 'xxx.exe')
1032 sub4_xxx_exe = test.workpath('sub4', 'xxx.exe')
1034 test.subdir('subdir', 'sub1', 'sub2', 'sub3', 'sub4')
1036 if sys.platform != 'win32':
1037 test.write(sub1_xxx_exe, "\n")
1039 os.mkdir(sub2_xxx_exe)
1041 test.write(sub3_xxx_exe, "\n")
1042 os.chmod(sub3_xxx_exe, 0777)
1044 test.write(sub4_xxx_exe, "\n")
1045 os.chmod(sub4_xxx_exe, 0777)
1047 env_path = os.environ['PATH']
1050 pathdirs_1234 = [ test.workpath('sub1'),
1051 test.workpath('sub2'),
1052 test.workpath('sub3'),
1053 test.workpath('sub4'),
1054 ] + string.split(env_path, os.pathsep)
1056 pathdirs_1243 = [ test.workpath('sub1'),
1057 test.workpath('sub2'),
1058 test.workpath('sub4'),
1059 test.workpath('sub3'),
1060 ] + string.split(env_path, os.pathsep)
1062 os.environ['PATH'] = string.join(pathdirs_1234, os.pathsep)
1063 wi = WhereIs('xxx.exe')
1064 assert wi == test.workpath(sub3_xxx_exe), wi
1065 wi = WhereIs('xxx.exe', pathdirs_1243)
1066 assert wi == test.workpath(sub4_xxx_exe), wi
1067 wi = WhereIs('xxx.exe', string.join(pathdirs_1243, os.pathsep))
1068 assert wi == test.workpath(sub4_xxx_exe), wi
1070 wi = WhereIs('xxx.exe',reject = sub3_xxx_exe)
1071 assert wi == test.workpath(sub4_xxx_exe), wi
1072 wi = WhereIs('xxx.exe', pathdirs_1243, reject = sub3_xxx_exe)
1073 assert wi == test.workpath(sub4_xxx_exe), wi
1075 os.environ['PATH'] = string.join(pathdirs_1243, os.pathsep)
1076 wi = WhereIs('xxx.exe')
1077 assert wi == test.workpath(sub4_xxx_exe), wi
1078 wi = WhereIs('xxx.exe', pathdirs_1234)
1079 assert wi == test.workpath(sub3_xxx_exe), wi
1080 wi = WhereIs('xxx.exe', string.join(pathdirs_1234, os.pathsep))
1081 assert wi == test.workpath(sub3_xxx_exe), wi
1083 if sys.platform == 'win32':
1084 wi = WhereIs('xxx', pathext = '')
1085 assert wi is None, wi
1087 wi = WhereIs('xxx', pathext = '.exe')
1088 assert wi == test.workpath(sub4_xxx_exe), wi
1090 wi = WhereIs('xxx', path = pathdirs_1234, pathext = '.BAT;.EXE')
1091 assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi
1093 # Test that we return a normalized path even when
1094 # the path contains forward slashes.
1095 forward_slash = test.workpath('') + '/sub3'
1096 wi = WhereIs('xxx', path = forward_slash, pathext = '.EXE')
1097 assert string.lower(wi) == string.lower(test.workpath(sub3_xxx_exe)), wi
1099 del os.environ['PATH']
1100 wi = WhereIs('xxx.exe')
1101 assert wi is None, wi
1104 os.environ['PATH'] = env_path
1107 def test_is_valid_construction_var(self):
1108 """Testing is_valid_construction_var()"""
1109 r = is_valid_construction_var("_a")
1110 assert not r is None, r
1111 r = is_valid_construction_var("z_")
1112 assert not r is None, r
1113 r = is_valid_construction_var("X_")
1114 assert not r is None, r
1115 r = is_valid_construction_var("2a")
1117 r = is_valid_construction_var("a2_")
1118 assert not r is None, r
1119 r = is_valid_construction_var("/")
1121 r = is_valid_construction_var("_/")
1123 r = is_valid_construction_var("a/")
1125 r = is_valid_construction_var(".b")
1127 r = is_valid_construction_var("_.b")
1129 r = is_valid_construction_var("b1._")
1131 r = is_valid_construction_var("-b")
1133 r = is_valid_construction_var("_-b")
1135 r = is_valid_construction_var("b1-_")
1138 def test_get_env_var(self):
1139 """Testing get_environment_var()."""
1140 assert get_environment_var("$FOO") == "FOO", get_environment_var("$FOO")
1141 assert get_environment_var("${BAR}") == "BAR", get_environment_var("${BAR}")
1142 assert get_environment_var("$FOO_BAR1234") == "FOO_BAR1234", get_environment_var("$FOO_BAR1234")
1143 assert get_environment_var("${BAR_FOO1234}") == "BAR_FOO1234", get_environment_var("${BAR_FOO1234}")
1144 assert get_environment_var("${BAR}FOO") == None, get_environment_var("${BAR}FOO")
1145 assert get_environment_var("$BAR ") == None, get_environment_var("$BAR ")
1146 assert get_environment_var("FOO$BAR") == None, get_environment_var("FOO$BAR")
1147 assert get_environment_var("$FOO[0]") == None, get_environment_var("$FOO[0]")
1148 assert get_environment_var("${some('complex expression')}") == None, get_environment_var("${some('complex expression')}")
1150 def test_Proxy(self):
1151 """Test generic Proxy class."""
1161 class ProxyTest(Proxy):
1167 assert p.foo() == 1, p.foo()
1168 assert p.bar() == 4, p.bar()
1169 assert p.baz == 3, p.baz
1174 assert p.baz == 5, p.baz
1175 assert p.get() == s, p.get()
1177 def test_Literal(self):
1178 """Test the Literal() function."""
1179 input_list = [ '$FOO', Literal('$BAR') ]
1180 dummy_env = DummyEnv({ 'FOO' : 'BAZ', 'BAR' : 'BLAT' })
1182 def escape_func(cmd):
1183 return '**' + cmd + '**'
1185 cmd_list = scons_subst_list(input_list, dummy_env)
1186 cmd_list = SCons.Util.escape_list(cmd_list[0], escape_func)
1187 assert cmd_list == ['BAZ', '**$BAR**'], cmd_list
1189 def test_SpecialAttrWrapper(self):
1190 """Test the SpecialAttrWrapper() function."""
1191 input_list = [ '$FOO', SpecialAttrWrapper('$BAR', 'BLEH') ]
1192 dummy_env = DummyEnv({ 'FOO' : 'BAZ', 'BAR' : 'BLAT' })
1194 def escape_func(cmd):
1195 return '**' + cmd + '**'
1197 cmd_list = scons_subst_list(input_list, dummy_env)
1198 cmd_list = SCons.Util.escape_list(cmd_list[0], escape_func)
1199 assert cmd_list == ['BAZ', '**$BAR**'], cmd_list
1201 cmd_list = scons_subst_list(input_list, dummy_env, mode=SUBST_SIG)
1202 cmd_list = SCons.Util.escape_list(cmd_list[0], escape_func)
1203 assert cmd_list == ['BAZ', '**BLEH**'], cmd_list
1205 def test_display(self):
1206 old_stdout = sys.stdout
1207 sys.stdout = OutBuffer()
1213 display("line4\n", append_newline=0)
1215 display("dont print1")
1216 display("dont print2\n", append_newline=0)
1218 assert sys.stdout.buffer == "line1\nline3\nline4\n"
1219 sys.stdout = old_stdout
1221 def test_fs_delete(self):
1222 test = TestCmd.TestCmd(workdir = '')
1223 base = test.workpath('')
1224 xxx = test.workpath('xxx.xxx')
1225 ZZZ = test.workpath('ZZZ.ZZZ')
1226 sub1_yyy = test.workpath('sub1', 'yyy.yyy')
1229 test.write(xxx, "\n")
1230 test.write(ZZZ, "\n")
1231 test.write(sub1_yyy, "\n")
1233 old_stdout = sys.stdout
1234 sys.stdout = OutBuffer()
1236 exp = "Removed " + os.path.join(base, ZZZ) + "\n" + \
1237 "Removed " + os.path.join(base, sub1_yyy) + '\n' + \
1238 "Removed directory " + os.path.join(base, 'sub1') + '\n' + \
1239 "Removed " + os.path.join(base, xxx) + '\n' + \
1240 "Removed directory " + base + '\n'
1242 fs_delete(base, remove=0)
1243 assert sys.stdout.buffer == exp, sys.stdout.buffer
1244 assert os.path.exists(sub1_yyy)
1246 sys.stdout.buffer = ""
1247 fs_delete(base, remove=1)
1248 assert sys.stdout.buffer == exp
1249 assert not os.path.exists(base)
1251 test._dirlist = None
1252 sys.stdout = old_stdout
1254 def test_get_native_path(self):
1255 """Test the get_native_path() function."""
1257 filename = tempfile.mktemp()
1258 str = '1234567890 ' + filename
1260 open(filename, 'w').write(str)
1261 assert open(get_native_path(filename)).read() == str
1268 def test_subst_dict(self):
1269 """Test substituting dictionary values in an Action
1273 d = subst_dict(target=t, source=s)
1274 assert str(d['TARGETS'][0]) == 't', d['TARGETS']
1275 assert str(d['TARGET']) == 't', d['TARGET']
1276 assert str(d['SOURCES'][0]) == 's', d['SOURCES']
1277 assert str(d['SOURCE']) == 's', d['SOURCE']
1279 t1 = DummyNode('t1')
1280 t2 = DummyNode('t2')
1281 s1 = DummyNode('s1')
1282 s2 = DummyNode('s2')
1283 d = subst_dict(target=[t1, t2], source=[s1, s2])
1284 TARGETS = map(lambda x: str(x), d['TARGETS'])
1286 assert TARGETS == ['t1', 't2'], d['TARGETS']
1287 assert str(d['TARGET']) == 't1', d['TARGET']
1288 SOURCES = map(lambda x: str(x), d['SOURCES'])
1290 assert SOURCES == ['s1', 's2'], d['SOURCES']
1291 assert str(d['SOURCE']) == 's1', d['SOURCE']
1294 def __init__(self, name):
1299 return self.__class__('rstr-' + self.name)
1300 def get_subst_proxy(self):
1304 t4 = DummyNode('t4')
1305 s3 = DummyNode('s3')
1307 d = subst_dict(target=[t3, t4], source=[s3, s4])
1308 TARGETS = map(lambda x: str(x), d['TARGETS'])
1310 assert TARGETS == ['t3', 't4'], d['TARGETS']
1311 SOURCES = map(lambda x: str(x), d['SOURCES'])
1313 assert SOURCES == ['rstr-s4', 's3'], d['SOURCES']
1315 def test_PrependPath(self):
1316 """Test prepending to a path"""
1317 p1 = r'C:\dir\num\one;C:\dir\num\two'
1318 p2 = r'C:\mydir\num\one;C:\mydir\num\two'
1319 # have to include the pathsep here so that the test will work on UNIX too.
1320 p1 = PrependPath(p1,r'C:\dir\num\two',sep = ';')
1321 p1 = PrependPath(p1,r'C:\dir\num\three',sep = ';')
1322 p2 = PrependPath(p2,r'C:\mydir\num\three',sep = ';')
1323 p2 = PrependPath(p2,r'C:\mydir\num\one',sep = ';')
1324 assert(p1 == r'C:\dir\num\three;C:\dir\num\two;C:\dir\num\one')
1325 assert(p2 == r'C:\mydir\num\one;C:\mydir\num\three;C:\mydir\num\two')
1327 def test_AppendPath(self):
1328 """Test appending to a path."""
1329 p1 = r'C:\dir\num\one;C:\dir\num\two'
1330 p2 = r'C:\mydir\num\one;C:\mydir\num\two'
1331 # have to include the pathsep here so that the test will work on UNIX too.
1332 p1 = AppendPath(p1,r'C:\dir\num\two',sep = ';')
1333 p1 = AppendPath(p1,r'C:\dir\num\three',sep = ';')
1334 p2 = AppendPath(p2,r'C:\mydir\num\three',sep = ';')
1335 p2 = AppendPath(p2,r'C:\mydir\num\one',sep = ';')
1336 assert(p1 == r'C:\dir\num\one;C:\dir\num\two;C:\dir\num\three')
1337 assert(p2 == r'C:\mydir\num\two;C:\mydir\num\three;C:\mydir\num\one')
1339 def test_NodeList(self):
1340 """Test NodeList class"""
1342 def __init__(self, name, child=None):
1346 return self.bar + "foo"
1350 t1 = TestClass('t1', TestClass('t1child'))
1351 t2 = TestClass('t2', TestClass('t2child'))
1352 t3 = TestClass('t3')
1354 nl = NodeList([t1, t2, t3])
1355 assert nl.foo() == [ 't1foo', 't2foo', 't3foo' ], nl.foo()
1356 assert nl.bar == [ 't1', 't2', 't3' ], nl.bar
1357 assert nl.getself().bar == [ 't1', 't2', 't3' ], nl.getself().bar
1358 assert nl[0:2].child.foo() == [ 't1childfoo', 't2childfoo' ], \
1360 assert nl[0:2].child.bar == [ 't1child', 't2child' ], \
1363 def test_CLVar(self):
1364 """Test the command-line construction variable class"""
1365 f = SCons.Util.CLVar('a b')
1368 assert isinstance(r, SCons.Util.CLVar), type(r)
1369 assert r.data == ['a', 'b', 'c', 'd'], r.data
1370 assert str(r) == 'a b c d', str(r)
1373 assert isinstance(r, SCons.Util.CLVar), type(r)
1374 assert r.data == ['a', 'b', 'c', 'd'], r.data
1375 assert str(r) == 'a b c d', str(r)
1378 assert isinstance(r, SCons.Util.CLVar), type(r)
1379 assert r.data == ['a', 'b', 'c d'], r.data
1380 assert str(r) == 'a b c d', str(r)
1383 assert isinstance(r, SCons.Util.CLVar), type(r)
1384 assert r.data == ['a', 'b', ' c d'], r.data
1385 assert str(r) == 'a b c d', str(r)
1388 assert isinstance(r, SCons.Util.CLVar), type(r)
1389 assert r.data == ['a', 'b', 'c', 'd'], r.data
1390 assert str(r) == 'a b c d', str(r)
1393 assert isinstance(r, SCons.Util.CLVar), type(r)
1394 assert r.data == ['a', 'b', ' c', 'd'], r.data
1395 assert str(r) == 'a b c d', str(r)
1397 f = SCons.Util.CLVar(['a b'])
1400 assert isinstance(r, SCons.Util.CLVar), type(r)
1401 assert r.data == ['a b', 'c', 'd'], r.data
1402 assert str(r) == 'a b c d', str(r)
1405 assert isinstance(r, SCons.Util.CLVar), type(r)
1406 assert r.data == ['a b', 'c', 'd'], r.data
1407 assert str(r) == 'a b c d', str(r)
1410 assert isinstance(r, SCons.Util.CLVar), type(r)
1411 assert r.data == ['a b', 'c d'], r.data
1412 assert str(r) == 'a b c d', str(r)
1415 assert isinstance(r, SCons.Util.CLVar), type(r)
1416 assert r.data == ['a b', ' c d'], r.data
1417 assert str(r) == 'a b c d', str(r)
1420 assert isinstance(r, SCons.Util.CLVar), type(r)
1421 assert r.data == ['a b', 'c', 'd'], r.data
1422 assert str(r) == 'a b c d', str(r)
1425 assert isinstance(r, SCons.Util.CLVar), type(r)
1426 assert r.data == ['a b', ' c', 'd'], r.data
1427 assert str(r) == 'a b c d', str(r)
1429 f = SCons.Util.CLVar(['a', 'b'])
1432 assert isinstance(r, SCons.Util.CLVar), type(r)
1433 assert r.data == ['a', 'b', 'c', 'd'], r.data
1434 assert str(r) == 'a b c d', str(r)
1437 assert isinstance(r, SCons.Util.CLVar), type(r)
1438 assert r.data == ['a', 'b', 'c', 'd'], r.data
1439 assert str(r) == 'a b c d', str(r)
1442 assert isinstance(r, SCons.Util.CLVar), type(r)
1443 assert r.data == ['a', 'b', 'c d'], r.data
1444 assert str(r) == 'a b c d', str(r)
1447 assert isinstance(r, SCons.Util.CLVar), type(r)
1448 assert r.data == ['a', 'b', ' c d'], r.data
1449 assert str(r) == 'a b c d', str(r)
1452 assert isinstance(r, SCons.Util.CLVar), type(r)
1453 assert r.data == ['a', 'b', 'c', 'd'], r.data
1454 assert str(r) == 'a b c d', str(r)
1457 assert isinstance(r, SCons.Util.CLVar), type(r)
1458 assert r.data == ['a', 'b', ' c', 'd'], r.data
1459 assert str(r) == 'a b c d', str(r)
1463 loc['BAR'] = SCons.Util.CLVar('bar')
1464 loc['CALL'] = lambda target, source, env, for_signature: 'call'
1467 cmd = SCons.Util.CLVar("test $FOO $BAR $CALL test")
1469 newcmd = scons_subst(cmd, env)
1470 assert newcmd == 'test foo bar call test', newcmd
1472 cmd_list = scons_subst_list(cmd, env)
1473 assert len(cmd_list) == 1, cmd_list
1474 assert cmd_list[0][0] == "test", cmd_list[0][0]
1475 assert cmd_list[0][1] == "foo", cmd_list[0][1]
1476 assert cmd_list[0][2] == "bar", cmd_list[0][2]
1477 assert cmd_list[0][3] == "call", cmd_list[0][3]
1478 assert cmd_list[0][4] == "test", cmd_list[0][4]
1480 def test_Selector(self):
1481 """Test the Selector class"""
1483 s = Selector({'a' : 'AAA', 'b' : 'BBB'})
1484 assert s['a'] == 'AAA', s['a']
1485 assert s['b'] == 'BBB', s['b']
1491 assert exc_caught, "should have caught a KeyError"
1493 assert s['c'] == 'CCC', s['c']
1495 class DummyEnv(UserDict.UserDict):
1496 def subst(self, key):
1498 return self[key[1:]]
1503 s = Selector({'.d' : 'DDD', '.e' : 'EEE'})
1504 ret = s(env, ['foo.d'])
1505 assert ret == 'DDD', ret
1506 ret = s(env, ['bar.e'])
1507 assert ret == 'EEE', ret
1508 ret = s(env, ['bar.x'])
1509 assert ret == None, ret
1511 ret = s(env, ['bar.x'])
1512 assert ret == 'XXX', ret
1514 env = DummyEnv({'FSUFF' : '.f', 'GSUFF' : '.g'})
1516 s = Selector({'$FSUFF' : 'FFF', '$GSUFF' : 'GGG'})
1517 ret = s(env, ['foo.f'])
1518 assert ret == 'FFF', ret
1519 ret = s(env, ['bar.g'])
1520 assert ret == 'GGG', ret
1522 def test_adjustixes(self):
1523 """Test the adjustixes() function"""
1524 r = adjustixes('file', 'pre-', '-suf')
1525 assert r == 'pre-file-suf', r
1526 r = adjustixes('pre-file', 'pre-', '-suf')
1527 assert r == 'pre-file-suf', r
1528 r = adjustixes('file-suf', 'pre-', '-suf')
1529 assert r == 'pre-file-suf', r
1530 r = adjustixes('pre-file-suf', 'pre-', '-suf')
1531 assert r == 'pre-file-suf', r
1532 r = adjustixes('pre-file.xxx', 'pre-', '-suf')
1533 assert r == 'pre-file.xxx', r
1534 r = adjustixes('dir/file', 'pre-', '-suf')
1535 assert r == os.path.join('dir', 'pre-file-suf'), r
1537 def test_containsAny(self):
1538 """Test the containsAny() function"""
1539 assert containsAny('*.py', '*?[]')
1540 assert not containsAny('file.txt', '*?[]')
1542 def test_containsAll(self):
1543 """Test the containsAll() function"""
1544 assert containsAll('43221', '123')
1545 assert not containsAll('134', '123')
1547 def test_containsOnly(self):
1548 """Test the containsOnly() function"""
1549 assert containsOnly('.83', '0123456789.')
1550 assert not containsOnly('43221', '123')
1552 if __name__ == "__main__":
1553 suite = unittest.makeSuite(UtilTestCase, 'test_')
1554 if not unittest.TextTestRunner().run(suite).wasSuccessful():