1
0

test_utils.py 9.7 KB

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