예제 #1
0
    def ServerManagement_WipeWorkspace_WithConfig( app ):
      StartJavaCompleterServerInDirectory(
        app, PathToTestFile( 'simple_eclipse_project', 'src' ) )

      project = PathToTestFile( 'simple_eclipse_project' )
      filepath = PathToTestFile( 'simple_eclipse_project',
                                 'src',
                                 'com',
                                 'youcompleteme',
                                 'Test.java' )

      app.post_json(
        '/run_completer_command',
        BuildRequest(
          filepath = filepath,
          filetype = 'java',
          command_arguments = [ 'WipeWorkspace', '--with-config' ],
        ),
      )

      WaitUntilCompleterServerReady( app, 'java' )

      assert_that(
        app.post_json( '/debug_info',
                       BuildRequest( filetype = 'java',
                                     filepath = filepath ) ).json,
        CompleterProjectDirectoryMatcher( project ) )
예제 #2
0
    def Test( app ):
      StartJavaCompleterServerInDirectory( app, tmp_dir )

      # Run the debug info to check that we have the correct project dir (cwd)
      request_data = BuildRequest( filetype = 'java' )
      assert_that( app.post_json( '/debug_info', request_data ).json,
                   _ProjectDirectoryMatcher( tmp_dir ) )
예제 #3
0
def ServerManagement_ServerDies_test(app):
    StartJavaCompleterServerInDirectory(
        app, PathToTestFile('simple_eclipse_project'))

    request_data = BuildRequest(filetype='java')
    debug_info = app.post_json('/debug_info', request_data).json
    print('Debug info: {0}'.format(debug_info))
    pid = debug_info['completer']['servers'][0]['pid']
    print('pid: {0}'.format(pid))
    process = psutil.Process(pid)
    process.terminate()

    for tries in range(0, 10):
        request_data = BuildRequest(filetype='java')
        debug_info = app.post_json('/debug_info', request_data).json
        if not debug_info['completer']['servers'][0]['is_running']:
            break

        time.sleep(0.5)

    assert_that(
        debug_info,
        has_entry(
            'completer',
            has_entry('servers', contains(has_entry('is_running', False)))))
def ServerManagement_ProjectDetection_NoParent_test( app ):
  with TemporaryTestDir() as tmp_dir:
    StartJavaCompleterServerInDirectory( app, tmp_dir )
    # Run the debug info to check that we have the correct project dir (cwd)
    request_data = BuildRequest( filetype = 'java' )
    assert_that( app.post_json( '/debug_info', request_data ).json,
                 CompleterProjectDirectoryMatcher( tmp_dir ) )
예제 #5
0
def PollForMessages_AbortedWhenServerDies_test(app):
    StartJavaCompleterServerInDirectory(
        app, PathToTestFile('simple_eclipse_project'))

    filepath = TestFactory
    contents = ReadFile(filepath)

    def AwaitMessages():
        for tries in range(0, 5):
            response = app.post_json(
                '/receive_messages',
                BuildRequest(filetype='java',
                             filepath=filepath,
                             contents=contents)).json
            if response is False:
                return

        raise AssertionError('The poll request was not aborted in 5 tries')

    message_poll_task = threading.Thread(target=AwaitMessages)
    message_poll_task.start()

    app.post_json(
        '/run_completer_command',
        BuildRequest(
            filetype='java',
            command_arguments=['StopServer'],
        ),
    )

    message_poll_task.join()
예제 #6
0
def PollForMessages_InvalidUri_test( app, *args ):
  StartJavaCompleterServerInDirectory(
    app,
    PathToTestFile( 'simple_eclipse_project' ) )

  filepath = TestFactory
  contents = ReadFile( filepath )

  with patch(
    'ycmd.completers.language_server.language_server_protocol.UriToFilePath',
    side_effect = lsp.InvalidUriException ):

    for tries in range( 0, 5 ):
      response = app.post_json( '/receive_messages',
                                BuildRequest(
                                  filetype = 'java',
                                  filepath = filepath,
                                  contents = contents ) ).json
      if response is True:
        break
      elif response is False:
        raise AssertionError( 'Message poll was aborted unexpectedly' )
      elif 'diagnostics' in response:
        raise AssertionError( 'Did not expect diagnostics when file paths '
                              'are invalid' )

      time.sleep( 0.5 )

  assert_that( response, equal_to( True ) )
