1
0

youcompleteme_test.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. # Copyright (C) 2016-2017 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 __future__ import unicode_literals
  18. from __future__ import print_function
  19. from __future__ import division
  20. from __future__ import absolute_import
  21. # Not installing aliases from python-future; it's unreliable and slow.
  22. from builtins import * # noqa
  23. from ycm.tests.test_utils import ( ExtendedMock, MockVimBuffers, MockVimModule,
  24. VimBuffer, VimMatch, VimSign )
  25. MockVimModule()
  26. import os
  27. import sys
  28. from hamcrest import ( assert_that, contains, empty, equal_to, is_in, is_not,
  29. matches_regexp )
  30. from mock import call, MagicMock, patch
  31. from ycm.paths import _PathToPythonUsedDuringBuild
  32. from ycm.vimsupport import SIGN_BUFFER_ID_INITIAL_VALUE
  33. from ycm.youcompleteme import YouCompleteMe
  34. from ycm.tests import ( MakeUserOptions, StopServer, test_utils,
  35. WaitUntilReady, YouCompleteMeInstance )
  36. from ycm.client.base_request import _LoadExtraConfFile
  37. from ycmd.responses import ServerError
  38. from ycm.tests.mock_utils import ( MockAsyncServerResponseDone,
  39. MockAsyncServerResponseInProgress,
  40. MockAsyncServerResponseException )
  41. from ycm import buffer as ycm_buffer_module
  42. @YouCompleteMeInstance()
  43. def YouCompleteMe_YcmCoreNotImported_test( ycm ):
  44. assert_that( 'ycm_core', is_not( is_in( sys.modules ) ) )
  45. @patch( 'ycm.vimsupport.PostVimMessage' )
  46. def YouCompleteMe_InvalidPythonInterpreterPath_test( post_vim_message ):
  47. try:
  48. with patch( 'ycm.tests.test_utils.server_python_interpreter',
  49. '/invalid/path/to/python' ):
  50. ycm = YouCompleteMe( MakeUserOptions() )
  51. assert_that( ycm.IsServerAlive(), equal_to( False ) )
  52. post_vim_message.assert_called_once_with(
  53. "Unable to start the ycmd server. "
  54. "Path in 'g:ycm_server_python_interpreter' option does not point "
  55. "to a valid Python 2.7 or 3.4+. "
  56. "Correct the error then restart the server with ':YcmRestartServer'." )
  57. post_vim_message.reset_mock()
  58. with patch( 'ycm.tests.test_utils.server_python_interpreter',
  59. _PathToPythonUsedDuringBuild() ):
  60. ycm.RestartServer()
  61. assert_that( ycm.IsServerAlive(), equal_to( True ) )
  62. post_vim_message.assert_called_once_with( 'Restarting ycmd server...' )
  63. finally:
  64. WaitUntilReady()
  65. StopServer( ycm )
  66. @patch( 'ycmd.utils.PathToFirstExistingExecutable', return_value = None )
  67. @patch( 'ycm.paths._EndsWithPython', return_value = False )
  68. @patch( 'ycm.vimsupport.PostVimMessage' )
  69. def YouCompleteMe_NoPythonInterpreterFound_test( post_vim_message, *args ):
  70. try:
  71. with patch( 'ycmd.utils.ReadFile', side_effect = IOError ):
  72. ycm = YouCompleteMe( MakeUserOptions() )
  73. assert_that( ycm.IsServerAlive(), equal_to( False ) )
  74. post_vim_message.assert_called_once_with(
  75. "Unable to start the ycmd server. Cannot find Python 2.7 or 3.4+. "
  76. "Set the 'g:ycm_server_python_interpreter' option to a Python "
  77. "interpreter path. "
  78. "Correct the error then restart the server with ':YcmRestartServer'." )
  79. post_vim_message.reset_mock()
  80. with patch( 'ycm.tests.test_utils.server_python_interpreter',
  81. _PathToPythonUsedDuringBuild() ):
  82. ycm.RestartServer()
  83. assert_that( ycm.IsServerAlive(), equal_to( True ) )
  84. post_vim_message.assert_called_once_with( 'Restarting ycmd server...' )
  85. finally:
  86. WaitUntilReady()
  87. StopServer( ycm )
  88. @YouCompleteMeInstance()
  89. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  90. def RunNotifyUserIfServerCrashed( ycm, test, post_vim_message ):
  91. StopServer( ycm )
  92. ycm._logger = MagicMock( autospec = True )
  93. ycm._server_popen = MagicMock( autospec = True )
  94. ycm._server_popen.poll.return_value = test[ 'return_code' ]
  95. ycm.OnFileReadyToParse()
  96. assert_that( ycm._logger.error.call_args[ 0 ][ 0 ],
  97. test[ 'expected_message' ] )
  98. assert_that( post_vim_message.call_args[ 0 ][ 0 ],
  99. test[ 'expected_message' ] )
  100. def YouCompleteMe_NotifyUserIfServerCrashed_UnexpectedCore_test():
  101. message = ( "The ycmd server SHUT DOWN \(restart with ':YcmRestartServer'\). "
  102. "Unexpected error while loading the YCM core library. Type "
  103. "':YcmToggleLogs ycmd_\d+_stderr_.+.log' to check the logs." )
  104. RunNotifyUserIfServerCrashed( {
  105. 'return_code': 3,
  106. 'expected_message': matches_regexp( message )
  107. } )
  108. def YouCompleteMe_NotifyUserIfServerCrashed_MissingCore_test():
  109. message = ( "The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). "
  110. "YCM core library not detected; you need to compile YCM before "
  111. "using it. Follow the instructions in the documentation." )
  112. RunNotifyUserIfServerCrashed( {
  113. 'return_code': 4,
  114. 'expected_message': equal_to( message )
  115. } )
  116. def YouCompleteMe_NotifyUserIfServerCrashed_Python2Core_test():
  117. message = ( "The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). "
  118. "YCM core library compiled for Python 2 but loaded in Python 3. "
  119. "Set the 'g:ycm_server_python_interpreter' option to a Python 2 "
  120. "interpreter path." )
  121. RunNotifyUserIfServerCrashed( {
  122. 'return_code': 5,
  123. 'expected_message': equal_to( message )
  124. } )
  125. def YouCompleteMe_NotifyUserIfServerCrashed_Python3Core_test():
  126. message = ( "The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). "
  127. "YCM core library compiled for Python 3 but loaded in Python 2. "
  128. "Set the 'g:ycm_server_python_interpreter' option to a Python 3 "
  129. "interpreter path." )
  130. RunNotifyUserIfServerCrashed( {
  131. 'return_code': 6,
  132. 'expected_message': equal_to( message )
  133. } )
  134. def YouCompleteMe_NotifyUserIfServerCrashed_OutdatedCore_test():
  135. message = ( "The ycmd server SHUT DOWN (restart with ':YcmRestartServer'). "
  136. "YCM core library too old; PLEASE RECOMPILE by running the "
  137. "install.py script. See the documentation for more details." )
  138. RunNotifyUserIfServerCrashed( {
  139. 'return_code': 7,
  140. 'expected_message': equal_to( message )
  141. } )
  142. def YouCompleteMe_NotifyUserIfServerCrashed_UnexpectedExitCode_test():
  143. message = ( "The ycmd server SHUT DOWN \(restart with ':YcmRestartServer'\). "
  144. "Unexpected exit code 1. Type "
  145. "':YcmToggleLogs ycmd_\d+_stderr_.+.log' to check the logs." )
  146. RunNotifyUserIfServerCrashed( {
  147. 'return_code': 1,
  148. 'expected_message': matches_regexp( message )
  149. } )
  150. @YouCompleteMeInstance( { 'extra_conf_vim_data': [ 'tempname()' ] } )
  151. def YouCompleteMe_DebugInfo_ServerRunning_test( ycm ):
  152. dir_of_script = os.path.dirname( os.path.abspath( __file__ ) )
  153. buf_name = os.path.join( dir_of_script, 'testdata', 'test.cpp' )
  154. extra_conf = os.path.join( dir_of_script, 'testdata', '.ycm_extra_conf.py' )
  155. _LoadExtraConfFile( extra_conf )
  156. current_buffer = VimBuffer( buf_name, filetype='cpp' )
  157. with MockVimBuffers( [ current_buffer ], current_buffer ):
  158. assert_that(
  159. ycm.DebugInfo(),
  160. matches_regexp(
  161. 'Client logfile: .+\n'
  162. 'Server Python interpreter: .+\n'
  163. 'Server Python version: .+\n'
  164. 'Server has Clang support compiled in: '
  165. '(?P<CLANG>True)?(?(CLANG)|False)\n'
  166. 'Clang version: .+\n'
  167. 'Extra configuration file found and loaded\n'
  168. 'Extra configuration path: .*testdata[/\\\\]\\.ycm_extra_conf\\.py\n'
  169. '(?(CLANG)C-family completer debug information:\n'
  170. ' Compilation database path: None\n'
  171. ' Flags: \\[\'_TEMP_FILE_\'.*\\]\n)'
  172. 'Server running at: .+\n'
  173. 'Server process ID: \d+\n'
  174. 'Server logfiles:\n'
  175. ' .+\n'
  176. ' .+' )
  177. )
  178. @YouCompleteMeInstance()
  179. def YouCompleteMe_DebugInfo_ServerNotRunning_test( ycm ):
  180. StopServer( ycm )
  181. current_buffer = VimBuffer( 'current_buffer' )
  182. with MockVimBuffers( [ current_buffer ], current_buffer ):
  183. assert_that(
  184. ycm.DebugInfo(),
  185. matches_regexp(
  186. 'Client logfile: .+\n'
  187. 'Server errored, no debug info from server\n'
  188. 'Server running at: .+\n'
  189. 'Server process ID: \d+\n'
  190. 'Server logfiles:\n'
  191. ' .+\n'
  192. ' .+' )
  193. )
  194. @YouCompleteMeInstance()
  195. def YouCompleteMe_OnVimLeave_RemoveClientLogfileByDefault_test( ycm ):
  196. client_logfile = ycm._client_logfile
  197. assert_that( os.path.isfile( client_logfile ),
  198. 'Logfile {0} does not exist.'.format( client_logfile ) )
  199. ycm.OnVimLeave()
  200. assert_that( not os.path.isfile( client_logfile ),
  201. 'Logfile {0} was not removed.'.format( client_logfile ) )
  202. @YouCompleteMeInstance( { 'keep_logfiles': 1 } )
  203. def YouCompleteMe_OnVimLeave_KeepClientLogfile_test( ycm ):
  204. client_logfile = ycm._client_logfile
  205. assert_that( os.path.isfile( client_logfile ),
  206. 'Logfile {0} does not exist.'.format( client_logfile ) )
  207. ycm.OnVimLeave()
  208. assert_that( os.path.isfile( client_logfile ),
  209. 'Logfile {0} was removed.'.format( client_logfile ) )
  210. @YouCompleteMeInstance()
  211. @patch( 'ycm.vimsupport.CloseBuffersForFilename', new_callable = ExtendedMock )
  212. @patch( 'ycm.vimsupport.OpenFilename', new_callable = ExtendedMock )
  213. def YouCompleteMe_ToggleLogs_WithParameters_test( ycm,
  214. open_filename,
  215. close_buffers_for_filename ):
  216. logfile_buffer = VimBuffer( ycm._client_logfile, window = 1 )
  217. with MockVimBuffers( [ logfile_buffer ], logfile_buffer ):
  218. ycm.ToggleLogs( os.path.basename( ycm._client_logfile ),
  219. 'nonexisting_logfile',
  220. os.path.basename( ycm._server_stdout ) )
  221. open_filename.assert_has_exact_calls( [
  222. call( ycm._server_stdout, { 'size': 12,
  223. 'watch': True,
  224. 'fix': True,
  225. 'focus': False,
  226. 'position': 'end' } )
  227. ] )
  228. close_buffers_for_filename.assert_has_exact_calls( [
  229. call( ycm._client_logfile )
  230. ] )
  231. @YouCompleteMeInstance()
  232. # Select the second item of the list which is the ycmd stderr logfile.
  233. @patch( 'ycm.vimsupport.SelectFromList', return_value = 1 )
  234. @patch( 'ycm.vimsupport.OpenFilename', new_callable = ExtendedMock )
  235. def YouCompleteMe_ToggleLogs_WithoutParameters_SelectLogfileNotAlreadyOpen_test(
  236. ycm, open_filename, *args ):
  237. current_buffer = VimBuffer( 'current_buffer' )
  238. with MockVimBuffers( [ current_buffer ], current_buffer ):
  239. ycm.ToggleLogs()
  240. open_filename.assert_has_exact_calls( [
  241. call( ycm._server_stderr, { 'size': 12,
  242. 'watch': True,
  243. 'fix': True,
  244. 'focus': False,
  245. 'position': 'end' } )
  246. ] )
  247. @YouCompleteMeInstance()
  248. # Select the third item of the list which is the ycmd stdout logfile.
  249. @patch( 'ycm.vimsupport.SelectFromList', return_value = 2 )
  250. @patch( 'ycm.vimsupport.CloseBuffersForFilename', new_callable = ExtendedMock )
  251. def YouCompleteMe_ToggleLogs_WithoutParameters_SelectLogfileAlreadyOpen_test(
  252. ycm, close_buffers_for_filename, *args ):
  253. logfile_buffer = VimBuffer( ycm._server_stdout, window = 1 )
  254. with MockVimBuffers( [ logfile_buffer ], logfile_buffer ):
  255. ycm.ToggleLogs()
  256. close_buffers_for_filename.assert_has_exact_calls( [
  257. call( ycm._server_stdout )
  258. ] )
  259. @YouCompleteMeInstance()
  260. @patch( 'ycm.vimsupport.SelectFromList',
  261. side_effect = RuntimeError( 'Error message' ) )
  262. @patch( 'ycm.vimsupport.PostVimMessage' )
  263. def YouCompleteMe_ToggleLogs_WithoutParameters_NoSelection_test(
  264. ycm, post_vim_message, *args ):
  265. current_buffer = VimBuffer( 'current_buffer' )
  266. with MockVimBuffers( [ current_buffer ], current_buffer ):
  267. ycm.ToggleLogs()
  268. assert_that(
  269. # Argument passed to PostVimMessage.
  270. post_vim_message.call_args[ 0 ][ 0 ],
  271. equal_to( 'Error message' )
  272. )
  273. @YouCompleteMeInstance()
  274. def YouCompleteMe_GetDefinedSubcommands_ListFromServer_test( ycm ):
  275. current_buffer = VimBuffer( 'buffer' )
  276. with MockVimBuffers( [ current_buffer ], current_buffer ):
  277. with patch( 'ycm.client.base_request.JsonFromFuture',
  278. return_value = [ 'SomeCommand', 'AnotherCommand' ] ):
  279. assert_that(
  280. ycm.GetDefinedSubcommands(),
  281. contains(
  282. 'SomeCommand',
  283. 'AnotherCommand'
  284. )
  285. )
  286. @YouCompleteMeInstance()
  287. @patch( 'ycm.client.base_request._logger', autospec = True )
  288. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  289. def YouCompleteMe_GetDefinedSubcommands_ErrorFromServer_test( ycm,
  290. post_vim_message,
  291. logger ):
  292. current_buffer = VimBuffer( 'buffer' )
  293. with MockVimBuffers( [ current_buffer ], current_buffer ):
  294. with patch( 'ycm.client.base_request.JsonFromFuture',
  295. side_effect = ServerError( 'Server error' ) ):
  296. result = ycm.GetDefinedSubcommands()
  297. logger.exception.assert_called_with( 'Error while handling server response' )
  298. post_vim_message.assert_has_exact_calls( [
  299. call( 'Server error', truncate = False )
  300. ] )
  301. assert_that( result, empty() )
  302. @YouCompleteMeInstance()
  303. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  304. def YouCompleteMe_ShowDetailedDiagnostic_MessageFromServer_test(
  305. ycm, post_vim_message ):
  306. current_buffer = VimBuffer( 'buffer' )
  307. with MockVimBuffers( [ current_buffer ], current_buffer ):
  308. with patch( 'ycm.client.base_request.JsonFromFuture',
  309. return_value = { 'message': 'some_detailed_diagnostic' } ):
  310. ycm.ShowDetailedDiagnostic(),
  311. post_vim_message.assert_has_exact_calls( [
  312. call( 'some_detailed_diagnostic', warning = False )
  313. ] )
  314. @YouCompleteMeInstance()
  315. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  316. def YouCompleteMe_ShowDiagnostics_FiletypeNotSupported_test( ycm,
  317. post_vim_message ):
  318. current_buffer = VimBuffer( 'buffer', filetype = 'not_supported' )
  319. with MockVimBuffers( [ current_buffer ], current_buffer ):
  320. ycm.ShowDiagnostics()
  321. post_vim_message.assert_called_once_with(
  322. 'Native filetype completion not supported for current file, '
  323. 'cannot force recompilation.', warning = False )
  324. @YouCompleteMeInstance()
  325. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  326. return_value = True )
  327. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  328. @patch( 'ycm.vimsupport.SetLocationListForWindow', new_callable = ExtendedMock )
  329. def YouCompleteMe_ShowDiagnostics_NoDiagnosticsDetected_test(
  330. ycm, set_location_list_for_window, post_vim_message, *args ):
  331. current_buffer = VimBuffer( 'buffer', filetype = 'cpp', window = 99 )
  332. with MockVimBuffers( [ current_buffer ], current_buffer ):
  333. with patch( 'ycm.client.event_notification.EventNotification.Response',
  334. return_value = {} ):
  335. ycm.ShowDiagnostics()
  336. post_vim_message.assert_has_exact_calls( [
  337. call( 'Forcing compilation, this will block Vim until done.',
  338. warning = False ),
  339. call( 'Diagnostics refreshed', warning = False ),
  340. call( 'No warnings or errors detected.', warning = False )
  341. ] )
  342. set_location_list_for_window.assert_called_once_with( 0, [] )
  343. @YouCompleteMeInstance( { 'log_level': 'debug',
  344. 'keep_logfiles': 1,
  345. 'open_loclist_on_ycm_diags': 0 } )
  346. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  347. return_value = True )
  348. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  349. @patch( 'ycm.vimsupport.SetLocationListForWindow', new_callable = ExtendedMock )
  350. def YouCompleteMe_ShowDiagnostics_DiagnosticsFound_DoNotOpenLocationList_test(
  351. ycm, set_location_list_for_window, post_vim_message, *args ):
  352. diagnostic = {
  353. 'kind': 'ERROR',
  354. 'text': 'error text',
  355. 'location': {
  356. 'filepath': 'buffer',
  357. 'line_num': 19,
  358. 'column_num': 2
  359. }
  360. }
  361. current_buffer = VimBuffer( 'buffer',
  362. filetype = 'cpp',
  363. number = 3,
  364. window = 99 )
  365. with MockVimBuffers( [ current_buffer ], current_buffer ):
  366. with patch( 'ycm.client.event_notification.EventNotification.Response',
  367. return_value = [ diagnostic ] ):
  368. ycm.ShowDiagnostics()
  369. post_vim_message.assert_has_exact_calls( [
  370. call( 'Forcing compilation, this will block Vim until done.',
  371. warning = False ),
  372. call( 'Diagnostics refreshed', warning = False )
  373. ] )
  374. set_location_list_for_window.assert_called_once_with( 0, [ {
  375. 'bufnr': 3,
  376. 'lnum': 19,
  377. 'col': 2,
  378. 'text': 'error text',
  379. 'type': 'E',
  380. 'valid': 1
  381. } ] )
  382. @YouCompleteMeInstance( { 'open_loclist_on_ycm_diags': 1 } )
  383. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  384. return_value = True )
  385. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  386. @patch( 'ycm.vimsupport.SetLocationListForWindow', new_callable = ExtendedMock )
  387. @patch( 'ycm.vimsupport.OpenLocationList', new_callable = ExtendedMock )
  388. def YouCompleteMe_ShowDiagnostics_DiagnosticsFound_OpenLocationList_test(
  389. ycm,
  390. open_location_list,
  391. set_location_list_for_window,
  392. post_vim_message,
  393. *args ):
  394. diagnostic = {
  395. 'kind': 'ERROR',
  396. 'text': 'error text',
  397. 'location': {
  398. 'filepath': 'buffer',
  399. 'line_num': 19,
  400. 'column_num': 2
  401. }
  402. }
  403. current_buffer = VimBuffer( 'buffer',
  404. filetype = 'cpp',
  405. number = 3,
  406. window = 99 )
  407. with MockVimBuffers( [ current_buffer ], current_buffer ):
  408. with patch( 'ycm.client.event_notification.EventNotification.Response',
  409. return_value = [ diagnostic ] ):
  410. ycm.ShowDiagnostics()
  411. post_vim_message.assert_has_exact_calls( [
  412. call( 'Forcing compilation, this will block Vim until done.',
  413. warning = False ),
  414. call( 'Diagnostics refreshed', warning = False )
  415. ] )
  416. set_location_list_for_window.assert_called_once_with( 0, [ {
  417. 'bufnr': 3,
  418. 'lnum': 19,
  419. 'col': 2,
  420. 'text': 'error text',
  421. 'type': 'E',
  422. 'valid': 1
  423. } ] )
  424. open_location_list.assert_called_once_with( focus = True )
  425. @YouCompleteMeInstance( { 'echo_current_diagnostic': 1,
  426. 'enable_diagnostic_signs': 1,
  427. 'enable_diagnostic_highlighting': 1 } )
  428. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  429. return_value = True )
  430. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  431. def YouCompleteMe_UpdateDiagnosticInterface_PrioritizeErrorsOverWarnings_test(
  432. ycm, post_vim_message, *args ):
  433. contents = """int main() {
  434. int x, y;
  435. x == y
  436. }"""
  437. # List of diagnostics returned by ycmd for the above code.
  438. diagnostics = [ {
  439. 'kind': 'ERROR',
  440. 'text': "expected ';' after expression",
  441. 'location': {
  442. 'filepath': 'buffer',
  443. 'line_num': 3,
  444. 'column_num': 9
  445. },
  446. # Looks strange but this is really what ycmd is returning.
  447. 'location_extent': {
  448. 'start': {
  449. 'filepath': '',
  450. 'line_num': 0,
  451. 'column_num': 0,
  452. },
  453. 'end': {
  454. 'filepath': '',
  455. 'line_num': 0,
  456. 'column_num': 0,
  457. }
  458. },
  459. 'ranges': [],
  460. 'fixit_available': True
  461. }, {
  462. 'kind': 'WARNING',
  463. 'text': 'equality comparison result unused',
  464. 'location': {
  465. 'filepath': 'buffer',
  466. 'line_num': 3,
  467. 'column_num': 7,
  468. },
  469. 'location_extent': {
  470. 'start': {
  471. 'filepath': 'buffer',
  472. 'line_num': 3,
  473. 'column_num': 5,
  474. },
  475. 'end': {
  476. 'filepath': 'buffer',
  477. 'line_num': 3,
  478. 'column_num': 7,
  479. }
  480. },
  481. 'ranges': [ {
  482. 'start': {
  483. 'filepath': 'buffer',
  484. 'line_num': 3,
  485. 'column_num': 3,
  486. },
  487. 'end': {
  488. 'filepath': 'buffer',
  489. 'line_num': 3,
  490. 'column_num': 9,
  491. }
  492. } ],
  493. 'fixit_available': True
  494. } ]
  495. current_buffer = VimBuffer( 'buffer',
  496. filetype = 'c',
  497. contents = contents.splitlines(),
  498. number = 5,
  499. window = 2 )
  500. test_utils.VIM_MATCHES = []
  501. test_utils.VIM_SIGNS = []
  502. with MockVimBuffers( [ current_buffer ], current_buffer, ( 3, 1 ) ):
  503. with patch( 'ycm.client.event_notification.EventNotification.Response',
  504. return_value = diagnostics ):
  505. ycm.OnFileReadyToParse()
  506. ycm.HandleFileParseRequest( block = True )
  507. # The error on the current line is echoed, not the warning.
  508. post_vim_message.assert_called_once_with(
  509. "expected ';' after expression (FixIt)",
  510. truncate = True, warning = False )
  511. # Error match is added after warning matches.
  512. assert_that(
  513. test_utils.VIM_MATCHES,
  514. contains(
  515. VimMatch( 'YcmWarningSection', '\%3l\%5c\_.\{-}\%3l\%7c' ),
  516. VimMatch( 'YcmWarningSection', '\%3l\%3c\_.\{-}\%3l\%9c' ),
  517. VimMatch( 'YcmErrorSection', '\%3l\%8c' )
  518. )
  519. )
  520. # Only the error sign is placed.
  521. assert_that(
  522. test_utils.VIM_SIGNS,
  523. contains(
  524. VimSign( SIGN_BUFFER_ID_INITIAL_VALUE, 3, 'YcmError', 5 )
  525. )
  526. )
  527. # The error is not echoed again when moving the cursor along the line.
  528. with MockVimBuffers( [ current_buffer ], current_buffer, ( 3, 2 ) ):
  529. post_vim_message.reset_mock()
  530. ycm.OnCursorMoved()
  531. post_vim_message.assert_not_called()
  532. # The error is cleared when moving the cursor to another line.
  533. with MockVimBuffers( [ current_buffer ], current_buffer, ( 2, 2 ) ):
  534. post_vim_message.reset_mock()
  535. ycm.OnCursorMoved()
  536. post_vim_message.assert_called_once_with( "", warning = False )
  537. # The error is echoed when moving the cursor back.
  538. with MockVimBuffers( [ current_buffer ], current_buffer, ( 3, 2 ) ):
  539. post_vim_message.reset_mock()
  540. ycm.OnCursorMoved()
  541. post_vim_message.assert_called_once_with(
  542. "expected ';' after expression (FixIt)",
  543. truncate = True, warning = False )
  544. with patch( 'ycm.client.event_notification.EventNotification.Response',
  545. return_value = diagnostics[ 1 : ] ):
  546. ycm.OnFileReadyToParse()
  547. ycm.HandleFileParseRequest( block = True )
  548. assert_that(
  549. test_utils.VIM_MATCHES,
  550. contains(
  551. VimMatch( 'YcmWarningSection', '\%3l\%5c\_.\{-}\%3l\%7c' ),
  552. VimMatch( 'YcmWarningSection', '\%3l\%3c\_.\{-}\%3l\%9c' )
  553. )
  554. )
  555. assert_that(
  556. test_utils.VIM_SIGNS,
  557. contains(
  558. VimSign( SIGN_BUFFER_ID_INITIAL_VALUE + 1, 3, 'YcmWarning', 5 )
  559. )
  560. )
  561. @YouCompleteMeInstance( { 'enable_diagnostic_highlighting': 1 } )
  562. def YouCompleteMe_UpdateMatches_ClearDiagnosticMatchesInNewBuffer_test( ycm ):
  563. current_buffer = VimBuffer( 'buffer',
  564. filetype = 'c',
  565. number = 5,
  566. window = 2 )
  567. test_utils.VIM_MATCHES = [
  568. VimMatch( 'YcmWarningSection', '\%3l\%5c\_.\{-}\%3l\%7c' ),
  569. VimMatch( 'YcmWarningSection', '\%3l\%3c\_.\{-}\%3l\%9c' ),
  570. VimMatch( 'YcmErrorSection', '\%3l\%8c' )
  571. ]
  572. with MockVimBuffers( [ current_buffer ], current_buffer ):
  573. ycm.UpdateMatches()
  574. assert_that( test_utils.VIM_MATCHES, empty() )
  575. @YouCompleteMeInstance( { 'echo_current_diagnostic': 1,
  576. 'always_populate_location_list': 1 } )
  577. @patch.object( ycm_buffer_module,
  578. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  579. [ 'ycmtest' ] )
  580. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  581. return_value = True )
  582. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  583. def YouCompleteMe_AsyncDiagnosticUpdate_SingleFile_test( ycm,
  584. post_vim_message,
  585. *args ):
  586. # This test simulates asynchronous diagnostic updates associated with a single
  587. # file (e.g. Translation Unit), but where the actual errors refer to other
  588. # open files and other non-open files. This is not strictly invalid, nor is it
  589. # completely normal, but it is supported and does work.
  590. # Contrast with the next test which sends the diagnostics filewise, which is
  591. # what the language server protocol will do.
  592. diagnostics = [
  593. {
  594. 'kind': 'ERROR',
  595. 'text': 'error text in current buffer',
  596. 'location': {
  597. 'filepath': '/current',
  598. 'line_num': 1,
  599. 'column_num': 1
  600. },
  601. },
  602. {
  603. 'kind': 'ERROR',
  604. 'text': 'error text in hidden buffer',
  605. 'location': {
  606. 'filepath': '/has_diags',
  607. 'line_num': 4,
  608. 'column_num': 2
  609. },
  610. },
  611. {
  612. 'kind': 'ERROR',
  613. 'text': 'error text in buffer not open in Vim',
  614. 'location': {
  615. 'filepath': '/not_open',
  616. 'line_num': 8,
  617. 'column_num': 4
  618. },
  619. },
  620. ]
  621. current_buffer = VimBuffer( '/current',
  622. filetype = 'ycmtest',
  623. number = 1,
  624. window = 10 )
  625. buffers = [
  626. current_buffer,
  627. VimBuffer( '/no_diags',
  628. filetype = 'ycmtest',
  629. number = 2,
  630. window = 9 ),
  631. VimBuffer( '/has_diags',
  632. filetype = 'ycmtest',
  633. number = 3,
  634. window = 8 ),
  635. ]
  636. # Register each buffer internally with YCM
  637. for current in buffers:
  638. with MockVimBuffers( buffers, current, ( 1, 1 ) ):
  639. ycm.OnFileReadyToParse()
  640. with patch( 'ycm.vimsupport.SetLocationListForWindow',
  641. new_callable = ExtendedMock ) as set_location_list_for_window:
  642. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  643. ycm.UpdateWithNewDiagnosticsForFile( '/current', diagnostics )
  644. # We update the diagnostic on the current cursor position
  645. post_vim_message.assert_has_exact_calls( [
  646. call( "error text in current buffer", truncate = True, warning = False ),
  647. ] )
  648. # Ensure we included all the diags though
  649. set_location_list_for_window.assert_has_exact_calls( [
  650. call( 0, [
  651. {
  652. 'lnum': 1,
  653. 'col': 1,
  654. 'bufnr': 1,
  655. 'valid': 1,
  656. 'type': 'E',
  657. 'text': 'error text in current buffer',
  658. },
  659. {
  660. 'lnum': 4,
  661. 'col': 2,
  662. 'bufnr': 3,
  663. 'valid': 1,
  664. 'type': 'E',
  665. 'text': 'error text in hidden buffer',
  666. },
  667. {
  668. 'lnum': 8,
  669. 'col': 4,
  670. 'bufnr': -1, # sic: Our mocked bufnr function actually returns -1,
  671. # even though YCM is passing "create if needed".
  672. # FIXME? we shouldn't do that, and we should pass
  673. # filename instead
  674. 'valid': 1,
  675. 'type': 'E',
  676. 'text': 'error text in buffer not open in Vim'
  677. }
  678. ] )
  679. ] )
  680. @YouCompleteMeInstance( { 'echo_current_diagnostic': 1,
  681. 'always_populate_location_list': 1 } )
  682. @patch.object( ycm_buffer_module,
  683. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  684. [ 'ycmtest' ] )
  685. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  686. return_value = True )
  687. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  688. def YouCompleteMe_AsyncDiagnosticUpdate_PerFile_test( ycm,
  689. post_vim_message,
  690. *args ):
  691. # This test simulates asynchronous diagnostic updates which are delivered per
  692. # file, including files which are open and files which are not.
  693. # Ordered to ensure that the calls to update are deterministic
  694. diagnostics_per_file = [
  695. ( '/current', [ {
  696. 'kind': 'ERROR',
  697. 'text': 'error text in current buffer',
  698. 'location': {
  699. 'filepath': '/current',
  700. 'line_num': 1,
  701. 'column_num': 1
  702. }, }, ] ),
  703. ( '/has_diags', [ {
  704. 'kind': 'ERROR',
  705. 'text': 'error text in hidden buffer',
  706. 'location': {
  707. 'filepath': '/has_diags',
  708. 'line_num': 4,
  709. 'column_num': 2
  710. }, }, ] ),
  711. ( '/not_open', [ {
  712. 'kind': 'ERROR',
  713. 'text': 'error text in buffer not open in Vim',
  714. 'location': {
  715. 'filepath': '/not_open',
  716. 'line_num': 8,
  717. 'column_num': 4
  718. }, }, ] )
  719. ]
  720. current_buffer = VimBuffer( '/current',
  721. filetype = 'ycmtest',
  722. number = 1,
  723. window = 10 )
  724. buffers = [
  725. current_buffer,
  726. VimBuffer( '/no_diags',
  727. filetype = 'ycmtest',
  728. number = 2,
  729. window = 9 ),
  730. VimBuffer( '/has_diags',
  731. filetype = 'ycmtest',
  732. number = 3,
  733. window = 8 ),
  734. ]
  735. # Register each buffer internally with YCM
  736. for current in buffers:
  737. with MockVimBuffers( buffers, current, ( 1, 1 ) ):
  738. ycm.OnFileReadyToParse()
  739. with patch( 'ycm.vimsupport.SetLocationListForWindow',
  740. new_callable = ExtendedMock ) as set_location_list_for_window:
  741. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  742. for filename, diagnostics in diagnostics_per_file:
  743. ycm.UpdateWithNewDiagnosticsForFile( filename, diagnostics )
  744. # We update the diagnostic on the current cursor position
  745. post_vim_message.assert_has_exact_calls( [
  746. call( "error text in current buffer", truncate = True, warning = False ),
  747. ] )
  748. # Ensure we included all the diags though
  749. set_location_list_for_window.assert_has_exact_calls( [
  750. call( 0, [
  751. {
  752. 'lnum': 1,
  753. 'col': 1,
  754. 'bufnr': 1,
  755. 'valid': 1,
  756. 'type': 'E',
  757. 'text': 'error text in current buffer',
  758. },
  759. ] ),
  760. call( 8, [
  761. {
  762. 'lnum': 4,
  763. 'col': 2,
  764. 'bufnr': 3,
  765. 'valid': 1,
  766. 'type': 'E',
  767. 'text': 'error text in hidden buffer',
  768. },
  769. ] )
  770. ] )
  771. @YouCompleteMeInstance()
  772. def YouCompleteMe_OnPeriodicTick_ServerNotRunning_test( ycm, *args ):
  773. with patch.object( ycm, 'IsServerAlive', return_value = False ):
  774. assert_that( ycm.OnPeriodicTick(), equal_to( False ) )
  775. @YouCompleteMeInstance()
  776. def YouCompleteMe_OnPeriodicTick_ServerNotReady_test( ycm, *args ):
  777. with patch.object( ycm, 'IsServerAlive', return_value = True ):
  778. with patch.object( ycm, 'IsServerReady', return_value = False ):
  779. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  780. @YouCompleteMeInstance()
  781. @patch.object( ycm_buffer_module,
  782. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  783. [ 'ycmtest' ] )
  784. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  785. return_value = True )
  786. @patch( 'ycm.client.base_request._ValidateResponseObject', return_value = True )
  787. @patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
  788. def YouCompleteMe_OnPeriodicTick_DontRetry_test( ycm,
  789. post_data_to_handler_async,
  790. *args ):
  791. current_buffer = VimBuffer( '/current',
  792. filetype = 'ycmtest',
  793. number = 1,
  794. window = 10 )
  795. buffers = [ current_buffer ]
  796. # Create the request and make the first poll; we expect no response
  797. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  798. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  799. post_data_to_handler_async.assert_called()
  800. assert ycm._message_poll_request is not None
  801. post_data_to_handler_async.reset_mock()
  802. # OK that sent the request, now poll to check if it is complete (say it is
  803. # not)
  804. with patch.object( ycm._message_poll_request,
  805. '_response_future',
  806. new = MockAsyncServerResponseInProgress() ) as mock_future:
  807. poll_again = ycm.OnPeriodicTick()
  808. mock_future.done.assert_called()
  809. mock_future.result.assert_not_called()
  810. assert_that( poll_again, equal_to( True ) )
  811. # Poll again, but return a response (telling us to stop polling)
  812. with patch.object( ycm._message_poll_request,
  813. '_response_future',
  814. new = MockAsyncServerResponseDone( False ) ) \
  815. as mock_future:
  816. poll_again = ycm.OnPeriodicTick()
  817. mock_future.done.assert_called()
  818. mock_future.result.assert_called()
  819. post_data_to_handler_async.assert_not_called()
  820. # We reset and don't poll anymore
  821. assert_that( ycm._message_poll_request is None )
  822. assert_that( poll_again, equal_to( False ) )
  823. @YouCompleteMeInstance()
  824. @patch.object( ycm_buffer_module,
  825. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  826. [ 'ycmtest' ] )
  827. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  828. return_value = True )
  829. @patch( 'ycm.client.base_request._ValidateResponseObject', return_value = True )
  830. @patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
  831. def YouCompleteMe_OnPeriodicTick_Exception_test( ycm,
  832. post_data_to_handler_async,
  833. *args ):
  834. current_buffer = VimBuffer( '/current',
  835. filetype = 'ycmtest',
  836. number = 1,
  837. window = 10 )
  838. buffers = [ current_buffer ]
  839. # Create the request and make the first poll; we expect no response
  840. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  841. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  842. post_data_to_handler_async.assert_called()
  843. post_data_to_handler_async.reset_mock()
  844. # Poll again, but return an exception response
  845. mock_response = MockAsyncServerResponseException( RuntimeError( 'test' ) )
  846. with patch.object( ycm._message_poll_request,
  847. '_response_future',
  848. new = mock_response ) as mock_future:
  849. assert_that( ycm.OnPeriodicTick(), equal_to( False ) )
  850. mock_future.done.assert_called()
  851. mock_future.result.assert_called()
  852. post_data_to_handler_async.assert_not_called()
  853. # We reset and don't poll anymore
  854. assert_that( ycm._message_poll_request is None )
  855. @YouCompleteMeInstance()
  856. @patch.object( ycm_buffer_module,
  857. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  858. [ 'ycmtest' ] )
  859. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  860. return_value = True )
  861. @patch( 'ycm.client.base_request._ValidateResponseObject', return_value = True )
  862. @patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
  863. @patch( 'ycm.client.messages_request._HandlePollResponse' )
  864. def YouCompleteMe_OnPeriodicTick_ValidResponse_test( ycm,
  865. handle_poll_response,
  866. post_data_to_handler_async,
  867. *args ):
  868. current_buffer = VimBuffer( '/current',
  869. filetype = 'ycmtest',
  870. number = 1,
  871. window = 10 )
  872. buffers = [ current_buffer ]
  873. # Create the request and make the first poll; we expect no response
  874. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  875. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  876. post_data_to_handler_async.assert_called()
  877. post_data_to_handler_async.reset_mock()
  878. # Poll again, and return a _proper_ response (finally!).
  879. # Note, _HandlePollResponse is tested independently (for simplicity)
  880. with patch.object( ycm._message_poll_request,
  881. '_response_future',
  882. new = MockAsyncServerResponseDone( [] ) ) as mock_future:
  883. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  884. handle_poll_response.assert_called()
  885. mock_future.done.assert_called()
  886. mock_future.result.assert_called()
  887. post_data_to_handler_async.assert_called() # Poll again!
  888. assert_that( ycm._message_poll_request is not None )