test_utils.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 future.utils import PY2
  25. from mock import MagicMock, patch
  26. from hamcrest import assert_that, equal_to
  27. import contextlib
  28. import functools
  29. import nose
  30. import os
  31. import re
  32. import sys
  33. from ycmd.utils import GetCurrentDirectory, ToBytes, ToUnicode
  34. BUFNR_REGEX = re.compile( '^bufnr\(\'(?P<buffer_filename>.+)\', ([01])\)$' )
  35. BUFWINNR_REGEX = re.compile( '^bufwinnr\((?P<buffer_number>[0-9]+)\)$' )
  36. BWIPEOUT_REGEX = re.compile(
  37. '^(?:silent! )bwipeout!? (?P<buffer_number>[0-9]+)$' )
  38. GETBUFVAR_REGEX = re.compile(
  39. '^getbufvar\((?P<buffer_number>[0-9]+), "(?P<option>.+)"\)$' )
  40. MATCHADD_REGEX = re.compile(
  41. '^matchadd\(\'(?P<group>.+)\', \'(?P<pattern>.+)\'\)$' )
  42. MATCHDELETE_REGEX = re.compile( '^matchdelete\((?P<id>\d+)\)$' )
  43. OMNIFUNC_REGEX_FORMAT = (
  44. '^{omnifunc_name}\((?P<findstart>[01]),[\'"](?P<base>.*)[\'"]\)$' )
  45. # One-and only instance of mocked Vim object. The first 'import vim' that is
  46. # executed binds the vim module to the instance of MagicMock that is created,
  47. # and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively
  48. # update them. The result is that while running the tests, we must assign only
  49. # one instance of MagicMock to sys.modules[ 'vim' ] and always return it.
  50. #
  51. # More explanation is available:
  52. # https://github.com/Valloric/YouCompleteMe/pull/1694
  53. VIM_MOCK = MagicMock()
  54. VIM_MATCHES = []
  55. @contextlib.contextmanager
  56. def CurrentWorkingDirectory( path ):
  57. old_cwd = GetCurrentDirectory()
  58. os.chdir( path )
  59. try:
  60. yield
  61. finally:
  62. os.chdir( old_cwd )
  63. def _MockGetBufferNumber( buffer_filename ):
  64. for vim_buffer in VIM_MOCK.buffers:
  65. if vim_buffer.name == buffer_filename:
  66. return vim_buffer.number
  67. return -1
  68. def _MockGetBufferWindowNumber( buffer_number ):
  69. for vim_buffer in VIM_MOCK.buffers:
  70. if vim_buffer.number == buffer_number and vim_buffer.window:
  71. return vim_buffer.window
  72. return -1
  73. def _MockGetBufferVariable( buffer_number, option ):
  74. for vim_buffer in VIM_MOCK.buffers:
  75. if vim_buffer.number == buffer_number:
  76. if option == '&mod':
  77. return vim_buffer.modified
  78. if option == '&ft':
  79. return vim_buffer.filetype
  80. if option == 'changedtick':
  81. return vim_buffer.changedtick
  82. if option == '&bh':
  83. return vim_buffer.bufhidden
  84. return ''
  85. return ''
  86. def _MockVimBufferEval( value ):
  87. if value == '&omnifunc':
  88. return VIM_MOCK.current.buffer.omnifunc_name
  89. if value == '&filetype':
  90. return VIM_MOCK.current.buffer.filetype
  91. match = BUFNR_REGEX.search( value )
  92. if match:
  93. buffer_filename = match.group( 'buffer_filename' )
  94. return _MockGetBufferNumber( buffer_filename )
  95. match = BUFWINNR_REGEX.search( value )
  96. if match:
  97. buffer_number = int( match.group( 'buffer_number' ) )
  98. return _MockGetBufferWindowNumber( buffer_number )
  99. match = GETBUFVAR_REGEX.search( value )
  100. if match:
  101. buffer_number = int( match.group( 'buffer_number' ) )
  102. option = match.group( 'option' )
  103. return _MockGetBufferVariable( buffer_number, option )
  104. current_buffer = VIM_MOCK.current.buffer
  105. match = re.search( OMNIFUNC_REGEX_FORMAT.format(
  106. omnifunc_name = current_buffer.omnifunc_name ),
  107. value )
  108. if match:
  109. findstart = int( match.group( 'findstart' ) )
  110. base = match.group( 'base' )
  111. value = current_buffer.omnifunc( findstart, base )
  112. return value if findstart else ToBytesOnPY2( value )
  113. return None
  114. def _MockVimOptionsEval( value ):
  115. if value == '&previewheight':
  116. return 12
  117. if value == '&columns':
  118. return 80
  119. if value == '&ruler':
  120. return 0
  121. if value == '&showcmd':
  122. return 1
  123. if value == '&hidden':
  124. return 0
  125. return None
  126. def _MockVimMatchEval( value ):
  127. if value == 'getmatches()':
  128. # Returning a copy, because ClearYcmSyntaxMatches() gets the result of
  129. # getmatches(), iterates over it and removes elements from VIM_MATCHES.
  130. return list( VIM_MATCHES )
  131. match = MATCHADD_REGEX.search( value )
  132. if match:
  133. group = match.group( 'group' )
  134. option = match.group( 'pattern' )
  135. vim_match = VimMatch( group, option )
  136. VIM_MATCHES.append( vim_match )
  137. return vim_match.id
  138. match = MATCHDELETE_REGEX.search( value )
  139. if match:
  140. identity = int( match.group( 'id' ) )
  141. for index, vim_match in enumerate( VIM_MATCHES ):
  142. if vim_match.id == identity:
  143. VIM_MATCHES.pop( index )
  144. return -1
  145. return 0
  146. return None
  147. def _MockVimEval( value ):
  148. if value == 'g:ycm_min_num_of_chars_for_completion':
  149. return 0
  150. if value == 'g:ycm_server_python_interpreter':
  151. return ''
  152. if value == 'tempname()':
  153. return '_TEMP_FILE_'
  154. if value == 'tagfiles()':
  155. return [ 'tags' ]
  156. result = _MockVimOptionsEval( value )
  157. if result is not None:
  158. return result
  159. result = _MockVimBufferEval( value )
  160. if result is not None:
  161. return result
  162. result = _MockVimMatchEval( value )
  163. if result is not None:
  164. return result
  165. raise ValueError( 'Unexpected evaluation: {0}'.format( value ) )
  166. def _MockWipeoutBuffer( buffer_number ):
  167. buffers = VIM_MOCK.buffers
  168. for index, buffer in enumerate( buffers ):
  169. if buffer.number == buffer_number:
  170. return buffers.pop( index )
  171. def MockVimCommand( command ):
  172. match = BWIPEOUT_REGEX.search( command )
  173. if match:
  174. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  175. raise RuntimeError( 'Unexpected command: ' + command )
  176. class VimBuffer( object ):
  177. """An object that looks like a vim.buffer object:
  178. - |name| : full path of the buffer with symbolic links resolved;
  179. - |number| : buffer number;
  180. - |contents| : list of lines representing the buffer contents;
  181. - |filetype| : buffer filetype. Empty string if no filetype is set;
  182. - |modified| : True if the buffer has unsaved changes, False otherwise;
  183. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  184. - |window| : number of the buffer window. None if the buffer is hidden;
  185. - |omnifunc| : omni completion function used by the buffer. Must be a Python
  186. function that takes the same arguments and returns the same
  187. values as a Vim completion function (:h complete-functions).
  188. Example:
  189. def Omnifunc( findstart, base ):
  190. if findstart:
  191. return 5
  192. return [ 'a', 'b', 'c' ]"""
  193. def __init__( self, name,
  194. number = 1,
  195. contents = [ '' ],
  196. filetype = '',
  197. modified = False,
  198. bufhidden = '',
  199. window = None,
  200. omnifunc = None ):
  201. self.name = os.path.realpath( name ) if name else ''
  202. self.number = number
  203. self.contents = contents
  204. self.filetype = filetype
  205. self.modified = modified
  206. self.bufhidden = bufhidden
  207. self.window = window
  208. self.omnifunc = omnifunc
  209. self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
  210. self.changedtick = 1
  211. def __getitem__( self, index ):
  212. """Returns the bytes for a given line at index |index|."""
  213. return self.contents[ index ]
  214. def __len__( self ):
  215. return len( self.contents )
  216. def __setitem__( self, key, value ):
  217. return self.contents.__setitem__( key, value )
  218. def GetLines( self ):
  219. """Returns the contents of the buffer as a list of unicode strings."""
  220. return [ ToUnicode( x ) for x in self.contents ]
  221. class VimMatch( object ):
  222. def __init__( self, group, pattern ):
  223. self.id = len( VIM_MATCHES )
  224. self.group = group
  225. self.pattern = pattern
  226. def __eq__( self, other ):
  227. return self.group == other.group and self.pattern == other.pattern
  228. def __repr__( self ):
  229. return "VimMatch( group = '{0}', pattern = '{1}' )".format( self.group,
  230. self.pattern )
  231. def __getitem__( self, key ):
  232. if key == 'group':
  233. return self.group
  234. elif key == 'id':
  235. return self.id
  236. @contextlib.contextmanager
  237. def MockVimBuffers( buffers, current_buffer, cursor_position = ( 1, 1 ) ):
  238. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  239. buffer displayed in the current window and |cursor_position| is the current
  240. cursor position. All buffers are represented by a VimBuffer object."""
  241. if current_buffer not in buffers:
  242. raise RuntimeError( 'Current buffer must be part of the buffers list.' )
  243. line = current_buffer.contents[ cursor_position[ 0 ] - 1 ]
  244. with patch( 'vim.buffers', buffers ):
  245. with patch( 'vim.current.buffer', current_buffer ):
  246. with patch( 'vim.current.window.cursor', cursor_position ):
  247. with patch( 'vim.current.line', line ):
  248. yield VIM_MOCK
  249. def MockVimModule():
  250. """The 'vim' module is something that is only present when running inside the
  251. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  252. need to add additional mocks to vim module functions, then use 'patch' from
  253. mock module, to ensure that the state of the vim mock is returned before the
  254. next test. That is:
  255. from ycm.tests.test_utils import MockVimModule
  256. from mock import patch
  257. # Do this once
  258. MockVimModule()
  259. @patch( 'vim.eval', return_value='test' )
  260. @patch( 'vim.command', side_effect=ValueError )
  261. def test( vim_command, vim_eval ):
  262. # use vim.command via vim_command, e.g.:
  263. vim_command.assert_has_calls( ... )
  264. Failure to use this approach may lead to unexpected failures in other
  265. tests."""
  266. VIM_MOCK.buffers = {}
  267. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  268. sys.modules[ 'vim' ] = VIM_MOCK
  269. return VIM_MOCK
  270. class VimError( Exception ):
  271. def __init__( self, code ):
  272. self.code = code
  273. def __str__( self ):
  274. return repr( self.code )
  275. class ExtendedMock( MagicMock ):
  276. """An extension to the MagicMock class which adds the ability to check that a
  277. callable is called with a precise set of calls in a precise order.
  278. Example Usage:
  279. from ycm.tests.test_utils import ExtendedMock
  280. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  281. def my_test( test_testing ):
  282. ...
  283. """
  284. def assert_has_exact_calls( self, calls, any_order = False ):
  285. self.assert_has_calls( calls, any_order )
  286. assert_that( self.call_count, equal_to( len( calls ) ) )
  287. def ExpectedFailure( reason, *exception_matchers ):
  288. """Defines a decorator to be attached to tests. This decorator
  289. marks the test as being known to fail, e.g. where documenting or exercising
  290. known incorrect behaviour.
  291. The parameters are:
  292. - |reason| a textual description of the reason for the known issue. This
  293. is used for the skip reason
  294. - |exception_matchers| additional arguments are hamcrest matchers to apply
  295. to the exception thrown. If the matchers don't match, then the
  296. test is marked as error, with the original exception.
  297. If the test fails (for the correct reason), then it is marked as skipped.
  298. If it fails for any other reason, it is marked as failed.
  299. If the test passes, then it is also marked as failed."""
  300. def decorator( test ):
  301. @functools.wraps( test )
  302. def Wrapper( *args, **kwargs ):
  303. try:
  304. test( *args, **kwargs )
  305. except Exception as test_exception:
  306. # Ensure that we failed for the right reason
  307. test_exception_message = ToUnicode( test_exception )
  308. try:
  309. for matcher in exception_matchers:
  310. assert_that( test_exception_message, matcher )
  311. except AssertionError:
  312. # Failed for the wrong reason!
  313. import traceback
  314. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  315. # Real failure reason is the *original* exception, we're only trapping
  316. # and ignoring the exception that is expected.
  317. raise test_exception
  318. # Failed for the right reason
  319. raise nose.SkipTest( reason )
  320. else:
  321. raise AssertionError( 'Test was expected to fail: {0}'.format(
  322. reason ) )
  323. return Wrapper
  324. return decorator
  325. def ToBytesOnPY2( data ):
  326. # To test the omnifunc, etc. returning strings, which can be of different
  327. # types depending on python version, we use ToBytes on PY2 and just the native
  328. # str on python3. This roughly matches what happens between py2 and py3
  329. # versions within Vim.
  330. if not PY2:
  331. return data
  332. if isinstance( data, list ):
  333. return [ ToBytesOnPY2( item ) for item in data ]
  334. if isinstance( data, dict ):
  335. for item in data:
  336. data[ item ] = ToBytesOnPY2( data[ item ] )
  337. return data
  338. return ToBytes( data )