test_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. # Copyright (C) 2011-2018 YouCompleteMe contributors
  2. #
  3. # This file is part of YouCompleteMe.
  4. #
  5. # YouCompleteMe is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # YouCompleteMe is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  17. from __future__ import unicode_literals
  18. from __future__ import print_function
  19. from __future__ import division
  20. from __future__ import absolute_import
  21. # Not installing aliases from python-future; it's unreliable and slow.
  22. from builtins import * # noqa
  23. from future.utils import PY2
  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, ToBytes, 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. OMNIFUNC_REGEX_FORMAT = (
  43. '^{omnifunc_name}\((?P<findstart>[01]),[\'"](?P<base>.*)[\'"]\)$' )
  44. FNAMEESCAPE_REGEX = re.compile( '^fnameescape\(\'(?P<filepath>.+)\'\)$' )
  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. # This variable exists to easily mock the 'g:ycm_server_python_interpreter'
  148. # option in tests.
  149. server_python_interpreter = ''
  150. def _MockVimEval( value ):
  151. if value == 'g:ycm_min_num_of_chars_for_completion':
  152. return 0
  153. if value == 'g:ycm_server_python_interpreter':
  154. return server_python_interpreter
  155. if value == 'tempname()':
  156. return '_TEMP_FILE_'
  157. if value == 'tagfiles()':
  158. return [ 'tags' ]
  159. result = _MockVimOptionsEval( value )
  160. if result is not None:
  161. return result
  162. result = _MockVimBufferEval( value )
  163. if result is not None:
  164. return result
  165. result = _MockVimMatchEval( value )
  166. if result is not None:
  167. return result
  168. match = FNAMEESCAPE_REGEX.search( value )
  169. if match:
  170. return match.group( 'filepath' )
  171. raise ValueError( 'Unexpected evaluation: {0}'.format( value ) )
  172. def _MockWipeoutBuffer( buffer_number ):
  173. buffers = VIM_MOCK.buffers
  174. for index, buffer in enumerate( buffers ):
  175. if buffer.number == buffer_number:
  176. return buffers.pop( index )
  177. def MockVimCommand( command ):
  178. match = BWIPEOUT_REGEX.search( command )
  179. if match:
  180. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  181. raise RuntimeError( 'Unexpected command: ' + command )
  182. class VimBuffer( object ):
  183. """An object that looks like a vim.buffer object:
  184. - |name| : full path of the buffer with symbolic links resolved;
  185. - |number| : buffer number;
  186. - |contents| : list of lines representing the buffer contents;
  187. - |filetype| : buffer filetype. Empty string if no filetype is set;
  188. - |modified| : True if the buffer has unsaved changes, False otherwise;
  189. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  190. - |window| : number of the buffer window. None if the buffer is hidden;
  191. - |omnifunc| : omni completion function used by the buffer. Must be a Python
  192. function that takes the same arguments and returns the same
  193. values as a Vim completion function (:h complete-functions).
  194. Example:
  195. def Omnifunc( findstart, base ):
  196. if findstart:
  197. return 5
  198. return [ 'a', 'b', 'c' ]"""
  199. def __init__( self, name,
  200. number = 1,
  201. contents = [ '' ],
  202. filetype = '',
  203. modified = False,
  204. bufhidden = '',
  205. window = None,
  206. omnifunc = None ):
  207. self.name = os.path.realpath( name ) if name else ''
  208. self.number = number
  209. self.contents = contents
  210. self.filetype = filetype
  211. self.modified = modified
  212. self.bufhidden = bufhidden
  213. self.window = window
  214. self.omnifunc = omnifunc
  215. self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
  216. self.changedtick = 1
  217. self.options = {
  218. 'mod': modified,
  219. 'bh': bufhidden
  220. }
  221. def __getitem__( self, index ):
  222. """Returns the bytes for a given line at index |index|."""
  223. return self.contents[ index ]
  224. def __len__( self ):
  225. return len( self.contents )
  226. def __setitem__( self, key, value ):
  227. return self.contents.__setitem__( key, value )
  228. def GetLines( self ):
  229. """Returns the contents of the buffer as a list of unicode strings."""
  230. return [ ToUnicode( x ) for x in self.contents ]
  231. class VimBuffers( object ):
  232. """An object that looks like a vim.buffers object."""
  233. def __init__( self, *buffers ):
  234. """Arguments are VimBuffer objects."""
  235. self._buffers = buffers
  236. def __getitem__( self, number ):
  237. """Emulates vim.buffers[ number ]"""
  238. for buffer_object in self._buffers:
  239. if number == buffer_object.number:
  240. return buffer_object
  241. raise KeyError( number )
  242. def __iter__( self ):
  243. """Emulates for loop on vim.buffers"""
  244. return iter( self._buffers )
  245. class VimMatch( object ):
  246. def __init__( self, group, pattern ):
  247. self.id = len( VIM_MATCHES )
  248. self.group = group
  249. self.pattern = pattern
  250. def __eq__( self, other ):
  251. return self.group == other.group and self.pattern == other.pattern
  252. def __repr__( self ):
  253. return "VimMatch( group = '{0}', pattern = '{1}' )".format( self.group,
  254. self.pattern )
  255. def __getitem__( self, key ):
  256. if key == 'group':
  257. return self.group
  258. elif key == 'id':
  259. return self.id
  260. @contextlib.contextmanager
  261. def MockVimBuffers( buffers, current_buffer, cursor_position = ( 1, 1 ) ):
  262. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  263. buffer displayed in the current window and |cursor_position| is the current
  264. cursor position. All buffers are represented by a VimBuffer object."""
  265. if current_buffer not in buffers:
  266. raise RuntimeError( 'Current buffer must be part of the buffers list.' )
  267. line = current_buffer.contents[ cursor_position[ 0 ] - 1 ]
  268. with patch( 'vim.buffers', VimBuffers( *buffers ) ):
  269. with patch( 'vim.current.buffer', current_buffer ):
  270. with patch( 'vim.current.window.cursor', cursor_position ):
  271. with patch( 'vim.current.line', line ):
  272. yield VIM_MOCK
  273. def MockVimModule():
  274. """The 'vim' module is something that is only present when running inside the
  275. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  276. need to add additional mocks to vim module functions, then use 'patch' from
  277. mock module, to ensure that the state of the vim mock is returned before the
  278. next test. That is:
  279. from ycm.tests.test_utils import MockVimModule
  280. from mock import patch
  281. # Do this once
  282. MockVimModule()
  283. @patch( 'vim.eval', return_value='test' )
  284. @patch( 'vim.command', side_effect=ValueError )
  285. def test( vim_command, vim_eval ):
  286. # use vim.command via vim_command, e.g.:
  287. vim_command.assert_has_calls( ... )
  288. Failure to use this approach may lead to unexpected failures in other
  289. tests."""
  290. VIM_MOCK.buffers = {}
  291. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  292. sys.modules[ 'vim' ] = VIM_MOCK
  293. return VIM_MOCK
  294. class VimError( Exception ):
  295. def __init__( self, code ):
  296. self.code = code
  297. def __str__( self ):
  298. return repr( self.code )
  299. class ExtendedMock( MagicMock ):
  300. """An extension to the MagicMock class which adds the ability to check that a
  301. callable is called with a precise set of calls in a precise order.
  302. Example Usage:
  303. from ycm.tests.test_utils import ExtendedMock
  304. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  305. def my_test( test_testing ):
  306. ...
  307. """
  308. def assert_has_exact_calls( self, calls, any_order = False ):
  309. self.assert_has_calls( calls, any_order )
  310. assert_that( self.call_count, equal_to( len( calls ) ) )
  311. def ExpectedFailure( reason, *exception_matchers ):
  312. """Defines a decorator to be attached to tests. This decorator
  313. marks the test as being known to fail, e.g. where documenting or exercising
  314. known incorrect behaviour.
  315. The parameters are:
  316. - |reason| a textual description of the reason for the known issue. This
  317. is used for the skip reason
  318. - |exception_matchers| additional arguments are hamcrest matchers to apply
  319. to the exception thrown. If the matchers don't match, then the
  320. test is marked as error, with the original exception.
  321. If the test fails (for the correct reason), then it is marked as skipped.
  322. If it fails for any other reason, it is marked as failed.
  323. If the test passes, then it is also marked as failed."""
  324. def decorator( test ):
  325. @functools.wraps( test )
  326. def Wrapper( *args, **kwargs ):
  327. try:
  328. test( *args, **kwargs )
  329. except Exception as test_exception:
  330. # Ensure that we failed for the right reason
  331. test_exception_message = ToUnicode( test_exception )
  332. try:
  333. for matcher in exception_matchers:
  334. assert_that( test_exception_message, matcher )
  335. except AssertionError:
  336. # Failed for the wrong reason!
  337. import traceback
  338. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  339. # Real failure reason is the *original* exception, we're only trapping
  340. # and ignoring the exception that is expected.
  341. raise test_exception
  342. # Failed for the right reason
  343. raise nose.SkipTest( reason )
  344. else:
  345. raise AssertionError( 'Test was expected to fail: {0}'.format(
  346. reason ) )
  347. return Wrapper
  348. return decorator
  349. def ToBytesOnPY2( data ):
  350. # To test the omnifunc, etc. returning strings, which can be of different
  351. # types depending on python version, we use ToBytes on PY2 and just the native
  352. # str on python3. This roughly matches what happens between py2 and py3
  353. # versions within Vim.
  354. if not PY2:
  355. return data
  356. if isinstance( data, list ):
  357. return [ ToBytesOnPY2( item ) for item in data ]
  358. if isinstance( data, dict ):
  359. for item in data:
  360. data[ item ] = ToBytesOnPY2( data[ item ] )
  361. return data
  362. return ToBytes( data )