event_notification_test.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. # coding: utf-8
  2. #
  3. # Copyright (C) 2015-2016 YouCompleteMe contributors
  4. #
  5. # This file is part of YouCompleteMe.
  6. #
  7. # YouCompleteMe is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # YouCompleteMe is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.
  19. from __future__ import unicode_literals
  20. from __future__ import print_function
  21. from __future__ import division
  22. from __future__ import absolute_import
  23. from future import standard_library
  24. standard_library.install_aliases()
  25. from builtins import * # noqa
  26. from ycm.tests.test_utils import ( CurrentWorkingDirectory, ExtendedMock,
  27. MockVimBuffers, MockVimModule, VimBuffer )
  28. MockVimModule()
  29. import contextlib
  30. import os
  31. from ycm.tests import PathToTestFile, YouCompleteMeInstance
  32. from ycmd.responses import ( BuildDiagnosticData, Diagnostic, Location, Range,
  33. UnknownExtraConf, ServerError )
  34. from hamcrest import assert_that, contains, has_entries, has_item
  35. from mock import call, MagicMock, patch
  36. from nose.tools import eq_, ok_
  37. def PresentDialog_Confirm_Call( message ):
  38. """Return a mock.call object for a call to vimsupport.PresentDialog, as called
  39. why vimsupport.Confirm with the supplied confirmation message"""
  40. return call( message, [ 'Ok', 'Cancel' ] )
  41. def PlaceSign_Call( sign_id, line_num, buffer_num, is_error ):
  42. sign_name = 'YcmError' if is_error else 'YcmWarning'
  43. return call( 'sign place {0} line={1} name={2} buffer={3}'
  44. .format( sign_id, line_num, sign_name, buffer_num ) )
  45. def UnplaceSign_Call( sign_id, buffer_num ):
  46. return call( 'try | exec "sign unplace {0} buffer={1}" |'
  47. ' catch /E158/ | endtry'.format( sign_id, buffer_num ) )
  48. @contextlib.contextmanager
  49. def MockArbitraryBuffer( filetype ):
  50. """Used via the with statement, set up a single buffer with an arbitrary name
  51. and no contents. Its filetype is set to the supplied filetype."""
  52. # Arbitrary, but valid, single buffer open.
  53. current_buffer = VimBuffer( os.path.realpath( 'TEST_BUFFER' ),
  54. window = 1,
  55. filetype = filetype )
  56. with MockVimBuffers( [ current_buffer ], current_buffer ):
  57. yield
  58. @contextlib.contextmanager
  59. def MockEventNotification( response_method, native_filetype_completer = True ):
  60. """Mock out the EventNotification client request object, replacing the
  61. Response handler's JsonFromFuture with the supplied |response_method|.
  62. Additionally mock out YouCompleteMe's FiletypeCompleterExistsForFiletype
  63. method to return the supplied |native_filetype_completer| parameter, rather
  64. than querying the server"""
  65. # We don't want the event to actually be sent to the server, just have it
  66. # return success
  67. with patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync',
  68. return_value = MagicMock( return_value=True ) ):
  69. # We set up a fake a Response (as called by EventNotification.Response)
  70. # which calls the supplied callback method. Generally this callback just
  71. # raises an apropriate exception, otherwise it would have to return a mock
  72. # future object.
  73. #
  74. # Note: JsonFromFuture is actually part of ycm.client.base_request, but we
  75. # must patch where an object is looked up, not where it is defined.
  76. # See https://docs.python.org/dev/library/unittest.mock.html#where-to-patch
  77. # for details.
  78. with patch( 'ycm.client.event_notification.JsonFromFuture',
  79. side_effect = response_method ):
  80. # Filetype available information comes from the server, so rather than
  81. # relying on that request, we mock out the check. The caller decides if
  82. # filetype completion is available
  83. with patch(
  84. 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  85. return_value = native_filetype_completer ):
  86. yield
  87. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  88. @YouCompleteMeInstance()
  89. def EventNotification_FileReadyToParse_NonDiagnostic_Error_test(
  90. ycm, post_vim_message ):
  91. # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest
  92. # in combination with YouCompleteMe.OnFileReadyToParse when the completer
  93. # raises an exception handling FileReadyToParse event notification
  94. ERROR_TEXT = 'Some completer response text'
  95. def ErrorResponse( *args ):
  96. raise ServerError( ERROR_TEXT )
  97. with MockArbitraryBuffer( 'javascript' ):
  98. with MockEventNotification( ErrorResponse ):
  99. ycm.OnFileReadyToParse()
  100. ok_( ycm.FileParseRequestReady() )
  101. ycm.HandleFileParseRequest()
  102. # The first call raises a warning
  103. post_vim_message.assert_has_exact_calls( [
  104. call( ERROR_TEXT, truncate = False )
  105. ] )
  106. # Subsequent calls don't re-raise the warning
  107. ycm.HandleFileParseRequest()
  108. post_vim_message.assert_has_exact_calls( [
  109. call( ERROR_TEXT, truncate = False )
  110. ] )
  111. # But it does if a subsequent event raises again
  112. ycm.OnFileReadyToParse()
  113. ok_( ycm.FileParseRequestReady() )
  114. ycm.HandleFileParseRequest()
  115. post_vim_message.assert_has_exact_calls( [
  116. call( ERROR_TEXT, truncate = False ),
  117. call( ERROR_TEXT, truncate = False )
  118. ] )
  119. @patch( 'vim.command' )
  120. @YouCompleteMeInstance()
  121. def EventNotification_FileReadyToParse_NonDiagnostic_Error_NonNative_test(
  122. ycm, vim_command ):
  123. with MockArbitraryBuffer( 'javascript' ):
  124. with MockEventNotification( None, False ):
  125. ycm.OnFileReadyToParse()
  126. ycm.HandleFileParseRequest()
  127. vim_command.assert_not_called()
  128. @patch( 'ycm.client.event_notification._LoadExtraConfFile',
  129. new_callable = ExtendedMock )
  130. @patch( 'ycm.client.event_notification._IgnoreExtraConfFile',
  131. new_callable = ExtendedMock )
  132. @YouCompleteMeInstance()
  133. def EventNotification_FileReadyToParse_NonDiagnostic_ConfirmExtraConf_test(
  134. ycm, ignore_extra_conf, load_extra_conf ):
  135. # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest
  136. # in combination with YouCompleteMe.OnFileReadyToParse when the completer
  137. # raises the (special) UnknownExtraConf exception
  138. FILE_NAME = 'a_file'
  139. MESSAGE = ( 'Found ' + FILE_NAME + '. Load? \n\n(Question can be '
  140. 'turned off with options, see YCM docs)' )
  141. def UnknownExtraConfResponse( *args ):
  142. raise UnknownExtraConf( FILE_NAME )
  143. with MockArbitraryBuffer( 'javascript' ):
  144. with MockEventNotification( UnknownExtraConfResponse ):
  145. # When the user accepts the extra conf, we load it
  146. with patch( 'ycm.vimsupport.PresentDialog',
  147. return_value = 0,
  148. new_callable = ExtendedMock ) as present_dialog:
  149. ycm.OnFileReadyToParse()
  150. ok_( ycm.FileParseRequestReady() )
  151. ycm.HandleFileParseRequest()
  152. present_dialog.assert_has_exact_calls( [
  153. PresentDialog_Confirm_Call( MESSAGE ),
  154. ] )
  155. load_extra_conf.assert_has_exact_calls( [
  156. call( FILE_NAME ),
  157. ] )
  158. # Subsequent calls don't re-raise the warning
  159. ycm.HandleFileParseRequest()
  160. present_dialog.assert_has_exact_calls( [
  161. PresentDialog_Confirm_Call( MESSAGE )
  162. ] )
  163. load_extra_conf.assert_has_exact_calls( [
  164. call( FILE_NAME ),
  165. ] )
  166. # But it does if a subsequent event raises again
  167. ycm.OnFileReadyToParse()
  168. ok_( ycm.FileParseRequestReady() )
  169. ycm.HandleFileParseRequest()
  170. present_dialog.assert_has_exact_calls( [
  171. PresentDialog_Confirm_Call( MESSAGE ),
  172. PresentDialog_Confirm_Call( MESSAGE ),
  173. ] )
  174. load_extra_conf.assert_has_exact_calls( [
  175. call( FILE_NAME ),
  176. call( FILE_NAME ),
  177. ] )
  178. # When the user rejects the extra conf, we reject it
  179. with patch( 'ycm.vimsupport.PresentDialog',
  180. return_value = 1,
  181. new_callable = ExtendedMock ) as present_dialog:
  182. ycm.OnFileReadyToParse()
  183. ok_( ycm.FileParseRequestReady() )
  184. ycm.HandleFileParseRequest()
  185. present_dialog.assert_has_exact_calls( [
  186. PresentDialog_Confirm_Call( MESSAGE ),
  187. ] )
  188. ignore_extra_conf.assert_has_exact_calls( [
  189. call( FILE_NAME ),
  190. ] )
  191. # Subsequent calls don't re-raise the warning
  192. ycm.HandleFileParseRequest()
  193. present_dialog.assert_has_exact_calls( [
  194. PresentDialog_Confirm_Call( MESSAGE )
  195. ] )
  196. ignore_extra_conf.assert_has_exact_calls( [
  197. call( FILE_NAME ),
  198. ] )
  199. # But it does if a subsequent event raises again
  200. ycm.OnFileReadyToParse()
  201. ok_( ycm.FileParseRequestReady() )
  202. ycm.HandleFileParseRequest()
  203. present_dialog.assert_has_exact_calls( [
  204. PresentDialog_Confirm_Call( MESSAGE ),
  205. PresentDialog_Confirm_Call( MESSAGE ),
  206. ] )
  207. ignore_extra_conf.assert_has_exact_calls( [
  208. call( FILE_NAME ),
  209. call( FILE_NAME ),
  210. ] )
  211. @YouCompleteMeInstance()
  212. def EventNotification_FileReadyToParse_Diagnostic_Error_Native_test( ycm ):
  213. _Check_FileReadyToParse_Diagnostic_Error( ycm )
  214. _Check_FileReadyToParse_Diagnostic_Warning( ycm )
  215. _Check_FileReadyToParse_Diagnostic_Clean( ycm )
  216. @patch( 'vim.command' )
  217. def _Check_FileReadyToParse_Diagnostic_Error( ycm, vim_command ):
  218. # Tests Vim sign placement and error/warning count python API
  219. # when one error is returned.
  220. def DiagnosticResponse( *args ):
  221. start = Location( 1, 2, 'TEST_BUFFER' )
  222. end = Location( 1, 4, 'TEST_BUFFER' )
  223. extent = Range( start, end )
  224. diagnostic = Diagnostic( [], start, extent, 'expected ;', 'ERROR' )
  225. return [ BuildDiagnosticData( diagnostic ) ]
  226. with MockArbitraryBuffer( 'cpp' ):
  227. with MockEventNotification( DiagnosticResponse ):
  228. ycm.OnFileReadyToParse()
  229. ok_( ycm.FileParseRequestReady() )
  230. ycm.HandleFileParseRequest()
  231. vim_command.assert_has_calls( [
  232. PlaceSign_Call( 1, 1, 1, True )
  233. ] )
  234. eq_( ycm.GetErrorCount(), 1 )
  235. eq_( ycm.GetWarningCount(), 0 )
  236. # Consequent calls to HandleFileParseRequest shouldn't mess with
  237. # existing diagnostics, when there is no new parse request.
  238. vim_command.reset_mock()
  239. ok_( not ycm.FileParseRequestReady() )
  240. ycm.HandleFileParseRequest()
  241. vim_command.assert_not_called()
  242. eq_( ycm.GetErrorCount(), 1 )
  243. eq_( ycm.GetWarningCount(), 0 )
  244. @patch( 'vim.command' )
  245. def _Check_FileReadyToParse_Diagnostic_Warning( ycm, vim_command ):
  246. # Tests Vim sign placement/unplacement and error/warning count python API
  247. # when one warning is returned.
  248. # Should be called after _Check_FileReadyToParse_Diagnostic_Error
  249. def DiagnosticResponse( *args ):
  250. start = Location( 2, 2, 'TEST_BUFFER' )
  251. end = Location( 2, 4, 'TEST_BUFFER' )
  252. extent = Range( start, end )
  253. diagnostic = Diagnostic( [], start, extent, 'cast', 'WARNING' )
  254. return [ BuildDiagnosticData( diagnostic ) ]
  255. with MockArbitraryBuffer( 'cpp' ):
  256. with MockEventNotification( DiagnosticResponse ):
  257. ycm.OnFileReadyToParse()
  258. ok_( ycm.FileParseRequestReady() )
  259. ycm.HandleFileParseRequest()
  260. vim_command.assert_has_calls( [
  261. PlaceSign_Call( 2, 2, 1, False ),
  262. UnplaceSign_Call( 1, 1 )
  263. ] )
  264. eq_( ycm.GetErrorCount(), 0 )
  265. eq_( ycm.GetWarningCount(), 1 )
  266. # Consequent calls to HandleFileParseRequest shouldn't mess with
  267. # existing diagnostics, when there is no new parse request.
  268. vim_command.reset_mock()
  269. ok_( not ycm.FileParseRequestReady() )
  270. ycm.HandleFileParseRequest()
  271. vim_command.assert_not_called()
  272. eq_( ycm.GetErrorCount(), 0 )
  273. eq_( ycm.GetWarningCount(), 1 )
  274. @patch( 'vim.command' )
  275. def _Check_FileReadyToParse_Diagnostic_Clean( ycm, vim_command ):
  276. # Tests Vim sign unplacement and error/warning count python API
  277. # when there are no errors/warnings left.
  278. # Should be called after _Check_FileReadyToParse_Diagnostic_Warning
  279. with MockArbitraryBuffer( 'cpp' ):
  280. with MockEventNotification( MagicMock( return_value = [] ) ):
  281. ycm.OnFileReadyToParse()
  282. ycm.HandleFileParseRequest()
  283. vim_command.assert_has_calls( [
  284. UnplaceSign_Call( 2, 1 )
  285. ] )
  286. eq_( ycm.GetErrorCount(), 0 )
  287. eq_( ycm.GetWarningCount(), 0 )
  288. @patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' )
  289. @YouCompleteMeInstance( { 'collect_identifiers_from_tags_files': 1 } )
  290. def EventNotification_FileReadyToParse_TagFiles_UnicodeWorkingDirectory_test(
  291. ycm, *args ):
  292. unicode_dir = PathToTestFile( 'uni¢𐍈d€' )
  293. current_buffer_file = PathToTestFile( 'uni¢𐍈d€', 'current_buffer' )
  294. current_buffer = VimBuffer( name = current_buffer_file,
  295. contents = [ 'current_buffer_contents' ],
  296. filetype = 'some_filetype' )
  297. with patch( 'ycm.client.base_request.BaseRequest.'
  298. 'PostDataToHandlerAsync' ) as post_data_to_handler_async:
  299. with CurrentWorkingDirectory( unicode_dir ):
  300. with MockVimBuffers( [ current_buffer ], current_buffer, ( 6, 5 ) ):
  301. ycm.OnFileReadyToParse()
  302. assert_that(
  303. # Positional arguments passed to PostDataToHandlerAsync.
  304. post_data_to_handler_async.call_args[ 0 ],
  305. contains(
  306. has_entries( {
  307. 'filepath': current_buffer_file,
  308. 'line_num': 6,
  309. 'column_num': 6,
  310. 'file_data': has_entries( {
  311. current_buffer_file: has_entries( {
  312. 'contents': 'current_buffer_contents\n',
  313. 'filetypes': [ 'some_filetype' ]
  314. } )
  315. } ),
  316. 'event_name': 'FileReadyToParse',
  317. 'tag_files': has_item( PathToTestFile( 'uni¢𐍈d€', 'tags' ) )
  318. } ),
  319. 'event_notification'
  320. )
  321. )
  322. @patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' )
  323. @YouCompleteMeInstance()
  324. def EventNotification_BufferVisit_BuildRequestForCurrentAndUnsavedBuffers_test(
  325. ycm, *args ):
  326. current_buffer_file = os.path.realpath( 'current_buffer' )
  327. current_buffer = VimBuffer( name = current_buffer_file,
  328. number = 1,
  329. contents = [ 'current_buffer_contents' ],
  330. filetype = 'some_filetype',
  331. modified = False )
  332. modified_buffer_file = os.path.realpath( 'modified_buffer' )
  333. modified_buffer = VimBuffer( name = modified_buffer_file,
  334. number = 2,
  335. contents = [ 'modified_buffer_contents' ],
  336. filetype = 'some_filetype',
  337. modified = True )
  338. unmodified_buffer_file = os.path.realpath( 'unmodified_buffer' )
  339. unmodified_buffer = VimBuffer( name = unmodified_buffer_file,
  340. number = 3,
  341. contents = [ 'unmodified_buffer_contents' ],
  342. filetype = 'some_filetype',
  343. modified = False )
  344. with patch( 'ycm.client.base_request.BaseRequest.'
  345. 'PostDataToHandlerAsync' ) as post_data_to_handler_async:
  346. with MockVimBuffers( [ current_buffer, modified_buffer, unmodified_buffer ],
  347. current_buffer,
  348. ( 3, 5 ) ):
  349. ycm.OnBufferVisit()
  350. assert_that(
  351. # Positional arguments passed to PostDataToHandlerAsync.
  352. post_data_to_handler_async.call_args[ 0 ],
  353. contains(
  354. has_entries( {
  355. 'filepath': current_buffer_file,
  356. 'line_num': 3,
  357. 'column_num': 6,
  358. 'file_data': has_entries( {
  359. current_buffer_file: has_entries( {
  360. 'contents': 'current_buffer_contents\n',
  361. 'filetypes': [ 'some_filetype' ]
  362. } ),
  363. modified_buffer_file: has_entries( {
  364. 'contents': 'modified_buffer_contents\n',
  365. 'filetypes': [ 'some_filetype' ]
  366. } )
  367. } ),
  368. 'event_name': 'BufferVisit'
  369. } ),
  370. 'event_notification'
  371. )
  372. )
  373. @YouCompleteMeInstance()
  374. def EventNotification_BufferUnload_BuildRequestForDeletedAndUnsavedBuffers_test(
  375. ycm ):
  376. current_buffer_file = os.path.realpath( 'current_buffer' )
  377. current_buffer = VimBuffer( name = current_buffer_file,
  378. number = 1,
  379. contents = [ 'current_buffer_contents' ],
  380. filetype = 'some_filetype',
  381. modified = True )
  382. deleted_buffer_file = os.path.realpath( 'deleted_buffer' )
  383. deleted_buffer = VimBuffer( name = deleted_buffer_file,
  384. number = 2,
  385. contents = [ 'deleted_buffer_contents' ],
  386. filetype = 'some_filetype',
  387. modified = False )
  388. with patch( 'ycm.client.base_request.BaseRequest.'
  389. 'PostDataToHandlerAsync' ) as post_data_to_handler_async:
  390. with MockVimBuffers( [ current_buffer, deleted_buffer ], current_buffer ):
  391. ycm.OnBufferUnload( deleted_buffer_file )
  392. assert_that(
  393. # Positional arguments passed to PostDataToHandlerAsync.
  394. post_data_to_handler_async.call_args[ 0 ],
  395. contains(
  396. has_entries( {
  397. 'filepath': deleted_buffer_file,
  398. 'line_num': 1,
  399. 'column_num': 1,
  400. 'file_data': has_entries( {
  401. current_buffer_file: has_entries( {
  402. 'contents': 'current_buffer_contents\n',
  403. 'filetypes': [ 'some_filetype' ]
  404. } ),
  405. deleted_buffer_file: has_entries( {
  406. 'contents': 'deleted_buffer_contents\n',
  407. 'filetypes': [ 'some_filetype' ]
  408. } )
  409. } ),
  410. 'event_name': 'BufferUnload'
  411. } ),
  412. 'event_notification'
  413. )
  414. )