test_utils.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. # Copyright (C) 2011-2019 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 collections import defaultdict, namedtuple
  18. from unittest.mock import DEFAULT, MagicMock, patch
  19. from unittest import skip
  20. from hamcrest import ( assert_that,
  21. contains_exactly,
  22. contains_inanyorder,
  23. equal_to )
  24. import contextlib
  25. import functools
  26. import json
  27. import os
  28. import re
  29. import sys
  30. from unittest import skipIf
  31. from ycmd.utils import GetCurrentDirectory, OnMac, OnWindows, ToUnicode
  32. BUFNR_REGEX = re.compile(
  33. '^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. PROP_ADD_REGEX = re.compile(
  40. '^prop_add\\( ' # A literal at the start
  41. '(?P<start_line>\\d+), ' # First argument - number
  42. '(?P<start_column>\\d+), ' # Second argument - number
  43. '{(?P<opts>.+)} ' # Third argument is a complex dict, which
  44. # we parse separately
  45. '\\)$' )
  46. PROP_REMOVE_REGEX = re.compile( '^prop_remove\\( (?P<prop>.+) \\)$' )
  47. OMNIFUNC_REGEX_FORMAT = (
  48. '^{omnifunc_name}\\((?P<findstart>[01]),[\'"](?P<base>.*)[\'"]\\)$' )
  49. FNAMEESCAPE_REGEX = re.compile( '^fnameescape\\(\'(?P<filepath>.+)\'\\)$' )
  50. STRDISPLAYWIDTH_REGEX = re.compile(
  51. '^strdisplaywidth\\( ?\'(?P<text>.+)\' ?\\)$' )
  52. REDIR_START_REGEX = re.compile( '^redir => (?P<variable>[\\w:]+)$' )
  53. REDIR_END_REGEX = re.compile( '^redir END$' )
  54. EXISTS_REGEX = re.compile( '^exists\\( \'(?P<option>[\\w:]+)\' \\)$' )
  55. LET_REGEX = re.compile( '^let (?P<option>[\\w:]+) = (?P<value>.*)$' )
  56. HAS_PATCH_REGEX = re.compile( '^has\\( \'patch(?P<patch>\\d+)\' \\)$' )
  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_PROPS_FOR_BUFFER = defaultdict( list )
  67. VIM_SIGNS = []
  68. VIM_OPTIONS = {
  69. '&completeopt': b'',
  70. '&previewheight': 12,
  71. '&columns': 80,
  72. '&ruler': 0,
  73. '&showcmd': 1,
  74. '&hidden': 0,
  75. '&expandtab': 1
  76. }
  77. Version = namedtuple( 'Version', [ 'major', 'minor', 'patch' ] )
  78. # This variable must be patched with a Version object for tests depending on a
  79. # recent Vim version. Example:
  80. #
  81. # @patch( 'ycm.tests.test_utils.VIM_VERSION', Version( 8, 1, 614 ) )
  82. # def ThisTestDependsOnTheVimVersion_test():
  83. # ...
  84. #
  85. # Default is the oldest supported version.
  86. VIM_VERSION = Version( 7, 4, 1578 )
  87. REDIR = {
  88. 'status': False,
  89. 'variable': '',
  90. 'output': ''
  91. }
  92. WindowsAndMacOnly = skipIf( not OnWindows() or not OnMac(),
  93. 'Windows and macOS only' )
  94. @contextlib.contextmanager
  95. def CurrentWorkingDirectory( path ):
  96. old_cwd = GetCurrentDirectory()
  97. os.chdir( path )
  98. try:
  99. yield
  100. finally:
  101. os.chdir( old_cwd )
  102. def _MockGetBufferNumber( buffer_filename ):
  103. for vim_buffer in VIM_MOCK.buffers:
  104. if vim_buffer.name == buffer_filename:
  105. return vim_buffer.number
  106. return -1
  107. def _MockGetBufferWindowNumber( buffer_number ):
  108. for window in VIM_MOCK.windows:
  109. if window.buffer.number == buffer_number:
  110. return window.number
  111. return -1
  112. def _MockGetBufferVariable( buffer_number, option ):
  113. for vim_buffer in VIM_MOCK.buffers:
  114. if vim_buffer.number == buffer_number:
  115. if option == '&mod':
  116. return vim_buffer.modified
  117. if option == '&ft':
  118. return vim_buffer.filetype
  119. if option == 'changedtick':
  120. return vim_buffer.changedtick
  121. if option == '&bh':
  122. return vim_buffer.bufhidden
  123. return ''
  124. return ''
  125. def _MockVimBufferEval( value ):
  126. if value == '&omnifunc':
  127. return VIM_MOCK.current.buffer.omnifunc_name
  128. if value == '&filetype':
  129. return VIM_MOCK.current.buffer.filetype
  130. match = BUFNR_REGEX.search( value )
  131. if match:
  132. buffer_filename = match.group( 'buffer_filename' )
  133. return _MockGetBufferNumber( buffer_filename )
  134. match = BUFWINNR_REGEX.search( value )
  135. if match:
  136. buffer_number = int( match.group( 'buffer_number' ) )
  137. return _MockGetBufferWindowNumber( buffer_number )
  138. match = GETBUFVAR_REGEX.search( value )
  139. if match:
  140. buffer_number = int( match.group( 'buffer_number' ) )
  141. option = match.group( 'option' )
  142. return _MockGetBufferVariable( buffer_number, option )
  143. current_buffer = VIM_MOCK.current.buffer
  144. match = re.search( OMNIFUNC_REGEX_FORMAT.format(
  145. omnifunc_name = current_buffer.omnifunc_name ),
  146. value )
  147. if match:
  148. findstart = int( match.group( 'findstart' ) )
  149. base = match.group( 'base' )
  150. return current_buffer.omnifunc( findstart, base )
  151. return None
  152. def _MockVimWindowEval( value ):
  153. if value == 'winnr("#")':
  154. # For simplicity, we always assume there is no previous window.
  155. return 0
  156. return None
  157. def _MockVimOptionsEval( value ):
  158. result = VIM_OPTIONS.get( value )
  159. if result is not None:
  160. return result
  161. if value == 'keys( g: )':
  162. global_options = {}
  163. for key, value in VIM_OPTIONS.items():
  164. if key.startswith( 'g:' ):
  165. global_options[ key[ 2: ] ] = value
  166. return global_options
  167. match = EXISTS_REGEX.search( value )
  168. if match:
  169. option = match.group( 'option' )
  170. return option in VIM_OPTIONS
  171. return None
  172. def _MockVimFunctionsEval( value ):
  173. if value == 'tempname()':
  174. return '_TEMP_FILE_'
  175. if value == 'tagfiles()':
  176. return [ 'tags' ]
  177. if value == 'shiftwidth()':
  178. return 2
  179. if value.startswith( 'has( "' ):
  180. return False
  181. match = re.match( 'sign_getplaced\\( (?P<bufnr>\\d+), '
  182. '{ "group": "ycm_signs" } \\)', value )
  183. if match:
  184. filtered = list( filter( lambda sign: sign.bufnr ==
  185. int( match.group( 'bufnr' ) ),
  186. VIM_SIGNS ) )
  187. r = [ { 'signs': filtered } ]
  188. return r
  189. match = re.match( 'sign_unplacelist\\( (?P<sign_list>\\[.*\\]) \\)', value )
  190. if match:
  191. sign_list = eval( match.group( 'sign_list' ) )
  192. for sign in sign_list:
  193. VIM_SIGNS.remove( sign )
  194. return True # Why True?
  195. match = re.match( 'sign_placelist\\( (?P<sign_list>\\[.*\\]) \\)', value )
  196. if match:
  197. sign_list = json.loads( match.group( 'sign_list' ).replace( "'", '"' ) )
  198. for sign in sign_list:
  199. VIM_SIGNS.append( VimSign( sign[ 'lnum' ],
  200. sign[ 'name' ],
  201. sign[ 'buffer' ] ) )
  202. return True # Why True?
  203. return None
  204. def _MockVimPropEval( value ):
  205. match = re.match( 'prop_list\\( (?P<lnum>\\d+), '
  206. '{ "bufnr": (?P<bufnr>\\d+) } \\)', value )
  207. if match:
  208. return [ p for p in VIM_PROPS_FOR_BUFFER[ int( match.group( 'bufnr' ) ) ]
  209. if p.start_line == int( match.group( 'lnum' ) ) ]
  210. match = PROP_ADD_REGEX.search( value )
  211. if match:
  212. prop_start_line = int( match.group( 'start_line' ) )
  213. prop_start_column = int( match.group( 'start_column' ) )
  214. import ast
  215. opts = ast.literal_eval( '{' + match.group( 'opts' ) + '}' )
  216. vim_prop = VimProp(
  217. opts[ 'type' ],
  218. prop_start_line,
  219. prop_start_column,
  220. int( opts[ 'end_lnum' ] ) if opts[ 'end_lnum' ] else prop_start_line,
  221. int( opts[ 'end_col' ] ) if opts[ 'end_col' ] else prop_start_column
  222. )
  223. VIM_PROPS_FOR_BUFFER[ int( opts[ 'bufnr' ] ) ].append( vim_prop )
  224. return vim_prop.id
  225. match = PROP_REMOVE_REGEX.search( value )
  226. if match:
  227. prop, lin_num = eval( match.group( 'prop' ) )
  228. vim_props = VIM_PROPS_FOR_BUFFER[ prop[ 'bufnr' ] ]
  229. for index, vim_prop in enumerate( vim_props ):
  230. if vim_prop.id == prop[ 'id' ]:
  231. vim_props.pop( index )
  232. return -1
  233. return 0
  234. return None
  235. def _MockVimVersionEval( value ):
  236. match = HAS_PATCH_REGEX.search( value )
  237. if match:
  238. if not isinstance( VIM_VERSION, Version ):
  239. raise RuntimeError( 'Vim version is not set.' )
  240. return VIM_VERSION.patch >= int( match.group( 'patch' ) )
  241. if value == 'v:version':
  242. if not isinstance( VIM_VERSION, Version ):
  243. raise RuntimeError( 'Vim version is not set.' )
  244. return VIM_VERSION.major * 100 + VIM_VERSION.minor
  245. return None
  246. def _MockVimEval( value ): # noqa
  247. if value == 'g:ycm_neovim_ns_id':
  248. return 1
  249. result = _MockVimOptionsEval( value )
  250. if result is not None:
  251. return result
  252. result = _MockVimFunctionsEval( value )
  253. if result is not None:
  254. return result
  255. result = _MockVimBufferEval( value )
  256. if result is not None:
  257. return result
  258. result = _MockVimWindowEval( value )
  259. if result is not None:
  260. return result
  261. result = _MockVimPropEval( value )
  262. if result is not None:
  263. return result
  264. result = _MockVimVersionEval( value )
  265. if result is not None:
  266. return result
  267. match = FNAMEESCAPE_REGEX.search( value )
  268. if match:
  269. return match.group( 'filepath' )
  270. if value == REDIR[ 'variable' ]:
  271. return REDIR[ 'output' ]
  272. match = STRDISPLAYWIDTH_REGEX.search( value )
  273. if match:
  274. return len( match.group( 'text' ) )
  275. raise VimError( f'Unexpected evaluation: { value }' )
  276. def _MockWipeoutBuffer( buffer_number ):
  277. buffers = VIM_MOCK.buffers
  278. for index, buffer in enumerate( buffers ):
  279. if buffer.number == buffer_number:
  280. return buffers.pop( index )
  281. def _MockVimCommand( command ):
  282. match = BWIPEOUT_REGEX.search( command )
  283. if match:
  284. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  285. match = REDIR_START_REGEX.search( command )
  286. if match:
  287. REDIR[ 'status' ] = True
  288. REDIR[ 'variable' ] = match.group( 'variable' )
  289. return
  290. match = REDIR_END_REGEX.search( command )
  291. if match:
  292. REDIR[ 'status' ] = False
  293. return
  294. if command == 'unlet ' + REDIR[ 'variable' ]:
  295. REDIR[ 'variable' ] = ''
  296. return
  297. match = LET_REGEX.search( command )
  298. if match:
  299. option = match.group( 'option' )
  300. value = json.loads( match.group( 'value' ) )
  301. VIM_OPTIONS[ option ] = value
  302. return
  303. return DEFAULT
  304. def _MockVimOptions( option ):
  305. result = VIM_OPTIONS.get( '&' + option )
  306. if result is not None:
  307. return result
  308. return None
  309. class VimBuffer:
  310. """An object that looks like a vim.buffer object:
  311. - |name| : full path of the buffer with symbolic links resolved;
  312. - |number| : buffer number;
  313. - |contents| : list of lines representing the buffer contents;
  314. - |filetype| : buffer filetype. Empty string if no filetype is set;
  315. - |modified| : True if the buffer has unsaved changes, False otherwise;
  316. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  317. - |vars|: dict for buffer-local variables
  318. - |omnifunc| : omni completion function used by the buffer. Must be a Python
  319. function that takes the same arguments and returns the same
  320. values as a Vim completion function (:h complete-functions).
  321. Example:
  322. def Omnifunc( findstart, base ):
  323. if findstart:
  324. return 5
  325. return [ 'a', 'b', 'c' ]"""
  326. def __init__( self, name,
  327. number = 1,
  328. contents = [ '' ],
  329. filetype = '',
  330. modified = False,
  331. bufhidden = '',
  332. omnifunc = None,
  333. visual_start = None,
  334. visual_end = None,
  335. vars = {} ):
  336. self.name = os.path.realpath( name ) if name else ''
  337. self.number = number
  338. self.contents = contents
  339. self.filetype = filetype
  340. self.modified = modified
  341. self.bufhidden = bufhidden
  342. self.omnifunc = omnifunc
  343. self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
  344. self.changedtick = 1
  345. self.options = {
  346. 'mod': modified,
  347. 'bh': bufhidden
  348. }
  349. self.visual_start = visual_start
  350. self.visual_end = visual_end
  351. self.vars = vars # should really be a vim-specific dict-like obj
  352. def __getitem__( self, index ):
  353. """Returns the bytes for a given line at index |index|."""
  354. return self.contents[ index ]
  355. def __len__( self ):
  356. return len( self.contents )
  357. def __setitem__( self, key, value ):
  358. return self.contents.__setitem__( key, value )
  359. def GetLines( self ):
  360. """Returns the contents of the buffer as a list of unicode strings."""
  361. return [ ToUnicode( x ) for x in self.contents ]
  362. def mark( self, name ):
  363. if name == '<':
  364. return self.visual_start
  365. if name == '>':
  366. return self.visual_end
  367. raise ValueError( f'Unexpected mark: { name }' )
  368. def __repr__( self ):
  369. return f"VimBuffer( name = '{ self.name }', number = { self.number } )"
  370. class VimBuffers:
  371. """An object that looks like a vim.buffers object."""
  372. def __init__( self, buffers ):
  373. """|buffers| is a list of VimBuffer objects."""
  374. self._buffers = buffers
  375. def __getitem__( self, number ):
  376. """Emulates vim.buffers[ number ]"""
  377. for buffer_object in self._buffers:
  378. if number == buffer_object.number:
  379. return buffer_object
  380. raise KeyError( number )
  381. def __iter__( self ):
  382. """Emulates for loop on vim.buffers"""
  383. return iter( self._buffers )
  384. def pop( self, index ):
  385. return self._buffers.pop( index )
  386. class VimWindow:
  387. """An object that looks like a vim.window object:
  388. - |number|: number of the window;
  389. - |buffer_object|: a VimBuffer object representing the buffer inside the
  390. window;
  391. - |cursor|: a tuple corresponding to the cursor position."""
  392. def __init__( self, number, buffer_object, cursor = None ):
  393. self.number = number
  394. self.buffer = buffer_object
  395. self.cursor = cursor
  396. self.options = {}
  397. self.vars = {}
  398. def __repr__( self ):
  399. return ( f'VimWindow( number = { self.number }, '
  400. f'buffer = { self.buffer }, '
  401. f'cursor = { self.cursor } )' )
  402. class VimWindows:
  403. """An object that looks like a vim.windows object."""
  404. def __init__( self, buffers, cursor ):
  405. """|buffers| is a list of VimBuffer objects corresponding to the window
  406. layout. The first element of that list is assumed to be the current window.
  407. |cursor| is the cursor position of that window."""
  408. windows = []
  409. windows.append( VimWindow( 1, buffers[ 0 ], cursor ) )
  410. for window_number in range( 1, len( buffers ) ):
  411. windows.append( VimWindow( window_number + 1, buffers[ window_number ] ) )
  412. self._windows = windows
  413. def __getitem__( self, number ):
  414. """Emulates vim.windows[ number ]"""
  415. try:
  416. return self._windows[ number ]
  417. except IndexError:
  418. raise IndexError( 'no such window' )
  419. def __iter__( self ):
  420. """Emulates for loop on vim.windows"""
  421. return iter( self._windows )
  422. class VimCurrent:
  423. """An object that looks like a vim.current object. |current_window| must be a
  424. VimWindow object."""
  425. def __init__( self, current_window ):
  426. self.buffer = current_window.buffer
  427. self.window = current_window
  428. self.line = self.buffer.contents[ current_window.cursor[ 0 ] - 1 ]
  429. class VimProp:
  430. def __init__( self,
  431. prop_type,
  432. start_line,
  433. start_column,
  434. end_line = None,
  435. end_column = None ):
  436. current_buffer = VIM_MOCK.current.buffer.number
  437. self.id = len( VIM_PROPS_FOR_BUFFER[ current_buffer ] ) + 1
  438. self.prop_type = prop_type
  439. self.start_line = start_line
  440. self.start_column = start_column
  441. self.end_line = end_line if end_line else start_line
  442. self.end_column = end_column if end_column else start_column
  443. def __eq__( self, other ):
  444. return ( self.prop_type == other.prop_type and
  445. self.start_line == other.start_line and
  446. self.start_column == other.start_column and
  447. self.end_line == other.end_line and
  448. self.end_column == other.end_column )
  449. def __repr__( self ):
  450. return ( f"VimProp( prop_type = '{ self.prop_type }',"
  451. f" start_line = { self.start_line }, "
  452. f" start_column = { self.start_column },"
  453. f" end_line = { self.end_line },"
  454. f" end_column = { self.end_column } )" )
  455. def __getitem__( self, key ):
  456. if key == 'type':
  457. return self.prop_type
  458. elif key == 'id':
  459. return self.id
  460. elif key == 'col':
  461. return self.start_column
  462. elif key == 'length':
  463. return self.end_column - self.start_column
  464. def get( self, key, default = None ):
  465. if key == 'type':
  466. return self.prop_type
  467. class VimSign:
  468. def __init__( self, line, name, bufnr ):
  469. self.line = line
  470. self.name = name
  471. self.bufnr = bufnr
  472. def __eq__( self, other ):
  473. if isinstance( other, dict ):
  474. other = VimSign( other[ 'lnum' ], other[ 'name' ], other[ 'buffer' ] )
  475. return ( self.line == other.line and
  476. self.name == other.name and
  477. self.bufnr == other.bufnr )
  478. def __repr__( self ):
  479. return ( f"VimSign( line = { self.line }, "
  480. f"name = '{ self.name }', bufnr = { self.bufnr } )" )
  481. def __getitem__( self, key ):
  482. if key == 'group':
  483. return self.group
  484. @contextlib.contextmanager
  485. def MockVimBuffers( buffers, window_buffers, cursor_position = ( 1, 1 ) ):
  486. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  487. buffer displayed in the current window and |cursor_position| is the current
  488. cursor position. All buffers are represented by a VimBuffer object."""
  489. if ( not isinstance( buffers, list ) or
  490. not all( isinstance( buf, VimBuffer ) for buf in buffers ) ):
  491. raise RuntimeError( 'First parameter must be a list of VimBuffer objects.' )
  492. if ( not isinstance( window_buffers, list ) or
  493. not all( isinstance( buf, VimBuffer ) for buf in window_buffers ) ):
  494. raise RuntimeError( 'Second parameter must be a list of VimBuffer objects '
  495. 'representing the window layout.' )
  496. if len( window_buffers ) < 1:
  497. raise RuntimeError( 'Second parameter must contain at least one element '
  498. 'which corresponds to the current window.' )
  499. with patch( 'vim.buffers', VimBuffers( buffers ) ):
  500. with patch( 'vim.windows', VimWindows( window_buffers,
  501. cursor_position ) ) as windows:
  502. with patch( 'vim.current', VimCurrent( windows[ 0 ] ) ):
  503. yield VIM_MOCK
  504. def MockVimModule():
  505. """The 'vim' module is something that is only present when running inside the
  506. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  507. need to add additional mocks to vim module functions, then use 'patch' from
  508. mock module, to ensure that the state of the vim mock is returned before the
  509. next test. That is:
  510. from ycm.tests.test_utils import MockVimModule
  511. from unittest.mock import patch
  512. # Do this once
  513. MockVimModule()
  514. @patch( 'vim.eval', return_value='test' )
  515. @patch( 'vim.command', side_effect=ValueError )
  516. def test( vim_command, vim_eval ):
  517. # use vim.command via vim_command, e.g.:
  518. vim_command.assert_has_calls( ... )
  519. Failure to use this approach may lead to unexpected failures in other
  520. tests."""
  521. VIM_MOCK.command = MagicMock( side_effect = _MockVimCommand )
  522. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  523. VIM_MOCK.error = VimError
  524. VIM_MOCK.options = MagicMock()
  525. VIM_MOCK.options.__getitem__.side_effect = _MockVimOptions
  526. sys.modules[ 'vim' ] = VIM_MOCK
  527. return VIM_MOCK
  528. class VimError( Exception ):
  529. def __init__( self, code ):
  530. self.code = code
  531. def __str__( self ):
  532. return repr( self.code )
  533. class ExtendedMock( MagicMock ):
  534. """An extension to the MagicMock class which adds the ability to check that a
  535. callable is called with a precise set of calls in a precise order.
  536. Example Usage:
  537. from ycm.tests.test_utils import ExtendedMock
  538. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  539. def my_test( test_testing ):
  540. ...
  541. """
  542. def assert_has_exact_calls( self, calls, any_order = False ):
  543. contains = contains_inanyorder if any_order else contains_exactly
  544. assert_that( self.call_args_list, contains( *calls ) )
  545. assert_that( self.call_count, equal_to( len( calls ) ) )
  546. def ExpectedFailure( reason, *exception_matchers ):
  547. """Defines a decorator to be attached to tests. This decorator
  548. marks the test as being known to fail, e.g. where documenting or exercising
  549. known incorrect behaviour.
  550. The parameters are:
  551. - |reason| a textual description of the reason for the known issue. This
  552. is used for the skip reason
  553. - |exception_matchers| additional arguments are hamcrest matchers to apply
  554. to the exception thrown. If the matchers don't match, then the
  555. test is marked as error, with the original exception.
  556. If the test fails (for the correct reason), then it is marked as skipped.
  557. If it fails for any other reason, it is marked as failed.
  558. If the test passes, then it is also marked as failed."""
  559. def decorator( test ):
  560. @functools.wraps( test )
  561. def Wrapper( *args, **kwargs ):
  562. try:
  563. test( *args, **kwargs )
  564. except Exception as test_exception:
  565. # Ensure that we failed for the right reason
  566. test_exception_message = ToUnicode( test_exception )
  567. try:
  568. for matcher in exception_matchers:
  569. assert_that( test_exception_message, matcher )
  570. except AssertionError:
  571. # Failed for the wrong reason!
  572. import traceback
  573. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  574. # Real failure reason is the *original* exception, we're only trapping
  575. # and ignoring the exception that is expected.
  576. raise test_exception
  577. # Failed for the right reason
  578. skip( reason )
  579. else:
  580. raise AssertionError( f'Test was expected to fail: { reason }' )
  581. return Wrapper
  582. return decorator