test_utils.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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 hamcrest import assert_that, equal_to
  20. import contextlib
  21. import functools
  22. import json
  23. import pytest
  24. import os
  25. import re
  26. import sys
  27. from unittest import skipIf
  28. from ycmd.utils import GetCurrentDirectory, OnMac, OnWindows, ToUnicode
  29. BUFNR_REGEX = re.compile( '^bufnr\\(\'(?P<buffer_filename>.+)\', ([01])\\)$' )
  30. BUFWINNR_REGEX = re.compile( '^bufwinnr\\((?P<buffer_number>[0-9]+)\\)$' )
  31. BWIPEOUT_REGEX = re.compile(
  32. '^(?:silent! )bwipeout!? (?P<buffer_number>[0-9]+)$' )
  33. GETBUFVAR_REGEX = re.compile(
  34. '^getbufvar\\((?P<buffer_number>[0-9]+), "(?P<option>.+)"\\)$' )
  35. MATCHADD_REGEX = re.compile(
  36. '^matchadd\\(\'(?P<group>.+)\', \'(?P<pattern>.+)\'\\)$' )
  37. MATCHDELETE_REGEX = re.compile( '^matchdelete\\((?P<id>\\d+)\\)$' )
  38. OMNIFUNC_REGEX_FORMAT = (
  39. '^{omnifunc_name}\\((?P<findstart>[01]),[\'"](?P<base>.*)[\'"]\\)$' )
  40. FNAMEESCAPE_REGEX = re.compile( '^fnameescape\\(\'(?P<filepath>.+)\'\\)$' )
  41. STRDISPLAYWIDTH_REGEX = re.compile(
  42. '^strdisplaywidth\\( ?\'(?P<text>.+)\' ?\\)$' )
  43. SIGN_LIST_REGEX = re.compile(
  44. '^silent! sign place buffer=(?P<bufnr>\\d+)$' )
  45. SIGN_PLACE_REGEX = re.compile(
  46. '^sign place (?P<id>\\d+) name=(?P<name>\\w+) line=(?P<line>\\d+) '
  47. 'buffer=(?P<bufnr>\\d+)$' )
  48. SIGN_UNPLACE_REGEX = re.compile(
  49. '^sign unplace (?P<id>\\d+) buffer=(?P<bufnr>\\d+)$' )
  50. REDIR_START_REGEX = re.compile( '^redir => (?P<variable>[\\w:]+)$' )
  51. REDIR_END_REGEX = re.compile( '^redir END$' )
  52. EXISTS_REGEX = re.compile( '^exists\\( \'(?P<option>[\\w:]+)\' \\)$' )
  53. LET_REGEX = re.compile( '^let (?P<option>[\\w:]+) = (?P<value>.*)$' )
  54. HAS_PATCH_REGEX = re.compile( '^has\\( \'patch(?P<patch>\\d+)\' \\)$' )
  55. # One-and only instance of mocked Vim object. The first 'import vim' that is
  56. # executed binds the vim module to the instance of MagicMock that is created,
  57. # and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively
  58. # update them. The result is that while running the tests, we must assign only
  59. # one instance of MagicMock to sys.modules[ 'vim' ] and always return it.
  60. #
  61. # More explanation is available:
  62. # https://github.com/Valloric/YouCompleteMe/pull/1694
  63. VIM_MOCK = MagicMock()
  64. VIM_MATCHES_FOR_WINDOW = defaultdict( list )
  65. VIM_SIGNS = []
  66. VIM_OPTIONS = {
  67. '&completeopt': b'',
  68. '&previewheight': 12,
  69. '&columns': 80,
  70. '&ruler': 0,
  71. '&showcmd': 1,
  72. '&hidden': 0,
  73. '&expandtab': 1
  74. }
  75. Version = namedtuple( 'Version', [ 'major', 'minor', 'patch' ] )
  76. # This variable must be patched with a Version object for tests depending on a
  77. # recent Vim version. Example:
  78. #
  79. # @patch( 'ycm.tests.test_utils.VIM_VERSION', Version( 8, 1, 614 ) )
  80. # def ThisTestDependsOnTheVimVersion_test():
  81. # ...
  82. #
  83. # Default is the oldest supported version.
  84. VIM_VERSION = Version( 7, 4, 1578 )
  85. REDIR = {
  86. 'status': False,
  87. 'variable': '',
  88. 'output': ''
  89. }
  90. WindowsAndMacOnly = skipIf( not OnWindows() or not OnMac(),
  91. 'Windows and macOS only' )
  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. return current_buffer.omnifunc( findstart, base )
  149. return None
  150. def _MockVimWindowEval( value ):
  151. if value == 'winnr("#")':
  152. # For simplicity, we always assume there is no previous window.
  153. return 0
  154. return None
  155. def _MockVimOptionsEval( value ):
  156. result = VIM_OPTIONS.get( value )
  157. if result is not None:
  158. return result
  159. if value == 'keys( g: )':
  160. global_options = {}
  161. for key, value in VIM_OPTIONS.items():
  162. if key.startswith( 'g:' ):
  163. global_options[ key[ 2: ] ] = value
  164. return global_options
  165. match = EXISTS_REGEX.search( value )
  166. if match:
  167. option = match.group( 'option' )
  168. return option in VIM_OPTIONS
  169. return None
  170. def _MockVimFunctionsEval( value ):
  171. if value == 'tempname()':
  172. return '_TEMP_FILE_'
  173. if value == 'tagfiles()':
  174. return [ 'tags' ]
  175. if value == 'shiftwidth()':
  176. return 2
  177. return None
  178. def _MockVimMatchEval( value ):
  179. current_window = VIM_MOCK.current.window.number
  180. if value == 'getmatches()':
  181. return VIM_MATCHES_FOR_WINDOW[ current_window ]
  182. match = MATCHADD_REGEX.search( value )
  183. if match:
  184. group = match.group( 'group' )
  185. option = match.group( 'pattern' )
  186. vim_match = VimMatch( group, option )
  187. VIM_MATCHES_FOR_WINDOW[ current_window ].append( vim_match )
  188. return vim_match.id
  189. match = MATCHDELETE_REGEX.search( value )
  190. if match:
  191. match_id = int( match.group( 'id' ) )
  192. vim_matches = VIM_MATCHES_FOR_WINDOW[ current_window ]
  193. for index, vim_match in enumerate( vim_matches ):
  194. if vim_match.id == match_id:
  195. vim_matches.pop( index )
  196. return -1
  197. return 0
  198. return None
  199. def _MockVimVersionEval( value ):
  200. match = HAS_PATCH_REGEX.search( value )
  201. if match:
  202. if not isinstance( VIM_VERSION, Version ):
  203. raise RuntimeError( 'Vim version is not set.' )
  204. return VIM_VERSION.patch >= int( match.group( 'patch' ) )
  205. if value == 'v:version':
  206. if not isinstance( VIM_VERSION, Version ):
  207. raise RuntimeError( 'Vim version is not set.' )
  208. return VIM_VERSION.major * 100 + VIM_VERSION.minor
  209. return None
  210. def _MockVimEval( value ):
  211. result = _MockVimOptionsEval( value )
  212. if result is not None:
  213. return result
  214. result = _MockVimFunctionsEval( value )
  215. if result is not None:
  216. return result
  217. result = _MockVimBufferEval( value )
  218. if result is not None:
  219. return result
  220. result = _MockVimWindowEval( value )
  221. if result is not None:
  222. return result
  223. result = _MockVimMatchEval( value )
  224. if result is not None:
  225. return result
  226. result = _MockVimVersionEval( value )
  227. if result is not None:
  228. return result
  229. match = FNAMEESCAPE_REGEX.search( value )
  230. if match:
  231. return match.group( 'filepath' )
  232. if value == REDIR[ 'variable' ]:
  233. return REDIR[ 'output' ]
  234. match = STRDISPLAYWIDTH_REGEX.search( value )
  235. if match:
  236. return len( match.group( 'text' ) )
  237. raise VimError( f'Unexpected evaluation: { value }' )
  238. def _MockWipeoutBuffer( buffer_number ):
  239. buffers = VIM_MOCK.buffers
  240. for index, buffer in enumerate( buffers ):
  241. if buffer.number == buffer_number:
  242. return buffers.pop( index )
  243. def _MockSignCommand( command ):
  244. match = SIGN_LIST_REGEX.search( command )
  245. if match and REDIR[ 'status' ]:
  246. bufnr = int( match.group( 'bufnr' ) )
  247. REDIR[ 'output' ] = ( '--- Signs ---\n'
  248. 'Signs for foo:\n' )
  249. for sign in VIM_SIGNS:
  250. if sign.bufnr == bufnr:
  251. if VIM_VERSION >= Version( 8, 1, 614 ):
  252. # 10 is the default priority.
  253. line_output = ' line={} id={} name={} priority=10'
  254. else:
  255. line_output = ' line={} id={} name={}'
  256. REDIR[ 'output' ] += line_output.format( sign.line, sign.id, sign.name )
  257. return True
  258. match = SIGN_PLACE_REGEX.search( command )
  259. if match:
  260. VIM_SIGNS.append( VimSign( int( match.group( 'id' ) ),
  261. int( match.group( 'line' ) ),
  262. match.group( 'name' ),
  263. int( match.group( 'bufnr' ) ) ) )
  264. return True
  265. match = SIGN_UNPLACE_REGEX.search( command )
  266. if match:
  267. sign_id = int( match.group( 'id' ) )
  268. bufnr = int( match.group( 'bufnr' ) )
  269. for sign in VIM_SIGNS:
  270. if sign.id == sign_id and sign.bufnr == bufnr:
  271. VIM_SIGNS.remove( sign )
  272. return True
  273. return False
  274. def _MockVimCommand( command ):
  275. match = BWIPEOUT_REGEX.search( command )
  276. if match:
  277. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  278. match = REDIR_START_REGEX.search( command )
  279. if match:
  280. REDIR[ 'status' ] = True
  281. REDIR[ 'variable' ] = match.group( 'variable' )
  282. return
  283. match = REDIR_END_REGEX.search( command )
  284. if match:
  285. REDIR[ 'status' ] = False
  286. return
  287. if command == 'unlet ' + REDIR[ 'variable' ]:
  288. REDIR[ 'variable' ] = ''
  289. return
  290. result = _MockSignCommand( command )
  291. if result:
  292. return
  293. match = LET_REGEX.search( command )
  294. if match:
  295. option = match.group( 'option' )
  296. value = json.loads( match.group( 'value' ) )
  297. VIM_OPTIONS[ option ] = value
  298. return
  299. return DEFAULT
  300. def _MockVimOptions( option ):
  301. result = VIM_OPTIONS.get( '&' + option )
  302. if result is not None:
  303. return result
  304. return None
  305. class VimBuffer:
  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( f'Unexpected mark: { name }' )
  361. def __repr__( self ):
  362. return f"VimBuffer( name = '{ self.name }', number = { self.number } )"
  363. class VimBuffers:
  364. """An object that looks like a vim.buffers object."""
  365. def __init__( self, buffers ):
  366. """|buffers| is a list of VimBuffer objects."""
  367. self._buffers = buffers
  368. def __getitem__( self, number ):
  369. """Emulates vim.buffers[ number ]"""
  370. for buffer_object in self._buffers:
  371. if number == buffer_object.number:
  372. return buffer_object
  373. raise KeyError( number )
  374. def __iter__( self ):
  375. """Emulates for loop on vim.buffers"""
  376. return iter( self._buffers )
  377. def pop( self, index ):
  378. return self._buffers.pop( index )
  379. class VimWindow:
  380. """An object that looks like a vim.window object:
  381. - |number|: number of the window;
  382. - |buffer_object|: a VimBuffer object representing the buffer inside the
  383. window;
  384. - |cursor|: a tuple corresponding to the cursor position."""
  385. def __init__( self, number, buffer_object, cursor = None ):
  386. self.number = number
  387. self.buffer = buffer_object
  388. self.cursor = cursor
  389. self.options = {}
  390. def __repr__( self ):
  391. return ( f'VimWindow( number = { self.number }, '
  392. f'buffer = { self.buffer }, '
  393. f'cursor = { self.cursor } )' )
  394. class VimWindows:
  395. """An object that looks like a vim.windows object."""
  396. def __init__( self, buffers, cursor ):
  397. """|buffers| is a list of VimBuffer objects corresponding to the window
  398. layout. The first element of that list is assumed to be the current window.
  399. |cursor| is the cursor position of that window."""
  400. windows = []
  401. windows.append( VimWindow( 1, buffers[ 0 ], cursor ) )
  402. for window_number in range( 1, len( buffers ) ):
  403. windows.append( VimWindow( window_number + 1, buffers[ window_number ] ) )
  404. self._windows = windows
  405. def __getitem__( self, number ):
  406. """Emulates vim.windows[ number ]"""
  407. try:
  408. return self._windows[ number ]
  409. except IndexError:
  410. raise IndexError( 'no such window' )
  411. def __iter__( self ):
  412. """Emulates for loop on vim.windows"""
  413. return iter( self._windows )
  414. class VimCurrent:
  415. """An object that looks like a vim.current object. |current_window| must be a
  416. VimWindow object."""
  417. def __init__( self, current_window ):
  418. self.buffer = current_window.buffer
  419. self.window = current_window
  420. self.line = self.buffer.contents[ current_window.cursor[ 0 ] - 1 ]
  421. class VimMatch:
  422. def __init__( self, group, pattern ):
  423. current_window = VIM_MOCK.current.window.number
  424. self.id = len( VIM_MATCHES_FOR_WINDOW[ current_window ] ) + 1
  425. self.group = group
  426. self.pattern = pattern
  427. def __eq__( self, other ):
  428. return self.group == other.group and self.pattern == other.pattern
  429. def __repr__( self ):
  430. return f"VimMatch( group = '{ self.group }', pattern = '{ self.pattern }' )"
  431. def __getitem__( self, key ):
  432. if key == 'group':
  433. return self.group
  434. elif key == 'id':
  435. return self.id
  436. class VimSign:
  437. def __init__( self, sign_id, line, name, bufnr ):
  438. self.id = sign_id
  439. self.line = line
  440. self.name = name
  441. self.bufnr = bufnr
  442. def __eq__( self, other ):
  443. return ( self.id == other.id and
  444. self.line == other.line and
  445. self.name == other.name and
  446. self.bufnr == other.bufnr )
  447. def __repr__( self ):
  448. return ( f"VimSign( id = { self.id }, line = { self.line }, "
  449. f"name = '{ self.name }', bufnr = { self.bufnr } )" )
  450. def __getitem__( self, key ):
  451. if key == 'group':
  452. return self.group
  453. elif key == 'id':
  454. return self.id
  455. @contextlib.contextmanager
  456. def MockVimBuffers( buffers, window_buffers, cursor_position = ( 1, 1 ) ):
  457. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  458. buffer displayed in the current window and |cursor_position| is the current
  459. cursor position. All buffers are represented by a VimBuffer object."""
  460. if ( not isinstance( buffers, list ) or
  461. not all( isinstance( buf, VimBuffer ) for buf in buffers ) ):
  462. raise RuntimeError( 'First parameter must be a list of VimBuffer objects.' )
  463. if ( not isinstance( window_buffers, list ) or
  464. not all( isinstance( buf, VimBuffer ) for buf in window_buffers ) ):
  465. raise RuntimeError( 'Second parameter must be a list of VimBuffer objects '
  466. 'representing the window layout.' )
  467. if len( window_buffers ) < 1:
  468. raise RuntimeError( 'Second parameter must contain at least one element '
  469. 'which corresponds to the current window.' )
  470. with patch( 'vim.buffers', VimBuffers( buffers ) ):
  471. with patch( 'vim.windows', VimWindows( window_buffers,
  472. cursor_position ) ) as windows:
  473. with patch( 'vim.current', VimCurrent( windows[ 0 ] ) ):
  474. yield VIM_MOCK
  475. def MockVimModule():
  476. """The 'vim' module is something that is only present when running inside the
  477. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  478. need to add additional mocks to vim module functions, then use 'patch' from
  479. mock module, to ensure that the state of the vim mock is returned before the
  480. next test. That is:
  481. from ycm.tests.test_utils import MockVimModule
  482. from unittest.mock import patch
  483. # Do this once
  484. MockVimModule()
  485. @patch( 'vim.eval', return_value='test' )
  486. @patch( 'vim.command', side_effect=ValueError )
  487. def test( vim_command, vim_eval ):
  488. # use vim.command via vim_command, e.g.:
  489. vim_command.assert_has_calls( ... )
  490. Failure to use this approach may lead to unexpected failures in other
  491. tests."""
  492. VIM_MOCK.command = MagicMock( side_effect = _MockVimCommand )
  493. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  494. VIM_MOCK.error = VimError
  495. VIM_MOCK.options = MagicMock()
  496. VIM_MOCK.options.__getitem__.side_effect = _MockVimOptions
  497. sys.modules[ 'vim' ] = VIM_MOCK
  498. return VIM_MOCK
  499. class VimError( Exception ):
  500. def __init__( self, code ):
  501. self.code = code
  502. def __str__( self ):
  503. return repr( self.code )
  504. class ExtendedMock( MagicMock ):
  505. """An extension to the MagicMock class which adds the ability to check that a
  506. callable is called with a precise set of calls in a precise order.
  507. Example Usage:
  508. from ycm.tests.test_utils import ExtendedMock
  509. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  510. def my_test( test_testing ):
  511. ...
  512. """
  513. def assert_has_exact_calls( self, calls, any_order = False ):
  514. self.assert_has_calls( calls, any_order )
  515. assert_that( self.call_count, equal_to( len( calls ) ) )
  516. def ExpectedFailure( reason, *exception_matchers ):
  517. """Defines a decorator to be attached to tests. This decorator
  518. marks the test as being known to fail, e.g. where documenting or exercising
  519. known incorrect behaviour.
  520. The parameters are:
  521. - |reason| a textual description of the reason for the known issue. This
  522. is used for the skip reason
  523. - |exception_matchers| additional arguments are hamcrest matchers to apply
  524. to the exception thrown. If the matchers don't match, then the
  525. test is marked as error, with the original exception.
  526. If the test fails (for the correct reason), then it is marked as skipped.
  527. If it fails for any other reason, it is marked as failed.
  528. If the test passes, then it is also marked as failed."""
  529. def decorator( test ):
  530. @functools.wraps( test )
  531. def Wrapper( *args, **kwargs ):
  532. try:
  533. test( *args, **kwargs )
  534. except Exception as test_exception:
  535. # Ensure that we failed for the right reason
  536. test_exception_message = ToUnicode( test_exception )
  537. try:
  538. for matcher in exception_matchers:
  539. assert_that( test_exception_message, matcher )
  540. except AssertionError:
  541. # Failed for the wrong reason!
  542. import traceback
  543. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  544. # Real failure reason is the *original* exception, we're only trapping
  545. # and ignoring the exception that is expected.
  546. raise test_exception
  547. # Failed for the right reason
  548. pytest.skip( reason )
  549. else:
  550. raise AssertionError( f'Test was expected to fail: { reason }' )
  551. return Wrapper
  552. return decorator