예제 #7
0
def DebugInfo_HandleNotificationInPollThread_Throw_test(app):
    filepath = PathToTestFile(DEFAULT_PROJECT_DIR, 'src', 'com',
                              'youcompleteme', 'Test.java')
    StartJavaCompleterServerInDirectory(app, filepath)

    # This mock will be called in the message pump thread, so syncronize the
    # result (thrown) using an Event
    thrown = threading.Event()

    def ThrowOnLogMessage(msg):
        thrown.set()
        raise RuntimeError("ThrowOnLogMessage")

    with patch.object(lsc.LanguageServerCompleter,
                      'HandleNotificationInPollThread',
                      side_effect=ThrowOnLogMessage):
        app.post_json(
            '/run_completer_command',
            BuildRequest(
                filepath=filepath,
                filetype='java',
                command_arguments=['RestartServer'],
            ),
        )

        # Ensure that we still process and handle messages even though a
        # message-pump-thread-handler raised an error.
        WaitUntilCompleterServerReady(app, 'java')

    # Prove that the exception was thrown.
    assert_that(thrown.is_set(), equal_to(True))
예제 #8
0
def ServerManagement_StopServerTwice_test(app):
    StartJavaCompleterServerInDirectory(
        app, PathToTestFile('simple_eclipse_project'))

    app.post_json(
        '/run_completer_command',
        BuildRequest(
            filetype='java',
            command_arguments=['StopServer'],
        ),
    )

    request_data = BuildRequest(filetype='java')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entry('servers', contains(has_entry('is_running', False)))))

    # Stopping a stopped server is a no-op
    app.post_json(
        '/run_completer_command',
        BuildRequest(
            filetype='java',
            command_arguments=['StopServer'],
        ),
    )

    request_data = BuildRequest(filetype='java')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entry('servers', contains(has_entry('is_running', False)))))
def FileReadyToParse_Diagnostics_InvalidURI_test( app, uri_to_filepath, *args ):
  StartJavaCompleterServerInDirectory( app,
                                       PathToTestFile( DEFAULT_PROJECT_DIR ) )

  filepath = TestFactory
  contents = ReadFile( filepath )

  # It can take a while for the diagnostics to be ready
  expiration = time.time() + 10
  while True:
    try:
      results = _WaitForDiagnosticsToBeReady( app, filepath, contents )
      print( 'Completer response: {0}'.format(
        json.dumps( results, indent=2 ) ) )

      uri_to_filepath.assert_called()

      assert_that( results, has_item(
        has_entries( {
          'kind': 'WARNING',
          'text': 'The value of the field TestFactory.Bar.testString is not '
                  'used',
          'location': LocationMatcher( '', 15, 19 ),
          'location_extent': RangeMatcher( '', ( 15, 19 ), ( 15, 29 ) ),
          'ranges': contains( RangeMatcher( '', ( 15, 19 ), ( 15, 29 ) ) ),
          'fixit_available': False
        } ),
      ) )

      return
    except AssertionError:
      if time.time() > expiration:
        raise
      time.sleep( 0.25 )
예제 #10
0
def FileReadyToParse_ServerNotReady_test( app ):
  filepath = TestFactory
  contents = ReadFile( filepath )

  StartJavaCompleterServerInDirectory( app, ProjectPath() )

  completer = handlers._server_state.GetFiletypeCompleter( [ 'java' ] )

  # It can take a while for the diagnostics to be ready
  for tries in range( 0, 60 ):
    event_data = BuildRequest( event_name = 'FileReadyToParse',
                               contents = contents,
                               filepath = filepath,
                               filetype = 'java' )

    results = app.post_json( '/event_notification', event_data ).json

    if results:
      break

    time.sleep( 0.5 )

  # To make the test fair, we make sure there are some results prior to the
  # 'server not running' call
  assert results

  # Call the FileReadyToParse handler but pretend that the server isn't running
  with patch.object( completer, 'ServerIsHealthy', return_value = False ):
    event_data = BuildRequest( event_name = 'FileReadyToParse',
                               contents = contents,
                               filepath = filepath,
                               filetype = 'java' )
    results = app.post_json( '/event_notification', event_data ).json
    assert_that( results, empty() )
