test_utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. if value == '&expandtab':
  126. return 1
  127. return None
  128. def _MockVimMatchEval( value ):
  129. if value == 'getmatches()':
  130. # Returning a copy, because ClearYcmSyntaxMatches() gets the result of
  131. # getmatches(), iterates over it and removes elements from VIM_MATCHES.
  132. return list( VIM_MATCHES )
  133. match = MATCHADD_REGEX.search( value )
  134. if match:
  135. group = match.group( 'group' )
  136. option = match.group( 'pattern' )
  137. vim_match = VimMatch( group, option )
  138. VIM_MATCHES.append( vim_match )
  139. return vim_match.id
  140. match = MATCHDELETE_REGEX.search( value )
  141. if match:
  142. identity = int( match.group( 'id' ) )
  143. for index, vim_match in enumerate( VIM_MATCHES ):
  144. if vim_match.id == identity:
  145. VIM_MATCHES.pop( index )
  146. return -1
  147. return 0
  148. return None
  149. # This variable exists to easily mock the 'g:ycm_server_python_interpreter'
  150. # option in tests.
  151. server_python_interpreter = ''
  152. def _MockVimEval( value ):
  153. if value == 'g:ycm_min_num_of_chars_for_completion':
  154. return 0
  155. if value == 'g:ycm_server_python_interpreter':
  156. return server_python_interpreter
  157. if value == 'tempname()':
  158. return '_TEMP_FILE_'
  159. if value == 'tagfiles()':
  160. return [ 'tags' ]
  161. if value == 'shiftwidth()':
  162. return 2
  163. result = _MockVimOptionsEval( value )
  164. if result is not None:
  165. return result
  166. result = _MockVimBufferEval( value )
  167. if result is not None:
  168. return result
  169. result = _MockVimMatchEval( value )
  170. if result is not None:
  171. return result
  172. match = FNAMEESCAPE_REGEX.search( value )
  173. if match:
  174. return match.group( 'filepath' )
  175. raise VimError( 'Unexpected evaluation: {0}'.format( value ) )
  176. def _MockWipeoutBuffer( buffer_number ):
  177. buffers = VIM_MOCK.buffers
  178. for index, buffer in enumerate( buffers ):
  179. if buffer.number == buffer_number:
  180. return buffers.pop( index )
  181. def MockVimCommand( command ):
  182. match = BWIPEOUT_REGEX.search( command )
  183. if match:
  184. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  185. raise RuntimeError( 'Unexpected command: ' + command )
  186. class VimBuffer( object ):
  187. """An object that looks like a vim.buffer object:
  188. - |name| : full path of the buffer with symbolic links resolved;
  189. - |number| : buffer number;
  190. - |contents| : list of lines representing the buffer contents;
  191. - |filetype| : buffer filetype. Empty string if no filetype is set;
  192. - |modified| : True if the buffer has unsaved changes, False otherwise;
  193. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  194. - |window| : number of the buffer window. None if the buffer is hidden;
  195. - |omnifunc| : omni completion function used by the buffer. Must be a Python
  196. function that takes the same arguments and returns the same
  197. values as a Vim completion function (:h complete-functions).
  198. Example:
  199. def Omnifunc( findstart, base ):
  200. if findstart:
  201. return 5
  202. return [ 'a', 'b', 'c' ]"""
  203. def __init__( self, name,
  204. number = 1,
  205. contents = [ '' ],
  206. filetype = '',
  207. modified = False,
  208. bufhidden = '',
  209. window = None,
  210. omnifunc = None,
  211. visual_start = None,
  212. visual_end = None ):
  213. self.name = os.path.realpath( name ) if name else ''
  214. self.number = number
  215. self.contents = contents
  216. self.filetype = filetype
  217. self.modified = modified
  218. self.bufhidden = bufhidden
  219. self.window = window
  220. self.omnifunc = omnifunc
  221. self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
  222. self.changedtick = 1
  223. self.options = {
  224. 'mod': modified,
  225. 'bh': bufhidden
  226. }
  227. self.visual_start = visual_start
  228. self.visual_end = visual_end
  229. def __getitem__( self, index ):
  230. """Returns the bytes for a given line at index |index|."""
  231. return self.contents[ index ]
  232. def __len__( self ):
  233. return len( self.contents )
  234. def __setitem__( self, key, value ):
  235. return self.contents.__setitem__( key, value )
  236. def GetLines( self ):
  237. """Returns the contents of the buffer as a list of unicode strings."""
  238. return [ ToUnicode( x ) for x in self.contents ]
  239. def mark( self, name ):
  240. if name == '<':
  241. return self.visual_start
  242. if name == '>':
  243. return self.visual_end
  244. raise ValueError( 'Unexpected mark: {name}'.format( name = name ) )
  245. class VimBuffers( object ):
  246. """An object that looks like a vim.buffers object."""
  247. def __init__( self, *buffers ):
  248. """Arguments are VimBuffer objects."""
  249. self._buffers = buffers
  250. def __getitem__( self, number ):
  251. """Emulates vim.buffers[ number ]"""
  252. for buffer_object in self._buffers:
  253. if number == buffer_object.number:
  254. return buffer_object
  255. raise KeyError( number )
  256. def __iter__( self ):
  257. """Emulates for loop on vim.buffers"""
  258. return iter( self._buffers )
  259. class VimMatch( object ):
  260. def __init__( self, group, pattern ):
  261. self.id = len( VIM_MATCHES )
  262. self.group = group
  263. self.pattern = pattern
  264. def __eq__( self, other ):
  265. return self.group == other.group and self.pattern == other.pattern
  266. def __repr__( self ):
  267. return "VimMatch( group = '{0}', pattern = '{1}' )".format( self.group,
  268. self.pattern )
  269. def __getitem__( self, key ):
  270. if key == 'group':
  271. return self.group
  272. elif key == 'id':
  273. return self.id
  274. @contextlib.contextmanager
  275. def MockVimBuffers( buffers, current_buffer, cursor_position = ( 1, 1 ) ):
  276. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  277. buffer displayed in the current window and |cursor_position| is the current
  278. cursor position. All buffers are represented by a VimBuffer object."""
  279. if current_buffer not in buffers:
  280. raise RuntimeError( 'Current buffer must be part of the buffers list.' )
  281. line = current_buffer.contents[ cursor_position[ 0 ] - 1 ]
  282. with patch( 'vim.buffers', VimBuffers( *buffers ) ):
  283. with patch( 'vim.current.buffer', current_buffer ):
  284. with patch( 'vim.current.window.cursor', cursor_position ):
  285. with patch( 'vim.current.line', line ):
  286. yield VIM_MOCK
  287. def MockVimModule():
  288. """The 'vim' module is something that is only present when running inside the
  289. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  290. need to add additional mocks to vim module functions, then use 'patch' from
  291. mock module, to ensure that the state of the vim mock is returned before the
  292. next test. That is:
  293. from ycm.tests.test_utils import MockVimModule
  294. from mock import patch
  295. # Do this once
  296. MockVimModule()
  297. @patch( 'vim.eval', return_value='test' )
  298. @patch( 'vim.command', side_effect=ValueError )
  299. def test( vim_command, vim_eval ):
  300. # use vim.command via vim_command, e.g.:
  301. vim_command.assert_has_calls( ... )
  302. Failure to use this approach may lead to unexpected failures in other
  303. tests."""
  304. VIM_MOCK.buffers = {}
  305. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  306. VIM_MOCK.error = VimError
  307. sys.modules[ 'vim' ] = VIM_MOCK
  308. return VIM_MOCK
  309. class VimError( Exception ):
  310. def __init__( self, code ):
  311. self.code = code
  312. def __str__( self ):
  313. return repr( self.code )
  314. class ExtendedMock( MagicMock ):
  315. """An extension to the MagicMock class which adds the ability to check that a
  316. callable is called with a precise set of calls in a precise order.
  317. Example Usage:
  318. from ycm.tests.test_utils import ExtendedMock
  319. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  320. def my_test( test_testing ):
  321. ...
  322. """
  323. def assert_has_exact_calls( self, calls, any_order = False ):
  324. self.assert_has_calls( calls, any_order )
  325. assert_that( self.call_count, equal_to( len( calls ) ) )
  326. def ExpectedFailure( reason, *exception_matchers ):
  327. """Defines a decorator to be attached to tests. This decorator
  328. marks the test as being known to fail, e.g. where documenting or exercising
  329. known incorrect behaviour.
  330. The parameters are:
  331. - |reason| a textual description of the reason for the known issue. This
  332. is used for the skip reason
  333. - |exception_matchers| additional arguments are hamcrest matchers to apply
  334. to the exception thrown. If the matchers don't match, then the
  335. test is marked as error, with the original exception.
  336. If the test fails (for the correct reason), then it is marked as skipped.
  337. If it fails for any other reason, it is marked as failed.
  338. If the test passes, then it is also marked as failed."""
  339. def decorator( test ):
  340. @functools.wraps( test )
  341. def Wrapper( *args, **kwargs ):
  342. try:
  343. test( *args, **kwargs )
  344. except Exception as test_exception:
  345. # Ensure that we failed for the right reason
  346. test_exception_message = ToUnicode( test_exception )
  347. try:
  348. for matcher in exception_matchers:
  349. assert_that( test_exception_message, matcher )
  350. except AssertionError:
  351. # Failed for the wrong reason!
  352. import traceback
  353. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  354. # Real failure reason is the *original* exception, we're only trapping
  355. # and ignoring the exception that is expected.
  356. raise test_exception
  357. # Failed for the right reason
  358. raise nose.SkipTest( reason )
  359. else:
  360. raise AssertionError( 'Test was expected to fail: {0}'.format(
  361. reason ) )
  362. return Wrapper
  363. return decorator
  364. def ToBytesOnPY2( data ):
  365. # To test the omnifunc, etc. returning strings, which can be of different
  366. # types depending on python version, we use ToBytes on PY2 and just the native
  367. # str on python3. This roughly matches what happens between py2 and py3
  368. # versions within Vim.
  369. if not PY2:
  370. return data
  371. if isinstance( data, list ):
  372. return [ ToBytesOnPY2( item ) for item in data ]
  373. if isinstance( data, dict ):
  374. for item in data:
  375. data[ item ] = ToBytesOnPY2( data[ item ] )
  376. return data
  377. return ToBytes( data )