blob: e30e78c1580f7921aac6ba843abfad544e87f31e [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001# ex:ts=4:sw=4:sts=4:et
2# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
3#
4# BitBake Test for codeparser.py
5#
6# Copyright (C) 2010 Chris Larson
7# Copyright (C) 2012 Richard Purdie
8#
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License version 2 as
11# published by the Free Software Foundation.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License along
19# with this program; if not, write to the Free Software Foundation, Inc.,
20# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21#
22
23import unittest
24import logging
25import bb
26
27logger = logging.getLogger('BitBake.TestCodeParser')
28
29# bb.data references bb.parse but can't directly import due to circular dependencies.
30# Hack around it for now :(
31import bb.parse
32import bb.data
33
34class ReferenceTest(unittest.TestCase):
35 def setUp(self):
36 self.d = bb.data.init()
37
38 def setEmptyVars(self, varlist):
39 for k in varlist:
40 self.d.setVar(k, "")
41
42 def setValues(self, values):
43 for k, v in values.items():
44 self.d.setVar(k, v)
45
46 def assertReferences(self, refs):
47 self.assertEqual(self.references, refs)
48
49 def assertExecs(self, execs):
50 self.assertEqual(self.execs, execs)
51
Brad Bishop6e60e8b2018-02-01 10:27:11 -050052 def assertContains(self, contains):
53 self.assertEqual(self.contains, contains)
54
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055class VariableReferenceTest(ReferenceTest):
56
57 def parseExpression(self, exp):
58 parsedvar = self.d.expandWithRefs(exp, None)
59 self.references = parsedvar.references
60
61 def test_simple_reference(self):
62 self.setEmptyVars(["FOO"])
63 self.parseExpression("${FOO}")
64 self.assertReferences(set(["FOO"]))
65
66 def test_nested_reference(self):
67 self.setEmptyVars(["BAR"])
68 self.d.setVar("FOO", "BAR")
69 self.parseExpression("${${FOO}}")
70 self.assertReferences(set(["FOO", "BAR"]))
71
72 def test_python_reference(self):
73 self.setEmptyVars(["BAR"])
Brad Bishop6e60e8b2018-02-01 10:27:11 -050074 self.parseExpression("${@d.getVar('BAR') + 'foo'}")
Patrick Williamsc124f4f2015-09-15 14:41:29 -050075 self.assertReferences(set(["BAR"]))
76
77class ShellReferenceTest(ReferenceTest):
78
79 def parseExpression(self, exp):
80 parsedvar = self.d.expandWithRefs(exp, None)
81 parser = bb.codeparser.ShellParser("ParserTest", logger)
82 parser.parse_shell(parsedvar.value)
83
84 self.references = parsedvar.references
85 self.execs = parser.execs
86
87 def test_quotes_inside_assign(self):
88 self.parseExpression('foo=foo"bar"baz')
89 self.assertReferences(set([]))
90
91 def test_quotes_inside_arg(self):
92 self.parseExpression('sed s#"bar baz"#"alpha beta"#g')
93 self.assertExecs(set(["sed"]))
94
95 def test_arg_continuation(self):
96 self.parseExpression("sed -i -e s,foo,bar,g \\\n *.pc")
97 self.assertExecs(set(["sed"]))
98
99 def test_dollar_in_quoted(self):
100 self.parseExpression('sed -i -e "foo$" *.pc')
101 self.assertExecs(set(["sed"]))
102
103 def test_quotes_inside_arg_continuation(self):
104 self.setEmptyVars(["bindir", "D", "libdir"])
105 self.parseExpression("""
106sed -i -e s#"moc_location=.*$"#"moc_location=${bindir}/moc4"# \\
107-e s#"uic_location=.*$"#"uic_location=${bindir}/uic4"# \\
108${D}${libdir}/pkgconfig/*.pc
109""")
110 self.assertReferences(set(["bindir", "D", "libdir"]))
111
112 def test_assign_subshell_expansion(self):
113 self.parseExpression("foo=$(echo bar)")
114 self.assertExecs(set(["echo"]))
115
116 def test_shell_unexpanded(self):
117 self.setEmptyVars(["QT_BASE_NAME"])
118 self.parseExpression('echo "${QT_BASE_NAME}"')
119 self.assertExecs(set(["echo"]))
120 self.assertReferences(set(["QT_BASE_NAME"]))
121
122 def test_incomplete_varexp_single_quotes(self):
123 self.parseExpression("sed -i -e 's:IP{:I${:g' $pc")
124 self.assertExecs(set(["sed"]))
125
126
127 def test_until(self):
128 self.parseExpression("until false; do echo true; done")
129 self.assertExecs(set(["false", "echo"]))
130 self.assertReferences(set())
131
132 def test_case(self):
133 self.parseExpression("""
134case $foo in
135*)
136bar
137;;
138esac
139""")
140 self.assertExecs(set(["bar"]))
141 self.assertReferences(set())
142
143 def test_assign_exec(self):
144 self.parseExpression("a=b c='foo bar' alpha 1 2 3")
145 self.assertExecs(set(["alpha"]))
146
147 def test_redirect_to_file(self):
148 self.setEmptyVars(["foo"])
149 self.parseExpression("echo foo >${foo}/bar")
150 self.assertExecs(set(["echo"]))
151 self.assertReferences(set(["foo"]))
152
153 def test_heredoc(self):
154 self.setEmptyVars(["theta"])
155 self.parseExpression("""
156cat <<END
157alpha
158beta
159${theta}
160END
161""")
162 self.assertReferences(set(["theta"]))
163
164 def test_redirect_from_heredoc(self):
165 v = ["B", "SHADOW_MAILDIR", "SHADOW_MAILFILE", "SHADOW_UTMPDIR", "SHADOW_LOGDIR", "bindir"]
166 self.setEmptyVars(v)
167 self.parseExpression("""
168cat <<END >${B}/cachedpaths
169shadow_cv_maildir=${SHADOW_MAILDIR}
170shadow_cv_mailfile=${SHADOW_MAILFILE}
171shadow_cv_utmpdir=${SHADOW_UTMPDIR}
172shadow_cv_logdir=${SHADOW_LOGDIR}
173shadow_cv_passwd_dir=${bindir}
174END
175""")
176 self.assertReferences(set(v))
177 self.assertExecs(set(["cat"]))
178
179# def test_incomplete_command_expansion(self):
180# self.assertRaises(reftracker.ShellSyntaxError, reftracker.execs,
181# bbvalue.shparse("cp foo`", self.d), self.d)
182
183# def test_rogue_dollarsign(self):
184# self.setValues({"D" : "/tmp"})
185# self.parseExpression("install -d ${D}$")
186# self.assertReferences(set(["D"]))
187# self.assertExecs(set(["install"]))
188
189
190class PythonReferenceTest(ReferenceTest):
191
192 def setUp(self):
193 self.d = bb.data.init()
194 if hasattr(bb.utils, "_context"):
195 self.context = bb.utils._context
196 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600197 import builtins
198 self.context = builtins.__dict__
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500199
200 def parseExpression(self, exp):
201 parsedvar = self.d.expandWithRefs(exp, None)
202 parser = bb.codeparser.PythonParser("ParserTest", logger)
203 parser.parse_python(parsedvar.value)
204
205 self.references = parsedvar.references | parser.references
206 self.execs = parser.execs
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500207 self.contains = parser.contains
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500208
209 @staticmethod
210 def indent(value):
211 """Python Snippets have to be indented, python values don't have to
212be. These unit tests are testing snippets."""
213 return " " + value
214
215 def test_getvar_reference(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500216 self.parseExpression("d.getVar('foo')")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500217 self.assertReferences(set(["foo"]))
218 self.assertExecs(set())
219
220 def test_getvar_computed_reference(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500221 self.parseExpression("d.getVar('f' + 'o' + 'o')")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500222 self.assertReferences(set())
223 self.assertExecs(set())
224
225 def test_getvar_exec_reference(self):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500226 self.parseExpression("eval('d.getVar(\"foo\")')")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500227 self.assertReferences(set())
228 self.assertExecs(set(["eval"]))
229
230 def test_var_reference(self):
231 self.context["foo"] = lambda x: x
232 self.setEmptyVars(["FOO"])
233 self.parseExpression("foo('${FOO}')")
234 self.assertReferences(set(["FOO"]))
235 self.assertExecs(set(["foo"]))
236 del self.context["foo"]
237
238 def test_var_exec(self):
239 for etype in ("func", "task"):
240 self.d.setVar("do_something", "echo 'hi mom! ${FOO}'")
241 self.d.setVarFlag("do_something", etype, True)
242 self.parseExpression("bb.build.exec_func('do_something', d)")
243 self.assertReferences(set([]))
244 self.assertExecs(set(["do_something"]))
245
246 def test_function_reference(self):
247 self.context["testfunc"] = lambda msg: bb.msg.note(1, None, msg)
248 self.d.setVar("FOO", "Hello, World!")
249 self.parseExpression("testfunc('${FOO}')")
250 self.assertReferences(set(["FOO"]))
251 self.assertExecs(set(["testfunc"]))
252 del self.context["testfunc"]
253
254 def test_qualified_function_reference(self):
255 self.parseExpression("time.time()")
256 self.assertExecs(set(["time.time"]))
257
258 def test_qualified_function_reference_2(self):
259 self.parseExpression("os.path.dirname('/foo/bar')")
260 self.assertExecs(set(["os.path.dirname"]))
261
262 def test_qualified_function_reference_nested(self):
263 self.parseExpression("time.strftime('%Y%m%d',time.gmtime())")
264 self.assertExecs(set(["time.strftime", "time.gmtime"]))
265
266 def test_function_reference_chained(self):
267 self.context["testget"] = lambda: "\tstrip me "
268 self.parseExpression("testget().strip()")
269 self.assertExecs(set(["testget"]))
270 del self.context["testget"]
271
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500272 def test_contains(self):
273 self.parseExpression('bb.utils.contains("TESTVAR", "one", "true", "false", d)')
274 self.assertContains({'TESTVAR': {'one'}})
275
276 def test_contains_multi(self):
277 self.parseExpression('bb.utils.contains("TESTVAR", "one two", "true", "false", d)')
278 self.assertContains({'TESTVAR': {'one two'}})
279
280 def test_contains_any(self):
281 self.parseExpression('bb.utils.contains_any("TESTVAR", "hello", "true", "false", d)')
282 self.assertContains({'TESTVAR': {'hello'}})
283
284 def test_contains_any_multi(self):
285 self.parseExpression('bb.utils.contains_any("TESTVAR", "one two three", "true", "false", d)')
286 self.assertContains({'TESTVAR': {'one', 'two', 'three'}})
287
288 def test_contains_filter(self):
289 self.parseExpression('bb.utils.filter("TESTVAR", "hello there world", d)')
290 self.assertContains({'TESTVAR': {'hello', 'there', 'world'}})
291
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500292
293class DependencyReferenceTest(ReferenceTest):
294
295 pydata = """
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500296d.getVar('somevar')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500297def test(d):
298 foo = 'bar %s' % 'foo'
299def test2(d):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500300 d.getVar(foo)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500301 d.getVar('bar', False)
302 test2(d)
303
304def a():
305 \"\"\"some
306 stuff
307 \"\"\"
308 return "heh"
309
310test(d)
311
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500312d.expand(d.getVar("something", False))
313d.expand("${inexpand} somethingelse")
314d.getVar(a(), False)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500315"""
316
317 def test_python(self):
318 self.d.setVar("FOO", self.pydata)
319 self.setEmptyVars(["inexpand", "a", "test2", "test"])
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500320 self.d.setVarFlags("FOO", {
321 "func": True,
322 "python": True,
323 "lineno": 1,
324 "filename": "example.bb",
325 })
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500326
327 deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), self.d)
328
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600329 self.assertEqual(deps, set(["somevar", "bar", "something", "inexpand", "test", "test2", "a"]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500330
331
332 shelldata = """
333foo () {
334bar
335}
336{
337echo baz
338$(heh)
339eval `moo`
340}
341a=b
342c=d
343(
344true && false
345test -f foo
346testval=something
347$testval
348) || aiee
349! inverted
350echo ${somevar}
351
352case foo in
353bar)
354echo bar
355;;
356baz)
357echo baz
358;;
359foo*)
360echo foo
361;;
362esac
363"""
364
365 def test_shell(self):
366 execs = ["bar", "echo", "heh", "moo", "true", "aiee"]
367 self.d.setVar("somevar", "heh")
368 self.d.setVar("inverted", "echo inverted...")
369 self.d.setVarFlag("inverted", "func", True)
370 self.d.setVar("FOO", self.shelldata)
371 self.d.setVarFlags("FOO", {"func": True})
372 self.setEmptyVars(execs)
373
374 deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), self.d)
375
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600376 self.assertEqual(deps, set(["somevar", "inverted"] + execs))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500377
378
379 def test_vardeps(self):
380 self.d.setVar("oe_libinstall", "echo test")
381 self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
382 self.d.setVarFlag("FOO", "vardeps", "oe_libinstall")
383
384 deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), self.d)
385
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600386 self.assertEqual(deps, set(["oe_libinstall"]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500387
388 def test_vardeps_expand(self):
389 self.d.setVar("oe_libinstall", "echo test")
390 self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
391 self.d.setVarFlag("FOO", "vardeps", "${@'oe_libinstall'}")
392
393 deps, values = bb.data.build_dependencies("FOO", set(self.d.keys()), set(), set(), self.d)
394
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600395 self.assertEqual(deps, set(["oe_libinstall"]))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500396
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500397 def test_contains_vardeps(self):
398 expr = '${@bb.utils.filter("TESTVAR", "somevalue anothervalue", d)} \
399 ${@bb.utils.contains("TESTVAR", "testval testval2", "yetanothervalue", "", d)} \
400 ${@bb.utils.contains("TESTVAR", "testval2 testval3", "blah", "", d)} \
401 ${@bb.utils.contains_any("TESTVAR", "testval2 testval3", "lastone", "", d)}'
402 parsedvar = self.d.expandWithRefs(expr, None)
403 # Check contains
404 self.assertEqual(parsedvar.contains, {'TESTVAR': {'testval2 testval3', 'anothervalue', 'somevalue', 'testval testval2', 'testval2', 'testval3'}})
405 # Check dependencies
406 self.d.setVar('ANOTHERVAR', expr)
407 self.d.setVar('TESTVAR', 'anothervalue testval testval2')
408 deps, values = bb.data.build_dependencies("ANOTHERVAR", set(self.d.keys()), set(), set(), self.d)
409 self.assertEqual(sorted(values.splitlines()),
410 sorted([expr,
411 'TESTVAR{anothervalue} = Set',
412 'TESTVAR{somevalue} = Unset',
413 'TESTVAR{testval testval2} = Set',
414 'TESTVAR{testval2 testval3} = Unset',
415 'TESTVAR{testval2} = Set',
416 'TESTVAR{testval3} = Unset'
417 ]))
418 # Check final value
419 self.assertEqual(self.d.getVar('ANOTHERVAR').split(), ['anothervalue', 'yetanothervalue', 'lastone'])
420
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500421 #Currently no wildcard support
422 #def test_vardeps_wildcards(self):
423 # self.d.setVar("oe_libinstall", "echo test")
424 # self.d.setVar("FOO", "foo=oe_libinstall; eval $foo")
425 # self.d.setVarFlag("FOO", "vardeps", "oe_*")
426 # self.assertEquals(deps, set(["oe_libinstall"]))
427
428