1#
2# Copyright OpenEmbedded Contributors
3#
4# SPDX-License-Identifier: MIT
5#
6
7import os
8import re
9import time
10import logging
11import bb.tinfoil
12
13from oeqa.selftest.case import OESelftestTestCase
14
15class TinfoilTests(OESelftestTestCase):
16    """ Basic tests for the tinfoil API """
17
18    def test_getvar(self):
19        with bb.tinfoil.Tinfoil() as tinfoil:
20            tinfoil.prepare(True)
21            machine = tinfoil.config_data.getVar('MACHINE')
22            if not machine:
23                self.fail('Unable to get MACHINE value - returned %s' % machine)
24
25    def test_expand(self):
26        with bb.tinfoil.Tinfoil() as tinfoil:
27            tinfoil.prepare(True)
28            expr = '${@os.getpid()}'
29            pid = tinfoil.config_data.expand(expr)
30            if not pid:
31                self.fail('Unable to expand "%s" - returned %s' % (expr, pid))
32
33    def test_getvar_bb_origenv(self):
34        with bb.tinfoil.Tinfoil() as tinfoil:
35            tinfoil.prepare(True)
36            origenv = tinfoil.config_data.getVar('BB_ORIGENV', False)
37            if not origenv:
38                self.fail('Unable to get BB_ORIGENV value - returned %s' % origenv)
39            self.assertEqual(origenv.getVar('HOME', False), os.environ['HOME'])
40
41    def test_parse_recipe(self):
42        with bb.tinfoil.Tinfoil() as tinfoil:
43            tinfoil.prepare(config_only=False, quiet=2)
44            testrecipe = 'mdadm'
45            best = tinfoil.find_best_provider(testrecipe)
46            if not best:
47                self.fail('Unable to find recipe providing %s' % testrecipe)
48            rd = tinfoil.parse_recipe_file(best[3])
49            self.assertEqual(testrecipe, rd.getVar('PN'))
50
51    def test_parse_recipe_copy_expand(self):
52        with bb.tinfoil.Tinfoil() as tinfoil:
53            tinfoil.prepare(config_only=False, quiet=2)
54            testrecipe = 'mdadm'
55            best = tinfoil.find_best_provider(testrecipe)
56            if not best:
57                self.fail('Unable to find recipe providing %s' % testrecipe)
58            rd = tinfoil.parse_recipe_file(best[3])
59            # Check we can get variable values
60            self.assertEqual(testrecipe, rd.getVar('PN'))
61            # Check that expanding a value that includes a variable reference works
62            self.assertEqual(testrecipe, rd.getVar('BPN'))
63            # Now check that changing the referenced variable's value in a copy gives that
64            # value when expanding
65            localdata = bb.data.createCopy(rd)
66            localdata.setVar('PN', 'hello')
67            self.assertEqual('hello', localdata.getVar('BPN'))
68
69    def test_list_recipes(self):
70        with bb.tinfoil.Tinfoil() as tinfoil:
71            tinfoil.prepare(config_only=False, quiet=2)
72            # Check pkg_pn
73            checkpns = ['tar', 'automake', 'coreutils', 'm4-native', 'nativesdk-gcc']
74            pkg_pn = tinfoil.cooker.recipecaches[''].pkg_pn
75            for pn in checkpns:
76                self.assertIn(pn, pkg_pn)
77            # Check pkg_fn
78            checkfns = {'nativesdk-gcc': '^virtual:nativesdk:.*', 'coreutils': '.*/coreutils_.*.bb'}
79            for fn, pn in tinfoil.cooker.recipecaches[''].pkg_fn.items():
80                if pn in checkpns:
81                    if pn in checkfns:
82                        self.assertTrue(re.match(checkfns[pn], fn), 'Entry for %s: %s did not match %s' % (pn, fn, checkfns[pn]))
83                    checkpns.remove(pn)
84            if checkpns:
85                self.fail('Unable to find pkg_fn entries for: %s' % ', '.join(checkpns))
86
87    def test_wait_event(self):
88        with bb.tinfoil.Tinfoil() as tinfoil:
89            tinfoil.prepare(config_only=True)
90
91            tinfoil.set_event_mask(['bb.event.FilesMatchingFound', 'bb.command.CommandCompleted', 'bb.command.CommandFailed', 'bb.command.CommandExit'])
92
93            # Need to drain events otherwise events that were masked may still be in the queue
94            while tinfoil.wait_event():
95                pass
96
97            pattern = 'conf'
98            res = tinfoil.run_command('testCookerCommandEvent', pattern, handle_events=False)
99            self.assertTrue(res)
100
101            eventreceived = False
102            commandcomplete = False
103            start = time.time()
104            # Wait for maximum 60s in total so we'd detect spurious heartbeat events for example
105            while (not (eventreceived == True and commandcomplete == True)
106                    and (time.time() - start < 60)):
107                # if we received both events (on let's say a good day), we are done
108                event = tinfoil.wait_event(1)
109                if event:
110                    if isinstance(event, bb.command.CommandCompleted):
111                        commandcomplete = True
112                    elif isinstance(event, bb.event.FilesMatchingFound):
113                        self.assertEqual(pattern, event._pattern)
114                        self.assertIn('A', event._matches)
115                        self.assertIn('B', event._matches)
116                        eventreceived = True
117                    elif isinstance(event, logging.LogRecord):
118                        continue
119                    else:
120                        self.fail('Unexpected event: %s' % event)
121
122            self.assertTrue(commandcomplete, 'Timed out waiting for CommandCompleted event from bitbake server (Matching event received: %s)' % str(eventreceived))
123            self.assertTrue(eventreceived, 'Did not receive FilesMatchingFound event from bitbake server')
124
125    def test_setvariable_clean(self):
126        # First check that setVariable affects the datastore
127        with bb.tinfoil.Tinfoil() as tinfoil:
128            tinfoil.prepare(config_only=True)
129            tinfoil.run_command('setVariable', 'TESTVAR', 'specialvalue')
130            self.assertEqual(tinfoil.config_data.getVar('TESTVAR'), 'specialvalue', 'Value set using setVariable is not reflected in client-side getVar()')
131
132        # Now check that the setVariable's effects are no longer present
133        # (this may legitimately break in future if we stop reinitialising
134        # the datastore, in which case we'll have to reconsider use of
135        # setVariable entirely)
136        with bb.tinfoil.Tinfoil() as tinfoil:
137            tinfoil.prepare(config_only=True)
138            self.assertNotEqual(tinfoil.config_data.getVar('TESTVAR'), 'specialvalue', 'Value set using setVariable is still present!')
139
140        # Now check that setVar on the main datastore works (uses setVariable internally)
141        with bb.tinfoil.Tinfoil() as tinfoil:
142            tinfoil.prepare(config_only=True)
143            tinfoil.config_data.setVar('TESTVAR', 'specialvalue')
144            value = tinfoil.run_command('getVariable', 'TESTVAR')
145            self.assertEqual(value, 'specialvalue', 'Value set using config_data.setVar() is not reflected in config_data.getVar()')
146
147    def test_datastore_operations(self):
148        with bb.tinfoil.Tinfoil() as tinfoil:
149            tinfoil.prepare(config_only=True)
150            # Test setVarFlag() / getVarFlag()
151            tinfoil.config_data.setVarFlag('TESTVAR', 'flagname', 'flagval')
152            value = tinfoil.config_data.getVarFlag('TESTVAR', 'flagname')
153            self.assertEqual(value, 'flagval', 'Value set using config_data.setVarFlag() is not reflected in config_data.getVarFlag()')
154            # Test delVarFlag()
155            tinfoil.config_data.setVarFlag('TESTVAR', 'otherflag', 'othervalue')
156            tinfoil.config_data.delVarFlag('TESTVAR', 'flagname')
157            value = tinfoil.config_data.getVarFlag('TESTVAR', 'flagname')
158            self.assertEqual(value, None, 'Varflag deleted using config_data.delVarFlag() is not reflected in config_data.getVarFlag()')
159            value = tinfoil.config_data.getVarFlag('TESTVAR', 'otherflag')
160            self.assertEqual(value, 'othervalue', 'Varflag deleted using config_data.delVarFlag() caused unrelated flag to be removed')
161            # Test delVar()
162            tinfoil.config_data.setVar('TESTVAR', 'varvalue')
163            value = tinfoil.config_data.getVar('TESTVAR')
164            self.assertEqual(value, 'varvalue', 'Value set using config_data.setVar() is not reflected in config_data.getVar()')
165            tinfoil.config_data.delVar('TESTVAR')
166            value = tinfoil.config_data.getVar('TESTVAR')
167            self.assertEqual(value, None, 'Variable deleted using config_data.delVar() appears to still have a value')
168            # Test renameVar()
169            tinfoil.config_data.setVar('TESTVAROLD', 'origvalue')
170            tinfoil.config_data.renameVar('TESTVAROLD', 'TESTVARNEW')
171            value = tinfoil.config_data.getVar('TESTVAROLD')
172            self.assertEqual(value, None, 'Variable renamed using config_data.renameVar() still seems to exist')
173            value = tinfoil.config_data.getVar('TESTVARNEW')
174            self.assertEqual(value, 'origvalue', 'Variable renamed using config_data.renameVar() does not appear with new name')
175            # Test overrides
176            tinfoil.config_data.setVar('TESTVAR', 'original')
177            tinfoil.config_data.setVar('TESTVAR:overrideone', 'one')
178            tinfoil.config_data.setVar('TESTVAR:overridetwo', 'two')
179            tinfoil.config_data.appendVar('OVERRIDES', ':overrideone')
180            value = tinfoil.config_data.getVar('TESTVAR')
181            self.assertEqual(value, 'one', 'Variable overrides not functioning correctly')
182
183    def test_variable_history(self):
184        # Basic test to ensure that variable history works when tracking=True
185        with bb.tinfoil.Tinfoil(tracking=True) as tinfoil:
186            tinfoil.prepare(config_only=False, quiet=2)
187            # Note that _tracking for any datastore we get will be
188            # false here, that's currently expected - so we can't check
189            # for that
190            history = tinfoil.config_data.varhistory.variable('DL_DIR')
191            for entry in history:
192                if entry['file'].endswith('/bitbake.conf'):
193                    if entry['op'] in ['set', 'set?']:
194                        break
195            else:
196                self.fail('Did not find history entry setting DL_DIR in bitbake.conf. History: %s' % history)
197            # Check it works for recipes as well
198            testrecipe = 'zlib'
199            rd = tinfoil.parse_recipe(testrecipe)
200            history = rd.varhistory.variable('LICENSE')
201            bbfound = -1
202            recipefound = -1
203            for i, entry in enumerate(history):
204                if entry['file'].endswith('/bitbake.conf'):
205                    if entry['detail'] == 'INVALID' and entry['op'] in ['set', 'set?']:
206                        bbfound = i
207                elif entry['file'].endswith('.bb'):
208                    if entry['op'] == 'set':
209                        recipefound = i
210            if bbfound == -1:
211                self.fail('Did not find history entry setting LICENSE in bitbake.conf parsing %s recipe. History: %s' % (testrecipe, history))
212            if recipefound == -1:
213                self.fail('Did not find history entry setting LICENSE in %s recipe. History: %s' % (testrecipe, history))
214            if bbfound > recipefound:
215                self.fail('History entry setting LICENSE in %s recipe and in bitbake.conf in wrong order. History: %s' % (testrecipe, history))
216