func_test.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2014 Google, Inc
  3. #
  4. import os
  5. import shutil
  6. import sys
  7. import tempfile
  8. import unittest
  9. import board
  10. import bsettings
  11. import cmdline
  12. import command
  13. import control
  14. import gitutil
  15. import terminal
  16. import toolchain
  17. settings_data = '''
  18. # Buildman settings file
  19. [toolchain]
  20. [toolchain-alias]
  21. [make-flags]
  22. src=/home/sjg/c/src
  23. chroot=/home/sjg/c/chroot
  24. vboot=VBOOT_DEBUG=1 MAKEFLAGS_VBOOT=DEBUG=1 CFLAGS_EXTRA_VBOOT=-DUNROLL_LOOPS VBOOT_SOURCE=${src}/platform/vboot_reference
  25. chromeos_coreboot=VBOOT=${chroot}/build/link/usr ${vboot}
  26. chromeos_daisy=VBOOT=${chroot}/build/daisy/usr ${vboot}
  27. chromeos_peach=VBOOT=${chroot}/build/peach_pit/usr ${vboot}
  28. '''
  29. boards = [
  30. ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 1', 'board0', ''],
  31. ['Active', 'arm', 'armv7', '', 'Tester', 'ARM Board 2', 'board1', ''],
  32. ['Active', 'powerpc', 'powerpc', '', 'Tester', 'PowerPC board 1', 'board2', ''],
  33. ['Active', 'sandbox', 'sandbox', '', 'Tester', 'Sandbox board', 'board4', ''],
  34. ]
  35. commit_shortlog = """4aca821 patman: Avoid changing the order of tags
  36. 39403bb patman: Use --no-pager' to stop git from forking a pager
  37. db6e6f2 patman: Remove the -a option
  38. f2ccf03 patman: Correct unit tests to run correctly
  39. 1d097f9 patman: Fix indentation in terminal.py
  40. d073747 patman: Support the 'reverse' option for 'git log
  41. """
  42. commit_log = ["""commit 7f6b8315d18f683c5181d0c3694818c1b2a20dcd
  43. Author: Masahiro Yamada <yamada.m@jp.panasonic.com>
  44. Date: Fri Aug 22 19:12:41 2014 +0900
  45. buildman: refactor help message
  46. "buildman [options]" is displayed by default.
  47. Append the rest of help messages to parser.usage
  48. instead of replacing it.
  49. Besides, "-b <branch>" is not mandatory since commit fea5858e.
  50. Drop it from the usage.
  51. Signed-off-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  52. """,
  53. """commit d0737479be6baf4db5e2cdbee123e96bc5ed0ba8
  54. Author: Simon Glass <sjg@chromium.org>
  55. Date: Thu Aug 14 16:48:25 2014 -0600
  56. patman: Support the 'reverse' option for 'git log'
  57. This option is currently not supported, but needs to be, for buildman to
  58. operate as expected.
  59. Series-changes: 7
  60. - Add new patch to fix the 'reverse' bug
  61. Series-version: 8
  62. Change-Id: I79078f792e8b390b8a1272a8023537821d45feda
  63. Reported-by: York Sun <yorksun@freescale.com>
  64. Signed-off-by: Simon Glass <sjg@chromium.org>
  65. """,
  66. """commit 1d097f9ab487c5019152fd47bda126839f3bf9fc
  67. Author: Simon Glass <sjg@chromium.org>
  68. Date: Sat Aug 9 11:44:32 2014 -0600
  69. patman: Fix indentation in terminal.py
  70. This code came from a different project with 2-character indentation. Fix
  71. it for U-Boot.
  72. Series-changes: 6
  73. - Add new patch to fix indentation in teminal.py
  74. Change-Id: I5a74d2ebbb3cc12a665f5c725064009ac96e8a34
  75. Signed-off-by: Simon Glass <sjg@chromium.org>
  76. """,
  77. """commit f2ccf03869d1e152c836515a3ceb83cdfe04a105
  78. Author: Simon Glass <sjg@chromium.org>
  79. Date: Sat Aug 9 11:08:24 2014 -0600
  80. patman: Correct unit tests to run correctly
  81. It seems that doctest behaves differently now, and some of the unit tests
  82. do not run. Adjust the tests to work correctly.
  83. ./tools/patman/patman --test
  84. <unittest.result.TestResult run=10 errors=0 failures=0>
  85. Series-changes: 6
  86. - Add new patch to fix patman unit tests
  87. Change-Id: I3d2ca588f4933e1f9d6b1665a00e4ae58269ff3b
  88. """,
  89. """commit db6e6f2f9331c5a37647d6668768d4a40b8b0d1c
  90. Author: Simon Glass <sjg@chromium.org>
  91. Date: Sat Aug 9 12:06:02 2014 -0600
  92. patman: Remove the -a option
  93. It seems that this is no longer needed, since checkpatch.pl will catch
  94. whitespace problems in patches. Also the option is not widely used, so
  95. it seems safe to just remove it.
  96. Series-changes: 6
  97. - Add new patch to remove patman's -a option
  98. Suggested-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  99. Change-Id: I5821a1c75154e532c46513486ca40b808de7e2cc
  100. """,
  101. """commit 39403bb4f838153028a6f21ca30bf100f3791133
  102. Author: Simon Glass <sjg@chromium.org>
  103. Date: Thu Aug 14 21:50:52 2014 -0600
  104. patman: Use --no-pager' to stop git from forking a pager
  105. """,
  106. """commit 4aca821e27e97925c039e69fd37375b09c6f129c
  107. Author: Simon Glass <sjg@chromium.org>
  108. Date: Fri Aug 22 15:57:39 2014 -0600
  109. patman: Avoid changing the order of tags
  110. patman collects tags that it sees in the commit and places them nicely
  111. sorted at the end of the patch. However, this is not really necessary and
  112. in fact is apparently not desirable.
  113. Series-changes: 9
  114. - Add new patch to avoid changing the order of tags
  115. Series-version: 9
  116. Suggested-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  117. Change-Id: Ib1518588c1a189ad5c3198aae76f8654aed8d0db
  118. """]
  119. TEST_BRANCH = '__testbranch'
  120. class TestFunctional(unittest.TestCase):
  121. """Functional test for buildman.
  122. This aims to test from just below the invocation of buildman (parsing
  123. of arguments) to 'make' and 'git' invocation. It is not a true
  124. emd-to-end test, as it mocks git, make and the tool chain. But this
  125. makes it easier to detect when the builder is doing the wrong thing,
  126. since in many cases this test code will fail. For example, only a
  127. very limited subset of 'git' arguments is supported - anything
  128. unexpected will fail.
  129. """
  130. def setUp(self):
  131. self._base_dir = tempfile.mkdtemp()
  132. self._output_dir = tempfile.mkdtemp()
  133. self._git_dir = os.path.join(self._base_dir, 'src')
  134. self._buildman_pathname = sys.argv[0]
  135. self._buildman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  136. command.test_result = self._HandleCommand
  137. self.setupToolchains()
  138. self._toolchains.Add('arm-gcc', test=False)
  139. self._toolchains.Add('powerpc-gcc', test=False)
  140. bsettings.Setup(None)
  141. bsettings.AddFile(settings_data)
  142. self._boards = board.Boards()
  143. for brd in boards:
  144. self._boards.AddBoard(board.Board(*brd))
  145. # Directories where the source been cloned
  146. self._clone_dirs = []
  147. self._commits = len(commit_shortlog.splitlines()) + 1
  148. self._total_builds = self._commits * len(boards)
  149. # Number of calls to make
  150. self._make_calls = 0
  151. # Map of [board, commit] to error messages
  152. self._error = {}
  153. self._test_branch = TEST_BRANCH
  154. # Avoid sending any output and clear all terminal output
  155. terminal.SetPrintTestMode()
  156. terminal.GetPrintTestLines()
  157. def tearDown(self):
  158. shutil.rmtree(self._base_dir)
  159. shutil.rmtree(self._output_dir)
  160. def setupToolchains(self):
  161. self._toolchains = toolchain.Toolchains()
  162. self._toolchains.Add('gcc', test=False)
  163. def _RunBuildman(self, *args):
  164. return command.RunPipe([[self._buildman_pathname] + list(args)],
  165. capture=True, capture_stderr=True)
  166. def _RunControl(self, *args, **kwargs):
  167. sys.argv = [sys.argv[0]] + list(args)
  168. options, args = cmdline.ParseArgs()
  169. result = control.DoBuildman(options, args, toolchains=self._toolchains,
  170. make_func=self._HandleMake, boards=self._boards,
  171. clean_dir=kwargs.get('clean_dir', True))
  172. self._builder = control.builder
  173. return result
  174. def testFullHelp(self):
  175. command.test_result = None
  176. result = self._RunBuildman('-H')
  177. help_file = os.path.join(self._buildman_dir, 'README')
  178. # Remove possible extraneous strings
  179. extra = '::::::::::::::\n' + help_file + '\n::::::::::::::\n'
  180. gothelp = result.stdout.replace(extra, '')
  181. self.assertEqual(len(gothelp), os.path.getsize(help_file))
  182. self.assertEqual(0, len(result.stderr))
  183. self.assertEqual(0, result.return_code)
  184. def testHelp(self):
  185. command.test_result = None
  186. result = self._RunBuildman('-h')
  187. help_file = os.path.join(self._buildman_dir, 'README')
  188. self.assertTrue(len(result.stdout) > 1000)
  189. self.assertEqual(0, len(result.stderr))
  190. self.assertEqual(0, result.return_code)
  191. def testGitSetup(self):
  192. """Test gitutils.Setup(), from outside the module itself"""
  193. command.test_result = command.CommandResult(return_code=1)
  194. gitutil.Setup()
  195. self.assertEqual(gitutil.use_no_decorate, False)
  196. command.test_result = command.CommandResult(return_code=0)
  197. gitutil.Setup()
  198. self.assertEqual(gitutil.use_no_decorate, True)
  199. def _HandleCommandGitLog(self, args):
  200. if args[-1] == '--':
  201. args = args[:-1]
  202. if '-n0' in args:
  203. return command.CommandResult(return_code=0)
  204. elif args[-1] == 'upstream/master..%s' % self._test_branch:
  205. return command.CommandResult(return_code=0, stdout=commit_shortlog)
  206. elif args[:3] == ['--no-color', '--no-decorate', '--reverse']:
  207. if args[-1] == self._test_branch:
  208. count = int(args[3][2:])
  209. return command.CommandResult(return_code=0,
  210. stdout=''.join(commit_log[:count]))
  211. # Not handled, so abort
  212. print('git log', args)
  213. sys.exit(1)
  214. def _HandleCommandGitConfig(self, args):
  215. config = args[0]
  216. if config == 'sendemail.aliasesfile':
  217. return command.CommandResult(return_code=0)
  218. elif config.startswith('branch.badbranch'):
  219. return command.CommandResult(return_code=1)
  220. elif config == 'branch.%s.remote' % self._test_branch:
  221. return command.CommandResult(return_code=0, stdout='upstream\n')
  222. elif config == 'branch.%s.merge' % self._test_branch:
  223. return command.CommandResult(return_code=0,
  224. stdout='refs/heads/master\n')
  225. # Not handled, so abort
  226. print('git config', args)
  227. sys.exit(1)
  228. def _HandleCommandGit(self, in_args):
  229. """Handle execution of a git command
  230. This uses a hacked-up parser.
  231. Args:
  232. in_args: Arguments after 'git' from the command line
  233. """
  234. git_args = [] # Top-level arguments to git itself
  235. sub_cmd = None # Git sub-command selected
  236. args = [] # Arguments to the git sub-command
  237. for arg in in_args:
  238. if sub_cmd:
  239. args.append(arg)
  240. elif arg[0] == '-':
  241. git_args.append(arg)
  242. else:
  243. if git_args and git_args[-1] in ['--git-dir', '--work-tree']:
  244. git_args.append(arg)
  245. else:
  246. sub_cmd = arg
  247. if sub_cmd == 'config':
  248. return self._HandleCommandGitConfig(args)
  249. elif sub_cmd == 'log':
  250. return self._HandleCommandGitLog(args)
  251. elif sub_cmd == 'clone':
  252. return command.CommandResult(return_code=0)
  253. elif sub_cmd == 'checkout':
  254. return command.CommandResult(return_code=0)
  255. # Not handled, so abort
  256. print('git', git_args, sub_cmd, args)
  257. sys.exit(1)
  258. def _HandleCommandNm(self, args):
  259. return command.CommandResult(return_code=0)
  260. def _HandleCommandObjdump(self, args):
  261. return command.CommandResult(return_code=0)
  262. def _HandleCommandObjcopy(self, args):
  263. return command.CommandResult(return_code=0)
  264. def _HandleCommandSize(self, args):
  265. return command.CommandResult(return_code=0)
  266. def _HandleCommand(self, **kwargs):
  267. """Handle a command execution.
  268. The command is in kwargs['pipe-list'], as a list of pipes, each a
  269. list of commands. The command should be emulated as required for
  270. testing purposes.
  271. Returns:
  272. A CommandResult object
  273. """
  274. pipe_list = kwargs['pipe_list']
  275. wc = False
  276. if len(pipe_list) != 1:
  277. if pipe_list[1] == ['wc', '-l']:
  278. wc = True
  279. else:
  280. print('invalid pipe', kwargs)
  281. sys.exit(1)
  282. cmd = pipe_list[0][0]
  283. args = pipe_list[0][1:]
  284. result = None
  285. if cmd == 'git':
  286. result = self._HandleCommandGit(args)
  287. elif cmd == './scripts/show-gnu-make':
  288. return command.CommandResult(return_code=0, stdout='make')
  289. elif cmd.endswith('nm'):
  290. return self._HandleCommandNm(args)
  291. elif cmd.endswith('objdump'):
  292. return self._HandleCommandObjdump(args)
  293. elif cmd.endswith('objcopy'):
  294. return self._HandleCommandObjcopy(args)
  295. elif cmd.endswith( 'size'):
  296. return self._HandleCommandSize(args)
  297. if not result:
  298. # Not handled, so abort
  299. print('unknown command', kwargs)
  300. sys.exit(1)
  301. if wc:
  302. result.stdout = len(result.stdout.splitlines())
  303. return result
  304. def _HandleMake(self, commit, brd, stage, cwd, *args, **kwargs):
  305. """Handle execution of 'make'
  306. Args:
  307. commit: Commit object that is being built
  308. brd: Board object that is being built
  309. stage: Stage that we are at (mrproper, config, build)
  310. cwd: Directory where make should be run
  311. args: Arguments to pass to make
  312. kwargs: Arguments to pass to command.RunPipe()
  313. """
  314. self._make_calls += 1
  315. if stage == 'mrproper':
  316. return command.CommandResult(return_code=0)
  317. elif stage == 'config':
  318. return command.CommandResult(return_code=0,
  319. combined='Test configuration complete')
  320. elif stage == 'build':
  321. stderr = ''
  322. if type(commit) is not str:
  323. stderr = self._error.get((brd.target, commit.sequence))
  324. if stderr:
  325. return command.CommandResult(return_code=1, stderr=stderr)
  326. return command.CommandResult(return_code=0)
  327. # Not handled, so abort
  328. print('make', stage)
  329. sys.exit(1)
  330. # Example function to print output lines
  331. def print_lines(self, lines):
  332. print(len(lines))
  333. for line in lines:
  334. print(line)
  335. #self.print_lines(terminal.GetPrintTestLines())
  336. def testNoBoards(self):
  337. """Test that buildman aborts when there are no boards"""
  338. self._boards = board.Boards()
  339. with self.assertRaises(SystemExit):
  340. self._RunControl()
  341. def testCurrentSource(self):
  342. """Very simple test to invoke buildman on the current source"""
  343. self.setupToolchains();
  344. self._RunControl('-o', self._output_dir)
  345. lines = terminal.GetPrintTestLines()
  346. self.assertIn('Building current source for %d boards' % len(boards),
  347. lines[0].text)
  348. def testBadBranch(self):
  349. """Test that we can detect an invalid branch"""
  350. with self.assertRaises(ValueError):
  351. self._RunControl('-b', 'badbranch')
  352. def testBadToolchain(self):
  353. """Test that missing toolchains are detected"""
  354. self.setupToolchains();
  355. ret_code = self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  356. lines = terminal.GetPrintTestLines()
  357. # Buildman always builds the upstream commit as well
  358. self.assertIn('Building %d commits for %d boards' %
  359. (self._commits, len(boards)), lines[0].text)
  360. self.assertEqual(self._builder.count, self._total_builds)
  361. # Only sandbox should succeed, the others don't have toolchains
  362. self.assertEqual(self._builder.fail,
  363. self._total_builds - self._commits)
  364. self.assertEqual(ret_code, 128)
  365. for commit in range(self._commits):
  366. for board in self._boards.GetList():
  367. if board.arch != 'sandbox':
  368. errfile = self._builder.GetErrFile(commit, board.target)
  369. fd = open(errfile)
  370. self.assertEqual(fd.readlines(),
  371. ['No tool chain for %s\n' % board.arch])
  372. fd.close()
  373. def testBranch(self):
  374. """Test building a branch with all toolchains present"""
  375. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  376. self.assertEqual(self._builder.count, self._total_builds)
  377. self.assertEqual(self._builder.fail, 0)
  378. def testCount(self):
  379. """Test building a specific number of commitst"""
  380. self._RunControl('-b', TEST_BRANCH, '-c2', '-o', self._output_dir)
  381. self.assertEqual(self._builder.count, 2 * len(boards))
  382. self.assertEqual(self._builder.fail, 0)
  383. # Each board has a mrproper, config, and then one make per commit
  384. self.assertEqual(self._make_calls, len(boards) * (2 + 2))
  385. def testIncremental(self):
  386. """Test building a branch twice - the second time should do nothing"""
  387. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  388. # Each board has a mrproper, config, and then one make per commit
  389. self.assertEqual(self._make_calls, len(boards) * (self._commits + 2))
  390. self._make_calls = 0
  391. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir, clean_dir=False)
  392. self.assertEqual(self._make_calls, 0)
  393. self.assertEqual(self._builder.count, self._total_builds)
  394. self.assertEqual(self._builder.fail, 0)
  395. def testForceBuild(self):
  396. """The -f flag should force a rebuild"""
  397. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  398. self._make_calls = 0
  399. self._RunControl('-b', TEST_BRANCH, '-f', '-o', self._output_dir, clean_dir=False)
  400. # Each board has a mrproper, config, and then one make per commit
  401. self.assertEqual(self._make_calls, len(boards) * (self._commits + 2))
  402. def testForceReconfigure(self):
  403. """The -f flag should force a rebuild"""
  404. self._RunControl('-b', TEST_BRANCH, '-C', '-o', self._output_dir)
  405. # Each commit has a mrproper, config and make
  406. self.assertEqual(self._make_calls, len(boards) * self._commits * 3)
  407. def testErrors(self):
  408. """Test handling of build errors"""
  409. self._error['board2', 1] = 'fred\n'
  410. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir)
  411. self.assertEqual(self._builder.count, self._total_builds)
  412. self.assertEqual(self._builder.fail, 1)
  413. # Remove the error. This should have no effect since the commit will
  414. # not be rebuilt
  415. del self._error['board2', 1]
  416. self._make_calls = 0
  417. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir, clean_dir=False)
  418. self.assertEqual(self._builder.count, self._total_builds)
  419. self.assertEqual(self._make_calls, 0)
  420. self.assertEqual(self._builder.fail, 1)
  421. # Now use the -F flag to force rebuild of the bad commit
  422. self._RunControl('-b', TEST_BRANCH, '-o', self._output_dir, '-F', clean_dir=False)
  423. self.assertEqual(self._builder.count, self._total_builds)
  424. self.assertEqual(self._builder.fail, 0)
  425. self.assertEqual(self._make_calls, 3)
  426. def testBranchWithSlash(self):
  427. """Test building a branch with a '/' in the name"""
  428. self._test_branch = '/__dev/__testbranch'
  429. self._RunControl('-b', self._test_branch, clean_dir=False)
  430. self.assertEqual(self._builder.count, self._total_builds)
  431. self.assertEqual(self._builder.fail, 0)
  432. def testBadOutputDir(self):
  433. """Test building with an output dir the same as out current dir"""
  434. self._test_branch = '/__dev/__testbranch'
  435. with self.assertRaises(SystemExit):
  436. self._RunControl('-b', self._test_branch, '-o', os.getcwd())
  437. with self.assertRaises(SystemExit):
  438. self._RunControl('-b', self._test_branch, '-o',
  439. os.path.join(os.getcwd(), 'test'))