xref: /openbmc/u-boot/tools/buildman/test.py (revision a22bbfda)
1#
2# Copyright (c) 2012 The Chromium OS Authors.
3#
4# SPDX-License-Identifier:	GPL-2.0+
5#
6
7import os
8import shutil
9import sys
10import tempfile
11import time
12import unittest
13
14# Bring in the patman libraries
15our_path = os.path.dirname(os.path.realpath(__file__))
16sys.path.append(os.path.join(our_path, '../patman'))
17
18import board
19import bsettings
20import builder
21import control
22import command
23import commit
24import terminal
25import toolchain
26
27settings_data = '''
28# Buildman settings file
29
30[toolchain]
31main: /usr/sbin
32
33[toolchain-alias]
34x86: i386 x86_64
35'''
36
37errors = [
38    '''main.c: In function 'main_loop':
39main.c:260:6: warning: unused variable 'joe' [-Wunused-variable]
40''',
41    '''main.c: In function 'main_loop2':
42main.c:295:2: error: 'fred' undeclared (first use in this function)
43main.c:295:2: note: each undeclared identifier is reported only once for each function it appears in
44make[1]: *** [main.o] Error 1
45make: *** [common/libcommon.o] Error 2
46Make failed
47''',
48    '''main.c: In function 'main_loop3':
49main.c:280:6: warning: unused variable 'mary' [-Wunused-variable]
50''',
51    '''powerpc-linux-ld: warning: dot moved backwards before `.bss'
52powerpc-linux-ld: warning: dot moved backwards before `.bss'
53powerpc-linux-ld: u-boot: section .text lma 0xfffc0000 overlaps previous sections
54powerpc-linux-ld: u-boot: section .rodata lma 0xfffef3ec overlaps previous sections
55powerpc-linux-ld: u-boot: section .reloc lma 0xffffa400 overlaps previous sections
56powerpc-linux-ld: u-boot: section .data lma 0xffffcd38 overlaps previous sections
57powerpc-linux-ld: u-boot: section .u_boot_cmd lma 0xffffeb40 overlaps previous sections
58powerpc-linux-ld: u-boot: section .bootpg lma 0xfffff198 overlaps previous sections
59''',
60   '''In file included from %(basedir)sarch/sandbox/cpu/cpu.c:9:0:
61%(basedir)sarch/sandbox/include/asm/state.h:44:0: warning: "xxxx" redefined [enabled by default]
62%(basedir)sarch/sandbox/include/asm/state.h:43:0: note: this is the location of the previous definition
63%(basedir)sarch/sandbox/cpu/cpu.c: In function 'do_reset':
64%(basedir)sarch/sandbox/cpu/cpu.c:27:1: error: unknown type name 'blah'
65%(basedir)sarch/sandbox/cpu/cpu.c:28:12: error: expected declaration specifiers or '...' before numeric constant
66make[2]: *** [arch/sandbox/cpu/cpu.o] Error 1
67make[1]: *** [arch/sandbox/cpu] Error 2
68make[1]: *** Waiting for unfinished jobs....
69In file included from %(basedir)scommon/board_f.c:55:0:
70%(basedir)sarch/sandbox/include/asm/state.h:44:0: warning: "xxxx" redefined [enabled by default]
71%(basedir)sarch/sandbox/include/asm/state.h:43:0: note: this is the location of the previous definition
72make: *** [sub-make] Error 2
73'''
74]
75
76
77# hash, subject, return code, list of errors/warnings
78commits = [
79    ['1234', 'upstream/master, ok', 0, []],
80    ['5678', 'Second commit, a warning', 0, errors[0:1]],
81    ['9012', 'Third commit, error', 1, errors[0:2]],
82    ['3456', 'Fourth commit, warning', 0, [errors[0], errors[2]]],
83    ['7890', 'Fifth commit, link errors', 1, [errors[0], errors[3]]],
84    ['abcd', 'Sixth commit, fixes all errors', 0, []],
85    ['ef01', 'Seventh commit, check directory suppression', 1, [errors[4]]],
86]
87
88boards = [
89    ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 1', 'board0',  ''],
90    ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 2', 'board1', ''],
91    ['Active', 'powerpc', 'powerpc', '', 'Tester', 'PowerPC board 1', 'board2', ''],
92    ['Active', 'sandbox', 'sandbox', '', 'Tester', 'Sandbox board', 'board4', ''],
93]
94
95BASE_DIR = 'base'
96
97class Options:
98    """Class that holds build options"""
99    pass
100
101class TestBuild(unittest.TestCase):
102    """Test buildman
103
104    TODO: Write tests for the rest of the functionality
105    """
106    def setUp(self):
107        # Set up commits to build
108        self.commits = []
109        sequence = 0
110        for commit_info in commits:
111            comm = commit.Commit(commit_info[0])
112            comm.subject = commit_info[1]
113            comm.return_code = commit_info[2]
114            comm.error_list = commit_info[3]
115            comm.sequence = sequence
116            sequence += 1
117            self.commits.append(comm)
118
119        # Set up boards to build
120        self.boards = board.Boards()
121        for brd in boards:
122            self.boards.AddBoard(board.Board(*brd))
123        self.boards.SelectBoards([])
124
125        # Add some test settings
126        bsettings.Setup(None)
127        bsettings.AddFile(settings_data)
128
129        # Set up the toolchains
130        self.toolchains = toolchain.Toolchains()
131        self.toolchains.Add('arm-linux-gcc', test=False)
132        self.toolchains.Add('sparc-linux-gcc', test=False)
133        self.toolchains.Add('powerpc-linux-gcc', test=False)
134        self.toolchains.Add('gcc', test=False)
135
136        # Avoid sending any output
137        terminal.SetPrintTestMode()
138        self._col = terminal.Color()
139
140    def Make(self, commit, brd, stage, *args, **kwargs):
141        global base_dir
142
143        result = command.CommandResult()
144        boardnum = int(brd.target[-1])
145        result.return_code = 0
146        result.stderr = ''
147        result.stdout = ('This is the test output for board %s, commit %s' %
148                (brd.target, commit.hash))
149        if ((boardnum >= 1 and boardnum >= commit.sequence) or
150                boardnum == 4 and commit.sequence == 6):
151            result.return_code = commit.return_code
152            result.stderr = (''.join(commit.error_list)
153                % {'basedir' : base_dir + '/.bm-work/00/'})
154        if stage == 'build':
155            target_dir = None
156            for arg in args:
157                if arg.startswith('O='):
158                    target_dir = arg[2:]
159
160            if not os.path.isdir(target_dir):
161                os.mkdir(target_dir)
162
163        result.combined = result.stdout + result.stderr
164        return result
165
166    def assertSummary(self, text, arch, plus, boards, ok=False):
167        col = self._col
168        expected_colour = col.GREEN if ok else col.RED
169        expect = '%10s: ' % arch
170        # TODO(sjg@chromium.org): If plus is '', we shouldn't need this
171        expect += ' ' + col.Color(expected_colour, plus)
172        expect += '  '
173        for board in boards:
174            expect += col.Color(expected_colour, ' %s' % board)
175        self.assertEqual(text, expect)
176
177    def testOutput(self):
178        """Test basic builder operation and output
179
180        This does a line-by-line verification of the summary output.
181        """
182        global base_dir
183
184        base_dir = tempfile.mkdtemp()
185        if not os.path.isdir(base_dir):
186            os.mkdir(base_dir)
187        build = builder.Builder(self.toolchains, base_dir, None, 1, 2,
188                                checkout=False, show_unknown=False)
189        build.do_make = self.Make
190        board_selected = self.boards.GetSelectedDict()
191
192        build.BuildBoards(self.commits, board_selected, keep_outputs=False,
193                          verbose=False)
194        lines = terminal.GetPrintTestLines()
195        count = 0
196        for line in lines:
197            if line.text.strip():
198                count += 1
199
200        # We should get two starting messages, then an update for every commit
201        # built.
202        self.assertEqual(count, len(commits) * len(boards) + 2)
203        build.SetDisplayOptions(show_errors=True);
204        build.ShowSummary(self.commits, board_selected)
205        #terminal.EchoPrintTestLines()
206        lines = terminal.GetPrintTestLines()
207        self.assertEqual(lines[0].text, '01: %s' % commits[0][1])
208        self.assertEqual(lines[1].text, '02: %s' % commits[1][1])
209
210        # We expect all archs to fail
211        col = terminal.Color()
212        self.assertSummary(lines[2].text, 'sandbox', '+', ['board4'])
213        self.assertSummary(lines[3].text, 'arm', '+', ['board1'])
214        self.assertSummary(lines[4].text, 'powerpc', '+', ['board2', 'board3'])
215
216        # Now we should have the compiler warning
217        self.assertEqual(lines[5].text, 'w+%s' %
218                errors[0].rstrip().replace('\n', '\nw+'))
219        self.assertEqual(lines[5].colour, col.MAGENTA)
220
221        self.assertEqual(lines[6].text, '03: %s' % commits[2][1])
222        self.assertSummary(lines[7].text, 'sandbox', '+', ['board4'])
223        self.assertSummary(lines[8].text, 'arm', '', ['board1'], ok=True)
224        self.assertSummary(lines[9].text, 'powerpc', '+', ['board2', 'board3'])
225
226        # Compiler error
227        self.assertEqual(lines[10].text, '+%s' %
228                errors[1].rstrip().replace('\n', '\n+'))
229
230        self.assertEqual(lines[11].text, '04: %s' % commits[3][1])
231        self.assertSummary(lines[12].text, 'sandbox', '', ['board4'], ok=True)
232        self.assertSummary(lines[13].text, 'powerpc', '', ['board2', 'board3'],
233                ok=True)
234
235        # Compile error fixed
236        self.assertEqual(lines[14].text, '-%s' %
237                errors[1].rstrip().replace('\n', '\n-'))
238        self.assertEqual(lines[14].colour, col.GREEN)
239
240        self.assertEqual(lines[15].text, 'w+%s' %
241                errors[2].rstrip().replace('\n', '\nw+'))
242        self.assertEqual(lines[15].colour, col.MAGENTA)
243
244        self.assertEqual(lines[16].text, '05: %s' % commits[4][1])
245        self.assertSummary(lines[17].text, 'sandbox', '+', ['board4'])
246        self.assertSummary(lines[18].text, 'powerpc', '', ['board3'], ok=True)
247
248        # The second line of errors[3] is a duplicate, so buildman will drop it
249        expect = errors[3].rstrip().split('\n')
250        expect = [expect[0]] + expect[2:]
251        self.assertEqual(lines[19].text, '+%s' %
252                '\n'.join(expect).replace('\n', '\n+'))
253
254        self.assertEqual(lines[20].text, 'w-%s' %
255                errors[2].rstrip().replace('\n', '\nw-'))
256
257        self.assertEqual(lines[21].text, '06: %s' % commits[5][1])
258        self.assertSummary(lines[22].text, 'sandbox', '', ['board4'], ok=True)
259
260        # The second line of errors[3] is a duplicate, so buildman will drop it
261        expect = errors[3].rstrip().split('\n')
262        expect = [expect[0]] + expect[2:]
263        self.assertEqual(lines[23].text, '-%s' %
264                '\n'.join(expect).replace('\n', '\n-'))
265
266        self.assertEqual(lines[24].text, 'w-%s' %
267                errors[0].rstrip().replace('\n', '\nw-'))
268
269        self.assertEqual(lines[25].text, '07: %s' % commits[6][1])
270        self.assertSummary(lines[26].text, 'sandbox', '+', ['board4'])
271
272        # Pick out the correct error lines
273        expect_str = errors[4].rstrip().replace('%(basedir)s', '').split('\n')
274        expect = expect_str[3:8] + [expect_str[-1]]
275        self.assertEqual(lines[27].text, '+%s' %
276                '\n'.join(expect).replace('\n', '\n+'))
277
278        # Now the warnings lines
279        expect = [expect_str[0]] + expect_str[10:12] + [expect_str[9]]
280        self.assertEqual(lines[28].text, 'w+%s' %
281                '\n'.join(expect).replace('\n', '\nw+'))
282
283        self.assertEqual(len(lines), 29)
284        shutil.rmtree(base_dir)
285
286    def _testGit(self):
287        """Test basic builder operation by building a branch"""
288        base_dir = tempfile.mkdtemp()
289        if not os.path.isdir(base_dir):
290            os.mkdir(base_dir)
291        options = Options()
292        options.git = os.getcwd()
293        options.summary = False
294        options.jobs = None
295        options.dry_run = False
296        #options.git = os.path.join(base_dir, 'repo')
297        options.branch = 'test-buildman'
298        options.force_build = False
299        options.list_tool_chains = False
300        options.count = -1
301        options.git_dir = None
302        options.threads = None
303        options.show_unknown = False
304        options.quick = False
305        options.show_errors = False
306        options.keep_outputs = False
307        args = ['tegra20']
308        control.DoBuildman(options, args)
309        shutil.rmtree(base_dir)
310
311    def testBoardSingle(self):
312        """Test single board selection"""
313        self.assertEqual(self.boards.SelectBoards(['sandbox']),
314                         {'all': 1, 'sandbox': 1})
315
316    def testBoardArch(self):
317        """Test single board selection"""
318        self.assertEqual(self.boards.SelectBoards(['arm']),
319                         {'all': 2, 'arm': 2})
320
321    def testBoardArchSingle(self):
322        """Test single board selection"""
323        self.assertEqual(self.boards.SelectBoards(['arm sandbox']),
324                         {'all': 3, 'arm': 2, 'sandbox' : 1})
325
326    def testBoardArchSingleMultiWord(self):
327        """Test single board selection"""
328        self.assertEqual(self.boards.SelectBoards(['arm', 'sandbox']),
329                         {'all': 3, 'arm': 2, 'sandbox' : 1})
330
331    def testBoardSingleAnd(self):
332        """Test single board selection"""
333        self.assertEqual(self.boards.SelectBoards(['Tester & arm']),
334                         {'all': 2, 'Tester&arm': 2})
335
336    def testBoardTwoAnd(self):
337        """Test single board selection"""
338        self.assertEqual(self.boards.SelectBoards(['Tester', '&', 'arm',
339                                                   'Tester' '&', 'powerpc',
340                                                   'sandbox']),
341                         {'all': 5, 'Tester&powerpc': 2, 'Tester&arm': 2,
342                          'sandbox' : 1})
343
344    def testBoardAll(self):
345        """Test single board selection"""
346        self.assertEqual(self.boards.SelectBoards([]), {'all': 5})
347
348    def testBoardRegularExpression(self):
349        """Test single board selection"""
350        self.assertEqual(self.boards.SelectBoards(['T.*r&^Po']),
351                         {'T.*r&^Po': 2, 'all': 2})
352
353    def testBoardDuplicate(self):
354        """Test single board selection"""
355        self.assertEqual(self.boards.SelectBoards(['sandbox sandbox',
356                                                   'sandbox']),
357                         {'all': 1, 'sandbox': 1})
358    def CheckDirs(self, build, dirname):
359        self.assertEqual('base%s' % dirname, build._GetOutputDir(1))
360        self.assertEqual('base%s/fred' % dirname,
361                         build.GetBuildDir(1, 'fred'))
362        self.assertEqual('base%s/fred/done' % dirname,
363                         build.GetDoneFile(1, 'fred'))
364        self.assertEqual('base%s/fred/u-boot.sizes' % dirname,
365                         build.GetFuncSizesFile(1, 'fred', 'u-boot'))
366        self.assertEqual('base%s/fred/u-boot.objdump' % dirname,
367                         build.GetObjdumpFile(1, 'fred', 'u-boot'))
368        self.assertEqual('base%s/fred/err' % dirname,
369                         build.GetErrFile(1, 'fred'))
370
371    def testOutputDir(self):
372        build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
373                                checkout=False, show_unknown=False)
374        build.commits = self.commits
375        build.commit_count = len(self.commits)
376        subject = self.commits[1].subject.translate(builder.trans_valid_chars)
377        dirname ='/%02d_of_%02d_g%s_%s' % (2, build.commit_count, commits[1][0],
378                                           subject[:20])
379        self.CheckDirs(build, dirname)
380
381    def testOutputDirCurrent(self):
382        build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
383                                checkout=False, show_unknown=False)
384        build.commits = None
385        build.commit_count = 0
386        self.CheckDirs(build, '/current')
387
388    def testOutputDirNoSubdirs(self):
389        build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
390                                checkout=False, show_unknown=False,
391                                no_subdirs=True)
392        build.commits = None
393        build.commit_count = 0
394        self.CheckDirs(build, '')
395
396    def testToolchainAliases(self):
397        self.assertTrue(self.toolchains.Select('arm') != None)
398        with self.assertRaises(ValueError):
399            self.toolchains.Select('no-arch')
400        with self.assertRaises(ValueError):
401            self.toolchains.Select('x86')
402
403        self.toolchains = toolchain.Toolchains()
404        self.toolchains.Add('x86_64-linux-gcc', test=False)
405        self.assertTrue(self.toolchains.Select('x86') != None)
406
407        self.toolchains = toolchain.Toolchains()
408        self.toolchains.Add('i386-linux-gcc', test=False)
409        self.assertTrue(self.toolchains.Select('x86') != None)
410
411    def testToolchainDownload(self):
412        """Test that we can download toolchains"""
413        self.assertEqual('https://www.kernel.org/pub/tools/crosstool/files/bin/x86_64/4.9.0/x86_64-gcc-4.9.0-nolibc_arm-unknown-linux-gnueabi.tar.xz',
414            self.toolchains.LocateArchUrl('arm'))
415
416
417if __name__ == "__main__":
418    unittest.main()
419