bintool_test.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright 2022 Google LLC
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. """Tests for the Bintool class"""
  6. import collections
  7. import os
  8. import shutil
  9. import tempfile
  10. import unittest
  11. import unittest.mock
  12. import urllib.error
  13. from binman import bintool
  14. from binman.bintool import Bintool
  15. from u_boot_pylib import command
  16. from u_boot_pylib import terminal
  17. from u_boot_pylib import test_util
  18. from u_boot_pylib import tools
  19. # pylint: disable=R0904
  20. class TestBintool(unittest.TestCase):
  21. """Tests for the Bintool class"""
  22. def setUp(self):
  23. # Create a temporary directory for test files
  24. self._indir = tempfile.mkdtemp(prefix='bintool.')
  25. self.seq = None
  26. self.count = None
  27. self.fname = None
  28. self.btools = None
  29. def tearDown(self):
  30. """Remove the temporary input directory and its contents"""
  31. if self._indir:
  32. shutil.rmtree(self._indir)
  33. self._indir = None
  34. def test_missing_btype(self):
  35. """Test that unknown bintool types are detected"""
  36. with self.assertRaises(ValueError) as exc:
  37. Bintool.create('missing')
  38. self.assertIn("No module named 'binman.btool.missing'",
  39. str(exc.exception))
  40. def test_fresh_bintool(self):
  41. """Check that the _testing bintool is not cached"""
  42. btest = Bintool.create('_testing')
  43. btest.present = True
  44. btest2 = Bintool.create('_testing')
  45. self.assertFalse(btest2.present)
  46. def test_version(self):
  47. """Check handling of a tool being present or absent"""
  48. btest = Bintool.create('_testing')
  49. with test_util.capture_sys_output() as (stdout, _):
  50. btest.show()
  51. self.assertFalse(btest.is_present())
  52. self.assertIn('-', stdout.getvalue())
  53. btest.present = True
  54. self.assertTrue(btest.is_present())
  55. self.assertEqual('123', btest.version())
  56. with test_util.capture_sys_output() as (stdout, _):
  57. btest.show()
  58. self.assertIn('123', stdout.getvalue())
  59. def test_fetch_present(self):
  60. """Test fetching of a tool"""
  61. btest = Bintool.create('_testing')
  62. btest.present = True
  63. col = terminal.Color()
  64. self.assertEqual(bintool.PRESENT,
  65. btest.fetch_tool(bintool.FETCH_ANY, col, True))
  66. @classmethod
  67. def check_fetch_url(cls, fake_download, method):
  68. """Check the output from fetching a tool
  69. Args:
  70. fake_download (function): Function to call instead of
  71. tools.download()
  72. method (bintool.FETCH_...: Fetch method to use
  73. Returns:
  74. str: Contents of stdout
  75. """
  76. btest = Bintool.create('_testing')
  77. col = terminal.Color()
  78. with unittest.mock.patch.object(tools, 'download',
  79. side_effect=fake_download):
  80. with test_util.capture_sys_output() as (stdout, _):
  81. btest.fetch_tool(method, col, False)
  82. return stdout.getvalue()
  83. def test_fetch_url_err(self):
  84. """Test an error while fetching a tool from a URL"""
  85. def fail_download(url):
  86. """Take the tools.download() function by raising an exception"""
  87. raise urllib.error.URLError('my error')
  88. stdout = self.check_fetch_url(fail_download, bintool.FETCH_ANY)
  89. self.assertIn('my error', stdout)
  90. def test_fetch_url_exception(self):
  91. """Test an exception while fetching a tool from a URL"""
  92. def cause_exc(url):
  93. raise ValueError('exc error')
  94. stdout = self.check_fetch_url(cause_exc, bintool.FETCH_ANY)
  95. self.assertIn('exc error', stdout)
  96. def test_fetch_method(self):
  97. """Test fetching using a particular method"""
  98. def fail_download(url):
  99. """Take the tools.download() function by raising an exception"""
  100. raise urllib.error.URLError('my error')
  101. stdout = self.check_fetch_url(fail_download, bintool.FETCH_BIN)
  102. self.assertIn('my error', stdout)
  103. def test_fetch_pass_fail(self):
  104. """Test fetching multiple tools with some passing and some failing"""
  105. def handle_download(_):
  106. """Take the tools.download() function by writing a file"""
  107. if self.seq:
  108. raise urllib.error.URLError('not found')
  109. self.seq += 1
  110. tools.write_file(fname, expected)
  111. return fname, dirname
  112. expected = b'this is a test'
  113. dirname = os.path.join(self._indir, 'download_dir')
  114. os.mkdir(dirname)
  115. fname = os.path.join(dirname, 'downloaded')
  116. # Rely on bintool to create this directory
  117. destdir = os.path.join(self._indir, 'dest_dir')
  118. dest_fname = os.path.join(destdir, '_testing')
  119. self.seq = 0
  120. with unittest.mock.patch.object(bintool.Bintool, 'tooldir', destdir):
  121. with unittest.mock.patch.object(tools, 'download',
  122. side_effect=handle_download):
  123. with test_util.capture_sys_output() as (stdout, _):
  124. Bintool.fetch_tools(bintool.FETCH_ANY, ['_testing'] * 2)
  125. self.assertTrue(os.path.exists(dest_fname))
  126. data = tools.read_file(dest_fname)
  127. self.assertEqual(expected, data)
  128. lines = stdout.getvalue().splitlines()
  129. self.assertTrue(len(lines) > 2)
  130. self.assertEqual('Tools fetched: 1: _testing', lines[-2])
  131. self.assertEqual('Failures: 1: _testing', lines[-1])
  132. def test_tool_list(self):
  133. """Test listing available tools"""
  134. self.assertGreater(len(Bintool.get_tool_list()), 3)
  135. def check_fetch_all(self, method):
  136. """Helper to check the operation of fetching all tools"""
  137. # pylint: disable=W0613
  138. def fake_fetch(method, col, skip_present):
  139. """Fakes the Binutils.fetch() function
  140. Returns FETCHED and FAIL on alternate calls
  141. """
  142. self.seq += 1
  143. result = bintool.FETCHED if self.seq & 1 else bintool.FAIL
  144. self.count[result] += 1
  145. return result
  146. self.seq = 0
  147. self.count = collections.defaultdict(int)
  148. with unittest.mock.patch.object(bintool.Bintool, 'fetch_tool',
  149. side_effect=fake_fetch):
  150. with test_util.capture_sys_output() as (stdout, _):
  151. Bintool.fetch_tools(method, ['all'])
  152. lines = stdout.getvalue().splitlines()
  153. self.assertIn(f'{self.count[bintool.FETCHED]}: ', lines[-2])
  154. self.assertIn(f'{self.count[bintool.FAIL]}: ', lines[-1])
  155. def test_fetch_all(self):
  156. """Test fetching all tools"""
  157. self.check_fetch_all(bintool.FETCH_ANY)
  158. def test_fetch_all_specific(self):
  159. """Test fetching all tools with a specific method"""
  160. self.check_fetch_all(bintool.FETCH_BIN)
  161. def test_fetch_missing(self):
  162. """Test fetching missing tools"""
  163. # pylint: disable=W0613
  164. def fake_fetch2(method, col, skip_present):
  165. """Fakes the Binutils.fetch() function
  166. Returns PRESENT only for the '_testing' bintool
  167. """
  168. btool = list(self.btools.values())[self.seq]
  169. self.seq += 1
  170. print('fetch', btool.name)
  171. if btool.name == '_testing':
  172. return bintool.PRESENT
  173. return bintool.FETCHED
  174. # Preload a list of tools to return when get_tool_list() and create()
  175. # are called
  176. all_tools = Bintool.get_tool_list(True)
  177. self.btools = collections.OrderedDict()
  178. for name in all_tools:
  179. self.btools[name] = Bintool.create(name)
  180. self.seq = 0
  181. with unittest.mock.patch.object(bintool.Bintool, 'fetch_tool',
  182. side_effect=fake_fetch2):
  183. with unittest.mock.patch.object(bintool.Bintool,
  184. 'get_tool_list',
  185. side_effect=[all_tools]):
  186. with unittest.mock.patch.object(bintool.Bintool, 'create',
  187. side_effect=self.btools.values()):
  188. with test_util.capture_sys_output() as (stdout, _):
  189. Bintool.fetch_tools(bintool.FETCH_ANY, ['missing'])
  190. lines = stdout.getvalue().splitlines()
  191. num_tools = len(self.btools)
  192. fetched = [line for line in lines if 'Tools fetched:' in line].pop()
  193. present = [line for line in lines if 'Already present:' in line].pop()
  194. self.assertIn(f'{num_tools - 1}: ', fetched)
  195. self.assertIn('1: ', present)
  196. def check_build_method(self, write_file):
  197. """Check the output from fetching using the BUILD method
  198. Args:
  199. write_file (bool): True to write the output file when 'make' is
  200. called
  201. Returns:
  202. tuple:
  203. str: Filename of written file (or missing 'make' output)
  204. str: Contents of stdout
  205. """
  206. def fake_run(*cmd):
  207. if cmd[0] == 'make':
  208. # See Bintool.build_from_git()
  209. tmpdir = cmd[2]
  210. self.fname = os.path.join(tmpdir, 'pathname')
  211. if write_file:
  212. tools.write_file(self.fname, b'hello')
  213. btest = Bintool.create('_testing')
  214. col = terminal.Color()
  215. self.fname = None
  216. with unittest.mock.patch.object(bintool.Bintool, 'tooldir',
  217. self._indir):
  218. with unittest.mock.patch.object(tools, 'run', side_effect=fake_run):
  219. with test_util.capture_sys_output() as (stdout, _):
  220. btest.fetch_tool(bintool.FETCH_BUILD, col, False)
  221. fname = os.path.join(self._indir, '_testing')
  222. return fname if write_file else self.fname, stdout.getvalue()
  223. def test_build_method(self):
  224. """Test fetching using the build method"""
  225. fname, stdout = self.check_build_method(write_file=True)
  226. self.assertTrue(os.path.exists(fname))
  227. self.assertIn(f"writing to '{fname}", stdout)
  228. def test_build_method_fail(self):
  229. """Test fetching using the build method when no file is produced"""
  230. fname, stdout = self.check_build_method(write_file=False)
  231. self.assertFalse(os.path.exists(fname))
  232. self.assertIn(f"File '{fname}' was not produced", stdout)
  233. def test_install(self):
  234. """Test fetching using the install method"""
  235. btest = Bintool.create('_testing')
  236. btest.install = True
  237. col = terminal.Color()
  238. with unittest.mock.patch.object(tools, 'run', return_value=None):
  239. with test_util.capture_sys_output() as _:
  240. result = btest.fetch_tool(bintool.FETCH_BIN, col, False)
  241. self.assertEqual(bintool.FETCHED, result)
  242. def test_no_fetch(self):
  243. """Test fetching when there is no method"""
  244. btest = Bintool.create('_testing')
  245. btest.disable = True
  246. col = terminal.Color()
  247. with test_util.capture_sys_output() as _:
  248. result = btest.fetch_tool(bintool.FETCH_BIN, col, False)
  249. self.assertEqual(bintool.FAIL, result)
  250. def test_all_bintools(self):
  251. """Test that all bintools can handle all available fetch types"""
  252. def handle_download(_):
  253. """Take the tools.download() function by writing a file"""
  254. tools.write_file(fname, expected)
  255. return fname, dirname
  256. def fake_run(*cmd):
  257. if cmd[0] == 'make':
  258. # See Bintool.build_from_git()
  259. tmpdir = cmd[2]
  260. self.fname = os.path.join(tmpdir, 'pathname')
  261. tools.write_file(self.fname, b'hello')
  262. expected = b'this is a test'
  263. dirname = os.path.join(self._indir, 'download_dir')
  264. os.mkdir(dirname)
  265. fname = os.path.join(dirname, 'downloaded')
  266. with unittest.mock.patch.object(tools, 'run', side_effect=fake_run):
  267. with unittest.mock.patch.object(tools, 'download',
  268. side_effect=handle_download):
  269. with test_util.capture_sys_output() as _:
  270. for name in Bintool.get_tool_list():
  271. btool = Bintool.create(name)
  272. for method in range(bintool.FETCH_COUNT):
  273. result = btool.fetch(method)
  274. self.assertTrue(result is not False)
  275. if result is not True and result is not None:
  276. result_fname, _ = result
  277. self.assertTrue(os.path.exists(result_fname))
  278. data = tools.read_file(result_fname)
  279. self.assertEqual(expected, data)
  280. os.remove(result_fname)
  281. def test_all_bintool_versions(self):
  282. """Test handling of bintool version when it cannot be run"""
  283. all_tools = Bintool.get_tool_list()
  284. for name in all_tools:
  285. btool = Bintool.create(name)
  286. with unittest.mock.patch.object(
  287. btool, 'run_cmd_result', return_value=command.CommandResult()):
  288. self.assertEqual('unknown', btool.version())
  289. def test_force_missing(self):
  290. btool = Bintool.create('_testing')
  291. btool.present = True
  292. self.assertTrue(btool.is_present())
  293. btool.present = None
  294. Bintool.set_missing_list(['_testing'])
  295. self.assertFalse(btool.is_present())
  296. def test_failed_command(self):
  297. """Check that running a command that does not exist returns None"""
  298. destdir = os.path.join(self._indir, 'dest_dir')
  299. os.mkdir(destdir)
  300. with unittest.mock.patch.object(bintool.Bintool, 'tooldir', destdir):
  301. btool = Bintool.create('_testing')
  302. result = btool.run_cmd_result('fred')
  303. self.assertIsNone(result)
  304. if __name__ == "__main__":
  305. unittest.main()