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