1#
2# SPDX-License-Identifier: MIT
3#
4
5import os
6import re
7
8import oeqa.utils.ftools as ftools
9from oeqa.utils.commands import runCmd, bitbake, get_bb_var, get_bb_vars
10
11from oeqa.selftest.case import OESelftestTestCase
12
13class BitbakeTests(OESelftestTestCase):
14
15    def getline(self, res, line):
16        for l in res.output.split('\n'):
17            if line in l:
18                return l
19
20    # Test bitbake can run from the <builddir>/conf directory
21    def test_run_bitbake_from_dir_1(self):
22        os.chdir(os.path.join(self.builddir, 'conf'))
23        self.assertEqual(bitbake('-e').status, 0, msg = "bitbake couldn't run from \"conf\" dir")
24
25    # Test bitbake can run from the <builddir>'s parent directory
26    def test_run_bitbake_from_dir_2(self):
27        my_env = os.environ.copy()
28        my_env['BBPATH'] = my_env['BUILDDIR']
29        os.chdir(os.path.dirname(os.environ['BUILDDIR']))
30        self.assertEqual(bitbake('-e', env=my_env).status, 0, msg = "bitbake couldn't run from builddir's parent directory")
31
32    # Test bitbake can run from some other random system location (we use /tmp/)
33    def test_run_bitbake_from_dir_3(self):
34        my_env = os.environ.copy()
35        my_env['BBPATH'] = my_env['BUILDDIR']
36        os.chdir("/tmp/")
37        self.assertEqual(bitbake('-e', env=my_env).status, 0, msg = "bitbake couldn't run from /tmp/")
38
39
40    def test_event_handler(self):
41        self.write_config("INHERIT += \"test_events\"")
42        result = bitbake('m4-native')
43        find_build_started = re.search(r"NOTE: Test for bb\.event\.BuildStarted(\n.*)*NOTE: Executing.*Tasks", result.output)
44        find_build_completed = re.search(r"Tasks Summary:.*(\n.*)*NOTE: Test for bb\.event\.BuildCompleted", result.output)
45        self.assertTrue(find_build_started, msg = "Match failed in:\n%s"  % result.output)
46        self.assertTrue(find_build_completed, msg = "Match failed in:\n%s" % result.output)
47        self.assertNotIn('Test for bb.event.InvalidEvent', result.output)
48
49    def test_local_sstate(self):
50        bitbake('m4-native')
51        bitbake('m4-native -cclean')
52        result = bitbake('m4-native')
53        find_setscene = re.search("m4-native.*do_.*_setscene", result.output)
54        self.assertTrue(find_setscene, msg = "No \"m4-native.*do_.*_setscene\" message found during bitbake m4-native. bitbake output: %s" % result.output )
55
56    def test_bitbake_invalid_recipe(self):
57        result = bitbake('-b asdf', ignore_status=True)
58        self.assertTrue("ERROR: Unable to find any recipe file matching 'asdf'" in result.output, msg = "Though asdf recipe doesn't exist, bitbake didn't output any err. message. bitbake output: %s" % result.output)
59
60    def test_bitbake_invalid_target(self):
61        result = bitbake('asdf', ignore_status=True)
62        self.assertIn("ERROR: Nothing PROVIDES 'asdf'", result.output)
63
64    def test_warnings_errors(self):
65        result = bitbake('-b asdf', ignore_status=True)
66        find_warnings = re.search("Summary: There w.{2,3}? [1-9][0-9]* WARNING messages* shown", result.output)
67        find_errors = re.search("Summary: There w.{2,3}? [1-9][0-9]* ERROR messages* shown", result.output)
68        self.assertTrue(find_warnings, msg="Did not find the mumber of warnings at the end of the build:\n" + result.output)
69        self.assertTrue(find_errors, msg="Did not find the mumber of errors at the end of the build:\n" + result.output)
70
71    def test_invalid_patch(self):
72        # This patch should fail to apply.
73        self.write_recipeinc('man-db', 'FILESEXTRAPATHS_prepend := "${THISDIR}/files:"\nSRC_URI += "file://0001-Test-patch-here.patch"')
74        self.write_config("INHERIT_remove = \"report-error\"")
75        result = bitbake('man-db -c patch', ignore_status=True)
76        self.delete_recipeinc('man-db')
77        bitbake('-cclean man-db')
78        found = False
79        for l in result.output.split('\n'):
80            if l.startswith("ERROR:") and "failed" in l and "do_patch" in l:
81                found = l
82        self.assertTrue(found and found.startswith("ERROR:"), msg = "Incorrectly formed patch application didn't fail. bitbake output: %s" % result.output)
83
84    def test_force_task_1(self):
85        # test 1 from bug 5875
86        test_recipe = 'zlib'
87        test_data = "Microsoft Made No Profit From Anyone's Zunes Yo"
88        bb_vars = get_bb_vars(['D', 'PKGDEST', 'mandir'], test_recipe)
89        image_dir = bb_vars['D']
90        pkgsplit_dir = bb_vars['PKGDEST']
91        man_dir = bb_vars['mandir']
92        self.write_config("PACKAGE_CLASSES = \"package_rpm\"")
93
94        bitbake('-c clean %s' % test_recipe)
95        bitbake('-c package -f %s' % test_recipe)
96        self.add_command_to_tearDown('bitbake -c clean %s' % test_recipe)
97
98        man_file = os.path.join(image_dir + man_dir, 'man3/zlib.3')
99        ftools.append_file(man_file, test_data)
100        bitbake('-c package -f %s' % test_recipe)
101
102        man_split_file = os.path.join(pkgsplit_dir, 'zlib-doc' + man_dir, 'man3/zlib.3')
103        man_split_content = ftools.read_file(man_split_file)
104        self.assertIn(test_data, man_split_content, 'The man file has not changed in packages-split.')
105
106        ret = bitbake(test_recipe)
107        self.assertIn('task do_package_write_rpm:', ret.output, 'Task do_package_write_rpm did not re-executed.')
108
109    def test_force_task_2(self):
110        # test 2 from bug 5875
111        test_recipe = 'zlib'
112
113        bitbake(test_recipe)
114        self.add_command_to_tearDown('bitbake -c clean %s' % test_recipe)
115
116        result = bitbake('-C compile %s' % test_recipe)
117        look_for_tasks = ['do_compile:', 'do_install:', 'do_populate_sysroot:', 'do_package:']
118        for task in look_for_tasks:
119            self.assertIn(task, result.output, msg="Couldn't find %s task.")
120
121    def test_bitbake_g(self):
122        recipe = 'base-files'
123        result = bitbake('-g %s' % recipe)
124        for f in ['pn-buildlist', 'task-depends.dot']:
125            self.addCleanup(os.remove, f)
126        self.assertTrue('Task dependencies saved to \'task-depends.dot\'' in result.output, msg = "No task dependency \"task-depends.dot\" file was generated for the given task target. bitbake output: %s" % result.output)
127        self.assertIn(recipe, ftools.read_file(os.path.join(self.builddir, 'task-depends.dot')))
128
129    def test_image_manifest(self):
130        bitbake('core-image-minimal')
131        bb_vars = get_bb_vars(["DEPLOY_DIR_IMAGE", "IMAGE_LINK_NAME"], "core-image-minimal")
132        deploydir = bb_vars["DEPLOY_DIR_IMAGE"]
133        imagename = bb_vars["IMAGE_LINK_NAME"]
134        manifest = os.path.join(deploydir, imagename + ".manifest")
135        self.assertTrue(os.path.islink(manifest), msg="No manifest file created for image. It should have been created in %s" % manifest)
136
137    def test_invalid_recipe_src_uri(self):
138        data = 'SRC_URI = "file://invalid"'
139        self.write_recipeinc('man-db', data)
140        self.write_config("""DL_DIR = \"${TOPDIR}/download-selftest\"
141SSTATE_DIR = \"${TOPDIR}/download-selftest\"
142INHERIT_remove = \"report-error\"
143""")
144        self.track_for_cleanup(os.path.join(self.builddir, "download-selftest"))
145
146        bitbake('-ccleanall man-db')
147        result = bitbake('-c fetch man-db', ignore_status=True)
148        bitbake('-ccleanall man-db')
149        self.delete_recipeinc('man-db')
150        self.assertEqual(result.status, 1, msg="Command succeded when it should have failed. bitbake output: %s" % result.output)
151        self.assertIn('Fetcher failure: Unable to find file file://invalid anywhere. The paths that were searched were:', result.output)
152        line = self.getline(result, 'Fetcher failure for URL: \'file://invalid\'. Unable to fetch URL from any source.')
153        self.assertTrue(line and line.startswith("ERROR:"), msg = "\"invalid\" file \
154doesn't exist, yet fetcher didn't report any error. bitbake output: %s" % result.output)
155
156    def test_rename_downloaded_file(self):
157        # TODO unique dldir instead of using cleanall
158        # TODO: need to set sstatedir?
159        self.write_config("""DL_DIR = \"${TOPDIR}/download-selftest\"
160SSTATE_DIR = \"${TOPDIR}/download-selftest\"
161""")
162        self.track_for_cleanup(os.path.join(self.builddir, "download-selftest"))
163
164        data = 'SRC_URI = "${GNU_MIRROR}/aspell/aspell-${PV}.tar.gz;downloadfilename=test-aspell.tar.gz"'
165        self.write_recipeinc('aspell', data)
166        result = bitbake('-f -c fetch aspell', ignore_status=True)
167        self.delete_recipeinc('aspell')
168        self.assertEqual(result.status, 0, msg = "Couldn't fetch aspell. %s" % result.output)
169        dl_dir = get_bb_var("DL_DIR")
170        self.assertTrue(os.path.isfile(os.path.join(dl_dir, 'test-aspell.tar.gz')), msg = "File rename failed. No corresponding test-aspell.tar.gz file found under %s" % dl_dir)
171        self.assertTrue(os.path.isfile(os.path.join(dl_dir, 'test-aspell.tar.gz.done')), "File rename failed. No corresponding test-aspell.tar.gz.done file found under %s" % dl_dir)
172
173    def test_environment(self):
174        self.write_config("TEST_ENV=\"localconf\"")
175        result = runCmd('bitbake -e | grep TEST_ENV=')
176        self.assertIn('localconf', result.output)
177
178    def test_dry_run(self):
179        result = runCmd('bitbake -n m4-native')
180        self.assertEqual(0, result.status, "bitbake dry run didn't run as expected. %s" % result.output)
181
182    def test_just_parse(self):
183        result = runCmd('bitbake -p')
184        self.assertEqual(0, result.status, "errors encountered when parsing recipes. %s" % result.output)
185
186    def test_version(self):
187        result = runCmd('bitbake -s | grep wget')
188        find = re.search(r"wget *:([0-9a-zA-Z\.\-]+)", result.output)
189        self.assertTrue(find, "No version returned for searched recipe. bitbake output: %s" % result.output)
190
191    def test_prefile(self):
192        preconf = os.path.join(self.builddir, 'conf/prefile.conf')
193        self.track_for_cleanup(preconf)
194        ftools.write_file(preconf ,"TEST_PREFILE=\"prefile\"")
195        result = runCmd('bitbake -r conf/prefile.conf -e | grep TEST_PREFILE=')
196        self.assertIn('prefile', result.output)
197        self.write_config("TEST_PREFILE=\"localconf\"")
198        result = runCmd('bitbake -r conf/prefile.conf -e | grep TEST_PREFILE=')
199        self.assertIn('localconf', result.output)
200
201    def test_postfile(self):
202        postconf = os.path.join(self.builddir, 'conf/postfile.conf')
203        self.track_for_cleanup(postconf)
204        ftools.write_file(postconf , "TEST_POSTFILE=\"postfile\"")
205        self.write_config("TEST_POSTFILE=\"localconf\"")
206        result = runCmd('bitbake -R conf/postfile.conf -e | grep TEST_POSTFILE=')
207        self.assertIn('postfile', result.output)
208
209    def test_checkuri(self):
210        result = runCmd('bitbake -c checkuri m4')
211        self.assertEqual(0, result.status, msg = "\"checkuri\" task was not executed. bitbake output: %s" % result.output)
212
213    def test_continue(self):
214        self.write_config("""DL_DIR = \"${TOPDIR}/download-selftest\"
215SSTATE_DIR = \"${TOPDIR}/download-selftest\"
216INHERIT_remove = \"report-error\"
217""")
218        self.track_for_cleanup(os.path.join(self.builddir, "download-selftest"))
219        self.write_recipeinc('man-db',"\ndo_fail_task () {\nexit 1 \n}\n\naddtask do_fail_task before do_fetch\n" )
220        runCmd('bitbake -c cleanall man-db xcursor-transparent-theme')
221        result = runCmd('bitbake -c unpack -k man-db xcursor-transparent-theme', ignore_status=True)
222        errorpos = result.output.find('ERROR: Function failed: do_fail_task')
223        manver = re.search("NOTE: recipe xcursor-transparent-theme-(.*?): task do_unpack: Started", result.output)
224        continuepos = result.output.find('NOTE: recipe xcursor-transparent-theme-%s: task do_unpack: Started' % manver.group(1))
225        self.assertLess(errorpos,continuepos, msg = "bitbake didn't pass do_fail_task. bitbake output: %s" % result.output)
226
227    def test_non_gplv3(self):
228        self.write_config('INCOMPATIBLE_LICENSE = "GPLv3"')
229        result = bitbake('selftest-ed', ignore_status=True)
230        self.assertEqual(result.status, 0, "Bitbake failed, exit code %s, output %s" % (result.status, result.output))
231        lic_dir = get_bb_var('LICENSE_DIRECTORY')
232        self.assertFalse(os.path.isfile(os.path.join(lic_dir, 'selftest-ed/generic_GPLv3')))
233        self.assertTrue(os.path.isfile(os.path.join(lic_dir, 'selftest-ed/generic_GPLv2')))
234
235    def test_setscene_only(self):
236        """ Bitbake option to restore from sstate only within a build (i.e. execute no real tasks, only setscene)"""
237        test_recipe = 'ed'
238
239        bitbake(test_recipe)
240        bitbake('-c clean %s' % test_recipe)
241        ret = bitbake('--setscene-only %s' % test_recipe)
242
243        tasks = re.findall(r'task\s+(do_\S+):', ret.output)
244
245        for task in tasks:
246            self.assertIn('_setscene', task, 'A task different from _setscene ran: %s.\n'
247                                             'Executed tasks were: %s' % (task, str(tasks)))
248
249    def test_skip_setscene(self):
250        test_recipe = 'ed'
251
252        bitbake(test_recipe)
253        bitbake('-c clean %s' % test_recipe)
254
255        ret = bitbake('--setscene-only %s' % test_recipe)
256        tasks = re.findall(r'task\s+(do_\S+):', ret.output)
257
258        for task in tasks:
259            self.assertIn('_setscene', task, 'A task different from _setscene ran: %s.\n'
260                                             'Executed tasks were: %s' % (task, str(tasks)))
261
262        # Run without setscene. Should do nothing
263        ret = bitbake('--skip-setscene %s' % test_recipe)
264        tasks = re.findall(r'task\s+(do_\S+):', ret.output)
265
266        self.assertFalse(tasks, 'Tasks %s ran when they should not have' % (str(tasks)))
267
268        # Clean (leave sstate cache) and run with --skip-setscene. No setscene
269        # tasks should run
270        bitbake('-c clean %s' % test_recipe)
271
272        ret = bitbake('--skip-setscene %s' % test_recipe)
273        tasks = re.findall(r'task\s+(do_\S+):', ret.output)
274
275        for task in tasks:
276            self.assertNotIn('_setscene', task, 'A _setscene task ran: %s.\n'
277                                                'Executed tasks were: %s' % (task, str(tasks)))
278
279    def test_bbappend_order(self):
280        """ Bitbake should bbappend to recipe in a predictable order """
281        test_recipe = 'ed'
282        bb_vars = get_bb_vars(['SUMMARY', 'PV'], test_recipe)
283        test_recipe_summary_before = bb_vars['SUMMARY']
284        test_recipe_pv = bb_vars['PV']
285        recipe_append_file = test_recipe + '_' + test_recipe_pv + '.bbappend'
286        expected_recipe_summary = test_recipe_summary_before
287
288        for i in range(5):
289            recipe_append_dir = test_recipe + '_test_' + str(i)
290            recipe_append_path = os.path.join(self.testlayer_path, 'recipes-test', recipe_append_dir, recipe_append_file)
291            os.mkdir(os.path.join(self.testlayer_path, 'recipes-test', recipe_append_dir))
292            feature = 'SUMMARY += "%s"\n' % i
293            ftools.write_file(recipe_append_path, feature)
294            expected_recipe_summary += ' %s' % i
295
296        self.add_command_to_tearDown('rm -rf %s' % os.path.join(self.testlayer_path, 'recipes-test',
297                                                               test_recipe + '_test_*'))
298
299        test_recipe_summary_after = get_bb_var('SUMMARY', test_recipe)
300        self.assertEqual(expected_recipe_summary, test_recipe_summary_after)
301