test_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. # Copyright (C) 2011-2012 Google Inc.
  2. # 2016 YouCompleteMe contributors
  3. #
  4. # This file is part of YouCompleteMe.
  5. #
  6. # YouCompleteMe is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # YouCompleteMe is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  18. from __future__ import unicode_literals
  19. from __future__ import print_function
  20. from __future__ import division
  21. from __future__ import absolute_import
  22. # Not installing aliases from python-future; it's unreliable and slow.
  23. from builtins import * # noqa
  24. from future.utils import PY2
  25. from mock import MagicMock, patch
  26. from hamcrest import assert_that, equal_to
  27. import contextlib
  28. import functools
  29. import nose
  30. import os
  31. import re
  32. import sys
  33. from ycmd.utils import GetCurrentDirectory, ToBytes, ToUnicode
  34. BUFNR_REGEX = re.compile( '^bufnr\(\'(?P<buffer_filename>.+)\', ([01])\)$' )
  35. BUFWINNR_REGEX = re.compile( '^bufwinnr\((?P<buffer_number>[0-9]+)\)$' )
  36. BWIPEOUT_REGEX = re.compile(
  37. '^(?:silent! )bwipeout!? (?P<buffer_number>[0-9]+)$' )
  38. GETBUFVAR_REGEX = re.compile(
  39. '^getbufvar\((?P<buffer_number>[0-9]+), "(?P<option>.+)"\)$' )
  40. MATCHADD_REGEX = re.compile(
  41. '^matchadd\(\'(?P<group>.+)\', \'(?P<pattern>.+)\'\)$' )
  42. MATCHDELETE_REGEX = re.compile( '^matchdelete\((?P<id>\d+)\)$' )
  43. OMNIFUNC_REGEX_FORMAT = (
  44. '^{omnifunc_name}\((?P<findstart>[01]),[\'"](?P<base>.*)[\'"]\)$' )
  45. FNAMEESCAPE_REGEX = re.compile( '^fnameescape\(\'(?P<filepath>.+)\'\)$' )
  46. # One-and only instance of mocked Vim object. The first 'import vim' that is
  47. # executed binds the vim module to the instance of MagicMock that is created,
  48. # and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively
  49. # update them. The result is that while running the tests, we must assign only
  50. # one instance of MagicMock to sys.modules[ 'vim' ] and always return it.
  51. #
  52. # More explanation is available:
  53. # https://github.com/Valloric/YouCompleteMe/pull/1694
  54. VIM_MOCK = MagicMock()
  55. VIM_MATCHES = []
  56. @contextlib.contextmanager
  57. def CurrentWorkingDirectory( path ):
  58. old_cwd = GetCurrentDirectory()
  59. os.chdir( path )
  60. try:
  61. yield
  62. finally:
  63. os.chdir( old_cwd )
  64. def _MockGetBufferNumber( buffer_filename ):
  65. for vim_buffer in VIM_MOCK.buffers:
  66. if vim_buffer.name == buffer_filename:
  67. return vim_buffer.number
  68. return -1
  69. def _MockGetBufferWindowNumber( buffer_number ):
  70. for vim_buffer in VIM_MOCK.buffers:
  71. if vim_buffer.number == buffer_number and vim_buffer.window:
  72. return vim_buffer.window
  73. return -1
  74. def _MockGetBufferVariable( buffer_number, option ):
  75. for vim_buffer in VIM_MOCK.buffers:
  76. if vim_buffer.number == buffer_number:
  77. if option == '&mod':
  78. return vim_buffer.modified
  79. if option == '&ft':
  80. return vim_buffer.filetype
  81. if option == 'changedtick':
  82. return vim_buffer.changedtick
  83. if option == '&bh':
  84. return vim_buffer.bufhidden
  85. return ''
  86. return ''
  87. def _MockVimBufferEval( value ):
  88. if value == '&omnifunc':
  89. return VIM_MOCK.current.buffer.omnifunc_name
  90. if value == '&filetype':
  91. return VIM_MOCK.current.buffer.filetype
  92. match = BUFNR_REGEX.search( value )
  93. if match:
  94. buffer_filename = match.group( 'buffer_filename' )
  95. return _MockGetBufferNumber( buffer_filename )
  96. match = BUFWINNR_REGEX.search( value )
  97. if match:
  98. buffer_number = int( match.group( 'buffer_number' ) )
  99. return _MockGetBufferWindowNumber( buffer_number )
  100. match = GETBUFVAR_REGEX.search( value )
  101. if match:
  102. buffer_number = int( match.group( 'buffer_number' ) )
  103. option = match.group( 'option' )
  104. return _MockGetBufferVariable( buffer_number, option )
  105. current_buffer = VIM_MOCK.current.buffer
  106. match = re.search( OMNIFUNC_REGEX_FORMAT.format(
  107. omnifunc_name = current_buffer.omnifunc_name ),
  108. value )
  109. if match:
  110. findstart = int( match.group( 'findstart' ) )
  111. base = match.group( 'base' )
  112. value = current_buffer.omnifunc( findstart, base )
  113. return value if findstart else ToBytesOnPY2( value )
  114. return None
  115. def _MockVimOptionsEval( value ):
  116. if value == '&previewheight':
  117. return 12
  118. if value == '&columns':
  119. return 80
  120. if value == '&ruler':
  121. return 0
  122. if value == '&showcmd':
  123. return 1
  124. if value == '&hidden':
  125. return 0
  126. return None
  127. def _MockVimMatchEval( value ):
  128. if value == 'getmatches()':
  129. # Returning a copy, because ClearYcmSyntaxMatches() gets the result of
  130. # getmatches(), iterates over it and removes elements from VIM_MATCHES.
  131. return list( VIM_MATCHES )
  132. match = MATCHADD_REGEX.search( value )
  133. if match:
  134. group = match.group( 'group' )
  135. option = match.group( 'pattern' )
  136. vim_match = VimMatch( group, option )
  137. VIM_MATCHES.append( vim_match )
  138. return vim_match.id
  139. match = MATCHDELETE_REGEX.search( value )
  140. if match:
  141. identity = int( match.group( 'id' ) )
  142. for index, vim_match in enumerate( VIM_MATCHES ):
  143. if vim_match.id == identity:
  144. VIM_MATCHES.pop( index )
  145. return -1
  146. return 0
  147. return None
  148. # This variable exists to easily mock the 'g:ycm_server_python_interpreter'
  149. # option in tests.
  150. server_python_interpreter = ''
  151. def _MockVimEval( value ):
  152. if value == 'g:ycm_min_num_of_chars_for_completion':
  153. return 0
  154. if value == 'g:ycm_server_python_interpreter':
  155. return server_python_interpreter
  156. if value == 'tempname()':
  157. return '_TEMP_FILE_'
  158. if value == 'tagfiles()':
  159. return [ 'tags' ]
  160. result = _MockVimOptionsEval( value )
  161. if result is not None:
  162. return result
  163. result = _MockVimBufferEval( value )
  164. if result is not None:
  165. return result
  166. result = _MockVimMatchEval( value )
  167. if result is not None:
  168. return result
  169. match = FNAMEESCAPE_REGEX.search( value )
  170. if match:
  171. return match.group( 'filepath' )
  172. raise ValueError( 'Unexpected evaluation: {0}'.format( value ) )
  173. def _MockWipeoutBuffer( buffer_number ):
  174. buffers = VIM_MOCK.buffers
  175. for index, buffer in enumerate( buffers ):
  176. if buffer.number == buffer_number:
  177. return buffers.pop( index )
  178. def MockVimCommand( command ):
  179. match = BWIPEOUT_REGEX.search( command )
  180. if match:
  181. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  182. raise RuntimeError( 'Unexpected command: ' + command )
  183. class VimBuffer( object ):
  184. """An object that looks like a vim.buffer object:
  185. - |name| : full path of the buffer with symbolic links resolved;
  186. - |number| : buffer number;
  187. - |contents| : list of lines representing the buffer contents;
  188. - |filetype| : buffer filetype. Empty string if no filetype is set;
  189. - |modified| : True if the buffer has unsaved changes, False otherwise;
  190. - |bufhidden|: value of the 'bufhidden' option (see :h bufhidden);
  191. - |window| : number of the buffer window. None if the buffer is hidden;
  192. - |omnifunc| : omni completion function used by the buffer. Must be a Python
  193. function that takes the same arguments and returns the same
  194. values as a Vim completion function (:h complete-functions).
  195. Example:
  196. def Omnifunc( findstart, base ):
  197. if findstart:
  198. return 5
  199. return [ 'a', 'b', 'c' ]"""
  200. def __init__( self, name,
  201. number = 1,
  202. contents = [ '' ],
  203. filetype = '',
  204. modified = False,
  205. bufhidden = '',
  206. window = None,
  207. omnifunc = None ):
  208. self.name = os.path.realpath( name ) if name else ''
  209. self.number = number
  210. self.contents = contents
  211. self.filetype = filetype
  212. self.modified = modified
  213. self.bufhidden = bufhidden
  214. self.window = window
  215. self.omnifunc = omnifunc
  216. self.omnifunc_name = omnifunc.__name__ if omnifunc else ''
  217. self.changedtick = 1
  218. def __getitem__( self, index ):
  219. """Returns the bytes for a given line at index |index|."""
  220. return self.contents[ index ]
  221. def __len__( self ):
  222. return len( self.contents )
  223. def __setitem__( self, key, value ):
  224. return self.contents.__setitem__( key, value )
  225. def GetLines( self ):
  226. """Returns the contents of the buffer as a list of unicode strings."""
  227. return [ ToUnicode( x ) for x in self.contents ]
  228. class VimMatch( object ):
  229. def __init__( self, group, pattern ):
  230. self.id = len( VIM_MATCHES )
  231. self.group = group
  232. self.pattern = pattern
  233. def __eq__( self, other ):
  234. return self.group == other.group and self.pattern == other.pattern
  235. def __repr__( self ):
  236. return "VimMatch( group = '{0}', pattern = '{1}' )".format( self.group,
  237. self.pattern )
  238. def __getitem__( self, key ):
  239. if key == 'group':
  240. return self.group
  241. elif key == 'id':
  242. return self.id
  243. @contextlib.contextmanager
  244. def MockVimBuffers( buffers, current_buffer, cursor_position = ( 1, 1 ) ):
  245. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  246. buffer displayed in the current window and |cursor_position| is the current
  247. cursor position. All buffers are represented by a VimBuffer object."""
  248. if current_buffer not in buffers:
  249. raise RuntimeError( 'Current buffer must be part of the buffers list.' )
  250. line = current_buffer.contents[ cursor_position[ 0 ] - 1 ]
  251. with patch( 'vim.buffers', buffers ):
  252. with patch( 'vim.current.buffer', current_buffer ):
  253. with patch( 'vim.current.window.cursor', cursor_position ):
  254. with patch( 'vim.current.line', line ):
  255. yield VIM_MOCK
  256. def MockVimModule():
  257. """The 'vim' module is something that is only present when running inside the
  258. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  259. need to add additional mocks to vim module functions, then use 'patch' from
  260. mock module, to ensure that the state of the vim mock is returned before the
  261. next test. That is:
  262. from ycm.tests.test_utils import MockVimModule
  263. from mock import patch
  264. # Do this once
  265. MockVimModule()
  266. @patch( 'vim.eval', return_value='test' )
  267. @patch( 'vim.command', side_effect=ValueError )
  268. def test( vim_command, vim_eval ):
  269. # use vim.command via vim_command, e.g.:
  270. vim_command.assert_has_calls( ... )
  271. Failure to use this approach may lead to unexpected failures in other
  272. tests."""
  273. VIM_MOCK.buffers = {}
  274. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  275. sys.modules[ 'vim' ] = VIM_MOCK
  276. return VIM_MOCK
  277. class VimError( Exception ):
  278. def __init__( self, code ):
  279. self.code = code
  280. def __str__( self ):
  281. return repr( self.code )
  282. class ExtendedMock( MagicMock ):
  283. """An extension to the MagicMock class which adds the ability to check that a
  284. callable is called with a precise set of calls in a precise order.
  285. Example Usage:
  286. from ycm.tests.test_utils import ExtendedMock
  287. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  288. def my_test( test_testing ):
  289. ...
  290. """
  291. def assert_has_exact_calls( self, calls, any_order = False ):
  292. self.assert_has_calls( calls, any_order )
  293. assert_that( self.call_count, equal_to( len( calls ) ) )
  294. def ExpectedFailure( reason, *exception_matchers ):
  295. """Defines a decorator to be attached to tests. This decorator
  296. marks the test as being known to fail, e.g. where documenting or exercising
  297. known incorrect behaviour.
  298. The parameters are:
  299. - |reason| a textual description of the reason for the known issue. This
  300. is used for the skip reason
  301. - |exception_matchers| additional arguments are hamcrest matchers to apply
  302. to the exception thrown. If the matchers don't match, then the
  303. test is marked as error, with the original exception.
  304. If the test fails (for the correct reason), then it is marked as skipped.
  305. If it fails for any other reason, it is marked as failed.
  306. If the test passes, then it is also marked as failed."""
  307. def decorator( test ):
  308. @functools.wraps( test )
  309. def Wrapper( *args, **kwargs ):
  310. try:
  311. test( *args, **kwargs )
  312. except Exception as test_exception:
  313. # Ensure that we failed for the right reason
  314. test_exception_message = ToUnicode( test_exception )
  315. try:
  316. for matcher in exception_matchers:
  317. assert_that( test_exception_message, matcher )
  318. except AssertionError:
  319. # Failed for the wrong reason!
  320. import traceback
  321. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  322. # Real failure reason is the *original* exception, we're only trapping
  323. # and ignoring the exception that is expected.
  324. raise test_exception
  325. # Failed for the right reason
  326. raise nose.SkipTest( reason )
  327. else:
  328. raise AssertionError( 'Test was expected to fail: {0}'.format(
  329. reason ) )
  330. return Wrapper
  331. return decorator
  332. def ToBytesOnPY2( data ):
  333. # To test the omnifunc, etc. returning strings, which can be of different
  334. # types depending on python version, we use ToBytes on PY2 and just the native
  335. # str on python3. This roughly matches what happens between py2 and py3
  336. # versions within Vim.
  337. if not PY2:
  338. return data
  339. if isinstance( data, list ):
  340. return [ ToBytesOnPY2( item ) for item in data ]
  341. if isinstance( data, dict ):
  342. for item in data:
  343. data[ item ] = ToBytesOnPY2( data[ item ] )
  344. return data
  345. return ToBytes( data )