예제 #11
0
def ServerManagement_OpenProject_RelativePath_test(app):
    StartJavaCompleterServerInDirectory(
        app,
        PathToTestFile('simple_gradle_project', 'src', 'main', 'java', 'com',
                       'test'))

    # Initially, we detect the gradle project...
    gradle_project = PathToTestFile('simple_gradle_project')
    maven_project = PathToTestFile('simple_maven_project')

    # Run the debug info to check that we have the correct project dir
    request_data = BuildRequest(filetype='java')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        CompleterProjectDirectoryMatcher(gradle_project))

    # We then force it to reload the maven project
    app.post_json(
        '/run_completer_command',
        BuildRequest(
            filetype='java',
            command_arguments=[
                'OpenProject',
                os.path.join('..', 'simple_maven_project'),
            ],
            working_dir=gradle_project,
        ),
    )

    # Run the debug info to check that we now have the maven project, without
    # changing anything else
    request_data = BuildRequest(filetype='java')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        CompleterProjectDirectoryMatcher(maven_project))
예제 #12
0
def Subcommands_GoToReferences_NoReferences_test( app ):
  StartJavaCompleterServerInDirectory( app,
                                       PathToTestFile( DEFAULT_PROJECT_DIR ) )
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'AbstractTestWidget.java' )
  contents = ReadFile( filepath )

  event_data = BuildRequest( filepath = filepath,
                             filetype = 'java',
                             line_num = 18,
                             column_num = 1,
                             contents = contents,
                             command_arguments = [ 'GoToReferences' ],
                             completer_target = 'filetype_default' )

  response = app.post_json( '/run_completer_command',
                            event_data,
                            expect_errors = True )

  eq_( response.status_code, requests.codes.internal_server_error )

  assert_that( response.json,
               ErrorMatcher( RuntimeError,
                             'Cannot jump to location' ) )
def DebugInfo_WorksAfterWatchdogErrors_test(watchdog_schedule, app):
    filepath = PathToTestFile('simple_eclipse_project', 'src', 'com', 'test',
                              'AbstractTestWidget.java')

    StartJavaCompleterServerInDirectory(app, filepath)
    request_data = BuildRequest(filepath=filepath, filetype='java')
    completer = handlers._server_state.GetFiletypeCompleter(['java'])
    connection = completer.GetConnection()
    assert_that(
        calling(connection._HandleDynamicRegistrations).with_args({
            'params': {
                'registrations': [{
                    'method': 'workspace/didChangeWatchedFiles',
                    'registerOptions': {
                        'watchers': [{
                            'globPattern': 'whatever'
                        }]
                    }
                }]
            }
        }), raises(RuntimeError))
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entries({
                'name':
                'Java',
                'servers':
                has_items(has_entries({
                    'name': 'jdt.ls',
                    'is_running': True
                }))
            })))
