test_utils.py 20 KB

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