test_utils.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 mock import MagicMock, patch
  25. from hamcrest import assert_that, equal_to
  26. import contextlib
  27. import functools
  28. import nose
  29. import os
  30. import re
  31. import sys
  32. from ycmd.utils import GetCurrentDirectory, ToUnicode
  33. BUFNR_REGEX = re.compile( '^bufnr\(\'(?P<buffer_filename>.+)\', ([01])\)$' )
  34. BUFWINNR_REGEX = re.compile( '^bufwinnr\((?P<buffer_number>[0-9]+)\)$' )
  35. BWIPEOUT_REGEX = re.compile(
  36. '^(?:silent! )bwipeout!? (?P<buffer_number>[0-9]+)$' )
  37. GETBUFVAR_REGEX = re.compile(
  38. '^getbufvar\((?P<buffer_number>[0-9]+), "&(?P<option>.+)"\)$' )
  39. # One-and only instance of mocked Vim object. The first 'import vim' that is
  40. # executed binds the vim module to the instance of MagicMock that is created,
  41. # and subsquent assignments to sys.modules[ 'vim' ] don't retrospectively
  42. # update them. The result is that while running the tests, we must assign only
  43. # one instance of MagicMock to sys.modules[ 'vim' ] and always return it.
  44. #
  45. # More explanation is available:
  46. # https://github.com/Valloric/YouCompleteMe/pull/1694
  47. VIM_MOCK = MagicMock()
  48. @contextlib.contextmanager
  49. def CurrentWorkingDirectory( path ):
  50. old_cwd = GetCurrentDirectory()
  51. os.chdir( path )
  52. try:
  53. yield
  54. finally:
  55. os.chdir( old_cwd )
  56. def _MockGetBufferNumber( buffer_filename ):
  57. for vim_buffer in VIM_MOCK.buffers:
  58. if vim_buffer.name == buffer_filename:
  59. return vim_buffer.number
  60. return -1
  61. def _MockGetBufferWindowNumber( buffer_number ):
  62. for vim_buffer in VIM_MOCK.buffers:
  63. if vim_buffer.number == buffer_number and vim_buffer.window:
  64. return vim_buffer.window
  65. return -1
  66. def _MockGetBufferVariable( buffer_number, option ):
  67. for vim_buffer in VIM_MOCK.buffers:
  68. if vim_buffer.number == buffer_number:
  69. if option == 'mod':
  70. return vim_buffer.modified
  71. if option == 'ft':
  72. return vim_buffer.filetype
  73. return ''
  74. return ''
  75. def _MockVimBufferEval( value ):
  76. if value == '&omnifunc':
  77. return VIM_MOCK.current.buffer.omnifunc
  78. if value == '&filetype':
  79. return VIM_MOCK.current.buffer.filetype
  80. match = BUFNR_REGEX.search( value )
  81. if match:
  82. buffer_filename = match.group( 'buffer_filename' )
  83. return _MockGetBufferNumber( buffer_filename )
  84. match = BUFWINNR_REGEX.search( value )
  85. if match:
  86. buffer_number = int( match.group( 'buffer_number' ) )
  87. return _MockGetBufferWindowNumber( buffer_number )
  88. match = GETBUFVAR_REGEX.search( value )
  89. if match:
  90. buffer_number = int( match.group( 'buffer_number' ) )
  91. option = match.group( 'option' )
  92. return _MockGetBufferVariable( buffer_number, option )
  93. return None
  94. def _MockVimOptionsEval( value ):
  95. if value == '&previewheight':
  96. return 12
  97. if value == '&columns':
  98. return 80
  99. if value == '&ruler':
  100. return 0
  101. if value == '&showcmd':
  102. return 1
  103. return None
  104. def _MockVimEval( value ):
  105. if value == 'g:ycm_min_num_of_chars_for_completion':
  106. return 0
  107. if value == 'g:ycm_server_python_interpreter':
  108. return ''
  109. if value == 'tempname()':
  110. return '_TEMP_FILE_'
  111. if value == 'complete_check()':
  112. return 0
  113. if value == 'tagfiles()':
  114. return [ 'tags' ]
  115. result = _MockVimOptionsEval( value )
  116. if result is not None:
  117. return result
  118. result = _MockVimBufferEval( value )
  119. if result is not None:
  120. return result
  121. raise ValueError( 'Unexpected evaluation: {0}'.format( value ) )
  122. def _MockWipeoutBuffer( buffer_number ):
  123. buffers = VIM_MOCK.buffers
  124. for index, buffer in enumerate( buffers ):
  125. if buffer.number == buffer_number:
  126. return buffers.pop( index )
  127. def MockVimCommand( command ):
  128. match = BWIPEOUT_REGEX.search( command )
  129. if match:
  130. return _MockWipeoutBuffer( int( match.group( 1 ) ) )
  131. raise RuntimeError( 'Unexpected command: ' + command )
  132. class VimBuffer( object ):
  133. """An object that looks like a vim.buffer object:
  134. - |name| : full path of the buffer with symbolic links resolved;
  135. - |number| : buffer number;
  136. - |contents|: list of lines representing the buffer contents;
  137. - |filetype|: buffer filetype. Empty string if no filetype is set;
  138. - |modified|: True if the buffer has unsaved changes, False otherwise;
  139. - |window| : number of the buffer window. None if the buffer is hidden;
  140. - |omnifunc|: omni completion function used by the buffer."""
  141. def __init__( self, name,
  142. number = 1,
  143. contents = [],
  144. filetype = '',
  145. modified = True,
  146. window = None,
  147. omnifunc = '' ):
  148. self.name = os.path.realpath( name ) if name else ''
  149. self.number = number
  150. self.contents = contents
  151. self.filetype = filetype
  152. self.modified = modified
  153. self.window = window
  154. self.omnifunc = omnifunc
  155. def __getitem__( self, index ):
  156. """Returns the bytes for a given line at index |index|."""
  157. return self.contents[ index ]
  158. def __len__( self ):
  159. return len( self.contents )
  160. def __setitem__( self, key, value ):
  161. return self.contents.__setitem__( key, value )
  162. def GetLines( self ):
  163. """Returns the contents of the buffer as a list of unicode strings."""
  164. return [ ToUnicode( x ) for x in self.contents ]
  165. @contextlib.contextmanager
  166. def MockVimBuffers( buffers, current_buffer, cursor_position = ( 1, 1 ) ):
  167. """Simulates the Vim buffers list |buffers| where |current_buffer| is the
  168. buffer displayed in the current window and |cursor_position| is the current
  169. cursor position. All buffers are represented by a VimBuffer object."""
  170. if current_buffer not in buffers:
  171. raise RuntimeError( 'Current buffer must be part of the buffers list.' )
  172. with patch( 'vim.buffers', buffers ):
  173. with patch( 'vim.current.buffer', current_buffer ):
  174. with patch( 'vim.current.window.cursor', cursor_position ):
  175. yield
  176. def MockVimModule():
  177. """The 'vim' module is something that is only present when running inside the
  178. Vim Python interpreter, so we replace it with a MagicMock for tests. If you
  179. need to add additional mocks to vim module functions, then use 'patch' from
  180. mock module, to ensure that the state of the vim mock is returned before the
  181. next test. That is:
  182. from ycm.tests.test_utils import MockVimModule
  183. from mock import patch
  184. # Do this once
  185. MockVimModule()
  186. @patch( 'vim.eval', return_value='test' )
  187. @patch( 'vim.command', side_effect=ValueError )
  188. def test( vim_command, vim_eval ):
  189. # use vim.command via vim_command, e.g.:
  190. vim_command.assert_has_calls( ... )
  191. Failure to use this approach may lead to unexpected failures in other
  192. tests."""
  193. VIM_MOCK.buffers = {}
  194. VIM_MOCK.eval = MagicMock( side_effect = _MockVimEval )
  195. sys.modules[ 'vim' ] = VIM_MOCK
  196. return VIM_MOCK
  197. class ExtendedMock( MagicMock ):
  198. """An extension to the MagicMock class which adds the ability to check that a
  199. callable is called with a precise set of calls in a precise order.
  200. Example Usage:
  201. from ycm.tests.test_utils import ExtendedMock
  202. @patch( 'test.testing', new_callable = ExtendedMock, ... )
  203. def my_test( test_testing ):
  204. ...
  205. """
  206. def assert_has_exact_calls( self, calls, any_order = False ):
  207. self.assert_has_calls( calls, any_order )
  208. assert_that( self.call_count, equal_to( len( calls ) ) )
  209. def ExpectedFailure( reason, *exception_matchers ):
  210. """Defines a decorator to be attached to tests. This decorator
  211. marks the test as being known to fail, e.g. where documenting or exercising
  212. known incorrect behaviour.
  213. The parameters are:
  214. - |reason| a textual description of the reason for the known issue. This
  215. is used for the skip reason
  216. - |exception_matchers| additional arguments are hamcrest matchers to apply
  217. to the exception thrown. If the matchers don't match, then the
  218. test is marked as error, with the original exception.
  219. If the test fails (for the correct reason), then it is marked as skipped.
  220. If it fails for any other reason, it is marked as failed.
  221. If the test passes, then it is also marked as failed."""
  222. def decorator( test ):
  223. @functools.wraps( test )
  224. def Wrapper( *args, **kwargs ):
  225. try:
  226. test( *args, **kwargs )
  227. except Exception as test_exception:
  228. # Ensure that we failed for the right reason
  229. test_exception_message = ToUnicode( test_exception )
  230. try:
  231. for matcher in exception_matchers:
  232. assert_that( test_exception_message, matcher )
  233. except AssertionError:
  234. # Failed for the wrong reason!
  235. import traceback
  236. print( 'Test failed for the wrong reason: ' + traceback.format_exc() )
  237. # Real failure reason is the *original* exception, we're only trapping
  238. # and ignoring the exception that is expected.
  239. raise test_exception
  240. # Failed for the right reason
  241. raise nose.SkipTest( reason )
  242. else:
  243. raise AssertionError( 'Test was expected to fail: {0}'.format(
  244. reason ) )
  245. return Wrapper
  246. return decorator