test.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 test_util
  21. import toolchain
  22. use_network = True
  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. '''arch/arm/dts/socfpga_arria10_socdk_sdmmc.dtb: Warning \
  42. (avoid_unnecessary_addr_size): /clocks: unnecessary #address-cells/#size-cells \
  43. without "ranges" or child "reg" property
  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. OUTCOME_OK, OUTCOME_WARN, OUTCOME_ERR = range(3)
  88. class Options:
  89. """Class that holds build options"""
  90. pass
  91. class TestBuild(unittest.TestCase):
  92. """Test buildman
  93. TODO: Write tests for the rest of the functionality
  94. """
  95. def setUp(self):
  96. # Set up commits to build
  97. self.commits = []
  98. sequence = 0
  99. for commit_info in commits:
  100. comm = commit.Commit(commit_info[0])
  101. comm.subject = commit_info[1]
  102. comm.return_code = commit_info[2]
  103. comm.error_list = commit_info[3]
  104. comm.sequence = sequence
  105. sequence += 1
  106. self.commits.append(comm)
  107. # Set up boards to build
  108. self.boards = board.Boards()
  109. for brd in boards:
  110. self.boards.AddBoard(board.Board(*brd))
  111. self.boards.SelectBoards([])
  112. # Add some test settings
  113. bsettings.Setup(None)
  114. bsettings.AddFile(settings_data)
  115. # Set up the toolchains
  116. self.toolchains = toolchain.Toolchains()
  117. self.toolchains.Add('arm-linux-gcc', test=False)
  118. self.toolchains.Add('sparc-linux-gcc', test=False)
  119. self.toolchains.Add('powerpc-linux-gcc', test=False)
  120. self.toolchains.Add('gcc', test=False)
  121. # Avoid sending any output
  122. terminal.SetPrintTestMode()
  123. self._col = terminal.Color()
  124. def Make(self, commit, brd, stage, *args, **kwargs):
  125. global base_dir
  126. result = command.CommandResult()
  127. boardnum = int(brd.target[-1])
  128. result.return_code = 0
  129. result.stderr = ''
  130. result.stdout = ('This is the test output for board %s, commit %s' %
  131. (brd.target, commit.hash))
  132. if ((boardnum >= 1 and boardnum >= commit.sequence) or
  133. boardnum == 4 and commit.sequence == 6):
  134. result.return_code = commit.return_code
  135. result.stderr = (''.join(commit.error_list)
  136. % {'basedir' : base_dir + '/.bm-work/00/'})
  137. result.combined = result.stdout + result.stderr
  138. return result
  139. def assertSummary(self, text, arch, plus, boards, outcome=OUTCOME_ERR):
  140. col = self._col
  141. expected_colour = (col.GREEN if outcome == OUTCOME_OK else
  142. col.YELLOW if outcome == OUTCOME_WARN else col.RED)
  143. expect = '%10s: ' % arch
  144. # TODO(sjg@chromium.org): If plus is '', we shouldn't need this
  145. expect += ' ' + col.Color(expected_colour, plus)
  146. expect += ' '
  147. for board in boards:
  148. expect += col.Color(expected_colour, ' %s' % board)
  149. self.assertEqual(text, expect)
  150. def testOutput(self):
  151. """Test basic builder operation and output
  152. This does a line-by-line verification of the summary output.
  153. """
  154. global base_dir
  155. base_dir = tempfile.mkdtemp()
  156. if not os.path.isdir(base_dir):
  157. os.mkdir(base_dir)
  158. build = builder.Builder(self.toolchains, base_dir, None, 1, 2,
  159. checkout=False, show_unknown=False)
  160. build.do_make = self.Make
  161. board_selected = self.boards.GetSelectedDict()
  162. # Build the boards for the pre-defined commits and warnings/errors
  163. # associated with each. This calls our Make() to inject the fake output.
  164. build.BuildBoards(self.commits, board_selected, keep_outputs=False,
  165. verbose=False)
  166. lines = terminal.GetPrintTestLines()
  167. count = 0
  168. for line in lines:
  169. if line.text.strip():
  170. count += 1
  171. # We should get two starting messages, then an update for every commit
  172. # built.
  173. self.assertEqual(count, len(commits) * len(boards) + 2)
  174. build.SetDisplayOptions(show_errors=True);
  175. build.ShowSummary(self.commits, board_selected)
  176. #terminal.EchoPrintTestLines()
  177. lines = terminal.GetPrintTestLines()
  178. # Upstream commit: no errors
  179. self.assertEqual(lines[0].text, '01: %s' % commits[0][1])
  180. # Second commit: all archs should fail with warnings
  181. self.assertEqual(lines[1].text, '02: %s' % commits[1][1])
  182. col = terminal.Color()
  183. self.assertSummary(lines[2].text, 'arm', 'w+', ['board1'],
  184. outcome=OUTCOME_WARN)
  185. self.assertSummary(lines[3].text, 'powerpc', 'w+', ['board2', 'board3'],
  186. outcome=OUTCOME_WARN)
  187. self.assertSummary(lines[4].text, 'sandbox', 'w+', ['board4'],
  188. outcome=OUTCOME_WARN)
  189. # Second commit: The warnings should be listed
  190. self.assertEqual(lines[5].text, 'w+%s' %
  191. errors[0].rstrip().replace('\n', '\nw+'))
  192. self.assertEqual(lines[5].colour, col.MAGENTA)
  193. # Third commit: Still fails
  194. self.assertEqual(lines[6].text, '03: %s' % commits[2][1])
  195. self.assertSummary(lines[7].text, 'arm', '', ['board1'],
  196. outcome=OUTCOME_OK)
  197. self.assertSummary(lines[8].text, 'powerpc', '+', ['board2', 'board3'])
  198. self.assertSummary(lines[9].text, 'sandbox', '+', ['board4'])
  199. # Expect a compiler error
  200. self.assertEqual(lines[10].text, '+%s' %
  201. errors[1].rstrip().replace('\n', '\n+'))
  202. # Fourth commit: Compile errors are fixed, just have warning for board3
  203. self.assertEqual(lines[11].text, '04: %s' % commits[3][1])
  204. expect = '%10s: ' % 'powerpc'
  205. expect += ' ' + col.Color(col.GREEN, '')
  206. expect += ' '
  207. expect += col.Color(col.GREEN, ' %s' % 'board2')
  208. expect += ' ' + col.Color(col.YELLOW, 'w+')
  209. expect += ' '
  210. expect += col.Color(col.YELLOW, ' %s' % 'board3')
  211. self.assertEqual(lines[12].text, expect)
  212. self.assertSummary(lines[13].text, 'sandbox', 'w+', ['board4'],
  213. outcome=OUTCOME_WARN)
  214. # Compile error fixed
  215. self.assertEqual(lines[14].text, '-%s' %
  216. errors[1].rstrip().replace('\n', '\n-'))
  217. self.assertEqual(lines[14].colour, col.GREEN)
  218. self.assertEqual(lines[15].text, 'w+%s' %
  219. errors[2].rstrip().replace('\n', '\nw+'))
  220. self.assertEqual(lines[15].colour, col.MAGENTA)
  221. # Fifth commit
  222. self.assertEqual(lines[16].text, '05: %s' % commits[4][1])
  223. self.assertSummary(lines[17].text, 'powerpc', '', ['board3'],
  224. outcome=OUTCOME_OK)
  225. self.assertSummary(lines[18].text, 'sandbox', '+', ['board4'])
  226. # The second line of errors[3] is a duplicate, so buildman will drop it
  227. expect = errors[3].rstrip().split('\n')
  228. expect = [expect[0]] + expect[2:]
  229. self.assertEqual(lines[19].text, '+%s' %
  230. '\n'.join(expect).replace('\n', '\n+'))
  231. self.assertEqual(lines[20].text, 'w-%s' %
  232. errors[2].rstrip().replace('\n', '\nw-'))
  233. # Sixth commit
  234. self.assertEqual(lines[21].text, '06: %s' % commits[5][1])
  235. self.assertSummary(lines[22].text, 'sandbox', '', ['board4'],
  236. outcome=OUTCOME_OK)
  237. # The second line of errors[3] is a duplicate, so buildman will drop it
  238. expect = errors[3].rstrip().split('\n')
  239. expect = [expect[0]] + expect[2:]
  240. self.assertEqual(lines[23].text, '-%s' %
  241. '\n'.join(expect).replace('\n', '\n-'))
  242. self.assertEqual(lines[24].text, 'w-%s' %
  243. errors[0].rstrip().replace('\n', '\nw-'))
  244. # Seventh commit
  245. self.assertEqual(lines[25].text, '07: %s' % commits[6][1])
  246. self.assertSummary(lines[26].text, 'sandbox', '+', ['board4'])
  247. # Pick out the correct error lines
  248. expect_str = errors[4].rstrip().replace('%(basedir)s', '').split('\n')
  249. expect = expect_str[3:8] + [expect_str[-1]]
  250. self.assertEqual(lines[27].text, '+%s' %
  251. '\n'.join(expect).replace('\n', '\n+'))
  252. # Now the warnings lines
  253. expect = [expect_str[0]] + expect_str[10:12] + [expect_str[9]]
  254. self.assertEqual(lines[28].text, 'w+%s' %
  255. '\n'.join(expect).replace('\n', '\nw+'))
  256. self.assertEqual(len(lines), 29)
  257. shutil.rmtree(base_dir)
  258. def _testGit(self):
  259. """Test basic builder operation by building a branch"""
  260. base_dir = tempfile.mkdtemp()
  261. if not os.path.isdir(base_dir):
  262. os.mkdir(base_dir)
  263. options = Options()
  264. options.git = os.getcwd()
  265. options.summary = False
  266. options.jobs = None
  267. options.dry_run = False
  268. #options.git = os.path.join(base_dir, 'repo')
  269. options.branch = 'test-buildman'
  270. options.force_build = False
  271. options.list_tool_chains = False
  272. options.count = -1
  273. options.git_dir = None
  274. options.threads = None
  275. options.show_unknown = False
  276. options.quick = False
  277. options.show_errors = False
  278. options.keep_outputs = False
  279. args = ['tegra20']
  280. control.DoBuildman(options, args)
  281. shutil.rmtree(base_dir)
  282. def testBoardSingle(self):
  283. """Test single board selection"""
  284. self.assertEqual(self.boards.SelectBoards(['sandbox']),
  285. ({'all': ['board4'], 'sandbox': ['board4']}, []))
  286. def testBoardArch(self):
  287. """Test single board selection"""
  288. self.assertEqual(self.boards.SelectBoards(['arm']),
  289. ({'all': ['board0', 'board1'],
  290. 'arm': ['board0', 'board1']}, []))
  291. def testBoardArchSingle(self):
  292. """Test single board selection"""
  293. self.assertEqual(self.boards.SelectBoards(['arm sandbox']),
  294. ({'sandbox': ['board4'],
  295. 'all': ['board0', 'board1', 'board4'],
  296. 'arm': ['board0', 'board1']}, []))
  297. def testBoardArchSingleMultiWord(self):
  298. """Test single board selection"""
  299. self.assertEqual(self.boards.SelectBoards(['arm', 'sandbox']),
  300. ({'sandbox': ['board4'],
  301. 'all': ['board0', 'board1', 'board4'],
  302. 'arm': ['board0', 'board1']}, []))
  303. def testBoardSingleAnd(self):
  304. """Test single board selection"""
  305. self.assertEqual(self.boards.SelectBoards(['Tester & arm']),
  306. ({'Tester&arm': ['board0', 'board1'],
  307. 'all': ['board0', 'board1']}, []))
  308. def testBoardTwoAnd(self):
  309. """Test single board selection"""
  310. self.assertEqual(self.boards.SelectBoards(['Tester', '&', 'arm',
  311. 'Tester' '&', 'powerpc',
  312. 'sandbox']),
  313. ({'sandbox': ['board4'],
  314. 'all': ['board0', 'board1', 'board2', 'board3',
  315. 'board4'],
  316. 'Tester&powerpc': ['board2', 'board3'],
  317. 'Tester&arm': ['board0', 'board1']}, []))
  318. def testBoardAll(self):
  319. """Test single board selection"""
  320. self.assertEqual(self.boards.SelectBoards([]),
  321. ({'all': ['board0', 'board1', 'board2', 'board3',
  322. 'board4']}, []))
  323. def testBoardRegularExpression(self):
  324. """Test single board selection"""
  325. self.assertEqual(self.boards.SelectBoards(['T.*r&^Po']),
  326. ({'all': ['board2', 'board3'],
  327. 'T.*r&^Po': ['board2', 'board3']}, []))
  328. def testBoardDuplicate(self):
  329. """Test single board selection"""
  330. self.assertEqual(self.boards.SelectBoards(['sandbox sandbox',
  331. 'sandbox']),
  332. ({'all': ['board4'], 'sandbox': ['board4']}, []))
  333. def CheckDirs(self, build, dirname):
  334. self.assertEqual('base%s' % dirname, build._GetOutputDir(1))
  335. self.assertEqual('base%s/fred' % dirname,
  336. build.GetBuildDir(1, 'fred'))
  337. self.assertEqual('base%s/fred/done' % dirname,
  338. build.GetDoneFile(1, 'fred'))
  339. self.assertEqual('base%s/fred/u-boot.sizes' % dirname,
  340. build.GetFuncSizesFile(1, 'fred', 'u-boot'))
  341. self.assertEqual('base%s/fred/u-boot.objdump' % dirname,
  342. build.GetObjdumpFile(1, 'fred', 'u-boot'))
  343. self.assertEqual('base%s/fred/err' % dirname,
  344. build.GetErrFile(1, 'fred'))
  345. def testOutputDir(self):
  346. build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
  347. checkout=False, show_unknown=False)
  348. build.commits = self.commits
  349. build.commit_count = len(self.commits)
  350. subject = self.commits[1].subject.translate(builder.trans_valid_chars)
  351. dirname ='/%02d_of_%02d_g%s_%s' % (2, build.commit_count, commits[1][0],
  352. subject[:20])
  353. self.CheckDirs(build, dirname)
  354. def testOutputDirCurrent(self):
  355. build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
  356. checkout=False, show_unknown=False)
  357. build.commits = None
  358. build.commit_count = 0
  359. self.CheckDirs(build, '/current')
  360. def testOutputDirNoSubdirs(self):
  361. build = builder.Builder(self.toolchains, BASE_DIR, None, 1, 2,
  362. checkout=False, show_unknown=False,
  363. no_subdirs=True)
  364. build.commits = None
  365. build.commit_count = 0
  366. self.CheckDirs(build, '')
  367. def testToolchainAliases(self):
  368. self.assertTrue(self.toolchains.Select('arm') != None)
  369. with self.assertRaises(ValueError):
  370. self.toolchains.Select('no-arch')
  371. with self.assertRaises(ValueError):
  372. self.toolchains.Select('x86')
  373. self.toolchains = toolchain.Toolchains()
  374. self.toolchains.Add('x86_64-linux-gcc', test=False)
  375. self.assertTrue(self.toolchains.Select('x86') != None)
  376. self.toolchains = toolchain.Toolchains()
  377. self.toolchains.Add('i386-linux-gcc', test=False)
  378. self.assertTrue(self.toolchains.Select('x86') != None)
  379. def testToolchainDownload(self):
  380. """Test that we can download toolchains"""
  381. if use_network:
  382. with test_util.capture_sys_output() as (stdout, stderr):
  383. url = self.toolchains.LocateArchUrl('arm')
  384. self.assertRegexpMatches(url, 'https://www.kernel.org/pub/tools/'
  385. 'crosstool/files/bin/x86_64/.*/'
  386. 'x86_64-gcc-.*-nolibc_arm-.*linux-gnueabi.tar.xz')
  387. if __name__ == "__main__":
  388. unittest.main()