예제 #14
0
def FileReadyToParse_ChangeFileContentsFileData_test( app ):
  filepath = TestFactory
  contents = ReadFile( filepath )
  unsaved_buffer_path = TestLauncher
  file_data = {
    unsaved_buffer_path: {
      'contents': 'package com.test; public class TestLauncher {}',
      'filetypes': [ 'java' ],
    }
  }

  StartJavaCompleterServerInDirectory( app, ProjectPath() )

  # It can take a while for the diagnostics to be ready
  results = _WaitForDiagnosticsToBeReady( app,
                                          filepath,
                                          contents )
  assert results

  # Check that we have diagnostics for the saved file
  diags = _WaitForDiagnosticsForFile( app,
                                      filepath,
                                      contents,
                                      unsaved_buffer_path,
                                      lambda d: d )
  assert_that( diags, DIAG_MATCHERS_PER_FILE[ unsaved_buffer_path ] )

  # Now update the unsaved file with new contents
  event_data = BuildRequest( event_name = 'FileReadyToParse',
                             contents = contents,
                             filepath = filepath,
                             filetype = 'java',
                             file_data = file_data )
  app.post_json( '/event_notification', event_data )

  # Check that we have no diagnostics for the dirty file
  diags = _WaitForDiagnosticsForFile( app,
                                      filepath,
                                      contents,
                                      unsaved_buffer_path,
                                      lambda d: not d )
  assert_that( diags, empty() )

  # Now send the request again, but don't include the unsaved file. It should be
  # read from disk, casuing the diagnostics for that file to appear.
  event_data = BuildRequest( event_name = 'FileReadyToParse',
                             contents = contents,
                             filepath = filepath,
                             filetype = 'java' )
  app.post_json( '/event_notification', event_data )

  # Check that we now have diagnostics for the previously-dirty file
  diags = _WaitForDiagnosticsForFile( app,
                                      filepath,
                                      contents,
                                      unsaved_buffer_path,
                                      lambda d: d )

  assert_that( diags, DIAG_MATCHERS_PER_FILE[ unsaved_buffer_path ] )
예제 #15
0
def FileReadyToParse_Diagnostics_FileNotOnDisk_test(app):
    StartJavaCompleterServerInDirectory(app,
                                        PathToTestFile(DEFAULT_PROJECT_DIR))

    contents = '''
    package com.test;
    class Test {
      public String test
    }
  '''
    filepath = ProjectPath('Test.java')

    event_data = BuildRequest(event_name='FileReadyToParse',
                              contents=contents,
                              filepath=filepath,
                              filetype='java')

    results = app.post_json('/event_notification', event_data).json

    # This is a new file, so the diagnostics can't possibly be available when the
    # initial parse request is sent. We receive these asynchronously.
    eq_(results, {})

    diag_matcher = contains(
        has_entries({
            'kind': 'ERROR',
            'text':
            'Syntax error, insert ";" to complete ClassBodyDeclarations',
            'location': LocationMatcher(filepath, 4, 21),
            'location_extent': RangeMatch(filepath, (4, 21), (4, 25)),
            'ranges': contains(RangeMatch(filepath, (4, 21), (4, 25))),
            'fixit_available': False
        }))

    # Poll until we receive the diags
    for message in PollForMessages(app, {
            'filepath': filepath,
            'contents': contents
    }):
        if 'diagnostics' in message and message['filepath'] == filepath:
            print('Message {0}'.format(pformat(message)))
            assert_that(
                message,
                has_entries({
                    'diagnostics': diag_matcher,
                    'filepath': filepath
                }))
            break

    # Now confirm that we _also_ get these from the FileReadyToParse request
    for tries in range(0, 60):
        results = app.post_json('/event_notification', event_data).json
        if results:
            break
        time.sleep(0.5)

    print('completer response: {0}'.format(pformat(results)))

    assert_that(results, diag_matcher)
예제 #16
0
def ServerManagement_ProjectDetection_EclipseParent_test( app ):
  StartJavaCompleterServerInDirectory(
    app, PathToTestFile( 'simple_eclipse_project', 'src' ) )

  project = PathToTestFile( 'simple_eclipse_project' )

  # Run the debug info to check that we have the correct project dir
  request_data = BuildRequest( filetype = 'java' )
  assert_that( app.post_json( '/debug_info', request_data ).json,
               _ProjectDirectoryMatcher( project ) )
예제 #17
0
def JavaCompleter_UnknownCommand_test( app ):
  StartJavaCompleterServerInDirectory( app, PathToTestFile() )
  completer = handlers._server_state.GetFiletypeCompleter( [ 'java' ] )

  notification = {
    'command': 'this_is_not_a_real_command',
    'params': {}
  }
  assert_that( completer.HandleServerCommand( BuildRequest(), notification ),
               equal_to( None ) )
