test_utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. # Copyright (C) 2011-2012 Google Inc.
  2. # 2016 YouCompleteMe contributors
  3. #
  4. # This file is part of YouCompleteMe.
  5. #
  6. # YouCompleteMe is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # YouCompleteMe is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  18. from __future__ import unicode_literals
  19. from __future__ import print_function
  20. from __future__ import division
  21. from __future__ import absolute_import
  22. # Not installing aliases from python-future; it's unreliable and slow.
  23. from builtins import * # noqa
  24. from mock import MagicMock, patch
  25. from hamcrest import assert_that, equal_to
  26. import contextlib
  27. import functools
  28. import nose
  29. import os
  30. import re
  31. import sys
  32. from ycmd.utils import GetCurrentDirectory, ToUnicode
  33. BUFNR_REGEX = re.compile( '^bufnr\(\'(?P<buffer_filename>.+)\', ([01])\)$' )
  34. BUFWINNR_REGEX = re.compile( '^bufwinnr\((?P<buffer_number>[0-9]+)\)$' )
  35. BWIPEOUT_REGEX = re.compile(
  36. '^(?:silent! )bwipeout!? (?P<buffer_number>[0-9]+)$' )
  37. GETBUFVAR_REGEX = re.compile(
  38. '^getbufvar\((?P<buffer_number>[0-9]+), "(?P<option>.+)"\)$' )
  39. MATCHADD_REGEX = re.compile(
  40. '^matchadd\(\'(?P<group>.+)\', \'(?P<pattern>.+)\'\)$' )
  41. MATCHDELETE_REGEX = re.compile( '^matchdelete\((?P<id>\d+)\)$' )
  42. # One-and only instance of mocked Vim object. The first 'import vim' that is
  43. # executed binds the vim module to the instance of MagicMock that is created,
  44. # and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively
  45. # update them. The result is that while running the tests, we must assign only
  46. # one instance of MagicMock to sys.modules[ 'vim' ] and always return it.
  47. #
  48. # More explanation is available:
  49. # https://github.com/Valloric/YouCompleteMe/pull/1694
  50. VIM_MOCK = MagicMock()
  51. VIM_MATCHES = []
  52. @contextlib.contextmanager
  53. def CurrentWorkingDirectory( path ):
  54. old_cwd = GetCurrentDirectory()
  55. os.chdir( path )
  56. try:
  57. yield
  58. finally:
  59. os.chdir( old_cwd )
  60. def _MockGetBufferNumber( buffer_filename ):
  61. for vim_buffer in VIM_MOCK.buffers:
  62. if vim_buffer.name == buffer_filename:
  63. return vim_buffer.number
  64. return -1
  65. def _MockGetBufferWindowNumber( buffer_number ):
  66. for vim_buffer in VIM_MOCK.buffers:
  67. if vim_buffer.number == buffer_number and vim_buffer.window:
  68. return vim_buffer.window
  69. return -1
  70. def _MockGetBufferVariable( buffer_number, option ):
  71. for vim_buffer in VIM_MOCK.buffers:
  72. if vim_buffer.number == buffer_number:
  73. if option == '&mod':
  74. return vim_buffer.modified
  75. if option == '&ft':
  76. return vim_buffer.filetype
  77. if option == 'changedtick':
  78. return vim_buffer.changedtick
  79. if option == '&bh':
  80. return vim_buffer.bufhidden
  81. return ''
  82. return ''
  83. def _MockVimBufferEval( value ):
  84. if value == '&omnifunc':
  85. return VIM_MOCK.current.buffer.omnifunc
  86. if value == '&filetype':
  87. return VIM_MOCK.current.buffer.filetype
  88. match = BUFNR_REGEX.search( value )
  89. if match:
  90. buffer_filename = match.group( 'buffer_filename' )
  91. return _MockGetBufferNumber( buffer_filename )
  92. match = BUFWINNR_REGEX.search( value )
  93. if match:
  94. buffer_number = int( match.group( 'buffer_number' ) )
  95. return _MockGetBufferWindowNumber( buffer_number )
  96. match = GETBUFVAR_REGEX.search( value )
  97. if match:
  98. buffer_number = int( match.group( 'buffer_number' ) )
  99. option = match.group( 'option' )
  100. return _MockGetBufferVariable( buffer_number, option )
  101. return None
  102. def _MockVimOptionsEval( value ):
  103. if value == '&previewheight':
  104. return 12
  105. if value == '&columns':
  106. return 80
  107. if value == '&ruler':
  108. return 0
  109. if value == '&showcmd':
  110. return 1
  111. if value == '&hidden':
  112. return 0
  113. return None
  114. def _MockVimMatchEval( value ):
  115. if value == 'getmatches()':
  116. # Returning a copy, because ClearYcmSyntaxMatches() gets the result of
  117. # getmatches(), iterates over it and removes elements from VIM_MATCHES.
  118. return list( VIM_MATCHES )
  119. match = MATCHADD_REGEX.search( value )
  120. if match:
  121. group = match.group( 'group' )
  122. option = match.group( 'pattern' )
  123. vim_match = VimMatch( group, option )
  124. VIM_MATCHES.append( vim_match )
  125. return vim_match.id
  126. match = MATCHDELETE_REGEX.search( value )
  127. if match:
  128. identity = int( match.group( 'id' ) )
  129. for index, vim_match in enumerate( VIM_MATCHES ):
  130. if vim_match.id == identity:
  131. VIM_MATCHES.pop( index )
  132. return -1
  133. return 0
  134. return None
  135. def _MockVimEval( value ):
  136. if value == 'g:ycm_min_num_of_chars_for_completion':
  137. return 0
  138. if value == 'g:ycm_server_python_interpreter':
  139. return ''
  140. if value == 'tempname()':
  141. return '_TEMP_FILE_'
  142. if value == 'tagfiles()':
  143. return [ 'tags' ]
  144. result = _MockVimOptionsEval( value )
  145. if result is not None:
  146. return result
  147. result = _MockVimBufferEval( value )
  148. if result is not None:
  149. return result
  150. result = _MockVimMatchEval( value )
  151. if result is not None:
  152. return result
  153. raise ValueError( 'Unexpected evaluation: {0}'.format( value ) )
  154. def _MockWipeoutBuffer( buffer_number ):
  155. buffers = VIM_MOCK.buffers
  156. for index, buffer in enumerate( buffers ):
  157. if buffer.number == buffer_number:
  158. return buffers.pop( index )
  159. def MockVimCommand( command ):
  160. match = BWIPEOUT_REGEX.search( command )
  161. if match:
  162. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  163. raise RuntimeError( 'Unexpected command: ' + command )
  164. class VimBuffer( object ):
  165. """An object that looks like a vim.buffer object:
  166. - |name| : full path of the buffer with symbolic links resolved;
  167. - |number| : buffer number;
  168. - |contents| : list of lines representing the buffer contents;
  169. - |filetype| : buffer filetype. Empty string if no filetype is set;
  170. - |modified| : True if the buffer has unsaved changes, False otherwise;
  171. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  172. - |window| : number of the buffer window. None if the buffer is hidden;
  173. - |omnifunc| : omni completion function used by the buffer."""
  174. def __init__( self, name,
  175. number = 1,
  176. contents = [],
  177. filetype = '',
  178. modified = False,
  179. bufhidden = '',
  180. window = None,
  181. omnifunc = '' ):
  182. self.name = os.path.realpath( name ) if name else ''
  183. self.number = number
  184. self.contents = contents
  185. self.filetype = filetype
  186. self.modified = modified
  187. self.bufhidden = bufhidden
  188. self.window = window
  189. self.omnifunc = omnifunc
  190. self.changedtick = 1
  191. def __getitem__( self, index ):
  192. """Returns the bytes for a given line at index |index|."""
  193. return self.contents[ index ]
  194. def __len__( self ):
  195. return len( self.contents )
  196. def __setitem__( self, key, value ):
  197. return self.contents.__setitem__( key, value )
  198. def GetLines( self ):
  199. """Returns the contents of the buffer as a list of unicode strings."""
  200. return [ ToUnicode( x ) for x in self.contents ]
  201. class VimMatch( object ):
  202. def __init__( self, group, pattern ):
  203. self.id = len( VIM_MATCHES )
  204. self.group = group
  205. self.pattern = pattern
  206. def __eq__( self, other ):
  207. return self.group == other.group and self.pattern == other.pattern
  208. def __repr__( self ):
  209. return "VimMatch( group = '{0}', pattern = '{1}' )".format( self.group,
  210. self.pattern )
  211. def __getitem__( self, key ):
  212. if key == 'group':
  213. return self.group
  214. elif key == 'id':
  215. return self.id
  216. @contextlib.contextmanager
  217. def MockVimBuffers( buffers, current_buffer, cursor_position = ( 1, 1 ) ):
  218. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  219. buffer displayed in the current window and |cursor_position| is the current
  220. cursor position. All buffers are represented by a VimBuffer object."""
  221. if current_buffer not in buffers:
  222. raise RuntimeError( 'Current buffer must be part of the buffers list.' )
  223. with patch( 'vim.buffers', buffers ):
  224. with patch( 'vim.current.buffer', current_buffer ):
  225. with patch( 'vim.current.window.cursor', cursor_position ):
  226. yield VIM_MOCK
  227. def MockVimModule():
  228. """The 'vim' module is something that is only present when running inside the
  229. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  230. need to add additional mocks to vim module functions, then use 'patch' from
  231. mock module, to ensure that the state of the vim mock is returned before the
  232. next test. That is:
  233. from ycm.tests.test_utils import MockVimModule
  234. from mock import patch
  235. # Do this once
  236. MockVimModule()
  237. @patch( 'vim.eval', return_value='test' )
  238. @patch( 'vim.command', side_effect=ValueError )
  239. def test( vim_command, vim_eval ):
  240. # use vim.command via vim_command, e.g.:
  241. vim_command.assert_has_calls( ... )
  242. Failure to use this approach may lead to unexpected failures in other
  243. tests."""
  244. VIM_MOCK.buffers = {}
  245. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  246. sys.modules[ 'vim' ] = VIM_MOCK
  247. return VIM_MOCK
  248. class VimError( Exception ):
  249. def __init__( self, code ):
  250. self.code = code
  251. def __str__( self ):
  252. return repr( self.code )
  253. class ExtendedMock( MagicMock ):
  254. """An extension to the MagicMock class which adds the ability to check that a
  255. callable is called with a precise set of calls in a precise order.
  256. Example Usage:
  257. from ycm.tests.test_utils import ExtendedMock
  258. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  259. def my_test( test_testing ):
  260. ...
  261. """
  262. def assert_has_exact_calls( self, calls, any_order = False ):
  263. self.assert_has_calls( calls, any_order )
  264. assert_that( self.call_count, equal_to( len( calls ) ) )
  265. def ExpectedFailure( reason, *exception_matchers ):
  266. """Defines a decorator to be attached to tests. This decorator
  267. marks the test as being known to fail, e.g. where documenting or exercising
  268. known incorrect behaviour.
  269. The parameters are:
  270. - |reason| a textual description of the reason for the known issue. This
  271. is used for the skip reason
  272. - |exception_matchers| additional arguments are hamcrest matchers to apply
  273. to the exception thrown. If the matchers don't match, then the
  274. test is marked as error, with the original exception.
  275. If the test fails (for the correct reason), then it is marked as skipped.
  276. If it fails for any other reason, it is marked as failed.
  277. If the test passes, then it is also marked as failed."""
  278. def decorator( test ):
  279. @functools.wraps( test )
  280. def Wrapper( *args, **kwargs ):
  281. try:
  282. test( *args, **kwargs )
  283. except Exception as test_exception:
  284. # Ensure that we failed for the right reason
  285. test_exception_message = ToUnicode( test_exception )
  286. try:
  287. for matcher in exception_matchers:
  288. assert_that( test_exception_message, matcher )
  289. except AssertionError:
  290. # Failed for the wrong reason!
  291. import traceback
  292. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  293. # Real failure reason is the *original* exception, we're only trapping
  294. # and ignoring the exception that is expected.
  295. raise test_exception
  296. # Failed for the right reason
  297. raise nose.SkipTest( reason )
  298. else:
  299. raise AssertionError( 'Test was expected to fail: {0}'.format(
  300. reason ) )
  301. return Wrapper
  302. return decorator