youcompleteme_test.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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( { 'echo_current_diagnostic': 1,
  562. 'always_populate_location_list': 1 } )
  563. @patch.object( ycm_buffer_module,
  564. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  565. [ 'ycmtest' ] )
  566. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  567. return_value = True )
  568. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  569. def YouCompleteMe_AsyncDiagnosticUpdate_SingleFile_test( ycm,
  570. post_vim_message,
  571. *args ):
  572. # This test simulates asynchronous diagnostic updates associated with a single
  573. # file (e.g. Translation Unit), but where the actual errors refer to other
  574. # open files and other non-open files. This is not strictly invalid, nor is it
  575. # completely normal, but it is supported and does work.
  576. # Contrast with the next test which sends the diagnostics filewise, which is
  577. # what the language server protocol will do.
  578. diagnostics = [
  579. {
  580. 'kind': 'ERROR',
  581. 'text': 'error text in current buffer',
  582. 'location': {
  583. 'filepath': '/current',
  584. 'line_num': 1,
  585. 'column_num': 1
  586. },
  587. },
  588. {
  589. 'kind': 'ERROR',
  590. 'text': 'error text in hidden buffer',
  591. 'location': {
  592. 'filepath': '/has_diags',
  593. 'line_num': 4,
  594. 'column_num': 2
  595. },
  596. },
  597. {
  598. 'kind': 'ERROR',
  599. 'text': 'error text in buffer not open in Vim',
  600. 'location': {
  601. 'filepath': '/not_open',
  602. 'line_num': 8,
  603. 'column_num': 4
  604. },
  605. },
  606. ]
  607. current_buffer = VimBuffer( '/current',
  608. filetype = 'ycmtest',
  609. number = 1,
  610. window = 10 )
  611. buffers = [
  612. current_buffer,
  613. VimBuffer( '/no_diags',
  614. filetype = 'ycmtest',
  615. number = 2,
  616. window = 9 ),
  617. VimBuffer( '/has_diags',
  618. filetype = 'ycmtest',
  619. number = 3,
  620. window = 8 ),
  621. ]
  622. # Register each buffer internally with YCM
  623. for current in buffers:
  624. with MockVimBuffers( buffers, current, ( 1, 1 ) ):
  625. ycm.OnFileReadyToParse()
  626. with patch( 'ycm.vimsupport.SetLocationListForWindow',
  627. new_callable = ExtendedMock ) as set_location_list_for_window:
  628. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  629. ycm.UpdateWithNewDiagnosticsForFile( '/current', diagnostics )
  630. # We update the diagnostic on the current cursor position
  631. post_vim_message.assert_has_exact_calls( [
  632. call( "error text in current buffer", truncate = True, warning = False ),
  633. ] )
  634. # Ensure we included all the diags though
  635. set_location_list_for_window.assert_has_exact_calls( [
  636. call( 0, [
  637. {
  638. 'lnum': 1,
  639. 'col': 1,
  640. 'bufnr': 1,
  641. 'valid': 1,
  642. 'type': 'E',
  643. 'text': 'error text in current buffer',
  644. },
  645. {
  646. 'lnum': 4,
  647. 'col': 2,
  648. 'bufnr': 3,
  649. 'valid': 1,
  650. 'type': 'E',
  651. 'text': 'error text in hidden buffer',
  652. },
  653. {
  654. 'lnum': 8,
  655. 'col': 4,
  656. 'bufnr': -1, # sic: Our mocked bufnr function actually returns -1,
  657. # even though YCM is passing "create if needed".
  658. # FIXME? we shouldn't do that, and we should pass
  659. # filename instead
  660. 'valid': 1,
  661. 'type': 'E',
  662. 'text': 'error text in buffer not open in Vim'
  663. }
  664. ] )
  665. ] )
  666. @YouCompleteMeInstance( { 'echo_current_diagnostic': 1,
  667. 'always_populate_location_list': 1 } )
  668. @patch.object( ycm_buffer_module,
  669. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  670. [ 'ycmtest' ] )
  671. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  672. return_value = True )
  673. @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock )
  674. def YouCompleteMe_AsyncDiagnosticUpdate_PerFile_test( ycm,
  675. post_vim_message,
  676. *args ):
  677. # This test simulates asynchronous diagnostic updates which are delivered per
  678. # file, including files which are open and files which are not.
  679. # Ordered to ensure that the calls to update are deterministic
  680. diagnostics_per_file = [
  681. ( '/current', [ {
  682. 'kind': 'ERROR',
  683. 'text': 'error text in current buffer',
  684. 'location': {
  685. 'filepath': '/current',
  686. 'line_num': 1,
  687. 'column_num': 1
  688. }, }, ] ),
  689. ( '/has_diags', [ {
  690. 'kind': 'ERROR',
  691. 'text': 'error text in hidden buffer',
  692. 'location': {
  693. 'filepath': '/has_diags',
  694. 'line_num': 4,
  695. 'column_num': 2
  696. }, }, ] ),
  697. ( '/not_open', [ {
  698. 'kind': 'ERROR',
  699. 'text': 'error text in buffer not open in Vim',
  700. 'location': {
  701. 'filepath': '/not_open',
  702. 'line_num': 8,
  703. 'column_num': 4
  704. }, }, ] )
  705. ]
  706. current_buffer = VimBuffer( '/current',
  707. filetype = 'ycmtest',
  708. number = 1,
  709. window = 10 )
  710. buffers = [
  711. current_buffer,
  712. VimBuffer( '/no_diags',
  713. filetype = 'ycmtest',
  714. number = 2,
  715. window = 9 ),
  716. VimBuffer( '/has_diags',
  717. filetype = 'ycmtest',
  718. number = 3,
  719. window = 8 ),
  720. ]
  721. # Register each buffer internally with YCM
  722. for current in buffers:
  723. with MockVimBuffers( buffers, current, ( 1, 1 ) ):
  724. ycm.OnFileReadyToParse()
  725. with patch( 'ycm.vimsupport.SetLocationListForWindow',
  726. new_callable = ExtendedMock ) as set_location_list_for_window:
  727. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  728. for filename, diagnostics in diagnostics_per_file:
  729. ycm.UpdateWithNewDiagnosticsForFile( filename, diagnostics )
  730. # We update the diagnostic on the current cursor position
  731. post_vim_message.assert_has_exact_calls( [
  732. call( "error text in current buffer", truncate = True, warning = False ),
  733. ] )
  734. # Ensure we included all the diags though
  735. set_location_list_for_window.assert_has_exact_calls( [
  736. call( 0, [
  737. {
  738. 'lnum': 1,
  739. 'col': 1,
  740. 'bufnr': 1,
  741. 'valid': 1,
  742. 'type': 'E',
  743. 'text': 'error text in current buffer',
  744. },
  745. ] ),
  746. call( 8, [
  747. {
  748. 'lnum': 4,
  749. 'col': 2,
  750. 'bufnr': 3,
  751. 'valid': 1,
  752. 'type': 'E',
  753. 'text': 'error text in hidden buffer',
  754. },
  755. ] )
  756. ] )
  757. @YouCompleteMeInstance()
  758. def YouCompleteMe_OnPeriodicTick_ServerNotRunning_test( ycm, *args ):
  759. with patch.object( ycm, 'IsServerAlive', return_value = False ):
  760. assert_that( ycm.OnPeriodicTick(), equal_to( False ) )
  761. @YouCompleteMeInstance()
  762. def YouCompleteMe_OnPeriodicTick_ServerNotReady_test( ycm, *args ):
  763. with patch.object( ycm, 'IsServerAlive', return_value = True ):
  764. with patch.object( ycm, 'IsServerReady', return_value = False ):
  765. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  766. @YouCompleteMeInstance()
  767. @patch.object( ycm_buffer_module,
  768. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  769. [ 'ycmtest' ] )
  770. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  771. return_value = True )
  772. @patch( 'ycm.client.base_request._ValidateResponseObject', return_value = True )
  773. @patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
  774. def YouCompleteMe_OnPeriodicTick_DontRetry_test( ycm,
  775. post_data_to_handler_async,
  776. *args ):
  777. current_buffer = VimBuffer( '/current',
  778. filetype = 'ycmtest',
  779. number = 1,
  780. window = 10 )
  781. buffers = [ current_buffer ]
  782. # Create the request and make the first poll; we expect no response
  783. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  784. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  785. post_data_to_handler_async.assert_called()
  786. assert ycm._message_poll_request is not None
  787. post_data_to_handler_async.reset_mock()
  788. # OK that sent the request, now poll to check if it is complete (say it is
  789. # not)
  790. with patch.object( ycm._message_poll_request,
  791. '_response_future',
  792. new = MockAsyncServerResponseInProgress() ) as mock_future:
  793. poll_again = ycm.OnPeriodicTick()
  794. mock_future.done.assert_called()
  795. mock_future.result.assert_not_called()
  796. assert_that( poll_again, equal_to( True ) )
  797. # Poll again, but return a response (telling us to stop polling)
  798. with patch.object( ycm._message_poll_request,
  799. '_response_future',
  800. new = MockAsyncServerResponseDone( False ) ) \
  801. as mock_future:
  802. poll_again = ycm.OnPeriodicTick()
  803. mock_future.done.assert_called()
  804. mock_future.result.assert_called()
  805. post_data_to_handler_async.assert_not_called()
  806. # We reset and don't poll anymore
  807. assert_that( ycm._message_poll_request is None )
  808. assert_that( poll_again, equal_to( False ) )
  809. @YouCompleteMeInstance()
  810. @patch.object( ycm_buffer_module,
  811. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  812. [ 'ycmtest' ] )
  813. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  814. return_value = True )
  815. @patch( 'ycm.client.base_request._ValidateResponseObject', return_value = True )
  816. @patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
  817. def YouCompleteMe_OnPeriodicTick_Exception_test( ycm,
  818. post_data_to_handler_async,
  819. *args ):
  820. current_buffer = VimBuffer( '/current',
  821. filetype = 'ycmtest',
  822. number = 1,
  823. window = 10 )
  824. buffers = [ current_buffer ]
  825. # Create the request and make the first poll; we expect no response
  826. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  827. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  828. post_data_to_handler_async.assert_called()
  829. post_data_to_handler_async.reset_mock()
  830. # Poll again, but return an exception response
  831. mock_response = MockAsyncServerResponseException( RuntimeError( 'test' ) )
  832. with patch.object( ycm._message_poll_request,
  833. '_response_future',
  834. new = mock_response ) as mock_future:
  835. assert_that( ycm.OnPeriodicTick(), equal_to( False ) )
  836. mock_future.done.assert_called()
  837. mock_future.result.assert_called()
  838. post_data_to_handler_async.assert_not_called()
  839. # We reset and don't poll anymore
  840. assert_that( ycm._message_poll_request is None )
  841. @YouCompleteMeInstance()
  842. @patch.object( ycm_buffer_module,
  843. 'DIAGNOSTIC_UI_ASYNC_FILETYPES',
  844. [ 'ycmtest' ] )
  845. @patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
  846. return_value = True )
  847. @patch( 'ycm.client.base_request._ValidateResponseObject', return_value = True )
  848. @patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync' )
  849. @patch( 'ycm.client.messages_request._HandlePollResponse' )
  850. def YouCompleteMe_OnPeriodicTick_ValidResponse_test( ycm,
  851. handle_poll_response,
  852. post_data_to_handler_async,
  853. *args ):
  854. current_buffer = VimBuffer( '/current',
  855. filetype = 'ycmtest',
  856. number = 1,
  857. window = 10 )
  858. buffers = [ current_buffer ]
  859. # Create the request and make the first poll; we expect no response
  860. with MockVimBuffers( buffers, current_buffer, ( 1, 1 ) ):
  861. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  862. post_data_to_handler_async.assert_called()
  863. post_data_to_handler_async.reset_mock()
  864. # Poll again, and return a _proper_ response (finally!).
  865. # Note, _HandlePollResponse is tested independently (for simplicity)
  866. with patch.object( ycm._message_poll_request,
  867. '_response_future',
  868. new = MockAsyncServerResponseDone( [] ) ) as mock_future:
  869. assert_that( ycm.OnPeriodicTick(), equal_to( True ) )
  870. handle_poll_response.assert_called()
  871. mock_future.done.assert_called()
  872. mock_future.result.assert_called()
  873. post_data_to_handler_async.assert_called() # Poll again!
  874. assert_that( ycm._message_poll_request is not None )