PageRenderTime 33ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/generate_stubs/generate_stubs_unittest.py

https://github.com/chromium/chromium
Python | 325 lines | 316 code | 1 blank | 8 comment | 2 complexity | a54ddc9d83865d9f38be8338414d2322 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, Apache-2.0, BSD-3-Clause
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Unittest for the generate_stubs.py.
  6. Since generate_stubs.py is a code generator, it is hard to do a very good
  7. test. Instead of creating a golden-file test, which might be flaky, this
  8. test elects instead to verify that various components "exist" within the
  9. generated file as a sanity check. In particular, there is a simple hit
  10. test to make sure that umbrella functions, etc., do try and include every
  11. function they are responsible for invoking. Missing an invocation is quite
  12. easily missed.
  13. There is no attempt to verify ordering of different components, or whether
  14. or not those components are going to parse incorrectly because of prior
  15. errors or positioning. Most of that should be caught really fast anyways
  16. during any attempt to use a badly behaving script.
  17. """
  18. import generate_stubs as gs
  19. import re
  20. import StringIO
  21. import sys
  22. import unittest
  23. def _MakeSignature(return_type, name, params):
  24. return {'return_type': return_type,
  25. 'name': name,
  26. 'params': params}
  27. SIMPLE_SIGNATURES = [
  28. ('int foo(int a)', _MakeSignature('int', 'foo', ['int a'])),
  29. ('int bar(int a, double b)', _MakeSignature('int', 'bar',
  30. ['int a', 'double b'])),
  31. ('int baz(void)', _MakeSignature('int', 'baz', ['void'])),
  32. ('void quux(void)', _MakeSignature('void', 'quux', ['void'])),
  33. ('void waldo(void);', _MakeSignature('void', 'waldo', ['void'])),
  34. ('int corge(void);', _MakeSignature('int', 'corge', ['void'])),
  35. ('int ferda(char **argv[]);',
  36. _MakeSignature('int', 'ferda', ['char **argv[]'])),
  37. ]
  38. TRICKY_SIGNATURES = [
  39. ('const struct name *foo(int a, struct Test* b); ',
  40. _MakeSignature('const struct name *',
  41. 'foo',
  42. ['int a', 'struct Test* b'])),
  43. ('const struct name &foo(int a, struct Test* b);',
  44. _MakeSignature('const struct name &',
  45. 'foo',
  46. ['int a', 'struct Test* b'])),
  47. ('const struct name &_foo(int a, struct Test* b);',
  48. _MakeSignature('const struct name &',
  49. '_foo',
  50. ['int a', 'struct Test* b'])),
  51. ('struct name const * const _foo(int a, struct Test* b) '
  52. '__attribute__((inline));',
  53. _MakeSignature('struct name const * const',
  54. '_foo',
  55. ['int a', 'struct Test* b']))
  56. ]
  57. INVALID_SIGNATURES = ['I am bad', 'Seriously bad(', ';;;']
  58. class GenerateStubModuleFunctionsUnittest(unittest.TestCase):
  59. def testExtractModuleName(self):
  60. self.assertEqual('somefile-2', gs.ExtractModuleName('somefile-2.ext'))
  61. def testParseSignatures_EmptyFile(self):
  62. # Empty file just generates empty signatures.
  63. infile = StringIO.StringIO()
  64. signatures = gs.ParseSignatures(infile)
  65. self.assertEqual(0, len(signatures))
  66. def testParseSignatures_SimpleSignatures(self):
  67. file_contents = '\n'.join([x[0] for x in SIMPLE_SIGNATURES])
  68. infile = StringIO.StringIO(file_contents)
  69. signatures = gs.ParseSignatures(infile)
  70. self.assertEqual(len(SIMPLE_SIGNATURES), len(signatures))
  71. # We assume signatures are in order.
  72. for i in xrange(len(SIMPLE_SIGNATURES)):
  73. self.assertEqual(SIMPLE_SIGNATURES[i][1], signatures[i],
  74. msg='Expected %s\nActual %s\nFor %s' %
  75. (SIMPLE_SIGNATURES[i][1],
  76. signatures[i],
  77. SIMPLE_SIGNATURES[i][0]))
  78. def testParseSignatures_TrickySignatures(self):
  79. file_contents = '\n'.join([x[0] for x in TRICKY_SIGNATURES])
  80. infile = StringIO.StringIO(file_contents)
  81. signatures = gs.ParseSignatures(infile)
  82. self.assertEqual(len(TRICKY_SIGNATURES), len(signatures))
  83. # We assume signatures are in order.
  84. for i in xrange(len(TRICKY_SIGNATURES)):
  85. self.assertEqual(TRICKY_SIGNATURES[i][1], signatures[i],
  86. msg='Expected %s\nActual %s\nFor %s' %
  87. (TRICKY_SIGNATURES[i][1],
  88. signatures[i],
  89. TRICKY_SIGNATURES[i][0]))
  90. def testParseSignatures_InvalidSignatures(self):
  91. for i in INVALID_SIGNATURES:
  92. infile = StringIO.StringIO(i)
  93. self.assertRaises(gs.BadSignatureError, gs.ParseSignatures, infile)
  94. def testParseSignatures_CommentsIgnored(self):
  95. my_sigs = []
  96. my_sigs.append('# a comment')
  97. my_sigs.append(SIMPLE_SIGNATURES[0][0])
  98. my_sigs.append('# another comment')
  99. my_sigs.append(SIMPLE_SIGNATURES[0][0])
  100. my_sigs.append('# a third comment')
  101. my_sigs.append(SIMPLE_SIGNATURES[0][0])
  102. my_sigs.append('// a fourth comment')
  103. my_sigs.append(SIMPLE_SIGNATURES[0][0])
  104. my_sigs.append('//')
  105. my_sigs.append(SIMPLE_SIGNATURES[0][0])
  106. file_contents = '\n'.join(my_sigs)
  107. infile = StringIO.StringIO(file_contents)
  108. signatures = gs.ParseSignatures(infile)
  109. self.assertEqual(5, len(signatures))
  110. class WindowsLibUnittest(unittest.TestCase):
  111. def testWriteWindowsDefFile(self):
  112. module_name = 'my_module-1'
  113. signatures = [sig[1] for sig in SIMPLE_SIGNATURES]
  114. outfile = StringIO.StringIO()
  115. gs.WriteWindowsDefFile(module_name, signatures, outfile)
  116. contents = outfile.getvalue()
  117. # Check that the file header is correct.
  118. self.assertTrue(contents.startswith("""LIBRARY %s
  119. EXPORTS
  120. """ % module_name))
  121. # Check that the signatures were exported.
  122. for sig in signatures:
  123. pattern = '\n %s\n' % sig['name']
  124. self.assertTrue(re.search(pattern, contents),
  125. msg='Expected match of "%s" in %s' % (pattern, contents))
  126. def testQuietRun(self):
  127. output = StringIO.StringIO()
  128. gs.QuietRun([
  129. sys.executable, '-c',
  130. 'from __future__ import print_function; print("line 1 and suffix\\nline 2")'
  131. ],
  132. write_to=output)
  133. self.assertEqual('line 1 and suffix\nline 2\n', output.getvalue())
  134. output = StringIO.StringIO()
  135. gs.QuietRun([
  136. sys.executable, '-c',
  137. 'from __future__ import print_function; print("line 1 and suffix\\nline 2")'
  138. ],
  139. filter='line 1',
  140. write_to=output)
  141. self.assertEqual('line 2\n', output.getvalue())
  142. class PosixStubWriterUnittest(unittest.TestCase):
  143. def setUp(self):
  144. self.module_name = 'my_module-1'
  145. self.signatures = [sig[1] for sig in SIMPLE_SIGNATURES]
  146. self.out_dir = 'out_dir'
  147. self.writer = gs.PosixStubWriter(self.module_name, '', self.signatures,
  148. 'VLOG(1)', 'base/logging.h')
  149. def testEnumName(self):
  150. self.assertEqual('kModuleMy_module1',
  151. gs.PosixStubWriter.EnumName(self.module_name))
  152. def testIsInitializedName(self):
  153. self.assertEqual('IsMy_module1Initialized',
  154. gs.PosixStubWriter.IsInitializedName(self.module_name))
  155. def testInitializeModuleName(self):
  156. self.assertEqual(
  157. 'InitializeMy_module1',
  158. gs.PosixStubWriter.InitializeModuleName(self.module_name))
  159. def testUninitializeModuleName(self):
  160. self.assertEqual(
  161. 'UninitializeMy_module1',
  162. gs.PosixStubWriter.UninitializeModuleName(self.module_name))
  163. def testStubFunctionPointer(self):
  164. self.assertEqual(
  165. 'static int (*foo_ptr)(int a) = NULL;',
  166. gs.PosixStubWriter.StubFunctionPointer(SIMPLE_SIGNATURES[0][1]))
  167. def testStubFunction(self):
  168. # Test for a signature with a return value and a parameter.
  169. self.assertEqual("""extern int foo(int a) __attribute__((weak));
  170. int foo(int a) {
  171. return foo_ptr(a);
  172. }""", gs.PosixStubWriter.StubFunction(SIMPLE_SIGNATURES[0][1]))
  173. # Test for a signature with a void return value and no parameters.
  174. self.assertEqual("""extern void waldo(void) __attribute__((weak));
  175. void waldo(void) {
  176. waldo_ptr();
  177. }""", gs.PosixStubWriter.StubFunction(SIMPLE_SIGNATURES[4][1]))
  178. # Test export macros.
  179. sig = _MakeSignature('int*', 'foo', ['bool b'])
  180. sig['export'] = 'TEST_EXPORT'
  181. self.assertEqual("""extern int* foo(bool b) __attribute__((weak));
  182. int* TEST_EXPORT foo(bool b) {
  183. return foo_ptr(b);
  184. }""", gs.PosixStubWriter.StubFunction(sig))
  185. # Test for a signature where an array is passed. It should be passed without
  186. # square brackets otherwise the compilation failure will occur..
  187. self.assertEqual("""extern int ferda(char **argv[]) __attribute__((weak));
  188. int ferda(char **argv[]) {
  189. return ferda_ptr(argv);
  190. }""", gs.PosixStubWriter.StubFunction(SIMPLE_SIGNATURES[6][1]))
  191. def testWriteImplemenationContents(self):
  192. outfile = StringIO.StringIO()
  193. self.writer.WriteImplementationContents('my_namespace', outfile)
  194. contents = outfile.getvalue()
  195. # Verify namespace exists somewhere.
  196. self.assertTrue(contents.find('namespace my_namespace {') != -1)
  197. # Verify that each signature has an _ptr and a function call in the file.
  198. # Check that the signatures were exported.
  199. for sig in self.signatures:
  200. decl = gs.PosixStubWriter.StubFunctionPointer(sig)
  201. self.assertTrue(contents.find(decl) != -1,
  202. msg='Expected "%s" in %s' % (decl, contents))
  203. # Verify that each signature has an stub function generated for it.
  204. for sig in self.signatures:
  205. decl = gs.PosixStubWriter.StubFunction(sig)
  206. self.assertTrue(contents.find(decl) != -1,
  207. msg='Expected "%s" in %s' % (decl, contents))
  208. # Find module initializer functions. Make sure all 3 exist.
  209. decl = gs.PosixStubWriter.InitializeModuleName(self.module_name)
  210. self.assertTrue(contents.find(decl) != -1,
  211. msg='Expected "%s" in %s' % (decl, contents))
  212. decl = gs.PosixStubWriter.UninitializeModuleName(self.module_name)
  213. self.assertTrue(contents.find(decl) != -1,
  214. msg='Expected "%s" in %s' % (decl, contents))
  215. decl = gs.PosixStubWriter.IsInitializedName(self.module_name)
  216. self.assertTrue(contents.find(decl) != -1,
  217. msg='Expected "%s" in %s' % (decl, contents))
  218. def testWriteHeaderContents(self):
  219. # Data for header generation.
  220. module_names = ['oneModule', 'twoModule']
  221. # Make the header.
  222. outfile = StringIO.StringIO()
  223. self.writer.WriteHeaderContents(module_names, 'my_namespace', 'GUARD_',
  224. outfile, 'base/logging.h')
  225. contents = outfile.getvalue()
  226. # Check for namespace and header guard.
  227. self.assertTrue(contents.find('namespace my_namespace {') != -1)
  228. self.assertTrue(contents.find('#ifndef GUARD_') != -1)
  229. # Check for umbrella initializer.
  230. self.assertTrue(contents.find('InitializeStubs(') != -1)
  231. # Check per-module declarations.
  232. for name in module_names:
  233. # Check for enums.
  234. decl = gs.PosixStubWriter.EnumName(name)
  235. self.assertTrue(contents.find(decl) != -1,
  236. msg='Expected "%s" in %s' % (decl, contents))
  237. # Check for module initializer functions.
  238. decl = gs.PosixStubWriter.IsInitializedName(name)
  239. self.assertTrue(contents.find(decl) != -1,
  240. msg='Expected "%s" in %s' % (decl, contents))
  241. decl = gs.PosixStubWriter.InitializeModuleName(name)
  242. self.assertTrue(contents.find(decl) != -1,
  243. msg='Expected "%s" in %s' % (decl, contents))
  244. decl = gs.PosixStubWriter.UninitializeModuleName(name)
  245. self.assertTrue(contents.find(decl) != -1,
  246. msg='Expected "%s" in %s' % (decl, contents))
  247. def testWriteUmbrellaInitializer(self):
  248. # Data for header generation.
  249. module_names = ['oneModule', 'twoModule']
  250. # Make the header.
  251. outfile = StringIO.StringIO()
  252. self.writer.WriteUmbrellaInitializer(module_names, 'my_namespace', outfile,
  253. 'VLOG(1)')
  254. contents = outfile.getvalue()
  255. # Check for umbrella initializer declaration.
  256. self.assertTrue(contents.find('bool InitializeStubs(') != -1)
  257. # If the umbrella initializer is correctly written, each module will have
  258. # its initializer called, checked, and uninitialized on failure. Sanity
  259. # check that here.
  260. for name in module_names:
  261. # Check for module initializer functions.
  262. decl = gs.PosixStubWriter.IsInitializedName(name)
  263. self.assertTrue(contents.find(decl) != -1,
  264. msg='Expected "%s" in %s' % (decl, contents))
  265. decl = gs.PosixStubWriter.InitializeModuleName(name)
  266. self.assertTrue(contents.find(decl) != -1,
  267. msg='Expected "%s" in %s' % (decl, contents))
  268. decl = gs.PosixStubWriter.UninitializeModuleName(name)
  269. self.assertTrue(contents.find(decl) != -1,
  270. msg='Expected "%s" in %s' % (decl, contents))
  271. if __name__ == '__main__':
  272. unittest.main()