예제 #18
0
 def test_ServerManagement_ProjectDetection_NoParent(self):
     with TemporaryTestDir() as tmp_dir:
         with isolated_app() as app:
             StartJavaCompleterServerInDirectory(app, tmp_dir)
             # Run the debug info to check that we have the correct project dir (cwd)
             request_data = BuildRequest(filetype='java',
                                         filepath=os.path.join(
                                             tmp_dir, 'foo.java'))
             assert_that(
                 app.post_json('/debug_info', request_data).json,
                 CompleterProjectDirectoryMatcher(tmp_dir))
예제 #19
0
def ServerManagement_ProjectDetection_MavenParent_Submodule_test(app):
    StartJavaCompleterServerInDirectory(
        app,
        PathToTestFile('simple_maven_project', 'simple_submodule', 'src',
                       'main', 'java', 'com', 'test'))

    project = PathToTestFile('simple_maven_project')

    # Run the debug info to check that we have the correct project dir
    request_data = BuildRequest(filetype='java')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        CompleterProjectDirectoryMatcher(project))
예제 #20
0
def Poll_Diagnostics_ProjectWide_Eclipse_test(app):
    StartJavaCompleterServerInDirectory(app,
                                        PathToTestFile(DEFAULT_PROJECT_DIR))

    filepath = TestLauncher
    contents = ReadFile(filepath)

    # Poll until we receive _all_ the diags asynchronously
    to_see = sorted(DIAG_MATCHERS_PER_FILE.keys())
    seen = {}

    try:
        for message in PollForMessages(app, {
                'filepath': filepath,
                'contents': contents,
                'filetype': 'java'
        }):
            print('Message {0}'.format(pformat(message)))
            if 'diagnostics' in message:
                seen[message['filepath']] = True
                if message['filepath'] not in DIAG_MATCHERS_PER_FILE:
                    raise AssertionError(
                        'Received diagnostics for unexpected file {0}. '
                        'Only expected {1}'.format(message['filepath'],
                                                   to_see))
                assert_that(
                    message,
                    has_entries({
                        'diagnostics':
                        DIAG_MATCHERS_PER_FILE[message['filepath']],
                        'filepath':
                        message['filepath']
                    }))

            if sorted(seen.keys()) == to_see:
                break
            else:
                print('Seen diagnostics for {0}, still waiting for {1}'.format(
                    json.dumps(sorted(seen.keys()), indent=2),
                    json.dumps([x for x in to_see if x not in seen],
                               indent=2)))

            # Eventually PollForMessages will throw
            # a timeout exception and we'll fail
            # if we don't see all of the expected diags
    except PollForMessagesTimeoutException as e:
        raise AssertionError(
            str(e) + 'Timed out waiting for full set of diagnostics. '
            'Expected to see diags for {0}, but only saw {1}.'.format(
                json.dumps(to_see, indent=2),
                json.dumps(sorted(seen.keys()), indent=2)))
예제 #21
0
def ServerManagement_CloseServer_Unclean_test(app, *args):
    StartJavaCompleterServerInDirectory(
        app, PathToTestFile('simple_eclipse_project'))

    app.post_json(
        '/run_completer_command',
        BuildRequest(filetype='java', command_arguments=['StopServer']))

    request_data = BuildRequest(filetype='java')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entry('servers', contains(has_entry('is_running', False)))))
예제 #22
0
def ServerManagement_WipeWorkspace_WithConfig_test( isolated_app ):
  with TemporaryTestDir() as tmp_dir:
    with isolated_app( {
      'java_jdtls_use_clean_workspace': 0,
      'java_jdtls_workspace_root_path': tmp_dir
    } ) as app:
      StartJavaCompleterServerInDirectory(
        app, PathToTestFile( 'simple_eclipse_project', 'src' ) )

      project = PathToTestFile( 'simple_eclipse_project' )
      filepath = PathToTestFile( 'simple_eclipse_project',
                                 'src',
                                 'com',
                                 'youcompleteme',
                                 'Test.java' )

      app.post_json(
        '/run_completer_command',
        BuildRequest(
          filepath = filepath,
          filetype = 'java',
          command_arguments = [ 'WipeWorkspace', '--with-config' ],
        ),
      )

      WaitUntilCompleterServerReady( app, 'java' )

      assert_that(
        app.post_json( '/debug_info',
                       BuildRequest( filetype = 'java',
                                     filepath = filepath ) ).json,
        CompleterProjectDirectoryMatcher( project ) )

      assert_that(
        app.post_json( '/debug_info',
                       BuildRequest( filetype = 'java',
                                     filepath = filepath ) ).json,
        has_entry(
          'completer',
          has_entry( 'servers', contains_exactly(
            has_entry( 'extras', has_item(
              has_entries( {
                'key': 'Workspace Path',
                'value': starts_with( tmp_dir ),
              } )
            ) )
          ) )
        ) )
