func_test.py 18 KB

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