youcompleteme_test.py 38 KB

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