test_utils.py 24 KB

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