예제 #23
0
def ServerManagement_RestartServer_test( app ):
  StartJavaCompleterServerInDirectory(
    app, PathToTestFile( 'simple_eclipse_project' ) )

  eclipse_project = PathToTestFile( 'simple_eclipse_project' )
  maven_project = PathToTestFile( 'simple_maven_project' )

  # Run the debug info to check that we have the correct project dir
  request_data = BuildRequest( filetype = 'java' )
  assert_that( app.post_json( '/debug_info', request_data ).json,
               _ProjectDirectoryMatcher( eclipse_project ) )

  # Restart the server with a different client working directory
  filepath = PathToTestFile( 'simple_maven_project',
                             'src',
                             'main',
                             'java',
                             'com',
                             'test',
                             'TestFactory.java' )

  app.post_json(
    '/run_completer_command',
    BuildRequest(
      filepath = filepath,
      filetype = 'java',
      working_dir = maven_project,
      command_arguments = [ 'RestartServer' ],
    ),
  )

  WaitUntilCompleterServerReady( app, 'java' )

  app.post_json(
    '/event_notification',
    BuildRequest(
      filepath = filepath,
      filetype = 'java',
      working_dir = maven_project,
      event_name = 'FileReadyToParse',
    )
  )

  # Run the debug info to check that we have the correct project dir
  request_data = BuildRequest( filetype = 'java' )
  assert_that( app.post_json( '/debug_info', request_data ).json,
               _ProjectDirectoryMatcher( maven_project ) )
예제 #24
0
def ServerManagement_ServerDiesWhileShuttingDown_test( app ):
  StartJavaCompleterServerInDirectory(
    app,
    PathToTestFile( 'simple_eclipse_project' ) )

  request_data = BuildRequest( filetype = 'java' )
  debug_info = app.post_json( '/debug_info', request_data ).json
  print( 'Debug info: {0}'.format( debug_info ) )
  pid = debug_info[ 'completer' ][ 'servers' ][ 0 ][ 'pid' ]
  print( 'pid: {0}'.format( pid ) )
  process = psutil.Process( pid )


  def StopServerInAnotherThread():
    app.post_json(
      '/run_completer_command',
      BuildRequest(
        filetype = 'java',
        command_arguments = [ 'StopServer' ],
      ),
    )

  completer = handlers._server_state.GetFiletypeCompleter( [ 'java' ] )

  # In this test we mock out the sending method so that we don't actually send
  # the shutdown request. We then assisted-suicide the downstream server, which
  # causes the shutdown request to be aborted. This is interpreted by the
  # shutdown code as a successful shutdown. We need to do the shutdown and
  # terminate in parallel as the post_json is a blocking call.
  with patch.object( completer.GetConnection(), 'WriteData' ):
    stop_server_task = threading.Thread( target=StopServerInAnotherThread )
    stop_server_task.start()
    process.terminate()
    stop_server_task.join()

  request_data = BuildRequest( filetype = 'java' )
  debug_info = app.post_json( '/debug_info', request_data ).json
  assert_that( debug_info,
               has_entry(
                 'completer',
                 has_entry( 'servers', contains(
                   has_entry( 'is_running', False )
                 ) )
               ) )
