func_test.py 18 KB

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