test_fdt.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0+
  3. # Copyright (c) 2018 Google, Inc
  4. # Written by Simon Glass <sjg@chromium.org>
  5. #
  6. from __future__ import print_function
  7. from optparse import OptionParser
  8. import glob
  9. import os
  10. import shutil
  11. import sys
  12. import tempfile
  13. import unittest
  14. # Bring in the patman libraries
  15. our_path = os.path.dirname(os.path.realpath(__file__))
  16. for dirname in ['../patman', '..']:
  17. sys.path.insert(0, os.path.join(our_path, dirname))
  18. import command
  19. import fdt
  20. from fdt import TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL, BytesToValue
  21. import fdt_util
  22. from fdt_util import fdt32_to_cpu
  23. import libfdt
  24. import test_util
  25. import tools
  26. def _GetPropertyValue(dtb, node, prop_name):
  27. """Low-level function to get the property value based on its offset
  28. This looks directly in the device tree at the property's offset to find
  29. its value. It is useful as a check that the property is in the correct
  30. place.
  31. Args:
  32. node: Node to look in
  33. prop_name: Property name to find
  34. Returns:
  35. Tuple:
  36. Prop object found
  37. Value of property as a string (found using property offset)
  38. """
  39. prop = node.props[prop_name]
  40. # Add 12, which is sizeof(struct fdt_property), to get to start of data
  41. offset = prop.GetOffset() + 12
  42. data = dtb.GetContents()[offset:offset + len(prop.value)]
  43. return prop, [tools.ToChar(x) for x in data]
  44. class TestFdt(unittest.TestCase):
  45. """Tests for the Fdt module
  46. This includes unit tests for some functions and functional tests for the fdt
  47. module.
  48. """
  49. @classmethod
  50. def setUpClass(cls):
  51. tools.PrepareOutputDir(None)
  52. @classmethod
  53. def tearDownClass(cls):
  54. tools.FinaliseOutputDir()
  55. def setUp(self):
  56. self.dtb = fdt.FdtScan('tools/dtoc/dtoc_test_simple.dts')
  57. def testFdt(self):
  58. """Test that we can open an Fdt"""
  59. self.dtb.Scan()
  60. root = self.dtb.GetRoot()
  61. self.assertTrue(isinstance(root, fdt.Node))
  62. def testGetNode(self):
  63. """Test the GetNode() method"""
  64. node = self.dtb.GetNode('/spl-test')
  65. self.assertTrue(isinstance(node, fdt.Node))
  66. node = self.dtb.GetNode('/i2c@0/pmic@9')
  67. self.assertTrue(isinstance(node, fdt.Node))
  68. self.assertEqual('pmic@9', node.name)
  69. self.assertIsNone(self.dtb.GetNode('/i2c@0/pmic@9/missing'))
  70. node = self.dtb.GetNode('/')
  71. self.assertTrue(isinstance(node, fdt.Node))
  72. self.assertEqual(0, node.Offset())
  73. def testFlush(self):
  74. """Check that we can flush the device tree out to its file"""
  75. fname = self.dtb._fname
  76. with open(fname, 'rb') as fd:
  77. data = fd.read()
  78. os.remove(fname)
  79. with self.assertRaises(IOError):
  80. open(fname, 'rb')
  81. self.dtb.Flush()
  82. with open(fname, 'rb') as fd:
  83. data = fd.read()
  84. def testPack(self):
  85. """Test that packing a device tree works"""
  86. self.dtb.Pack()
  87. def testGetFdt(self):
  88. """Tetst that we can access the raw device-tree data"""
  89. self.assertTrue(isinstance(self.dtb.GetContents(), bytearray))
  90. def testGetProps(self):
  91. """Tests obtaining a list of properties"""
  92. node = self.dtb.GetNode('/spl-test')
  93. props = self.dtb.GetProps(node)
  94. self.assertEqual(['boolval', 'bytearray', 'byteval', 'compatible',
  95. 'intarray', 'intval', 'longbytearray', 'notstring',
  96. 'stringarray', 'stringval', 'u-boot,dm-pre-reloc'],
  97. sorted(props.keys()))
  98. def testCheckError(self):
  99. """Tests the ChecKError() function"""
  100. with self.assertRaises(ValueError) as e:
  101. fdt.CheckErr(-libfdt.NOTFOUND, 'hello')
  102. self.assertIn('FDT_ERR_NOTFOUND: hello', str(e.exception))
  103. def testGetFdt(self):
  104. node = self.dtb.GetNode('/spl-test')
  105. self.assertEqual(self.dtb, node.GetFdt())
  106. def testBytesToValue(self):
  107. self.assertEqual(BytesToValue(b'this\0is\0'),
  108. (TYPE_STRING, ['this', 'is']))
  109. class TestNode(unittest.TestCase):
  110. """Test operation of the Node class"""
  111. @classmethod
  112. def setUpClass(cls):
  113. tools.PrepareOutputDir(None)
  114. @classmethod
  115. def tearDownClass(cls):
  116. tools.FinaliseOutputDir()
  117. def setUp(self):
  118. self.dtb = fdt.FdtScan('tools/dtoc/dtoc_test_simple.dts')
  119. self.node = self.dtb.GetNode('/spl-test')
  120. def testOffset(self):
  121. """Tests that we can obtain the offset of a node"""
  122. self.assertTrue(self.node.Offset() > 0)
  123. def testDelete(self):
  124. """Tests that we can delete a property"""
  125. node2 = self.dtb.GetNode('/spl-test2')
  126. offset1 = node2.Offset()
  127. self.node.DeleteProp('intval')
  128. offset2 = node2.Offset()
  129. self.assertTrue(offset2 < offset1)
  130. self.node.DeleteProp('intarray')
  131. offset3 = node2.Offset()
  132. self.assertTrue(offset3 < offset2)
  133. with self.assertRaises(libfdt.FdtException):
  134. self.node.DeleteProp('missing')
  135. def testDeleteGetOffset(self):
  136. """Test that property offset update when properties are deleted"""
  137. self.node.DeleteProp('intval')
  138. prop, value = _GetPropertyValue(self.dtb, self.node, 'longbytearray')
  139. self.assertEqual(prop.value, value)
  140. def testFindNode(self):
  141. """Tests that we can find a node using the FindNode() functoin"""
  142. node = self.dtb.GetRoot().FindNode('i2c@0')
  143. self.assertEqual('i2c@0', node.name)
  144. subnode = node.FindNode('pmic@9')
  145. self.assertEqual('pmic@9', subnode.name)
  146. self.assertEqual(None, node.FindNode('missing'))
  147. def testRefreshMissingNode(self):
  148. """Test refreshing offsets when an extra node is present in dtb"""
  149. # Delete it from our tables, not the device tree
  150. del self.dtb._root.subnodes[-1]
  151. with self.assertRaises(ValueError) as e:
  152. self.dtb.Refresh()
  153. self.assertIn('Internal error, offset', str(e.exception))
  154. def testRefreshExtraNode(self):
  155. """Test refreshing offsets when an expected node is missing"""
  156. # Delete it from the device tre, not our tables
  157. self.dtb.GetFdtObj().del_node(self.node.Offset())
  158. with self.assertRaises(ValueError) as e:
  159. self.dtb.Refresh()
  160. self.assertIn('Internal error, node name mismatch '
  161. 'spl-test != spl-test2', str(e.exception))
  162. def testRefreshMissingProp(self):
  163. """Test refreshing offsets when an extra property is present in dtb"""
  164. # Delete it from our tables, not the device tree
  165. del self.node.props['notstring']
  166. with self.assertRaises(ValueError) as e:
  167. self.dtb.Refresh()
  168. self.assertIn("Internal error, property 'notstring' missing, offset ",
  169. str(e.exception))
  170. def testLookupPhandle(self):
  171. """Test looking up a single phandle"""
  172. dtb = fdt.FdtScan('tools/dtoc/dtoc_test_phandle.dts')
  173. node = dtb.GetNode('/phandle-source2')
  174. prop = node.props['clocks']
  175. target = dtb.GetNode('/phandle-target')
  176. self.assertEqual(target, dtb.LookupPhandle(fdt32_to_cpu(prop.value)))
  177. class TestProp(unittest.TestCase):
  178. """Test operation of the Prop class"""
  179. @classmethod
  180. def setUpClass(cls):
  181. tools.PrepareOutputDir(None)
  182. @classmethod
  183. def tearDownClass(cls):
  184. tools.FinaliseOutputDir()
  185. def setUp(self):
  186. self.dtb = fdt.FdtScan('tools/dtoc/dtoc_test_simple.dts')
  187. self.node = self.dtb.GetNode('/spl-test')
  188. self.fdt = self.dtb.GetFdtObj()
  189. def testMissingNode(self):
  190. self.assertEqual(None, self.dtb.GetNode('missing'))
  191. def testPhandle(self):
  192. dtb = fdt.FdtScan('tools/dtoc/dtoc_test_phandle.dts')
  193. node = dtb.GetNode('/phandle-source2')
  194. prop = node.props['clocks']
  195. self.assertTrue(fdt32_to_cpu(prop.value) > 0)
  196. def _ConvertProp(self, prop_name):
  197. """Helper function to look up a property in self.node and return it
  198. Args:
  199. Property name to find
  200. Return fdt.Prop object for this property
  201. """
  202. p = self.fdt.getprop(self.node.Offset(), prop_name)
  203. return fdt.Prop(self.node, -1, prop_name, p)
  204. def testMakeProp(self):
  205. """Test we can convert all the the types that are supported"""
  206. prop = self._ConvertProp('boolval')
  207. self.assertEqual(fdt.TYPE_BOOL, prop.type)
  208. self.assertEqual(True, prop.value)
  209. prop = self._ConvertProp('intval')
  210. self.assertEqual(fdt.TYPE_INT, prop.type)
  211. self.assertEqual(1, fdt32_to_cpu(prop.value))
  212. prop = self._ConvertProp('intarray')
  213. self.assertEqual(fdt.TYPE_INT, prop.type)
  214. val = [fdt32_to_cpu(val) for val in prop.value]
  215. self.assertEqual([2, 3, 4], val)
  216. prop = self._ConvertProp('byteval')
  217. self.assertEqual(fdt.TYPE_BYTE, prop.type)
  218. self.assertEqual(5, ord(prop.value))
  219. prop = self._ConvertProp('longbytearray')
  220. self.assertEqual(fdt.TYPE_BYTE, prop.type)
  221. val = [ord(val) for val in prop.value]
  222. self.assertEqual([9, 10, 11, 12, 13, 14, 15, 16, 17], val)
  223. prop = self._ConvertProp('stringval')
  224. self.assertEqual(fdt.TYPE_STRING, prop.type)
  225. self.assertEqual('message', prop.value)
  226. prop = self._ConvertProp('stringarray')
  227. self.assertEqual(fdt.TYPE_STRING, prop.type)
  228. self.assertEqual(['multi-word', 'message'], prop.value)
  229. prop = self._ConvertProp('notstring')
  230. self.assertEqual(fdt.TYPE_BYTE, prop.type)
  231. val = [ord(val) for val in prop.value]
  232. self.assertEqual([0x20, 0x21, 0x22, 0x10, 0], val)
  233. def testGetEmpty(self):
  234. """Tests the GetEmpty() function for the various supported types"""
  235. self.assertEqual(True, fdt.Prop.GetEmpty(fdt.TYPE_BOOL))
  236. self.assertEqual(chr(0), fdt.Prop.GetEmpty(fdt.TYPE_BYTE))
  237. self.assertEqual(tools.GetBytes(0, 4), fdt.Prop.GetEmpty(fdt.TYPE_INT))
  238. self.assertEqual('', fdt.Prop.GetEmpty(fdt.TYPE_STRING))
  239. def testGetOffset(self):
  240. """Test we can get the offset of a property"""
  241. prop, value = _GetPropertyValue(self.dtb, self.node, 'longbytearray')
  242. self.assertEqual(prop.value, value)
  243. def testWiden(self):
  244. """Test widening of values"""
  245. node2 = self.dtb.GetNode('/spl-test2')
  246. prop = self.node.props['intval']
  247. # No action
  248. prop2 = node2.props['intval']
  249. prop.Widen(prop2)
  250. self.assertEqual(fdt.TYPE_INT, prop.type)
  251. self.assertEqual(1, fdt32_to_cpu(prop.value))
  252. # Convert singla value to array
  253. prop2 = self.node.props['intarray']
  254. prop.Widen(prop2)
  255. self.assertEqual(fdt.TYPE_INT, prop.type)
  256. self.assertTrue(isinstance(prop.value, list))
  257. # A 4-byte array looks like a single integer. When widened by a longer
  258. # byte array, it should turn into an array.
  259. prop = self.node.props['longbytearray']
  260. prop2 = node2.props['longbytearray']
  261. self.assertFalse(isinstance(prop2.value, list))
  262. self.assertEqual(4, len(prop2.value))
  263. prop2.Widen(prop)
  264. self.assertTrue(isinstance(prop2.value, list))
  265. self.assertEqual(9, len(prop2.value))
  266. # Similarly for a string array
  267. prop = self.node.props['stringval']
  268. prop2 = node2.props['stringarray']
  269. self.assertFalse(isinstance(prop.value, list))
  270. self.assertEqual(7, len(prop.value))
  271. prop.Widen(prop2)
  272. self.assertTrue(isinstance(prop.value, list))
  273. self.assertEqual(3, len(prop.value))
  274. # Enlarging an existing array
  275. prop = self.node.props['stringarray']
  276. prop2 = node2.props['stringarray']
  277. self.assertTrue(isinstance(prop.value, list))
  278. self.assertEqual(2, len(prop.value))
  279. prop.Widen(prop2)
  280. self.assertTrue(isinstance(prop.value, list))
  281. self.assertEqual(3, len(prop.value))
  282. def testAdd(self):
  283. """Test adding properties"""
  284. self.fdt.pack()
  285. # This function should automatically expand the device tree
  286. self.node.AddZeroProp('one')
  287. self.node.AddZeroProp('two')
  288. self.node.AddZeroProp('three')
  289. self.dtb.Sync(auto_resize=True)
  290. # Updating existing properties should be OK, since the device-tree size
  291. # does not change
  292. self.fdt.pack()
  293. self.node.SetInt('one', 1)
  294. self.node.SetInt('two', 2)
  295. self.node.SetInt('three', 3)
  296. self.dtb.Sync(auto_resize=False)
  297. # This should fail since it would need to increase the device-tree size
  298. self.node.AddZeroProp('four')
  299. with self.assertRaises(libfdt.FdtException) as e:
  300. self.dtb.Sync(auto_resize=False)
  301. self.assertIn('FDT_ERR_NOSPACE', str(e.exception))
  302. self.dtb.Sync(auto_resize=True)
  303. def testAddNode(self):
  304. self.fdt.pack()
  305. self.node.AddSubnode('subnode')
  306. with self.assertRaises(libfdt.FdtException) as e:
  307. self.dtb.Sync(auto_resize=False)
  308. self.assertIn('FDT_ERR_NOSPACE', str(e.exception))
  309. self.dtb.Sync(auto_resize=True)
  310. offset = self.fdt.path_offset('/spl-test/subnode')
  311. self.assertTrue(offset > 0)
  312. def testAddMore(self):
  313. """Test various other methods for adding and setting properties"""
  314. self.node.AddZeroProp('one')
  315. self.dtb.Sync(auto_resize=True)
  316. data = self.fdt.getprop(self.node.Offset(), 'one')
  317. self.assertEqual(0, fdt32_to_cpu(data))
  318. self.node.SetInt('one', 1)
  319. self.dtb.Sync(auto_resize=False)
  320. data = self.fdt.getprop(self.node.Offset(), 'one')
  321. self.assertEqual(1, fdt32_to_cpu(data))
  322. val = '123' + chr(0) + '456'
  323. self.node.AddString('string', val)
  324. self.dtb.Sync(auto_resize=True)
  325. data = self.fdt.getprop(self.node.Offset(), 'string')
  326. self.assertEqual(tools.ToBytes(val) + b'\0', data)
  327. self.fdt.pack()
  328. self.node.SetString('string', val + 'x')
  329. with self.assertRaises(libfdt.FdtException) as e:
  330. self.dtb.Sync(auto_resize=False)
  331. self.assertIn('FDT_ERR_NOSPACE', str(e.exception))
  332. self.node.SetString('string', val[:-1])
  333. prop = self.node.props['string']
  334. prop.SetData(tools.ToBytes(val))
  335. self.dtb.Sync(auto_resize=False)
  336. data = self.fdt.getprop(self.node.Offset(), 'string')
  337. self.assertEqual(tools.ToBytes(val), data)
  338. self.node.AddEmptyProp('empty', 5)
  339. self.dtb.Sync(auto_resize=True)
  340. prop = self.node.props['empty']
  341. prop.SetData(tools.ToBytes(val))
  342. self.dtb.Sync(auto_resize=False)
  343. data = self.fdt.getprop(self.node.Offset(), 'empty')
  344. self.assertEqual(tools.ToBytes(val), data)
  345. self.node.SetData('empty', b'123')
  346. self.assertEqual(b'123', prop.bytes)
  347. def testFromData(self):
  348. dtb2 = fdt.Fdt.FromData(self.dtb.GetContents())
  349. self.assertEqual(dtb2.GetContents(), self.dtb.GetContents())
  350. self.node.AddEmptyProp('empty', 5)
  351. self.dtb.Sync(auto_resize=True)
  352. self.assertTrue(dtb2.GetContents() != self.dtb.GetContents())
  353. def testMissingSetInt(self):
  354. """Test handling of a missing property with SetInt"""
  355. with self.assertRaises(ValueError) as e:
  356. self.node.SetInt('one', 1)
  357. self.assertIn("node '/spl-test': Missing property 'one'",
  358. str(e.exception))
  359. def testMissingSetData(self):
  360. """Test handling of a missing property with SetData"""
  361. with self.assertRaises(ValueError) as e:
  362. self.node.SetData('one', b'data')
  363. self.assertIn("node '/spl-test': Missing property 'one'",
  364. str(e.exception))
  365. def testMissingSetString(self):
  366. """Test handling of a missing property with SetString"""
  367. with self.assertRaises(ValueError) as e:
  368. self.node.SetString('one', 1)
  369. self.assertIn("node '/spl-test': Missing property 'one'",
  370. str(e.exception))
  371. def testGetFilename(self):
  372. """Test the dtb filename can be provided"""
  373. self.assertEqual(tools.GetOutputFilename('source.dtb'),
  374. self.dtb.GetFilename())
  375. class TestFdtUtil(unittest.TestCase):
  376. """Tests for the fdt_util module
  377. This module will likely be mostly replaced at some point, once upstream
  378. libfdt has better Python support. For now, this provides tests for current
  379. functionality.
  380. """
  381. @classmethod
  382. def setUpClass(cls):
  383. tools.PrepareOutputDir(None)
  384. @classmethod
  385. def tearDownClass(cls):
  386. tools.FinaliseOutputDir()
  387. def setUp(self):
  388. self.dtb = fdt.FdtScan('tools/dtoc/dtoc_test_simple.dts')
  389. self.node = self.dtb.GetNode('/spl-test')
  390. def testGetInt(self):
  391. self.assertEqual(1, fdt_util.GetInt(self.node, 'intval'))
  392. self.assertEqual(3, fdt_util.GetInt(self.node, 'missing', 3))
  393. with self.assertRaises(ValueError) as e:
  394. self.assertEqual(3, fdt_util.GetInt(self.node, 'intarray'))
  395. self.assertIn("property 'intarray' has list value: expecting a single "
  396. 'integer', str(e.exception))
  397. def testGetString(self):
  398. self.assertEqual('message', fdt_util.GetString(self.node, 'stringval'))
  399. self.assertEqual('test', fdt_util.GetString(self.node, 'missing',
  400. 'test'))
  401. with self.assertRaises(ValueError) as e:
  402. self.assertEqual(3, fdt_util.GetString(self.node, 'stringarray'))
  403. self.assertIn("property 'stringarray' has list value: expecting a "
  404. 'single string', str(e.exception))
  405. def testGetBool(self):
  406. self.assertEqual(True, fdt_util.GetBool(self.node, 'boolval'))
  407. self.assertEqual(False, fdt_util.GetBool(self.node, 'missing'))
  408. self.assertEqual(True, fdt_util.GetBool(self.node, 'missing', True))
  409. self.assertEqual(False, fdt_util.GetBool(self.node, 'missing', False))
  410. def testGetByte(self):
  411. self.assertEqual(5, fdt_util.GetByte(self.node, 'byteval'))
  412. self.assertEqual(3, fdt_util.GetByte(self.node, 'missing', 3))
  413. with self.assertRaises(ValueError) as e:
  414. fdt_util.GetByte(self.node, 'longbytearray')
  415. self.assertIn("property 'longbytearray' has list value: expecting a "
  416. 'single byte', str(e.exception))
  417. with self.assertRaises(ValueError) as e:
  418. fdt_util.GetByte(self.node, 'intval')
  419. self.assertIn("property 'intval' has length 4, expecting 1",
  420. str(e.exception))
  421. def testGetPhandleList(self):
  422. dtb = fdt.FdtScan('tools/dtoc/dtoc_test_phandle.dts')
  423. node = dtb.GetNode('/phandle-source2')
  424. self.assertEqual([1], fdt_util.GetPhandleList(node, 'clocks'))
  425. node = dtb.GetNode('/phandle-source')
  426. self.assertEqual([1, 2, 11, 3, 12, 13, 1],
  427. fdt_util.GetPhandleList(node, 'clocks'))
  428. self.assertEqual(None, fdt_util.GetPhandleList(node, 'missing'))
  429. def testGetDataType(self):
  430. self.assertEqual(1, fdt_util.GetDatatype(self.node, 'intval', int))
  431. self.assertEqual('message', fdt_util.GetDatatype(self.node, 'stringval',
  432. str))
  433. with self.assertRaises(ValueError) as e:
  434. self.assertEqual(3, fdt_util.GetDatatype(self.node, 'boolval',
  435. bool))
  436. def testFdtCellsToCpu(self):
  437. val = self.node.props['intarray'].value
  438. self.assertEqual(0, fdt_util.fdt_cells_to_cpu(val, 0))
  439. self.assertEqual(2, fdt_util.fdt_cells_to_cpu(val, 1))
  440. dtb2 = fdt.FdtScan('tools/dtoc/dtoc_test_addr64.dts')
  441. node1 = dtb2.GetNode('/test1')
  442. val = node1.props['reg'].value
  443. self.assertEqual(0x1234, fdt_util.fdt_cells_to_cpu(val, 2))
  444. node2 = dtb2.GetNode('/test2')
  445. val = node2.props['reg'].value
  446. self.assertEqual(0x1234567890123456, fdt_util.fdt_cells_to_cpu(val, 2))
  447. self.assertEqual(0x9876543210987654, fdt_util.fdt_cells_to_cpu(val[2:],
  448. 2))
  449. self.assertEqual(0x12345678, fdt_util.fdt_cells_to_cpu(val, 1))
  450. def testEnsureCompiled(self):
  451. """Test a degenerate case of this function (file already compiled)"""
  452. dtb = fdt_util.EnsureCompiled('tools/dtoc/dtoc_test_simple.dts')
  453. self.assertEqual(dtb, fdt_util.EnsureCompiled(dtb))
  454. def testEnsureCompiledTmpdir(self):
  455. """Test providing a temporary directory"""
  456. try:
  457. old_outdir = tools.outdir
  458. tools.outdir= None
  459. tmpdir = tempfile.mkdtemp(prefix='test_fdt.')
  460. dtb = fdt_util.EnsureCompiled('tools/dtoc/dtoc_test_simple.dts',
  461. tmpdir)
  462. self.assertEqual(tmpdir, os.path.dirname(dtb))
  463. shutil.rmtree(tmpdir)
  464. finally:
  465. tools.outdir= old_outdir
  466. def RunTestCoverage():
  467. """Run the tests and check that we get 100% coverage"""
  468. test_util.RunTestCoverage('tools/dtoc/test_fdt.py', None,
  469. ['tools/patman/*.py', '*test_fdt.py'], options.build_dir)
  470. def RunTests(args):
  471. """Run all the test we have for the fdt model
  472. Args:
  473. args: List of positional args provided to fdt. This can hold a test
  474. name to execute (as in 'fdt -t testFdt', for example)
  475. """
  476. result = unittest.TestResult()
  477. sys.argv = [sys.argv[0]]
  478. test_name = args and args[0] or None
  479. for module in (TestFdt, TestNode, TestProp, TestFdtUtil):
  480. if test_name:
  481. try:
  482. suite = unittest.TestLoader().loadTestsFromName(test_name, module)
  483. except AttributeError:
  484. continue
  485. else:
  486. suite = unittest.TestLoader().loadTestsFromTestCase(module)
  487. suite.run(result)
  488. print(result)
  489. for _, err in result.errors:
  490. print(err)
  491. for _, err in result.failures:
  492. print(err)
  493. if __name__ != '__main__':
  494. sys.exit(1)
  495. parser = OptionParser()
  496. parser.add_option('-B', '--build-dir', type='string', default='b',
  497. help='Directory containing the build output')
  498. parser.add_option('-P', '--processes', type=int,
  499. help='set number of processes to use for running tests')
  500. parser.add_option('-t', '--test', action='store_true', dest='test',
  501. default=False, help='run tests')
  502. parser.add_option('-T', '--test-coverage', action='store_true',
  503. default=False, help='run tests and check for 100% coverage')
  504. (options, args) = parser.parse_args()
  505. # Run our meagre tests
  506. if options.test:
  507. RunTests(args)
  508. elif options.test_coverage:
  509. RunTestCoverage()