예제 #25
0
def ServerManagement_ConnectionRaisesWhileShuttingDown_test( app ):
  StartJavaCompleterServerInDirectory(
    app,
    PathToTestFile( 'simple_eclipse_project' ) )

  request_data = BuildRequest( filetype = 'java' )
  debug_info = app.post_json( '/debug_info', request_data ).json
  print( 'Debug info: {0}'.format( debug_info ) )
  pid = debug_info[ 'completer' ][ 'servers' ][ 0 ][ 'pid' ]
  print( 'pid: {0}'.format( pid ) )
  process = psutil.Process( pid )

  completer = handlers._server_state.GetFiletypeCompleter( [ 'java' ] )

  # In this test we mock out the GetResponse method, which is used to send the
  # shutdown request. This means we only send the exit notification. It's
  # possible that the server won't like this, but it seems reasonable for it to
  # actually exit at that point.
  with patch.object( completer.GetConnection(),
                     'GetResponse',
                     side_effect = RuntimeError ):
    app.post_json(
      '/run_completer_command',
      BuildRequest(
        filetype = 'java',
        command_arguments = [ 'StopServer' ],
      ),
    )

  request_data = BuildRequest( filetype = 'java' )
  debug_info = app.post_json( '/debug_info', request_data ).json
  assert_that( debug_info,
               has_entry(
                 'completer',
                 has_entry( 'servers', contains(
                   has_entry( 'is_running', False )
                 ) )
               ) )

  if process.is_running():
    process.terminate()
    raise AssertionError( 'jst.ls process is still running after exit handler' )
예제 #26
0
def PollForMessages_ServerNotRunning_test(app):
    StartJavaCompleterServerInDirectory(
        app, PathToTestFile('simple_eclipse_project'))

    filepath = TestFactory
    contents = ReadFile(filepath)
    app.post_json(
        '/run_completer_command',
        BuildRequest(
            filetype='java',
            command_arguments=['StopServer'],
        ),
    )

    response = app.post_json(
        '/receive_messages',
        BuildRequest(filetype='java', filepath=filepath,
                     contents=contents)).json

    assert_that(response, equal_to(False))
def DebugInfo_JvmArgs_test(app):
    StartJavaCompleterServerInDirectory(
        app, PathToTestFile('lombok_project', 'src'))

    filepath = PathToTestFile('lombok_project', 'src', 'main', 'java', 'com',
                              'ycmd', 'App.java')

    request_data = BuildRequest(filepath=filepath, filetype='java')

    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entries({
                'servers':
                contains_exactly(
                    has_entries({
                        'executable':
                        has_items(starts_with('-javaagent:')),
                    }))
            })))
예제 #28
0
def PollForMessages_AbortedWhenServerDies_test( app ):
  StartJavaCompleterServerInDirectory(
    app,
    PathToTestFile( 'simple_eclipse_project' ) )

  filepath = TestFactory
  contents = ReadFile( filepath )

  state = {
    'aborted': False
  }

  def AwaitMessages():
    max_tries = 20
    for tries in range( 0, max_tries ):
      response = app.post_json( '/receive_messages',
                                BuildRequest(
                                  filetype = 'java',
                                  filepath = filepath,
                                  contents = contents ) ).json
      if response is False:
        state[ 'aborted' ] = True
        return

    raise AssertionError( 'The poll request was not aborted in {} tries'.format(
      max_tries ) )

  message_poll_task = StartThread( AwaitMessages )

  app.post_json(
    '/run_completer_command',
    BuildRequest(
      filetype = 'java',
      command_arguments = [ 'StopServer' ],
    ),
  )

  message_poll_task.join()
  eq_( state[ 'aborted' ], True )
