test_utils.py 22 KB

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