test.py 17 KB

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