예제 #29
0
def Poll_Diagnostics_ChangeFileContents_test( app ):
  StartJavaCompleterServerInDirectory( app,
                                       PathToTestFile( DEFAULT_PROJECT_DIR ) )

  filepath = youcompleteme_Test
  old_contents = """package com.youcompleteme;

public class Test {
  public String test;
}"""

  messages_for_filepath = []

  def PollForMessagesInAnotherThread( filepath, contents ):
    try:
      for message in PollForMessages( app,
                                      { 'filepath': filepath,
                                        'contents': contents,
                                        'filetype': 'java' } ):
        if 'filepath' in message and message[ 'filepath' ] == filepath:
          messages_for_filepath.append( message )
    except PollForMessagesTimeoutException:
      pass

  StartThread( PollForMessagesInAnotherThread, filepath, old_contents )

  new_contents = """package com.youcompleteme;

public class Test {
  public String test;
  public String test;
}"""

  event_data = BuildRequest( event_name = 'FileReadyToParse',
                             contents = new_contents,
                             filepath = filepath,
                             filetype = 'java' )
  app.post_json( '/event_notification', event_data ).json

  expiration = time.time() + 10
  while True:
    try:
      assert_that(
        messages_for_filepath,
        has_item( has_entries( {
          'filepath': filepath,
          'diagnostics': contains(
            has_entries( {
              'kind': 'ERROR',
              'text': 'Duplicate field Test.test',
              'location': LocationMatcher( youcompleteme_Test, 4, 17 ),
              'location_extent': RangeMatcher( youcompleteme_Test,
                                               ( 4, 17 ),
                                               ( 4, 21 ) ),
              'ranges': contains( RangeMatcher( youcompleteme_Test,
                                                ( 4, 17 ),
                                                ( 4, 21 ) ) ),
              'fixit_available': False
            } ),
            has_entries( {
              'kind': 'ERROR',
              'text': 'Duplicate field Test.test',
              'location': LocationMatcher( youcompleteme_Test, 5, 17 ),
              'location_extent': RangeMatcher( youcompleteme_Test,
                                               ( 5, 17 ),
                                               ( 5, 21 ) ),
              'ranges': contains( RangeMatcher( youcompleteme_Test,
                                                ( 5, 17 ),
                                                ( 5, 21 ) ) ),
              'fixit_available': False
            } )
          )
        } ) )
      )
      break
    except AssertionError:
      if time.time() > expiration:
        raise

      time.sleep( 0.25 )
예제 #30
0
def FileReadyToParse_ChangeFileContents_test( app ):
  filepath = TestFactory
  contents = ReadFile( filepath )

  StartJavaCompleterServerInDirectory( app, ProjectPath() )

  # It can take a while for the diagnostics to be ready
  for tries in range( 0, 60 ):
    event_data = BuildRequest( event_name = 'FileReadyToParse',
                               contents = contents,
                               filepath = filepath,
                               filetype = 'java' )

    results = app.post_json( '/event_notification', event_data ).json

    if results:
      break

    time.sleep( 0.5 )

  # To make the test fair, we make sure there are some results prior to the
  # 'server not running' call
  assert results

  # Call the FileReadyToParse handler but pretend that the server isn't running
  contents = 'package com.test; class TestFactory {}'
  # It can take a while for the diagnostics to be ready
  event_data = BuildRequest( event_name = 'FileReadyToParse',
                             contents = contents,
                             filepath = filepath,
                             filetype = 'java' )

  app.post_json( '/event_notification', event_data )

  diags = None
  try:
    for message in PollForMessages( app,
                                    { 'filepath': filepath,
                                      'contents': contents,
                                      'filetype': 'java' } ):
      print( 'Message {0}'.format( pformat( message ) ) )
      if 'diagnostics' in message and message[ 'filepath' ]  == filepath:
        diags = message[ 'diagnostics' ]
        if not diags:
          break

      # Eventually PollForMessages will throw a timeout exception and we'll fail
      # if we don't see the diagnostics go empty
  except PollForMessagesTimeoutException as e:
    raise AssertionError(
      '{0}. Timed out waiting for diagnostics to clear for updated file. '
      'Expected to see none, but diags were: {1}'.format( e, diags ) )

  assert_that( diags, empty() )

  # Close the file (ensuring no exception)
  event_data = BuildRequest( event_name = 'BufferUnload',
                             contents = contents,
                             filepath = filepath,
                             filetype = 'java' )
  result = app.post_json( '/event_notification', event_data ).json
  assert_that( result, equal_to( {} ) )

  # Close the file again, someone erroneously (ensuring no exception)
  event_data = BuildRequest( event_name = 'BufferUnload',
                             contents = contents,
                             filepath = filepath,
                             filetype = 'java' )
  result = app.post_json( '/event_notification', event_data ).json
  assert_that( result, equal_to( {} ) )