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