test.py 16 KB

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