test_utils.py 18 KB

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