test_utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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 _MockVimOptionsEval( value ):
  152. result = VIM_OPTIONS.get( value )
  153. if result is not None:
  154. return result
  155. if value == 'keys( g: )':
  156. global_options = {}
  157. for key, value in iteritems( VIM_OPTIONS ):
  158. if key.startswith( 'g:' ):
  159. global_options[ key[ 2: ] ] = value
  160. return global_options
  161. match = EXISTS_REGEX.search( value )
  162. if match:
  163. option = match.group( 'option' )
  164. return option in VIM_OPTIONS
  165. return None
  166. def _MockVimFunctionsEval( value ):
  167. if value == 'tempname()':
  168. return '_TEMP_FILE_'
  169. if value == 'tagfiles()':
  170. return [ 'tags' ]
  171. if value == 'shiftwidth()':
  172. return 2
  173. return None
  174. def _MockVimMatchEval( value ):
  175. current_window = VIM_MOCK.current.window.number
  176. if value == 'getmatches()':
  177. return VIM_MATCHES_FOR_WINDOW[ current_window ]
  178. match = MATCHADD_REGEX.search( value )
  179. if match:
  180. group = match.group( 'group' )
  181. option = match.group( 'pattern' )
  182. vim_match = VimMatch( group, option )
  183. VIM_MATCHES_FOR_WINDOW[ current_window ].append( vim_match )
  184. return vim_match.id
  185. match = MATCHDELETE_REGEX.search( value )
  186. if match:
  187. match_id = int( match.group( 'id' ) )
  188. vim_matches = VIM_MATCHES_FOR_WINDOW[ current_window ]
  189. for index, vim_match in enumerate( vim_matches ):
  190. if vim_match.id == match_id:
  191. vim_matches.pop( index )
  192. return -1
  193. return 0
  194. return None
  195. def _MockVimVersionEval( value ):
  196. match = HAS_PATCH_REGEX.search( value )
  197. if match:
  198. if not isinstance( VIM_VERSION, Version ):
  199. raise RuntimeError( 'Vim version is not set.' )
  200. return VIM_VERSION.patch >= int( match.group( 'patch' ) )
  201. if value == 'v:version':
  202. if not isinstance( VIM_VERSION, Version ):
  203. raise RuntimeError( 'Vim version is not set.' )
  204. return VIM_VERSION.major * 100 + VIM_VERSION.minor
  205. return None
  206. def _MockVimEval( value ):
  207. result = _MockVimOptionsEval( value )
  208. if result is not None:
  209. return result
  210. result = _MockVimFunctionsEval( value )
  211. if result is not None:
  212. return result
  213. result = _MockVimBufferEval( value )
  214. if result is not None:
  215. return result
  216. result = _MockVimMatchEval( value )
  217. if result is not None:
  218. return result
  219. result = _MockVimVersionEval( value )
  220. if result is not None:
  221. return result
  222. match = FNAMEESCAPE_REGEX.search( value )
  223. if match:
  224. return match.group( 'filepath' )
  225. if value == REDIR[ 'variable' ]:
  226. return REDIR[ 'output' ]
  227. raise VimError( 'Unexpected evaluation: {0}'.format( value ) )
  228. def _MockWipeoutBuffer( buffer_number ):
  229. buffers = VIM_MOCK.buffers
  230. for index, buffer in enumerate( buffers ):
  231. if buffer.number == buffer_number:
  232. return buffers.pop( index )
  233. def _MockSignCommand( command ):
  234. match = SIGN_LIST_REGEX.search( command )
  235. if match and REDIR[ 'status' ]:
  236. bufnr = int( match.group( 'bufnr' ) )
  237. REDIR[ 'output' ] = ( '--- Signs ---\n'
  238. 'Signs for foo:\n' )
  239. for sign in VIM_SIGNS:
  240. if sign.bufnr == bufnr:
  241. REDIR[ 'output' ] += (
  242. ' line={0} id={1} name={2}'.format( sign.line,
  243. sign.id,
  244. sign.name ) )
  245. return True
  246. match = SIGN_PLACE_REGEX.search( command )
  247. if match:
  248. VIM_SIGNS.append( VimSign( int( match.group( 'id' ) ),
  249. int( match.group( 'line' ) ),
  250. match.group( 'name' ),
  251. int( match.group( 'bufnr' ) ) ) )
  252. return True
  253. match = SIGN_UNPLACE_REGEX.search( command )
  254. if match:
  255. sign_id = int( match.group( 'id' ) )
  256. bufnr = int( match.group( 'bufnr' ) )
  257. for sign in VIM_SIGNS:
  258. if sign.id == sign_id and sign.bufnr == bufnr:
  259. VIM_SIGNS.remove( sign )
  260. return True
  261. return False
  262. def _MockVimCommand( command ):
  263. match = BWIPEOUT_REGEX.search( command )
  264. if match:
  265. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  266. match = REDIR_START_REGEX.search( command )
  267. if match:
  268. REDIR[ 'status' ] = True
  269. REDIR[ 'variable' ] = match.group( 'variable' )
  270. return
  271. match = REDIR_END_REGEX.search( command )
  272. if match:
  273. REDIR[ 'status' ] = False
  274. return
  275. if command == 'unlet ' + REDIR[ 'variable' ]:
  276. REDIR[ 'variable' ] = ''
  277. return
  278. result = _MockSignCommand( command )
  279. if result:
  280. return
  281. match = LET_REGEX.search( command )
  282. if match:
  283. option = match.group( 'option' )
  284. value = json.loads( match.group( 'value' ) )
  285. VIM_OPTIONS[ option ] = value
  286. return
  287. return DEFAULT
  288. class VimBuffer( object ):
  289. """An object that looks like a vim.buffer object:
  290. - |name| : full path of the buffer with symbolic links resolved;
  291. - |number| : buffer number;
  292. - |contents| : list of lines representing the buffer contents;
  293. - |filetype| : buffer filetype. Empty string if no filetype is set;
  294. - |modified| : True if the buffer has unsaved changes, False otherwise;
  295. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  296. - |omnifunc| : omni completion function used by the buffer. Must be a Python
  297. function that takes the same arguments and returns the same
  298. values as a Vim completion function (:h complete-functions).
  299. Example:
  300. def Omnifunc( findstart, base ):
  301. if findstart:
  302. return 5
  303. return [ 'a', 'b', 'c' ]"""
  304. def __init__( self, name,
  305. number = 1,
  306. contents = [ '' ],
  307. filetype = '',
  308. modified = False,
  309. bufhidden = '',
  310. omnifunc = None,
  311. visual_start = None,
  312. visual_end = None ):
  313. self.name = os.path.realpath( name ) if name else ''
  314. self.number = number
  315. self.contents = contents
  316. self.filetype = filetype
  317. self.modified = modified
  318. self.bufhidden = bufhidden
  319. self.omnifunc = omnifunc
  320. self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
  321. self.changedtick = 1
  322. self.options = {
  323. 'mod': modified,
  324. 'bh': bufhidden
  325. }
  326. self.visual_start = visual_start
  327. self.visual_end = visual_end
  328. def __getitem__( self, index ):
  329. """Returns the bytes for a given line at index |index|."""
  330. return self.contents[ index ]
  331. def __len__( self ):
  332. return len( self.contents )
  333. def __setitem__( self, key, value ):
  334. return self.contents.__setitem__( key, value )
  335. def GetLines( self ):
  336. """Returns the contents of the buffer as a list of unicode strings."""
  337. return [ ToUnicode( x ) for x in self.contents ]
  338. def mark( self, name ):
  339. if name == '<':
  340. return self.visual_start
  341. if name == '>':
  342. return self.visual_end
  343. raise ValueError( 'Unexpected mark: {name}'.format( name = name ) )
  344. class VimBuffers( object ):
  345. """An object that looks like a vim.buffers object."""
  346. def __init__( self, buffers ):
  347. """|buffers| is a list of VimBuffer objects."""
  348. self._buffers = buffers
  349. def __getitem__( self, number ):
  350. """Emulates vim.buffers[ number ]"""
  351. for buffer_object in self._buffers:
  352. if number == buffer_object.number:
  353. return buffer_object
  354. raise KeyError( number )
  355. def __iter__( self ):
  356. """Emulates for loop on vim.buffers"""
  357. return iter( self._buffers )
  358. def pop( self, index ):
  359. return self._buffers.pop( index )
  360. class VimWindow( object ):
  361. """An object that looks like a vim.window object:
  362. - |number|: number of the window;
  363. - |buffer_object|: a VimBuffer object representing the buffer inside the
  364. window;
  365. - |cursor|: a tuple corresponding to the cursor position."""
  366. def __init__( self, number, buffer_object, cursor = None ):
  367. self.number = number
  368. self.buffer = buffer_object
  369. self.cursor = cursor
  370. self.options = {}
  371. class VimWindows( object ):
  372. """An object that looks like a vim.windows object."""
  373. def __init__( self, buffers, cursor ):
  374. """|buffers| is a list of VimBuffer objects corresponding to the window
  375. layout. The first element of that list is assumed to be the current window.
  376. |cursor| is the cursor position of that window."""
  377. windows = []
  378. windows.append( VimWindow( 1, buffers[ 0 ], cursor ) )
  379. for window_number in range( 1, len( buffers ) ):
  380. windows.append( VimWindow( window_number + 1, buffers[ window_number ] ) )
  381. self._windows = windows
  382. def __getitem__( self, number ):
  383. """Emulates vim.windows[ number ]"""
  384. for window in self._windows:
  385. if number == window.number:
  386. return window
  387. raise KeyError( number )
  388. def __iter__( self ):
  389. """Emulates for loop on vim.windows"""
  390. return iter( self._windows )
  391. class VimCurrent( object ):
  392. """An object that looks like a vim.current object. |current_window| must be a
  393. VimWindow object."""
  394. def __init__( self, current_window ):
  395. self.buffer = current_window.buffer
  396. self.window = current_window
  397. self.line = self.buffer.contents[ current_window.cursor[ 0 ] - 1 ]
  398. class VimMatch( object ):
  399. def __init__( self, group, pattern ):
  400. current_window = VIM_MOCK.current.window.number
  401. self.id = len( VIM_MATCHES_FOR_WINDOW[ current_window ] ) + 1
  402. self.group = group
  403. self.pattern = pattern
  404. def __eq__( self, other ):
  405. return self.group == other.group and self.pattern == other.pattern
  406. def __repr__( self ):
  407. return "VimMatch( group = '{0}', pattern = '{1}' )".format( self.group,
  408. self.pattern )
  409. def __getitem__( self, key ):
  410. if key == 'group':
  411. return self.group
  412. elif key == 'id':
  413. return self.id
  414. class VimSign( object ):
  415. def __init__( self, sign_id, line, name, bufnr ):
  416. self.id = sign_id
  417. self.line = line
  418. self.name = name
  419. self.bufnr = bufnr
  420. def __eq__( self, other ):
  421. return ( self.id == other.id and
  422. self.line == other.line and
  423. self.name == other.name and
  424. self.bufnr == other.bufnr )
  425. def __repr__( self ):
  426. return ( "VimSign( id = {0}, line = {1}, "
  427. "name = '{2}', bufnr = {3} )".format( self.id,
  428. self.line,
  429. self.name,
  430. self.bufnr ) )
  431. def __getitem__( self, key ):
  432. if key == 'group':
  433. return self.group
  434. elif key == 'id':
  435. return self.id
  436. @contextlib.contextmanager
  437. def MockVimBuffers( buffers, window_buffers, cursor_position = ( 1, 1 ) ):
  438. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  439. buffer displayed in the current window and |cursor_position| is the current
  440. cursor position. All buffers are represented by a VimBuffer object."""
  441. if ( not isinstance( buffers, list ) or
  442. not all( isinstance( buf, VimBuffer ) for buf in buffers ) ):
  443. raise RuntimeError( 'First parameter must be a list of VimBuffer objects.' )
  444. if ( not isinstance( window_buffers, list ) or
  445. not all( isinstance( buf, VimBuffer ) for buf in window_buffers ) ):
  446. raise RuntimeError( 'Second parameter must be a list of VimBuffer objects '
  447. 'representing the window layout.' )
  448. if len( window_buffers ) < 1:
  449. raise RuntimeError( 'Second parameter must contain at least one element '
  450. 'which corresponds to the current window.' )
  451. with patch( 'vim.buffers', VimBuffers( buffers ) ):
  452. with patch( 'vim.windows', VimWindows( window_buffers,
  453. cursor_position ) ) as windows:
  454. with patch( 'vim.current', VimCurrent( windows[ 1 ] ) ):
  455. yield VIM_MOCK
  456. def MockVimModule():
  457. """The 'vim' module is something that is only present when running inside the
  458. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  459. need to add additional mocks to vim module functions, then use 'patch' from
  460. mock module, to ensure that the state of the vim mock is returned before the
  461. next test. That is:
  462. from ycm.tests.test_utils import MockVimModule
  463. from mock import patch
  464. # Do this once
  465. MockVimModule()
  466. @patch( 'vim.eval', return_value='test' )
  467. @patch( 'vim.command', side_effect=ValueError )
  468. def test( vim_command, vim_eval ):
  469. # use vim.command via vim_command, e.g.:
  470. vim_command.assert_has_calls( ... )
  471. Failure to use this approach may lead to unexpected failures in other
  472. tests."""
  473. VIM_MOCK.command = MagicMock( side_effect = _MockVimCommand )
  474. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  475. VIM_MOCK.error = VimError
  476. sys.modules[ 'vim' ] = VIM_MOCK
  477. return VIM_MOCK
  478. class VimError( Exception ):
  479. def __init__( self, code ):
  480. self.code = code
  481. def __str__( self ):
  482. return repr( self.code )
  483. class ExtendedMock( MagicMock ):
  484. """An extension to the MagicMock class which adds the ability to check that a
  485. callable is called with a precise set of calls in a precise order.
  486. Example Usage:
  487. from ycm.tests.test_utils import ExtendedMock
  488. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  489. def my_test( test_testing ):
  490. ...
  491. """
  492. def assert_has_exact_calls( self, calls, any_order = False ):
  493. self.assert_has_calls( calls, any_order )
  494. assert_that( self.call_count, equal_to( len( calls ) ) )
  495. def ExpectedFailure( reason, *exception_matchers ):
  496. """Defines a decorator to be attached to tests. This decorator
  497. marks the test as being known to fail, e.g. where documenting or exercising
  498. known incorrect behaviour.
  499. The parameters are:
  500. - |reason| a textual description of the reason for the known issue. This
  501. is used for the skip reason
  502. - |exception_matchers| additional arguments are hamcrest matchers to apply
  503. to the exception thrown. If the matchers don't match, then the
  504. test is marked as error, with the original exception.
  505. If the test fails (for the correct reason), then it is marked as skipped.
  506. If it fails for any other reason, it is marked as failed.
  507. If the test passes, then it is also marked as failed."""
  508. def decorator( test ):
  509. @functools.wraps( test )
  510. def Wrapper( *args, **kwargs ):
  511. try:
  512. test( *args, **kwargs )
  513. except Exception as test_exception:
  514. # Ensure that we failed for the right reason
  515. test_exception_message = ToUnicode( test_exception )
  516. try:
  517. for matcher in exception_matchers:
  518. assert_that( test_exception_message, matcher )
  519. except AssertionError:
  520. # Failed for the wrong reason!
  521. import traceback
  522. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  523. # Real failure reason is the *original* exception, we're only trapping
  524. # and ignoring the exception that is expected.
  525. raise test_exception
  526. # Failed for the right reason
  527. raise nose.SkipTest( reason )
  528. else:
  529. raise AssertionError( 'Test was expected to fail: {0}'.format(
  530. reason ) )
  531. return Wrapper
  532. return decorator
  533. def ToBytesOnPY2( data ):
  534. # To test the omnifunc, etc. returning strings, which can be of different
  535. # types depending on python version, we use ToBytes on PY2 and just the native
  536. # str on python3. This roughly matches what happens between py2 and py3
  537. # versions within Vim.
  538. if not PY2:
  539. return data
  540. if isinstance( data, list ):
  541. return [ ToBytesOnPY2( item ) for item in data ]
  542. if isinstance( data, dict ):
  543. for item in data:
  544. data[ item ] = ToBytesOnPY2( data[ item ] )
  545. return data
  546. return ToBytes( data )