func_test.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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', 'sandbox', 'sandbox', '', 'Tester', 'Sandbox board', 'board4', ''],
  36. ]
  37. commit_shortlog = """4aca821 patman: Avoid changing the order of tags
  38. 39403bb patman: Use --no-pager' to stop git from forking a pager
  39. db6e6f2 patman: Remove the -a option
  40. f2ccf03 patman: Correct unit tests to run correctly
  41. 1d097f9 patman: Fix indentation in terminal.py
  42. d073747 patman: Support the 'reverse' option for 'git log
  43. """
  44. commit_log = ["""commit 7f6b8315d18f683c5181d0c3694818c1b2a20dcd
  45. Author: Masahiro Yamada <yamada.m@jp.panasonic.com>
  46. Date: Fri Aug 22 19:12:41 2014 +0900
  47. buildman: refactor help message
  48. "buildman [options]" is displayed by default.
  49. Append the rest of help messages to parser.usage
  50. instead of replacing it.
  51. Besides, "-b <branch>" is not mandatory since commit fea5858e.
  52. Drop it from the usage.
  53. Signed-off-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  54. """,
  55. """commit d0737479be6baf4db5e2cdbee123e96bc5ed0ba8
  56. Author: Simon Glass <sjg@chromium.org>
  57. Date: Thu Aug 14 16:48:25 2014 -0600
  58. patman: Support the 'reverse' option for 'git log'
  59. This option is currently not supported, but needs to be, for buildman to
  60. operate as expected.
  61. Series-changes: 7
  62. - Add new patch to fix the 'reverse' bug
  63. Series-version: 8
  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. Series-version: 9
  118. Suggested-by: Masahiro Yamada <yamada.m@jp.panasonic.com>
  119. Change-Id: Ib1518588c1a189ad5c3198aae76f8654aed8d0db
  120. """]
  121. TEST_BRANCH = '__testbranch'
  122. class TestFunctional(unittest.TestCase):
  123. """Functional test for buildman.
  124. This aims to test from just below the invocation of buildman (parsing
  125. of arguments) to 'make' and 'git' invocation. It is not a true
  126. emd-to-end test, as it mocks git, make and the tool chain. But this
  127. makes it easier to detect when the builder is doing the wrong thing,
  128. since in many cases this test code will fail. For example, only a
  129. very limited subset of 'git' arguments is supported - anything
  130. unexpected will fail.
  131. """
  132. def setUp(self):
  133. self._base_dir = tempfile.mkdtemp()
  134. self._git_dir = os.path.join(self._base_dir, 'src')
  135. self._buildman_pathname = sys.argv[0]
  136. self._buildman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
  137. command.test_result = self._HandleCommand
  138. self.setupToolchains()
  139. self._toolchains.Add('arm-gcc', test=False)
  140. self._toolchains.Add('powerpc-gcc', test=False)
  141. bsettings.Setup(None)
  142. bsettings.AddFile(settings_data)
  143. self._boards = board.Boards()
  144. for brd in boards:
  145. self._boards.AddBoard(board.Board(*brd))
  146. # Directories where the source been cloned
  147. self._clone_dirs = []
  148. self._commits = len(commit_shortlog.splitlines()) + 1
  149. self._total_builds = self._commits * len(boards)
  150. # Number of calls to make
  151. self._make_calls = 0
  152. # Map of [board, commit] to error messages
  153. self._error = {}
  154. self._test_branch = TEST_BRANCH
  155. # Avoid sending any output and clear all terminal output
  156. terminal.SetPrintTestMode()
  157. terminal.GetPrintTestLines()
  158. def tearDown(self):
  159. shutil.rmtree(self._base_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 _HandleCommandSize(self, args):
  263. return command.CommandResult(return_code=0)
  264. def _HandleCommand(self, **kwargs):
  265. """Handle a command execution.
  266. The command is in kwargs['pipe-list'], as a list of pipes, each a
  267. list of commands. The command should be emulated as required for
  268. testing purposes.
  269. Returns:
  270. A CommandResult object
  271. """
  272. pipe_list = kwargs['pipe_list']
  273. wc = False
  274. if len(pipe_list) != 1:
  275. if pipe_list[1] == ['wc', '-l']:
  276. wc = True
  277. else:
  278. print 'invalid pipe', kwargs
  279. sys.exit(1)
  280. cmd = pipe_list[0][0]
  281. args = pipe_list[0][1:]
  282. result = None
  283. if cmd == 'git':
  284. result = self._HandleCommandGit(args)
  285. elif cmd == './scripts/show-gnu-make':
  286. return command.CommandResult(return_code=0, stdout='make')
  287. elif cmd.endswith('nm'):
  288. return self._HandleCommandNm(args)
  289. elif cmd.endswith('objdump'):
  290. return self._HandleCommandObjdump(args)
  291. elif cmd.endswith( 'size'):
  292. return self._HandleCommandSize(args)
  293. if not result:
  294. # Not handled, so abort
  295. print 'unknown command', kwargs
  296. sys.exit(1)
  297. if wc:
  298. result.stdout = len(result.stdout.splitlines())
  299. return result
  300. def _HandleMake(self, commit, brd, stage, cwd, *args, **kwargs):
  301. """Handle execution of 'make'
  302. Args:
  303. commit: Commit object that is being built
  304. brd: Board object that is being built
  305. stage: Stage that we are at (mrproper, config, build)
  306. cwd: Directory where make should be run
  307. args: Arguments to pass to make
  308. kwargs: Arguments to pass to command.RunPipe()
  309. """
  310. self._make_calls += 1
  311. if stage == 'mrproper':
  312. return command.CommandResult(return_code=0)
  313. elif stage == 'config':
  314. return command.CommandResult(return_code=0,
  315. combined='Test configuration complete')
  316. elif stage == 'build':
  317. stderr = ''
  318. if type(commit) is not str:
  319. stderr = self._error.get((brd.target, commit.sequence))
  320. if stderr:
  321. return command.CommandResult(return_code=1, stderr=stderr)
  322. return command.CommandResult(return_code=0)
  323. # Not handled, so abort
  324. print 'make', stage
  325. sys.exit(1)
  326. # Example function to print output lines
  327. def print_lines(self, lines):
  328. print len(lines)
  329. for line in lines:
  330. print line
  331. #self.print_lines(terminal.GetPrintTestLines())
  332. def testNoBoards(self):
  333. """Test that buildman aborts when there are no boards"""
  334. self._boards = board.Boards()
  335. with self.assertRaises(SystemExit):
  336. self._RunControl()
  337. def testCurrentSource(self):
  338. """Very simple test to invoke buildman on the current source"""
  339. self.setupToolchains();
  340. self._RunControl()
  341. lines = terminal.GetPrintTestLines()
  342. self.assertIn('Building current source for %d boards' % len(boards),
  343. lines[0].text)
  344. def testBadBranch(self):
  345. """Test that we can detect an invalid branch"""
  346. with self.assertRaises(ValueError):
  347. self._RunControl('-b', 'badbranch')
  348. def testBadToolchain(self):
  349. """Test that missing toolchains are detected"""
  350. self.setupToolchains();
  351. ret_code = self._RunControl('-b', TEST_BRANCH)
  352. lines = terminal.GetPrintTestLines()
  353. # Buildman always builds the upstream commit as well
  354. self.assertIn('Building %d commits for %d boards' %
  355. (self._commits, len(boards)), lines[0].text)
  356. self.assertEqual(self._builder.count, self._total_builds)
  357. # Only sandbox should succeed, the others don't have toolchains
  358. self.assertEqual(self._builder.fail,
  359. self._total_builds - self._commits)
  360. self.assertEqual(ret_code, 128)
  361. for commit in range(self._commits):
  362. for board in self._boards.GetList():
  363. if board.arch != 'sandbox':
  364. errfile = self._builder.GetErrFile(commit, board.target)
  365. fd = open(errfile)
  366. self.assertEqual(fd.readlines(),
  367. ['No tool chain for %s\n' % board.arch])
  368. fd.close()
  369. def testBranch(self):
  370. """Test building a branch with all toolchains present"""
  371. self._RunControl('-b', TEST_BRANCH)
  372. self.assertEqual(self._builder.count, self._total_builds)
  373. self.assertEqual(self._builder.fail, 0)
  374. def testCount(self):
  375. """Test building a specific number of commitst"""
  376. self._RunControl('-b', TEST_BRANCH, '-c2')
  377. self.assertEqual(self._builder.count, 2 * len(boards))
  378. self.assertEqual(self._builder.fail, 0)
  379. # Each board has a mrproper, config, and then one make per commit
  380. self.assertEqual(self._make_calls, len(boards) * (2 + 2))
  381. def testIncremental(self):
  382. """Test building a branch twice - the second time should do nothing"""
  383. self._RunControl('-b', TEST_BRANCH)
  384. # Each board has a mrproper, config, and then one make per commit
  385. self.assertEqual(self._make_calls, len(boards) * (self._commits + 2))
  386. self._make_calls = 0
  387. self._RunControl('-b', TEST_BRANCH, clean_dir=False)
  388. self.assertEqual(self._make_calls, 0)
  389. self.assertEqual(self._builder.count, self._total_builds)
  390. self.assertEqual(self._builder.fail, 0)
  391. def testForceBuild(self):
  392. """The -f flag should force a rebuild"""
  393. self._RunControl('-b', TEST_BRANCH)
  394. self._make_calls = 0
  395. self._RunControl('-b', TEST_BRANCH, '-f', clean_dir=False)
  396. # Each board has a mrproper, config, and then one make per commit
  397. self.assertEqual(self._make_calls, len(boards) * (self._commits + 2))
  398. def testForceReconfigure(self):
  399. """The -f flag should force a rebuild"""
  400. self._RunControl('-b', TEST_BRANCH, '-C')
  401. # Each commit has a mrproper, config and make
  402. self.assertEqual(self._make_calls, len(boards) * self._commits * 3)
  403. def testErrors(self):
  404. """Test handling of build errors"""
  405. self._error['board2', 1] = 'fred\n'
  406. self._RunControl('-b', TEST_BRANCH)
  407. self.assertEqual(self._builder.count, self._total_builds)
  408. self.assertEqual(self._builder.fail, 1)
  409. # Remove the error. This should have no effect since the commit will
  410. # not be rebuilt
  411. del self._error['board2', 1]
  412. self._make_calls = 0
  413. self._RunControl('-b', TEST_BRANCH, clean_dir=False)
  414. self.assertEqual(self._builder.count, self._total_builds)
  415. self.assertEqual(self._make_calls, 0)
  416. self.assertEqual(self._builder.fail, 1)
  417. # Now use the -F flag to force rebuild of the bad commit
  418. self._RunControl('-b', TEST_BRANCH, '-F', clean_dir=False)
  419. self.assertEqual(self._builder.count, self._total_builds)
  420. self.assertEqual(self._builder.fail, 0)
  421. self.assertEqual(self._make_calls, 3)
  422. def testBranchWithSlash(self):
  423. """Test building a branch with a '/' in the name"""
  424. self._test_branch = '/__dev/__testbranch'
  425. self._RunControl('-b', self._test_branch, clean_dir=False)
  426. self.assertEqual(self._builder.count, self._total_builds)
  427. self.assertEqual(self._builder.fail, 0)