test.py 17 KB

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