test_utils.py 21 KB

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