buildman: Make -I the default
[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         self.base_dir = tempfile.mkdtemp()
147         if not os.path.isdir(self.base_dir):
148             os.mkdir(self.base_dir)
149
150     def tearDown(self):
151         shutil.rmtree(self.base_dir)
152
153     def Make(self, commit, brd, stage, *args, **kwargs):
154         result = command.CommandResult()
155         boardnum = int(brd.target[-1])
156         result.return_code = 0
157         result.stderr = ''
158         result.stdout = ('This is the test output for board %s, commit %s' %
159                 (brd.target, commit.hash))
160         if ((boardnum >= 1 and boardnum >= commit.sequence) or
161                 boardnum == 4 and commit.sequence == 6):
162             result.return_code = commit.return_code
163             result.stderr = (''.join(commit.error_list)
164                 % {'basedir' : self.base_dir + '/.bm-work/00/'})
165
166         result.combined = result.stdout + result.stderr
167         return result
168
169     def assertSummary(self, text, arch, plus, boards, outcome=OUTCOME_ERR):
170         col = self._col
171         expected_colour = (col.GREEN if outcome == OUTCOME_OK else
172                            col.YELLOW if outcome == OUTCOME_WARN else col.RED)
173         expect = '%10s: ' % arch
174         # TODO(sjg@chromium.org): If plus is '', we shouldn't need this
175         expect += ' ' + col.Color(expected_colour, plus)
176         expect += '  '
177         for board in boards:
178             expect += col.Color(expected_colour, ' %s' % board)
179         self.assertEqual(text, expect)
180
181     def _SetupTest(self, echo_lines=False, **kwdisplay_args):
182         """Set up the test by running a build and summary
183
184         Args:
185             echo_lines: True to echo lines to the terminal to aid test
186                 development
187             kwdisplay_args: Dict of arguemnts to pass to
188                 Builder.SetDisplayOptions()
189
190         Returns:
191             Iterator containing the output lines, each a PrintLine() object
192         """
193         build = builder.Builder(self.toolchains, self.base_dir, None, 1, 2,
194                                 checkout=False, show_unknown=False)
195         build.do_make = self.Make
196         board_selected = self.boards.GetSelectedDict()
197
198         # Build the boards for the pre-defined commits and warnings/errors
199         # associated with each. This calls our Make() to inject the fake output.
200         build.BuildBoards(self.commits, board_selected, keep_outputs=False,
201                           verbose=False)
202         lines = terminal.GetPrintTestLines()
203         count = 0
204         for line in lines:
205             if line.text.strip():
206                 count += 1
207
208         # We should get two starting messages, an update for every commit built
209         # and a summary message
210         self.assertEqual(count, len(commits) * len(boards) + 3)
211         build.SetDisplayOptions(**kwdisplay_args);
212         build.ShowSummary(self.commits, board_selected)
213         if echo_lines:
214             terminal.EchoPrintTestLines()
215         return iter(terminal.GetPrintTestLines())
216
217     def _CheckOutput(self, lines, list_error_boards):
218         """Check for expected output from the build summary
219
220         Args:
221             lines: Iterator containing the lines returned from the summary
222             list_error_boards: Adjust the check for output produced with the
223                --list-error-boards flag
224         """
225         def add_line_prefix(prefix, boards, error_str, colour):
226             """Add a prefix to each line of a string
227
228             The training \n in error_str is removed before processing
229
230             Args:
231                 prefix: String prefix to add
232                 error_str: Error string containing the lines
233                 colour: Expected colour for the line. Note that the board list,
234                     if present, always appears in magenta
235
236             Returns:
237                 New string where each line has the prefix added
238             """
239             lines = error_str.strip().splitlines()
240             new_lines = []
241             for line in lines:
242                 if boards:
243                     expect = self._col.Color(colour, prefix + '(')
244                     expect += self._col.Color(self._col.MAGENTA, boards,
245                                               bright=False)
246                     expect += self._col.Color(colour, ') %s' % line)
247                 else:
248                     expect = self._col.Color(colour, prefix + line)
249                 new_lines.append(expect)
250             return '\n'.join(new_lines)
251
252         boards1234 = 'board1 board2 board3 board4' if list_error_boards else ''
253         boards234 = 'board2 board3 board4' if list_error_boards else ''
254         boards34 = 'board3 board4' if list_error_boards else ''
255         boards4 = 'board4' if list_error_boards else ''
256
257         # Upstream commit: no errors
258         self.assertEqual(next(lines).text, '01: %s' % commits[0][1])
259
260         # Second commit: all archs should fail with warnings
261         self.assertEqual(next(lines).text, '02: %s' % commits[1][1])
262
263         col = terminal.Color()
264         self.assertSummary(next(lines).text, 'arm', 'w+', ['board1'],
265                            outcome=OUTCOME_WARN)
266         self.assertSummary(next(lines).text, 'powerpc', 'w+',
267                            ['board2', 'board3'], outcome=OUTCOME_WARN)
268         self.assertSummary(next(lines).text, 'sandbox', 'w+', ['board4'],
269                            outcome=OUTCOME_WARN)
270
271         # Second commit: The warnings should be listed
272         self.assertEqual(next(lines).text,
273             add_line_prefix('w+', boards1234, errors[0], col.YELLOW))
274
275         # Third commit: Still fails
276         self.assertEqual(next(lines).text, '03: %s' % commits[2][1])
277         self.assertSummary(next(lines).text, 'arm', '', ['board1'],
278                            outcome=OUTCOME_OK)
279         self.assertSummary(next(lines).text, 'powerpc', '+',
280                            ['board2', 'board3'])
281         self.assertSummary(next(lines).text, 'sandbox', '+', ['board4'])
282
283         # Expect a compiler error
284         self.assertEqual(next(lines).text,
285                          add_line_prefix('+', boards234, errors[1], col.RED))
286
287         # Fourth commit: Compile errors are fixed, just have warning for board3
288         self.assertEqual(next(lines).text, '04: %s' % commits[3][1])
289         expect = '%10s: ' % 'powerpc'
290         expect += ' ' + col.Color(col.GREEN, '')
291         expect += '  '
292         expect += col.Color(col.GREEN, ' %s' % 'board2')
293         expect += ' ' + col.Color(col.YELLOW, 'w+')
294         expect += '  '
295         expect += col.Color(col.YELLOW, ' %s' % 'board3')
296         self.assertEqual(next(lines).text, expect)
297         self.assertSummary(next(lines).text, 'sandbox', 'w+', ['board4'],
298                            outcome=OUTCOME_WARN)
299
300         # Compile error fixed
301         self.assertEqual(next(lines).text,
302                          add_line_prefix('-', boards234, errors[1], col.GREEN))
303
304         self.assertEqual(next(lines).text,
305                          add_line_prefix('w+', boards34, errors[2], col.YELLOW))
306
307         # Fifth commit
308         self.assertEqual(next(lines).text, '05: %s' % commits[4][1])
309         self.assertSummary(next(lines).text, 'powerpc', '', ['board3'],
310                            outcome=OUTCOME_OK)
311         self.assertSummary(next(lines).text, 'sandbox', '+', ['board4'])
312
313         # The second line of errors[3] is a duplicate, so buildman will drop it
314         expect = errors[3].rstrip().split('\n')
315         expect = [expect[0]] + expect[2:]
316         expect = '\n'.join(expect)
317         self.assertEqual(next(lines).text,
318                          add_line_prefix('+', boards4, expect, col.RED))
319
320         self.assertEqual(next(lines).text,
321                          add_line_prefix('w-', boards34, errors[2], col.CYAN))
322
323         # Sixth commit
324         self.assertEqual(next(lines).text, '06: %s' % commits[5][1])
325         self.assertSummary(next(lines).text, 'sandbox', '', ['board4'],
326                            outcome=OUTCOME_OK)
327
328         # The second line of errors[3] is a duplicate, so buildman will drop it
329         expect = errors[3].rstrip().split('\n')
330         expect = [expect[0]] + expect[2:]
331         expect = '\n'.join(expect)
332         self.assertEqual(next(lines).text,
333                          add_line_prefix('-', boards4, expect, col.GREEN))
334         self.assertEqual(next(lines).text,
335                          add_line_prefix('w-', boards4, errors[0], col.CYAN))
336
337         # Seventh commit
338         self.assertEqual(next(lines).text, '07: %s' % commits[6][1])
339         self.assertSummary(next(lines).text, 'sandbox', '+', ['board4'])
340
341         # Pick out the correct error lines
342         expect_str = errors[4].rstrip().replace('%(basedir)s', '').split('\n')
343         expect = expect_str[3:8] + [expect_str[-1]]
344         expect = '\n'.join(expect)
345         self.assertEqual(next(lines).text,
346                          add_line_prefix('+', boards4, expect, col.RED))
347
348         # Now the warnings lines
349         expect = [expect_str[0]] + expect_str[10:12] + [expect_str[9]]
350         expect = '\n'.join(expect)
351         self.assertEqual(next(lines).text,
352                          add_line_prefix('w+', boards4, expect, col.YELLOW))
353
354     def testOutput(self):
355         """Test basic builder operation and output
356
357         This does a line-by-line verification of the summary output.
358         """
359         lines = self._SetupTest(show_errors=True)
360         self._CheckOutput(lines, list_error_boards=False)
361
362     def testErrorBoards(self):
363         """Test output with --list-error-boards
364
365         This does a line-by-line verification of the summary output.
366         """
367         lines = self._SetupTest(show_errors=True, list_error_boards=True)
368         self._CheckOutput(lines, list_error_boards=True)
369
370     def _testGit(self):
371         """Test basic builder operation by building a branch"""
372         options = Options()
373         options.git = os.getcwd()
374         options.summary = False
375         options.jobs = None
376         options.dry_run = False
377         #options.git = os.path.join(self.base_dir, 'repo')
378         options.branch = 'test-buildman'
379         options.force_build = False
380         options.list_tool_chains = False
381         options.count = -1
382         options.git_dir = None
383         options.threads = None
384         options.show_unknown = False
385         options.quick = False
386         options.show_errors = False
387         options.keep_outputs = False
388         args = ['tegra20']
389         control.DoBuildman(options, args)
390
391     def testBoardSingle(self):
392         """Test single board selection"""
393         self.assertEqual(self.boards.SelectBoards(['sandbox']),
394                          ({'all': ['board4'], 'sandbox': ['board4']}, []))
395
396     def testBoardArch(self):
397         """Test single board selection"""
398         self.assertEqual(self.boards.SelectBoards(['arm']),
399                          ({'all': ['board0', 'board1'],
400                           'arm': ['board0', 'board1']}, []))
401
402     def testBoardArchSingle(self):
403         """Test single board selection"""
404         self.assertEqual(self.boards.SelectBoards(['arm sandbox']),
405                          ({'sandbox': ['board4'],
406                           'all': ['board0', 'board1', 'board4'],
407                           'arm': ['board0', 'board1']}, []))
408
409
410     def testBoardArchSingleMultiWord(self):
411         """Test single board selection"""
412         self.assertEqual(self.boards.SelectBoards(['arm', 'sandbox']),
413                          ({'sandbox': ['board4'],
414                           'all': ['board0', 'board1', 'board4'],
415                           'arm': ['board0', 'board1']}, []))
416
417     def testBoardSingleAnd(self):
418         """Test single board selection"""
419         self.assertEqual(self.boards.SelectBoards(['Tester & arm']),
420                          ({'Tester&arm': ['board0', 'board1'],
421                            'all': ['board0', 'board1']}, []))
422
423     def testBoardTwoAnd(self):
424         """Test single board selection"""
425         self.assertEqual(self.boards.SelectBoards(['Tester', '&', 'arm',
426                                                    'Tester' '&', 'powerpc',
427                                                    'sandbox']),
428                          ({'sandbox': ['board4'],
429                           'all': ['board0', 'board1', 'board2', 'board3',
430                                   'board4'],
431                           'Tester&powerpc': ['board2', 'board3'],
432                           'Tester&arm': ['board0', 'board1']}, []))
433
434     def testBoardAll(self):
435         """Test single board selection"""
436         self.assertEqual(self.boards.SelectBoards([]),
437                          ({'all': ['board0', 'board1', 'board2', 'board3',
438                                   'board4']}, []))
439
440     def testBoardRegularExpression(self):
441         """Test single board selection"""
442         self.assertEqual(self.boards.SelectBoards(['T.*r&^Po']),
443                          ({'all': ['board2', 'board3'],
444                           'T.*r&^Po': ['board2', 'board3']}, []))
445
446     def testBoardDuplicate(self):
447         """Test single board selection"""
448         self.assertEqual(self.boards.SelectBoards(['sandbox sandbox',
449                                                    'sandbox']),
450                          ({'all': ['board4'], 'sandbox': ['board4']}, []))
451     def CheckDirs(self, build, dirname):
452         self.assertEqual('base%s' % dirname, build._GetOutputDir(1))
453         self.assertEqual('base%s/fred' % dirname,
454                          build.GetBuildDir(1, 'fred'))
455         self.assertEqual('base%s/fred/done' % dirname,
456                          build.GetDoneFile(1, 'fred'))
457         self.assertEqual('base%s/fred/u-boot.sizes' % dirname,
458                          build.GetFuncSizesFile(1, 'fred', 'u-boot'))
459         self.assertEqual('base%s/fred/u-boot.objdump' % dirname,
460                          build.GetObjdumpFile(1, 'fred', 'u-boot'))
461         self.assertEqual('base%s/fred/err' % dirname,
462                          build.GetErrFile(1, 'fred'))
463
464     def testOutputDir(self):
465         build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
466                                 checkout=False, show_unknown=False)
467         build.commits = self.commits
468         build.commit_count = len(self.commits)
469         subject = self.commits[1].subject.translate(builder.trans_valid_chars)
470         dirname ='/%02d_of_%02d_g%s_%s' % (2, build.commit_count, commits[1][0],
471                                            subject[:20])
472         self.CheckDirs(build, dirname)
473
474     def testOutputDirCurrent(self):
475         build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
476                                 checkout=False, show_unknown=False)
477         build.commits = None
478         build.commit_count = 0
479         self.CheckDirs(build, '/current')
480
481     def testOutputDirNoSubdirs(self):
482         build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
483                                 checkout=False, show_unknown=False,
484                                 no_subdirs=True)
485         build.commits = None
486         build.commit_count = 0
487         self.CheckDirs(build, '')
488
489     def testToolchainAliases(self):
490         self.assertTrue(self.toolchains.Select('arm') != None)
491         with self.assertRaises(ValueError):
492             self.toolchains.Select('no-arch')
493         with self.assertRaises(ValueError):
494             self.toolchains.Select('x86')
495
496         self.toolchains = toolchain.Toolchains()
497         self.toolchains.Add('x86_64-linux-gcc', test=False)
498         self.assertTrue(self.toolchains.Select('x86') != None)
499
500         self.toolchains = toolchain.Toolchains()
501         self.toolchains.Add('i386-linux-gcc', test=False)
502         self.assertTrue(self.toolchains.Select('x86') != None)
503
504     def testToolchainDownload(self):
505         """Test that we can download toolchains"""
506         if use_network:
507             with test_util.capture_sys_output() as (stdout, stderr):
508                 url = self.toolchains.LocateArchUrl('arm')
509             self.assertRegexpMatches(url, 'https://www.kernel.org/pub/tools/'
510                     'crosstool/files/bin/x86_64/.*/'
511                     'x86_64-gcc-.*-nolibc_arm-.*linux-gnueabi.tar.xz')
512
513     def testGetEnvArgs(self):
514         """Test the GetEnvArgs() function"""
515         tc = self.toolchains.Select('arm')
516         self.assertEqual('arm-linux-',
517                          tc.GetEnvArgs(toolchain.VAR_CROSS_COMPILE))
518         self.assertEqual('', tc.GetEnvArgs(toolchain.VAR_PATH))
519         self.assertEqual('arm',
520                          tc.GetEnvArgs(toolchain.VAR_ARCH))
521         self.assertEqual('', tc.GetEnvArgs(toolchain.VAR_MAKE_ARGS))
522
523         self.toolchains.Add('/path/to/x86_64-linux-gcc', test=False)
524         tc = self.toolchains.Select('x86')
525         self.assertEqual('/path/to',
526                          tc.GetEnvArgs(toolchain.VAR_PATH))
527         tc.override_toolchain = 'clang'
528         self.assertEqual('HOSTCC=clang CC=clang',
529                          tc.GetEnvArgs(toolchain.VAR_MAKE_ARGS))
530
531     def testPrepareOutputSpace(self):
532         def _Touch(fname):
533             tools.WriteFile(os.path.join(base_dir, fname), b'')
534
535         base_dir = tempfile.mkdtemp()
536
537         # Add various files that we want removed and left alone
538         to_remove = ['01_of_22_g0982734987_title', '102_of_222_g92bf_title',
539                      '01_of_22_g2938abd8_title']
540         to_leave = ['something_else', '01-something.patch', '01_of_22_another']
541         for name in to_remove + to_leave:
542             _Touch(name)
543
544         build = builder.Builder(self.toolchains, base_dir, None, 1, 2)
545         build.commits = self.commits
546         build.commit_count = len(commits)
547         result = set(build._GetOutputSpaceRemovals())
548         expected = set([os.path.join(base_dir, f) for f in to_remove])
549         self.assertEqual(expected, result)
550
551 if __name__ == "__main__":
552     unittest.main()