func_test.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2014 Google, Inc
  3. #
  4. import os
  5. from pathlib import Path
  6. import shutil
  7. import sys
  8. import tempfile
  9. import time
  10. import unittest
  11. from buildman import board
  12. from buildman import boards
  13. from buildman import bsettings
  14. from buildman import cmdline
  15. from buildman import control
  16. from buildman import toolchain
  17. from patman import gitutil
  18. from u_boot_pylib import command
  19. from u_boot_pylib import terminal
  20. from u_boot_pylib import test_util
  21. from u_boot_pylib import tools
  22. settings_data = '''
  23. # Buildman settings file
  24. [global]
  25. [toolchain]
  26. [toolchain-alias]
  27. [make-flags]
  28. src=/home/sjg/c/src
  29. chroot=/home/sjg/c/chroot
  30. vboot=VBOOT_DEBUG=1 MAKEFLAGS_VBOOT=DEBUG=1 CFLAGS_EXTRA_VBOOT=-DUNROLL_LOOPS VBOOT_SOURCE=${src}/platform/vboot_reference
  31. chromeos_coreboot=VBOOT=${chroot}/build/link/usr ${vboot}
  32. chromeos_daisy=VBOOT=${chroot}/build/daisy/usr ${vboot}
  33. chromeos_peach=VBOOT=${chroot}/build/peach_pit/usr ${vboot}
  34. '''
  35. BOARDS = [
  36. ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 0', 'board0', ''],
  37. ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 1', 'board1', ''],
  38. ['Active', 'powerpc', 'powerpc', '', 'Tester', 'PowerPC board 1', 'board2', ''],
  39. ['Active', 'sandbox', 'sandbox', '', 'Tester', 'Sandbox board', 'board4', ''],
  40. ]
  41. commit_shortlog = """4aca821 patman: Avoid changing the order of tags
  42. 39403bb patman: Use --no-pager' to stop git from forking a pager
  43. db6e6f2 patman: Remove the -a option
  44. f2ccf03 patman: Correct unit tests to run correctly
  45. 1d097f9 patman: Fix indentation in terminal.py
  46. d073747 patman: Support the 'reverse' option for 'git log
  47. """
  48. commit_log = ["""commit 7f6b8315d18f683c5181d0c3694818c1b2a20dcd
  49. Author: Masahiro Yamada <yamada.m@jp.panasonic.com>
  50. Date: Fri Aug 22 19:12:41 2014 +0900
  51. buildman: refactor help message
  52. "buildman [options]" is displayed by default.
  53. Append the rest of help messages to parser.usage
  54. instead of replacing it.
  55. Besides, "-b <branch>" is not mandatory since commit fea5858e.
  56. Drop it from the usage.
  57. Signed-off-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  58. """,
  59. """commit d0737479be6baf4db5e2cdbee123e96bc5ed0ba8
  60. Author: Simon Glass <sjg@chromium.org>
  61. Date: Thu Aug 14 16:48:25 2014 -0600
  62. patman: Support the 'reverse' option for 'git log'
  63. This option is currently not supported, but needs to be, for buildman to
  64. operate as expected.
  65. Series-changes: 7
  66. - Add new patch to fix the 'reverse' bug
  67. Series-version: 8
  68. Change-Id: I79078f792e8b390b8a1272a8023537821d45feda
  69. Reported-by: York Sun <yorksun@freescale.com>
  70. Signed-off-by: Simon Glass <sjg@chromium.org>
  71. """,
  72. """commit 1d097f9ab487c5019152fd47bda126839f3bf9fc
  73. Author: Simon Glass <sjg@chromium.org>
  74. Date: Sat Aug 9 11:44:32 2014 -0600
  75. patman: Fix indentation in terminal.py
  76. This code came from a different project with 2-character indentation. Fix
  77. it for U-Boot.
  78. Series-changes: 6
  79. - Add new patch to fix indentation in teminal.py
  80. Change-Id: I5a74d2ebbb3cc12a665f5c725064009ac96e8a34
  81. Signed-off-by: Simon Glass <sjg@chromium.org>
  82. """,
  83. """commit f2ccf03869d1e152c836515a3ceb83cdfe04a105
  84. Author: Simon Glass <sjg@chromium.org>
  85. Date: Sat Aug 9 11:08:24 2014 -0600
  86. patman: Correct unit tests to run correctly
  87. It seems that doctest behaves differently now, and some of the unit tests
  88. do not run. Adjust the tests to work correctly.
  89. ./tools/patman/patman --test
  90. <unittest.result.TestResult run=10 errors=0 failures=0>
  91. Series-changes: 6
  92. - Add new patch to fix patman unit tests
  93. Change-Id: I3d2ca588f4933e1f9d6b1665a00e4ae58269ff3b
  94. """,
  95. """commit db6e6f2f9331c5a37647d6668768d4a40b8b0d1c
  96. Author: Simon Glass <sjg@chromium.org>
  97. Date: Sat Aug 9 12:06:02 2014 -0600
  98. patman: Remove the -a option
  99. It seems that this is no longer needed, since checkpatch.pl will catch
  100. whitespace problems in patches. Also the option is not widely used, so
  101. it seems safe to just remove it.
  102. Series-changes: 6
  103. - Add new patch to remove patman's -a option
  104. Suggested-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  105. Change-Id: I5821a1c75154e532c46513486ca40b808de7e2cc
  106. """,
  107. """commit 39403bb4f838153028a6f21ca30bf100f3791133
  108. Author: Simon Glass <sjg@chromium.org>
  109. Date: Thu Aug 14 21:50:52 2014 -0600
  110. patman: Use --no-pager' to stop git from forking a pager
  111. """,
  112. """commit 4aca821e27e97925c039e69fd37375b09c6f129c
  113. Author: Simon Glass <sjg@chromium.org>
  114. Date: Fri Aug 22 15:57:39 2014 -0600
  115. patman: Avoid changing the order of tags
  116. patman collects tags that it sees in the commit and places them nicely
  117. sorted at the end of the patch. However, this is not really necessary and
  118. in fact is apparently not desirable.
  119. Series-changes: 9
  120. - Add new patch to avoid changing the order of tags
  121. Series-version: 9
  122. Suggested-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  123. Change-Id: Ib1518588c1a189ad5c3198aae76f8654aed8d0db
  124. """]
  125. TEST_BRANCH = '__testbranch'
  126. class TestFunctional(unittest.TestCase):
  127. """Functional test for buildman.
  128. This aims to test from just below the invocation of buildman (parsing
  129. of arguments) to 'make' and 'git' invocation. It is not a true
  130. emd-to-end test, as it mocks git, make and the tool chain. But this
  131. makes it easier to detect when the builder is doing the wrong thing,
  132. since in many cases this test code will fail. For example, only a
  133. very limited subset of 'git' arguments is supported - anything
  134. unexpected will fail.
  135. """
  136. def setUp(self):
  137. self._base_dir = tempfile.mkdtemp()
  138. self._output_dir = tempfile.mkdtemp()
  139. self._git_dir = os.path.join(self._base_dir, 'src')
  140. self._buildman_pathname = sys.argv[0]
  141. self._buildman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  142. command.test_result = self._HandleCommand
  143. bsettings.setup(None)
  144. bsettings.add_file(settings_data)
  145. self.setupToolchains()
  146. self._toolchains.Add('arm-gcc', test=False)
  147. self._toolchains.Add('powerpc-gcc', test=False)
  148. self._boards = boards.Boards()
  149. for brd in BOARDS:
  150. self._boards.add_board(board.Board(*brd))
  151. # Directories where the source been cloned
  152. self._clone_dirs = []
  153. self._commits = len(commit_shortlog.splitlines()) + 1
  154. self._total_builds = self._commits * len(BOARDS)
  155. # Number of calls to make
  156. self._make_calls = 0
  157. # Map of [board, commit] to error messages
  158. self._error = {}
  159. self._test_branch = TEST_BRANCH
  160. # Set to True to report missing blobs
  161. self._missing = False
  162. self._buildman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  163. self._test_dir = os.path.join(self._buildman_dir, 'test')
  164. # Set up some fake source files
  165. shutil.copytree(self._test_dir, self._git_dir)
  166. # Avoid sending any output and clear all terminal output
  167. terminal.set_print_test_mode()
  168. terminal.get_print_test_lines()
  169. def tearDown(self):
  170. shutil.rmtree(self._base_dir)
  171. shutil.rmtree(self._output_dir)
  172. def setupToolchains(self):
  173. self._toolchains = toolchain.Toolchains()
  174. self._toolchains.Add('gcc', test=False)
  175. def _RunBuildman(self, *args):
  176. return command.run_pipe([[self._buildman_pathname] + list(args)],
  177. capture=True, capture_stderr=True)
  178. def _RunControl(self, *args, brds=False, clean_dir=False,
  179. test_thread_exceptions=False, get_builder=True):
  180. """Run buildman
  181. Args:
  182. args: List of arguments to pass
  183. brds: Boards object, or False to pass self._boards, or None to pass
  184. None
  185. clean_dir: Used for tests only, indicates that the existing output_dir
  186. should be removed before starting the build
  187. test_thread_exceptions: Uses for tests only, True to make the threads
  188. raise an exception instead of reporting their result. This simulates
  189. a failure in the code somewhere
  190. get_builder (bool): Set self._builder to the resulting builder
  191. Returns:
  192. result code from buildman
  193. """
  194. sys.argv = [sys.argv[0]] + list(args)
  195. args = cmdline.parse_args()
  196. if brds == False:
  197. brds = self._boards
  198. result = control.do_buildman(
  199. args, toolchains=self._toolchains, make_func=self._HandleMake,
  200. brds=brds, clean_dir=clean_dir,
  201. test_thread_exceptions=test_thread_exceptions)
  202. if get_builder:
  203. self._builder = control.TEST_BUILDER
  204. return result
  205. def testFullHelp(self):
  206. command.test_result = None
  207. result = self._RunBuildman('-H')
  208. help_file = os.path.join(self._buildman_dir, 'README.rst')
  209. # Remove possible extraneous strings
  210. extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
  211. gothelp = result.stdout.replace(extra, '')
  212. self.assertEqual(len(gothelp), os.path.getsize(help_file))
  213. self.assertEqual(0, len(result.stderr))
  214. self.assertEqual(0, result.return_code)
  215. def testHelp(self):
  216. command.test_result = None
  217. result = self._RunBuildman('-h')
  218. help_file = os.path.join(self._buildman_dir, 'README.rst')
  219. self.assertTrue(len(result.stdout) > 1000)
  220. self.assertEqual(0, len(result.stderr))
  221. self.assertEqual(0, result.return_code)
  222. def testGitSetup(self):
  223. """Test gitutils.Setup(), from outside the module itself"""
  224. command.test_result = command.CommandResult(return_code=1)
  225. gitutil.setup()
  226. self.assertEqual(gitutil.use_no_decorate, False)
  227. command.test_result = command.CommandResult(return_code=0)
  228. gitutil.setup()
  229. self.assertEqual(gitutil.use_no_decorate, True)
  230. def _HandleCommandGitLog(self, args):
  231. if args[-1] == '--':
  232. args = args[:-1]
  233. if '-n0' in args:
  234. return command.CommandResult(return_code=0)
  235. elif args[-1] == 'upstream/master..%s' % self._test_branch:
  236. return command.CommandResult(return_code=0, stdout=commit_shortlog)
  237. elif args[:3] == ['--no-color', '--no-decorate', '--reverse']:
  238. if args[-1] == self._test_branch:
  239. count = int(args[3][2:])
  240. return command.CommandResult(return_code=0,
  241. stdout=''.join(commit_log[:count]))
  242. # Not handled, so abort
  243. print('git log', args)
  244. sys.exit(1)
  245. def _HandleCommandGitConfig(self, args):
  246. config = args[0]
  247. if config == 'sendemail.aliasesfile':
  248. return command.CommandResult(return_code=0)
  249. elif config.startswith('branch.badbranch'):
  250. return command.CommandResult(return_code=1)
  251. elif config == 'branch.%s.remote' % self._test_branch:
  252. return command.CommandResult(return_code=0, stdout='upstream\n')
  253. elif config == 'branch.%s.merge' % self._test_branch:
  254. return command.CommandResult(return_code=0,
  255. stdout='refs/heads/master\n')
  256. # Not handled, so abort
  257. print('git config', args)
  258. sys.exit(1)
  259. def _HandleCommandGit(self, in_args):
  260. """Handle execution of a git command
  261. This uses a hacked-up parser.
  262. Args:
  263. in_args: Arguments after 'git' from the command line
  264. """
  265. git_args = [] # Top-level arguments to git itself
  266. sub_cmd = None # Git sub-command selected
  267. args = [] # Arguments to the git sub-command
  268. for arg in in_args:
  269. if sub_cmd:
  270. args.append(arg)
  271. elif arg[0] == '-':
  272. git_args.append(arg)
  273. else:
  274. if git_args and git_args[-1] in ['--git-dir', '--work-tree']:
  275. git_args.append(arg)
  276. else:
  277. sub_cmd = arg
  278. if sub_cmd == 'config':
  279. return self._HandleCommandGitConfig(args)
  280. elif sub_cmd == 'log':
  281. return self._HandleCommandGitLog(args)
  282. elif sub_cmd == 'clone':
  283. return command.CommandResult(return_code=0)
  284. elif sub_cmd == 'checkout':
  285. return command.CommandResult(return_code=0)
  286. elif sub_cmd == 'worktree':
  287. return command.CommandResult(return_code=0)
  288. # Not handled, so abort
  289. print('git', git_args, sub_cmd, args)
  290. sys.exit(1)
  291. def _HandleCommandNm(self, args):
  292. return command.CommandResult(return_code=0)
  293. def _HandleCommandObjdump(self, args):
  294. return command.CommandResult(return_code=0)
  295. def _HandleCommandObjcopy(self, args):
  296. return command.CommandResult(return_code=0)
  297. def _HandleCommandSize(self, args):
  298. return command.CommandResult(return_code=0)
  299. def _HandleCommand(self, **kwargs):
  300. """Handle a command execution.
  301. The command is in kwargs['pipe-list'], as a list of pipes, each a
  302. list of commands. The command should be emulated as required for
  303. testing purposes.
  304. Returns:
  305. A CommandResult object
  306. """
  307. pipe_list = kwargs['pipe_list']
  308. wc = False
  309. if len(pipe_list) != 1:
  310. if pipe_list[1] == ['wc', '-l']:
  311. wc = True
  312. else:
  313. print('invalid pipe', kwargs)
  314. sys.exit(1)
  315. cmd = pipe_list[0][0]
  316. args = pipe_list[0][1:]
  317. result = None
  318. if cmd == 'git':
  319. result = self._HandleCommandGit(args)
  320. elif cmd == './scripts/show-gnu-make':
  321. return command.CommandResult(return_code=0, stdout='make')
  322. elif cmd.endswith('nm'):
  323. return self._HandleCommandNm(args)
  324. elif cmd.endswith('objdump'):
  325. return self._HandleCommandObjdump(args)
  326. elif cmd.endswith('objcopy'):
  327. return self._HandleCommandObjcopy(args)
  328. elif cmd.endswith( 'size'):
  329. return self._HandleCommandSize(args)
  330. if not result:
  331. # Not handled, so abort
  332. print('unknown command', kwargs)
  333. sys.exit(1)
  334. if wc:
  335. result.stdout = len(result.stdout.splitlines())
  336. return result
  337. def _HandleMake(self, commit, brd, stage, cwd, *args, **kwargs):
  338. """Handle execution of 'make'
  339. Args:
  340. commit: Commit object that is being built
  341. brd: Board object that is being built
  342. stage: Stage that we are at (mrproper, config, build)
  343. cwd: Directory where make should be run
  344. args: Arguments to pass to make
  345. kwargs: Arguments to pass to command.run_pipe()
  346. """
  347. self._make_calls += 1
  348. out_dir = ''
  349. for arg in args:
  350. if arg.startswith('O='):
  351. out_dir = arg[2:]
  352. if stage == 'mrproper':
  353. return command.CommandResult(return_code=0)
  354. elif stage == 'config':
  355. fname = os.path.join(cwd or '', out_dir, '.config')
  356. tools.write_file(fname, b'CONFIG_SOMETHING=1')
  357. return command.CommandResult(return_code=0,
  358. combined='Test configuration complete')
  359. elif stage == 'build':
  360. stderr = ''
  361. fname = os.path.join(cwd or '', out_dir, 'u-boot')
  362. tools.write_file(fname, b'U-Boot')
  363. # Handle missing blobs
  364. if self._missing:
  365. if 'BINMAN_ALLOW_MISSING=1' in args:
  366. stderr = '''+Image 'main-section' is missing external blobs and is non-functional: intel-descriptor intel-ifwi intel-fsp-m intel-fsp-s intel-vbt
  367. Image 'main-section' has faked external blobs and is non-functional: descriptor.bin fsp_m.bin fsp_s.bin vbt.bin
  368. Some images are invalid'''
  369. else:
  370. stderr = "binman: Filename 'fsp.bin' not found in input path"
  371. elif type(commit) is not str:
  372. stderr = self._error.get((brd.target, commit.sequence))
  373. if stderr:
  374. return command.CommandResult(return_code=2, stderr=stderr)
  375. return command.CommandResult(return_code=0)
  376. # Not handled, so abort
  377. print('make', stage)
  378. sys.exit(1)
  379. # Example function to print output lines
  380. def print_lines(self, lines):
  381. print(len(lines))
  382. for line in lines:
  383. print(line)
  384. #self.print_lines(terminal.get_print_test_lines())
  385. def testNoBoards(self):
  386. """Test that buildman aborts when there are no boards"""
  387. self._boards = boards.Boards()
  388. with self.assertRaises(SystemExit):
  389. self._RunControl()
  390. def testCurrentSource(self):
  391. """Very simple test to invoke buildman on the current source"""
  392. self.setupToolchains();
  393. self._RunControl('-o', self._output_dir)
  394. lines = terminal.get_print_test_lines()
  395. self.assertIn('Building current source for %d boards' % len(BOARDS),
  396. lines[0].text)
  397. def testBadBranch(self):
  398. """Test that we can detect an invalid branch"""
  399. with self.assertRaises(ValueError):
  400. self._RunControl('-b', 'badbranch')
  401. def testBadToolchain(self):
  402. """Test that missing toolchains are detected"""
  403. self.setupToolchains();
  404. ret_code = self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  405. lines = terminal.get_print_test_lines()
  406. # Buildman always builds the upstream commit as well
  407. self.assertIn('Building %d commits for %d boards' %
  408. (self._commits, len(BOARDS)), lines[0].text)
  409. self.assertEqual(self._builder.count, self._total_builds)
  410. # Only sandbox should succeed, the others don't have toolchains
  411. self.assertEqual(self._builder.fail,
  412. self._total_builds - self._commits)
  413. self.assertEqual(ret_code, 100)
  414. for commit in range(self._commits):
  415. for brd in self._boards.get_list():
  416. if brd.arch != 'sandbox':
  417. errfile = self._builder.get_err_file(commit, brd.target)
  418. fd = open(errfile)
  419. self.assertEqual(
  420. fd.readlines(),
  421. [f'Tool chain error for {brd.arch}: '
  422. f"No tool chain found for arch '{brd.arch}'"])
  423. fd.close()
  424. def testBranch(self):
  425. """Test building a branch with all toolchains present"""
  426. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  427. self.assertEqual(self._builder.count, self._total_builds)
  428. self.assertEqual(self._builder.fail, 0)
  429. def testCount(self):
  430. """Test building a specific number of commitst"""
  431. self._RunControl('-b', TEST_BRANCH, '-c2', '-o', self._output_dir)
  432. self.assertEqual(self._builder.count, 2 * len(BOARDS))
  433. self.assertEqual(self._builder.fail, 0)
  434. # Each board has a config, and then one make per commit
  435. self.assertEqual(self._make_calls, len(BOARDS) * (1 + 2))
  436. def testIncremental(self):
  437. """Test building a branch twice - the second time should do nothing"""
  438. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  439. # Each board has a mrproper, config, and then one make per commit
  440. self.assertEqual(self._make_calls, len(BOARDS) * (self._commits + 1))
  441. self._make_calls = 0
  442. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir, clean_dir=False)
  443. self.assertEqual(self._make_calls, 0)
  444. self.assertEqual(self._builder.count, self._total_builds)
  445. self.assertEqual(self._builder.fail, 0)
  446. def testForceBuild(self):
  447. """The -f flag should force a rebuild"""
  448. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  449. self._make_calls = 0
  450. self._RunControl('-b', TEST_BRANCH, '-f', '-o', self._output_dir, clean_dir=False)
  451. # Each board has a config and one make per commit
  452. self.assertEqual(self._make_calls, len(BOARDS) * (self._commits + 1))
  453. def testForceReconfigure(self):
  454. """The -f flag should force a rebuild"""
  455. self._RunControl('-b', TEST_BRANCH, '-C', '-o', self._output_dir)
  456. # Each commit has a config and make
  457. self.assertEqual(self._make_calls, len(BOARDS) * self._commits * 2)
  458. def testMrproper(self):
  459. """The -f flag should force a rebuild"""
  460. self._RunControl('-b', TEST_BRANCH, '-m', '-o', self._output_dir)
  461. # Each board has a mkproper, config and then one make per commit
  462. self.assertEqual(self._make_calls, len(BOARDS) * (self._commits + 2))
  463. def testErrors(self):
  464. """Test handling of build errors"""
  465. self._error['board2', 1] = 'fred\n'
  466. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  467. self.assertEqual(self._builder.count, self._total_builds)
  468. self.assertEqual(self._builder.fail, 1)
  469. # Remove the error. This should have no effect since the commit will
  470. # not be rebuilt
  471. del self._error['board2', 1]
  472. self._make_calls = 0
  473. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir, clean_dir=False)
  474. self.assertEqual(self._builder.count, self._total_builds)
  475. self.assertEqual(self._make_calls, 0)
  476. self.assertEqual(self._builder.fail, 1)
  477. # Now use the -F flag to force rebuild of the bad commit
  478. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir, '-F', clean_dir=False)
  479. self.assertEqual(self._builder.count, self._total_builds)
  480. self.assertEqual(self._builder.fail, 0)
  481. self.assertEqual(self._make_calls, 2)
  482. def testBranchWithSlash(self):
  483. """Test building a branch with a '/' in the name"""
  484. self._test_branch = '/__dev/__testbranch'
  485. self._RunControl('-b', self._test_branch, '-o', self._output_dir,
  486. clean_dir=False)
  487. self.assertEqual(self._builder.count, self._total_builds)
  488. self.assertEqual(self._builder.fail, 0)
  489. def testEnvironment(self):
  490. """Test that the done and environment files are written to out-env"""
  491. self._RunControl('-o', self._output_dir)
  492. board0_dir = os.path.join(self._output_dir, 'current', 'board0')
  493. self.assertTrue(os.path.exists(os.path.join(board0_dir, 'done')))
  494. self.assertTrue(os.path.exists(os.path.join(board0_dir, 'out-env')))
  495. def testEnvironmentUnicode(self):
  496. """Test there are no unicode errors when the env has non-ASCII chars"""
  497. try:
  498. varname = b'buildman_test_var'
  499. os.environb[varname] = b'strange\x80chars'
  500. self.assertEqual(0, self._RunControl('-o', self._output_dir))
  501. board0_dir = os.path.join(self._output_dir, 'current', 'board0')
  502. self.assertTrue(os.path.exists(os.path.join(board0_dir, 'done')))
  503. self.assertTrue(os.path.exists(os.path.join(board0_dir, 'out-env')))
  504. finally:
  505. del os.environb[varname]
  506. def testWorkInOutput(self):
  507. """Test the -w option which should write directly to the output dir"""
  508. board_list = boards.Boards()
  509. board_list.add_board(board.Board(*BOARDS[0]))
  510. self._RunControl('-o', self._output_dir, '-w', clean_dir=False,
  511. brds=board_list)
  512. self.assertTrue(
  513. os.path.exists(os.path.join(self._output_dir, 'u-boot')))
  514. self.assertTrue(
  515. os.path.exists(os.path.join(self._output_dir, 'done')))
  516. self.assertTrue(
  517. os.path.exists(os.path.join(self._output_dir, 'out-env')))
  518. def testWorkInOutputFail(self):
  519. """Test the -w option failures"""
  520. with self.assertRaises(SystemExit) as e:
  521. self._RunControl('-o', self._output_dir, '-w', clean_dir=False)
  522. self.assertIn("single board", str(e.exception))
  523. self.assertFalse(
  524. os.path.exists(os.path.join(self._output_dir, 'u-boot')))
  525. board_list = boards.Boards()
  526. board_list.add_board(board.Board(*BOARDS[0]))
  527. with self.assertRaises(SystemExit) as e:
  528. self._RunControl('-b', self._test_branch, '-o', self._output_dir,
  529. '-w', clean_dir=False, brds=board_list)
  530. self.assertIn("single commit", str(e.exception))
  531. board_list = boards.Boards()
  532. board_list.add_board(board.Board(*BOARDS[0]))
  533. with self.assertRaises(SystemExit) as e:
  534. self._RunControl('-w', clean_dir=False)
  535. self.assertIn("specify -o", str(e.exception))
  536. def testThreadExceptions(self):
  537. """Test that exceptions in threads are reported"""
  538. with test_util.capture_sys_output() as (stdout, stderr):
  539. self.assertEqual(102, self._RunControl('-o', self._output_dir,
  540. test_thread_exceptions=True))
  541. self.assertIn(
  542. 'Thread exception (use -T0 to run without threads): test exception',
  543. stdout.getvalue())
  544. def testBlobs(self):
  545. """Test handling of missing blobs"""
  546. self._missing = True
  547. board0_dir = os.path.join(self._output_dir, 'current', 'board0')
  548. errfile = os.path.join(board0_dir, 'err')
  549. logfile = os.path.join(board0_dir, 'log')
  550. # We expect failure when there are missing blobs
  551. result = self._RunControl('board0', '-o', self._output_dir)
  552. self.assertEqual(100, result)
  553. self.assertTrue(os.path.exists(os.path.join(board0_dir, 'done')))
  554. self.assertTrue(os.path.exists(errfile))
  555. self.assertIn(b"Filename 'fsp.bin' not found in input path",
  556. tools.read_file(errfile))
  557. def testBlobsAllowMissing(self):
  558. """Allow missing blobs - still failure but a different exit code"""
  559. self._missing = True
  560. result = self._RunControl('board0', '-o', self._output_dir, '-M',
  561. clean_dir=True)
  562. self.assertEqual(101, result)
  563. board0_dir = os.path.join(self._output_dir, 'current', 'board0')
  564. errfile = os.path.join(board0_dir, 'err')
  565. self.assertTrue(os.path.exists(errfile))
  566. self.assertIn(b'Some images are invalid', tools.read_file(errfile))
  567. def testBlobsWarning(self):
  568. """Allow missing blobs and ignore warnings"""
  569. self._missing = True
  570. result = self._RunControl('board0', '-o', self._output_dir, '-MW')
  571. self.assertEqual(0, result)
  572. board0_dir = os.path.join(self._output_dir, 'current', 'board0')
  573. errfile = os.path.join(board0_dir, 'err')
  574. self.assertIn(b'Some images are invalid', tools.read_file(errfile))
  575. def testBlobSettings(self):
  576. """Test with no settings"""
  577. self.assertEqual(False,
  578. control.get_allow_missing(False, False, 1, False))
  579. self.assertEqual(True,
  580. control.get_allow_missing(True, False, 1, False))
  581. self.assertEqual(False,
  582. control.get_allow_missing(True, True, 1, False))
  583. def testBlobSettingsAlways(self):
  584. """Test the 'always' policy"""
  585. bsettings.set_item('global', 'allow-missing', 'always')
  586. self.assertEqual(True,
  587. control.get_allow_missing(False, False, 1, False))
  588. self.assertEqual(False,
  589. control.get_allow_missing(False, True, 1, False))
  590. def testBlobSettingsBranch(self):
  591. """Test the 'branch' policy"""
  592. bsettings.set_item('global', 'allow-missing', 'branch')
  593. self.assertEqual(False,
  594. control.get_allow_missing(False, False, 1, False))
  595. self.assertEqual(True,
  596. control.get_allow_missing(False, False, 1, True))
  597. self.assertEqual(False,
  598. control.get_allow_missing(False, True, 1, True))
  599. def testBlobSettingsMultiple(self):
  600. """Test the 'multiple' policy"""
  601. bsettings.set_item('global', 'allow-missing', 'multiple')
  602. self.assertEqual(False,
  603. control.get_allow_missing(False, False, 1, False))
  604. self.assertEqual(True,
  605. control.get_allow_missing(False, False, 2, False))
  606. self.assertEqual(False,
  607. control.get_allow_missing(False, True, 2, False))
  608. def testBlobSettingsBranchMultiple(self):
  609. """Test the 'branch multiple' policy"""
  610. bsettings.set_item('global', 'allow-missing', 'branch multiple')
  611. self.assertEqual(False,
  612. control.get_allow_missing(False, False, 1, False))
  613. self.assertEqual(True,
  614. control.get_allow_missing(False, False, 1, True))
  615. self.assertEqual(True,
  616. control.get_allow_missing(False, False, 2, False))
  617. self.assertEqual(True,
  618. control.get_allow_missing(False, False, 2, True))
  619. self.assertEqual(False,
  620. control.get_allow_missing(False, True, 2, True))
  621. def check_command(self, *extra_args):
  622. """Run a command with the extra arguments and return the commands used
  623. Args:
  624. extra_args (list of str): List of extra arguments
  625. Returns:
  626. list of str: Lines returned in the out-cmd file
  627. """
  628. self._RunControl('-o', self._output_dir, *extra_args)
  629. board0_dir = os.path.join(self._output_dir, 'current', 'board0')
  630. self.assertTrue(os.path.exists(os.path.join(board0_dir, 'done')))
  631. cmd_fname = os.path.join(board0_dir, 'out-cmd')
  632. self.assertTrue(os.path.exists(cmd_fname))
  633. data = tools.read_file(cmd_fname)
  634. config_fname = os.path.join(board0_dir, '.config')
  635. self.assertTrue(os.path.exists(config_fname))
  636. cfg_data = tools.read_file(config_fname)
  637. return data.splitlines(), cfg_data
  638. def testCmdFile(self):
  639. """Test that the -cmd-out file is produced"""
  640. lines = self.check_command()[0]
  641. self.assertEqual(2, len(lines))
  642. self.assertRegex(lines[0], b'make O=/.*board0_defconfig')
  643. self.assertRegex(lines[0], b'make O=/.*-s.*')
  644. def testNoLto(self):
  645. """Test that the --no-lto flag works"""
  646. lines = self.check_command('-L')[0]
  647. self.assertIn(b'NO_LTO=1', lines[0])
  648. def testReproducible(self):
  649. """Test that the -r flag works"""
  650. lines, cfg_data = self.check_command('-r')
  651. self.assertIn(b'SOURCE_DATE_EPOCH=0', lines[0])
  652. # We should see CONFIG_LOCALVERSION_AUTO unset
  653. self.assertEqual(b'''CONFIG_SOMETHING=1
  654. # CONFIG_LOCALVERSION_AUTO is not set
  655. ''', cfg_data)
  656. with test_util.capture_sys_output() as (stdout, stderr):
  657. lines, cfg_data = self.check_command('-r', '-a', 'LOCALVERSION')
  658. self.assertIn(b'SOURCE_DATE_EPOCH=0', lines[0])
  659. # We should see CONFIG_LOCALVERSION_AUTO unset
  660. self.assertEqual(b'''CONFIG_SOMETHING=1
  661. CONFIG_LOCALVERSION=y
  662. ''', cfg_data)
  663. self.assertIn('Not dropping LOCALVERSION_AUTO', stdout.getvalue())
  664. def test_scan_defconfigs(self):
  665. """Test scanning the defconfigs to obtain all the boards"""
  666. src = self._git_dir
  667. # Scan the test directory which contains a Kconfig and some *_defconfig
  668. # files
  669. params, warnings = self._boards.scan_defconfigs(src, src)
  670. # We should get two boards
  671. self.assertEquals(2, len(params))
  672. self.assertFalse(warnings)
  673. first = 0 if params[0]['target'] == 'board0' else 1
  674. board0 = params[first]
  675. board2 = params[1 - first]
  676. self.assertEquals('arm', board0['arch'])
  677. self.assertEquals('armv7', board0['cpu'])
  678. self.assertEquals('-', board0['soc'])
  679. self.assertEquals('Tester', board0['vendor'])
  680. self.assertEquals('ARM Board 0', board0['board'])
  681. self.assertEquals('config0', board0['config'])
  682. self.assertEquals('board0', board0['target'])
  683. self.assertEquals('powerpc', board2['arch'])
  684. self.assertEquals('ppc', board2['cpu'])
  685. self.assertEquals('mpc85xx', board2['soc'])
  686. self.assertEquals('Tester', board2['vendor'])
  687. self.assertEquals('PowerPC board 1', board2['board'])
  688. self.assertEquals('config2', board2['config'])
  689. self.assertEquals('board2', board2['target'])
  690. def test_output_is_new(self):
  691. """Test detecting new changes to Kconfig"""
  692. base = self._base_dir
  693. src = self._git_dir
  694. config_dir = os.path.join(src, 'configs')
  695. delay = 0.02
  696. # Create a boards.cfg file
  697. boards_cfg = os.path.join(base, 'boards.cfg')
  698. content = b'''#
  699. # List of boards
  700. # Automatically generated by buildman/boards.py: don't edit
  701. #
  702. # Status, Arch, CPU, SoC, Vendor, Board, Target, Config, Maintainers
  703. Active aarch64 armv8 - armltd corstone1000 board0
  704. Active aarch64 armv8 - armltd total_compute board2
  705. '''
  706. # Check missing file
  707. self.assertFalse(boards.output_is_new(boards_cfg, config_dir, src))
  708. # Check that the board.cfg file is newer
  709. time.sleep(delay)
  710. tools.write_file(boards_cfg, content)
  711. self.assertTrue(boards.output_is_new(boards_cfg, config_dir, src))
  712. # Touch the Kconfig files after a show delay to avoid a race
  713. time.sleep(delay)
  714. Path(os.path.join(src, 'Kconfig')).touch()
  715. self.assertFalse(boards.output_is_new(boards_cfg, config_dir, src))
  716. Path(boards_cfg).touch()
  717. self.assertTrue(boards.output_is_new(boards_cfg, config_dir, src))
  718. # Touch a different Kconfig file
  719. time.sleep(delay)
  720. Path(os.path.join(src, 'Kconfig.something')).touch()
  721. self.assertFalse(boards.output_is_new(boards_cfg, config_dir, src))
  722. Path(boards_cfg).touch()
  723. self.assertTrue(boards.output_is_new(boards_cfg, config_dir, src))
  724. # Touch a MAINTAINERS file
  725. time.sleep(delay)
  726. Path(os.path.join(src, 'MAINTAINERS')).touch()
  727. self.assertFalse(boards.output_is_new(boards_cfg, config_dir, src))
  728. Path(boards_cfg).touch()
  729. self.assertTrue(boards.output_is_new(boards_cfg, config_dir, src))
  730. # Touch a defconfig file
  731. time.sleep(delay)
  732. Path(os.path.join(config_dir, 'board0_defconfig')).touch()
  733. self.assertFalse(boards.output_is_new(boards_cfg, config_dir, src))
  734. Path(boards_cfg).touch()
  735. self.assertTrue(boards.output_is_new(boards_cfg, config_dir, src))
  736. # Remove a board and check that the board.cfg file is now older
  737. Path(os.path.join(config_dir, 'board0_defconfig')).unlink()
  738. self.assertFalse(boards.output_is_new(boards_cfg, config_dir, src))
  739. def test_maintainers(self):
  740. """Test detecting boards without a MAINTAINERS entry"""
  741. src = self._git_dir
  742. main = os.path.join(src, 'boards', 'board0', 'MAINTAINERS')
  743. other = os.path.join(src, 'boards', 'board2', 'MAINTAINERS')
  744. kc_file = os.path.join(src, 'Kconfig')
  745. config_dir = os.path.join(src, 'configs')
  746. params_list, warnings = self._boards.build_board_list(config_dir, src)
  747. # There should be two boards no warnings
  748. self.assertEquals(2, len(params_list))
  749. self.assertFalse(warnings)
  750. # Set an invalid status line in the file
  751. orig_data = tools.read_file(main, binary=False)
  752. lines = ['S: Other\n' if line.startswith('S:') else line
  753. for line in orig_data.splitlines(keepends=True)]
  754. tools.write_file(main, ''.join(lines), binary=False)
  755. params_list, warnings = self._boards.build_board_list(config_dir, src)
  756. self.assertEquals(2, len(params_list))
  757. params = params_list[0]
  758. if params['target'] == 'board2':
  759. params = params_list[1]
  760. self.assertEquals('-', params['status'])
  761. self.assertEquals(["WARNING: Other: unknown status for 'board0'"],
  762. warnings)
  763. # Remove the status line (S:) from a file
  764. lines = [line for line in orig_data.splitlines(keepends=True)
  765. if not line.startswith('S:')]
  766. tools.write_file(main, ''.join(lines), binary=False)
  767. params_list, warnings = self._boards.build_board_list(config_dir, src)
  768. self.assertEquals(2, len(params_list))
  769. self.assertEquals(["WARNING: -: unknown status for 'board0'"], warnings)
  770. # Remove the configs/ line (F:) from a file - this is the last line
  771. data = ''.join(orig_data.splitlines(keepends=True)[:-1])
  772. tools.write_file(main, data, binary=False)
  773. params_list, warnings = self._boards.build_board_list(config_dir, src)
  774. self.assertEquals(2, len(params_list))
  775. self.assertEquals(["WARNING: no maintainers for 'board0'"], warnings)
  776. # Mark a board as orphaned - this should give a warning
  777. lines = ['S: Orphaned' if line.startswith('S') else line
  778. for line in orig_data.splitlines(keepends=True)]
  779. tools.write_file(main, ''.join(lines), binary=False)
  780. params_list, warnings = self._boards.build_board_list(config_dir, src)
  781. self.assertEquals(2, len(params_list))
  782. self.assertEquals(["WARNING: no maintainers for 'board0'"], warnings)
  783. # Change the maintainer to '-' - this should give a warning
  784. lines = ['M: -' if line.startswith('M') else line
  785. for line in orig_data.splitlines(keepends=True)]
  786. tools.write_file(main, ''.join(lines), binary=False)
  787. params_list, warnings = self._boards.build_board_list(config_dir, src)
  788. self.assertEquals(2, len(params_list))
  789. self.assertEquals(["WARNING: -: unknown status for 'board0'"], warnings)
  790. # Remove the maintainer line (M:) from a file
  791. lines = [line for line in orig_data.splitlines(keepends=True)
  792. if not line.startswith('M:')]
  793. tools.write_file(main, ''.join(lines), binary=False)
  794. params_list, warnings = self._boards.build_board_list(config_dir, src)
  795. self.assertEquals(2, len(params_list))
  796. self.assertEquals(["WARNING: no maintainers for 'board0'"], warnings)
  797. # Move the contents of the second file into this one, removing the
  798. # second file, to check multiple records in a single file.
  799. both_data = orig_data + tools.read_file(other, binary=False)
  800. tools.write_file(main, both_data, binary=False)
  801. os.remove(other)
  802. params_list, warnings = self._boards.build_board_list(config_dir, src)
  803. self.assertEquals(2, len(params_list))
  804. self.assertFalse(warnings)
  805. # Add another record, this should be ignored with a warning
  806. extra = '\n\nAnother\nM: Fred\nF: configs/board9_defconfig\nS: other\n'
  807. tools.write_file(main, both_data + extra, binary=False)
  808. params_list, warnings = self._boards.build_board_list(config_dir, src)
  809. self.assertEquals(2, len(params_list))
  810. self.assertFalse(warnings)
  811. # Add another TARGET to the Kconfig
  812. tools.write_file(main, both_data, binary=False)
  813. orig_kc_data = tools.read_file(kc_file)
  814. extra = (b'''
  815. if TARGET_BOARD2
  816. config TARGET_OTHER
  817. \tbool "other"
  818. \tdefault y
  819. endif
  820. ''')
  821. tools.write_file(kc_file, orig_kc_data + extra)
  822. params_list, warnings = self._boards.build_board_list(config_dir, src,
  823. warn_targets=True)
  824. self.assertEquals(2, len(params_list))
  825. self.assertEquals(
  826. ['WARNING: board2_defconfig: Duplicate TARGET_xxx: board2 and other'],
  827. warnings)
  828. # Remove the TARGET_BOARD0 Kconfig option
  829. lines = [b'' if line == b'config TARGET_BOARD2\n' else line
  830. for line in orig_kc_data.splitlines(keepends=True)]
  831. tools.write_file(kc_file, b''.join(lines))
  832. params_list, warnings = self._boards.build_board_list(config_dir, src,
  833. warn_targets=True)
  834. self.assertEquals(2, len(params_list))
  835. self.assertEquals(
  836. ['WARNING: board2_defconfig: No TARGET_BOARD2 enabled'],
  837. warnings)
  838. tools.write_file(kc_file, orig_kc_data)
  839. # Replace the last F: line of board 2 with an N: line
  840. data = ''.join(both_data.splitlines(keepends=True)[:-1])
  841. tools.write_file(main, data + 'N: oa.*2\n', binary=False)
  842. params_list, warnings = self._boards.build_board_list(config_dir, src)
  843. self.assertEquals(2, len(params_list))
  844. self.assertFalse(warnings)
  845. def testRegenBoards(self):
  846. """Test that we can regenerate the boards.cfg file"""
  847. outfile = os.path.join(self._output_dir, 'test-boards.cfg')
  848. if os.path.exists(outfile):
  849. os.remove(outfile)
  850. with test_util.capture_sys_output() as (stdout, stderr):
  851. result = self._RunControl('-R', outfile, brds=None,
  852. get_builder=False)
  853. self.assertTrue(os.path.exists(outfile))
  854. def test_print_prefix(self):
  855. """Test that we can print the toolchain prefix"""
  856. with test_util.capture_sys_output() as (stdout, stderr):
  857. result = self._RunControl('-A', 'board0')
  858. self.assertEqual('arm-\n', stdout.getvalue())
  859. self.assertEqual('', stderr.getvalue())
  860. def test_exclude_one(self):
  861. """Test excluding a single board from an arch"""
  862. self._RunControl('arm', '-x', 'board1', '-o', self._output_dir)
  863. self.assertEqual(['board0'],
  864. [b.target for b in self._boards.get_selected()])
  865. def test_exclude_arch(self):
  866. """Test excluding an arch"""
  867. self._RunControl('-x', 'arm', '-o', self._output_dir)
  868. self.assertEqual(['board2', 'board4'],
  869. [b.target for b in self._boards.get_selected()])
  870. def test_exclude_comma(self):
  871. """Test excluding a comma-separated list of things"""
  872. self._RunControl('-x', 'arm,powerpc', '-o', self._output_dir)
  873. self.assertEqual(['board4'],
  874. [b.target for b in self._boards.get_selected()])
  875. def test_exclude_list(self):
  876. """Test excluding a list of things"""
  877. self._RunControl('-x', 'board2', '-x' 'board4', '-o', self._output_dir)
  878. self.assertEqual(['board0', 'board1'],
  879. [b.target for b in self._boards.get_selected()])
  880. def test_single_boards(self):
  881. """Test building single boards"""
  882. self._RunControl('--boards', 'board1', '-o', self._output_dir)
  883. self.assertEqual(1, self._builder.count)
  884. self._RunControl('--boards', 'board1', '--boards', 'board2',
  885. '-o', self._output_dir)
  886. self.assertEqual(2, self._builder.count)
  887. self._RunControl('--boards', 'board1,board2', '--boards', 'board4',
  888. '-o', self._output_dir)
  889. self.assertEqual(3, self._builder.count)
  890. def test_print_arch(self):
  891. """Test that we can print the board architecture"""
  892. with test_util.capture_sys_output() as (stdout, stderr):
  893. result = self._RunControl('--print-arch', 'board0')
  894. self.assertEqual('arm\n', stdout.getvalue())
  895. self.assertEqual('', stderr.getvalue())