test_utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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 DEFAULT, 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. SIGN_LIST_REGEX = re.compile(
  46. "^silent! sign place buffer=(?P<bufnr>\d+)$" )
  47. SIGN_PLACE_REGEX = re.compile(
  48. '^sign place (?P<id>\d+) name=(?P<name>\w+) line=(?P<line>\d+) '
  49. 'buffer=(?P<bufnr>\d+)$' )
  50. SIGN_UNPLACE_REGEX = re.compile(
  51. '^sign unplace (?P<id>\d+) buffer=(?P<bufnr>\d+)$' )
  52. REDIR_START_REGEX = re.compile( '^redir => (?P<variable>[\w:]+)$' )
  53. REDIR_END_REGEX = re.compile( '^redir END$' )
  54. # One-and only instance of mocked Vim object. The first 'import vim' that is
  55. # executed binds the vim module to the instance of MagicMock that is created,
  56. # and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively
  57. # update them. The result is that while running the tests, we must assign only
  58. # one instance of MagicMock to sys.modules[ 'vim' ] and always return it.
  59. #
  60. # More explanation is available:
  61. # https://github.com/Valloric/YouCompleteMe/pull/1694
  62. VIM_MOCK = MagicMock()
  63. VIM_MATCHES = []
  64. VIM_SIGNS = []
  65. REDIR = {
  66. 'status': False,
  67. 'variable': '',
  68. 'output': ''
  69. }
  70. @contextlib.contextmanager
  71. def CurrentWorkingDirectory( path ):
  72. old_cwd = GetCurrentDirectory()
  73. os.chdir( path )
  74. try:
  75. yield
  76. finally:
  77. os.chdir( old_cwd )
  78. def _MockGetBufferNumber( buffer_filename ):
  79. for vim_buffer in VIM_MOCK.buffers:
  80. if vim_buffer.name == buffer_filename:
  81. return vim_buffer.number
  82. return -1
  83. def _MockGetBufferWindowNumber( buffer_number ):
  84. for vim_buffer in VIM_MOCK.buffers:
  85. if vim_buffer.number == buffer_number and vim_buffer.window:
  86. return vim_buffer.window
  87. return -1
  88. def _MockGetBufferVariable( buffer_number, option ):
  89. for vim_buffer in VIM_MOCK.buffers:
  90. if vim_buffer.number == buffer_number:
  91. if option == '&mod':
  92. return vim_buffer.modified
  93. if option == '&ft':
  94. return vim_buffer.filetype
  95. if option == 'changedtick':
  96. return vim_buffer.changedtick
  97. if option == '&bh':
  98. return vim_buffer.bufhidden
  99. return ''
  100. return ''
  101. def _MockVimBufferEval( value ):
  102. if value == '&omnifunc':
  103. return VIM_MOCK.current.buffer.omnifunc_name
  104. if value == '&filetype':
  105. return VIM_MOCK.current.buffer.filetype
  106. match = BUFNR_REGEX.search( value )
  107. if match:
  108. buffer_filename = match.group( 'buffer_filename' )
  109. return _MockGetBufferNumber( buffer_filename )
  110. match = BUFWINNR_REGEX.search( value )
  111. if match:
  112. buffer_number = int( match.group( 'buffer_number' ) )
  113. return _MockGetBufferWindowNumber( buffer_number )
  114. match = GETBUFVAR_REGEX.search( value )
  115. if match:
  116. buffer_number = int( match.group( 'buffer_number' ) )
  117. option = match.group( 'option' )
  118. return _MockGetBufferVariable( buffer_number, option )
  119. current_buffer = VIM_MOCK.current.buffer
  120. match = re.search( OMNIFUNC_REGEX_FORMAT.format(
  121. omnifunc_name = current_buffer.omnifunc_name ),
  122. value )
  123. if match:
  124. findstart = int( match.group( 'findstart' ) )
  125. base = match.group( 'base' )
  126. value = current_buffer.omnifunc( findstart, base )
  127. return value if findstart else ToBytesOnPY2( value )
  128. return None
  129. def _MockVimOptionsEval( value ):
  130. if value == '&previewheight':
  131. return 12
  132. if value == '&columns':
  133. return 80
  134. if value == '&ruler':
  135. return 0
  136. if value == '&showcmd':
  137. return 1
  138. if value == '&hidden':
  139. return 0
  140. if value == '&expandtab':
  141. return 1
  142. return None
  143. def _MockVimFunctionsEval( value ):
  144. if value == 'tempname()':
  145. return '_TEMP_FILE_'
  146. if value == 'tagfiles()':
  147. return [ 'tags' ]
  148. if value == 'shiftwidth()':
  149. return 2
  150. return None
  151. def _MockVimMatchEval( value ):
  152. if value == 'getmatches()':
  153. # Returning a copy, because ClearYcmSyntaxMatches() gets the result of
  154. # getmatches(), iterates over it and removes elements from VIM_MATCHES.
  155. return list( VIM_MATCHES )
  156. match = MATCHADD_REGEX.search( value )
  157. if match:
  158. group = match.group( 'group' )
  159. option = match.group( 'pattern' )
  160. vim_match = VimMatch( group, option )
  161. VIM_MATCHES.append( vim_match )
  162. return vim_match.id
  163. match = MATCHDELETE_REGEX.search( value )
  164. if match:
  165. match_id = int( match.group( 'id' ) )
  166. for index, vim_match in enumerate( VIM_MATCHES ):
  167. if vim_match.id == match_id:
  168. VIM_MATCHES.pop( index )
  169. return -1
  170. return 0
  171. return None
  172. # This variable exists to easily mock the 'g:ycm_server_python_interpreter'
  173. # option in tests.
  174. server_python_interpreter = ''
  175. def _MockVimEval( value ):
  176. if value == 'g:ycm_min_num_of_chars_for_completion':
  177. return 0
  178. if value == 'g:ycm_server_python_interpreter':
  179. return server_python_interpreter
  180. result = _MockVimFunctionsEval( value )
  181. if result is not None:
  182. return result
  183. result = _MockVimOptionsEval( value )
  184. if result is not None:
  185. return result
  186. result = _MockVimBufferEval( value )
  187. if result is not None:
  188. return result
  189. result = _MockVimMatchEval( value )
  190. if result is not None:
  191. return result
  192. match = FNAMEESCAPE_REGEX.search( value )
  193. if match:
  194. return match.group( 'filepath' )
  195. if value == REDIR[ 'variable' ]:
  196. return REDIR[ 'output' ]
  197. raise VimError( 'Unexpected evaluation: {0}'.format( value ) )
  198. def _MockWipeoutBuffer( buffer_number ):
  199. buffers = VIM_MOCK.buffers
  200. for index, buffer in enumerate( buffers ):
  201. if buffer.number == buffer_number:
  202. return buffers.pop( index )
  203. def _MockSignCommand( command ):
  204. match = SIGN_LIST_REGEX.search( command )
  205. if match and REDIR[ 'status' ]:
  206. bufnr = int( match.group( 'bufnr' ) )
  207. REDIR[ 'output' ] = ( '--- Signs ---\n'
  208. 'Signs for foo:\n' )
  209. for sign in VIM_SIGNS:
  210. if sign.bufnr == bufnr:
  211. REDIR[ 'output' ] += (
  212. ' line={0} id={1} name={2}'.format( sign.line,
  213. sign.id,
  214. sign.name ) )
  215. return True
  216. match = SIGN_PLACE_REGEX.search( command )
  217. if match:
  218. VIM_SIGNS.append( VimSign( int( match.group( 'id' ) ),
  219. int( match.group( 'line' ) ),
  220. match.group( 'name' ),
  221. int( match.group( 'bufnr' ) ) ) )
  222. return True
  223. match = SIGN_UNPLACE_REGEX.search( command )
  224. if match:
  225. sign_id = int( match.group( 'id' ) )
  226. bufnr = int( match.group( 'bufnr' ) )
  227. for sign in VIM_SIGNS:
  228. if sign.id == sign_id and sign.bufnr == bufnr:
  229. VIM_SIGNS.remove( sign )
  230. return True
  231. return False
  232. def _MockVimCommand( command ):
  233. match = BWIPEOUT_REGEX.search( command )
  234. if match:
  235. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  236. match = REDIR_START_REGEX.search( command )
  237. if match:
  238. REDIR[ 'status' ] = True
  239. REDIR[ 'variable' ] = match.group( 'variable' )
  240. return
  241. match = REDIR_END_REGEX.search( command )
  242. if match:
  243. REDIR[ 'status' ] = False
  244. return
  245. if command == 'unlet ' + REDIR[ 'variable' ]:
  246. REDIR[ 'variable' ] = ''
  247. return
  248. result = _MockSignCommand( command )
  249. if result:
  250. return
  251. return DEFAULT
  252. class VimBuffer( object ):
  253. """An object that looks like a vim.buffer object:
  254. - |name| : full path of the buffer with symbolic links resolved;
  255. - |number| : buffer number;
  256. - |contents| : list of lines representing the buffer contents;
  257. - |filetype| : buffer filetype. Empty string if no filetype is set;
  258. - |modified| : True if the buffer has unsaved changes, False otherwise;
  259. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  260. - |window| : number of the buffer window. None if the buffer is hidden;
  261. - |omnifunc| : omni completion function used by the buffer. Must be a Python
  262. function that takes the same arguments and returns the same
  263. values as a Vim completion function (:h complete-functions).
  264. Example:
  265. def Omnifunc( findstart, base ):
  266. if findstart:
  267. return 5
  268. return [ 'a', 'b', 'c' ]"""
  269. def __init__( self, name,
  270. number = 1,
  271. contents = [ '' ],
  272. filetype = '',
  273. modified = False,
  274. bufhidden = '',
  275. window = None,
  276. omnifunc = None,
  277. visual_start = None,
  278. visual_end = None ):
  279. self.name = os.path.realpath( name ) if name else ''
  280. self.number = number
  281. self.contents = contents
  282. self.filetype = filetype
  283. self.modified = modified
  284. self.bufhidden = bufhidden
  285. self.window = window
  286. self.omnifunc = omnifunc
  287. self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
  288. self.changedtick = 1
  289. self.options = {
  290. 'mod': modified,
  291. 'bh': bufhidden
  292. }
  293. self.visual_start = visual_start
  294. self.visual_end = visual_end
  295. def __getitem__( self, index ):
  296. """Returns the bytes for a given line at index |index|."""
  297. return self.contents[ index ]
  298. def __len__( self ):
  299. return len( self.contents )
  300. def __setitem__( self, key, value ):
  301. return self.contents.__setitem__( key, value )
  302. def GetLines( self ):
  303. """Returns the contents of the buffer as a list of unicode strings."""
  304. return [ ToUnicode( x ) for x in self.contents ]
  305. def mark( self, name ):
  306. if name == '<':
  307. return self.visual_start
  308. if name == '>':
  309. return self.visual_end
  310. raise ValueError( 'Unexpected mark: {name}'.format( name = name ) )
  311. class VimBuffers( object ):
  312. """An object that looks like a vim.buffers object."""
  313. def __init__( self, *buffers ):
  314. """Arguments are VimBuffer objects."""
  315. self._buffers = list( buffers )
  316. def __getitem__( self, number ):
  317. """Emulates vim.buffers[ number ]"""
  318. for buffer_object in self._buffers:
  319. if number == buffer_object.number:
  320. return buffer_object
  321. raise KeyError( number )
  322. def __iter__( self ):
  323. """Emulates for loop on vim.buffers"""
  324. return iter( self._buffers )
  325. def pop( self, index ):
  326. return self._buffers.pop( index )
  327. class VimMatch( object ):
  328. def __init__( self, group, pattern ):
  329. self.id = len( VIM_MATCHES ) + 1
  330. self.group = group
  331. self.pattern = pattern
  332. def __eq__( self, other ):
  333. return self.group == other.group and self.pattern == other.pattern
  334. def __repr__( self ):
  335. return "VimMatch( group = '{0}', pattern = '{1}' )".format( self.group,
  336. self.pattern )
  337. def __getitem__( self, key ):
  338. if key == 'group':
  339. return self.group
  340. elif key == 'id':
  341. return self.id
  342. class VimSign( object ):
  343. def __init__( self, sign_id, line, name, bufnr ):
  344. self.id = sign_id
  345. self.line = line
  346. self.name = name
  347. self.bufnr = bufnr
  348. def __eq__( self, other ):
  349. return ( self.id == other.id and
  350. self.line == other.line and
  351. self.name == other.name and
  352. self.bufnr == other.bufnr )
  353. def __repr__( self ):
  354. return ( "VimSign( id = {0}, line = {1}, "
  355. "name = '{2}', bufnr = {3} )".format( self.id,
  356. self.line,
  357. self.name,
  358. self.bufnr ) )
  359. def __getitem__( self, key ):
  360. if key == 'group':
  361. return self.group
  362. elif key == 'id':
  363. return self.id
  364. @contextlib.contextmanager
  365. def MockVimBuffers( buffers, current_buffer, cursor_position = ( 1, 1 ) ):
  366. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  367. buffer displayed in the current window and |cursor_position| is the current
  368. cursor position. All buffers are represented by a VimBuffer object."""
  369. if current_buffer not in buffers:
  370. raise RuntimeError( 'Current buffer must be part of the buffers list.' )
  371. line = current_buffer.contents[ cursor_position[ 0 ] - 1 ]
  372. with patch( 'vim.buffers', VimBuffers( *buffers ) ):
  373. with patch( 'vim.current.buffer', current_buffer ):
  374. with patch( 'vim.current.window.cursor', cursor_position ):
  375. with patch( 'vim.current.line', line ):
  376. yield VIM_MOCK
  377. def MockVimModule():
  378. """The 'vim' module is something that is only present when running inside the
  379. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  380. need to add additional mocks to vim module functions, then use 'patch' from
  381. mock module, to ensure that the state of the vim mock is returned before the
  382. next test. That is:
  383. from ycm.tests.test_utils import MockVimModule
  384. from mock import patch
  385. # Do this once
  386. MockVimModule()
  387. @patch( 'vim.eval', return_value='test' )
  388. @patch( 'vim.command', side_effect=ValueError )
  389. def test( vim_command, vim_eval ):
  390. # use vim.command via vim_command, e.g.:
  391. vim_command.assert_has_calls( ... )
  392. Failure to use this approach may lead to unexpected failures in other
  393. tests."""
  394. VIM_MOCK.buffers = {}
  395. VIM_MOCK.command = MagicMock( side_effect = _MockVimCommand )
  396. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  397. VIM_MOCK.error = VimError
  398. sys.modules[ 'vim' ] = VIM_MOCK
  399. return VIM_MOCK
  400. class VimError( Exception ):
  401. def __init__( self, code ):
  402. self.code = code
  403. def __str__( self ):
  404. return repr( self.code )
  405. class ExtendedMock( MagicMock ):
  406. """An extension to the MagicMock class which adds the ability to check that a
  407. callable is called with a precise set of calls in a precise order.
  408. Example Usage:
  409. from ycm.tests.test_utils import ExtendedMock
  410. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  411. def my_test( test_testing ):
  412. ...
  413. """
  414. def assert_has_exact_calls( self, calls, any_order = False ):
  415. self.assert_has_calls( calls, any_order )
  416. assert_that( self.call_count, equal_to( len( calls ) ) )
  417. def ExpectedFailure( reason, *exception_matchers ):
  418. """Defines a decorator to be attached to tests. This decorator
  419. marks the test as being known to fail, e.g. where documenting or exercising
  420. known incorrect behaviour.
  421. The parameters are:
  422. - |reason| a textual description of the reason for the known issue. This
  423. is used for the skip reason
  424. - |exception_matchers| additional arguments are hamcrest matchers to apply
  425. to the exception thrown. If the matchers don't match, then the
  426. test is marked as error, with the original exception.
  427. If the test fails (for the correct reason), then it is marked as skipped.
  428. If it fails for any other reason, it is marked as failed.
  429. If the test passes, then it is also marked as failed."""
  430. def decorator( test ):
  431. @functools.wraps( test )
  432. def Wrapper( *args, **kwargs ):
  433. try:
  434. test( *args, **kwargs )
  435. except Exception as test_exception:
  436. # Ensure that we failed for the right reason
  437. test_exception_message = ToUnicode( test_exception )
  438. try:
  439. for matcher in exception_matchers:
  440. assert_that( test_exception_message, matcher )
  441. except AssertionError:
  442. # Failed for the wrong reason!
  443. import traceback
  444. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  445. # Real failure reason is the *original* exception, we're only trapping
  446. # and ignoring the exception that is expected.
  447. raise test_exception
  448. # Failed for the right reason
  449. raise nose.SkipTest( reason )
  450. else:
  451. raise AssertionError( 'Test was expected to fail: {0}'.format(
  452. reason ) )
  453. return Wrapper
  454. return decorator
  455. def ToBytesOnPY2( data ):
  456. # To test the omnifunc, etc. returning strings, which can be of different
  457. # types depending on python version, we use ToBytes on PY2 and just the native
  458. # str on python3. This roughly matches what happens between py2 and py3
  459. # versions within Vim.
  460. if not PY2:
  461. return data
  462. if isinstance( data, list ):
  463. return [ ToBytesOnPY2( item ) for item in data ]
  464. if isinstance( data, dict ):
  465. for item in data:
  466. data[ item ] = ToBytesOnPY2( data[ item ] )
  467. return data
  468. return ToBytes( data )