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,
               CompleterProjectDirectoryMatcher( project ) )
Example #2
0
    def test_ServerManagement_ProjectDetection_MavenParent_Submodule(
            self, 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))
Example #3
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 ),
              } )
            ) )
          ) )
        ) )
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
                }))
            })))
Example #5
0
def ServerManagement_StartServer_Fails_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'youcompleteme',
                             'Test.java' )
  with patch( 'ycmd.completers.language_server.language_server_completer.'
              'LanguageServerConnection.AwaitServerConnection',
              side_effect = LanguageServerConnectionTimeout ):
    resp = app.post_json( '/event_notification',
                   BuildRequest(
                     event_name = 'FileReadyToParse',
                     filetype = 'java',
                     filepath = filepath,
                     contents = ""
                   ) )

    assert_that( resp.status_code, equal_to( 200 ) )

    request_data = BuildRequest( filetype = 'java' )
    assert_that( app.post_json( '/debug_info', request_data ).json,
                 has_entry(
                   'completer',
                   has_entry( 'servers', contains_exactly(
                     has_entry( 'is_running', False )
                   ) )
                 ) )
Example #6
0
def Subcommands_FixIt_SingleDiag_SingleOption_Modify_test():
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'TestFactory.java' )

  # TODO: As there is only one option, we automatically apply it.
  # In Java case this might not be the right thing. It's a code assist, not a
  # FixIt really. Perhaps we should change the client to always ask for
  # confirmation?
  fixits = has_entries ( {
    'fixits': contains(
      has_entries( {
        'text': "Change type of 'test' to 'boolean'",
        'chunks': contains(
          # For some reason, eclipse returns modifies as deletes + adds,
          # although overlapping ranges aren't allowed.
          ChunkMatcher( 'boolean',
                        LocationMatcher( filepath, 14, 12 ),
                        LocationMatcher( filepath, 14, 12 ) ),
          ChunkMatcher( '',
                        LocationMatcher( filepath, 14, 12 ),
                        LocationMatcher( filepath, 14, 15 ) ),
        ),
      } ),
    )
  } )

  yield ( RunFixItTest, 'FixIts can change lines as well as add them',
          filepath, 27, 12, fixits )
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)))))
Example #8
0
def Subcommands_RequestFailed_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'youcompleteme',
                             'Test.java' )

  connection = handlers._server_state.GetFiletypeCompleter(
    [ 'java' ] ).GetConnection()

  def WriteJunkToServer( data ):
    junk = data.replace( bytes( b'textDocument/codeAction' ),
                         bytes( b'textDocument/codeFAILED' ) )

    with connection._stdin_lock:
       connection._server_stdin.write( junk )
       connection._server_stdin.flush()


  with patch.object( connection, 'WriteData', side_effect = WriteJunkToServer ):
    RunTest( app, {
      'description': 'Response errors propagate to the client',
      'request': {
        'command': 'FixIt',
        'line_num': 1,
        'column_num': 1,
        'filepath': filepath,
      },
      'expect': {
        'response': requests.codes.internal_server_error,
        'data': ErrorMatcher( ResponseFailedException )
      }
    } )
Example #9
0
def Subcommands_FixIt_SingleDiag_MultiOption_Delete_test():
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'TestFactory.java' )

  fixits = has_entries ( {
    'fixits': contains_inanyorder(
      has_entries( {
        'text': "Remove 'testString', keep assignments with side effects",
        'chunks': contains(
          ChunkMatcher( '',
                        LocationMatcher( filepath, 14, 21 ),
                        LocationMatcher( filepath, 15, 5 ) ),
          ChunkMatcher( '',
                        LocationMatcher( filepath, 15, 5 ),
                        LocationMatcher( filepath, 15, 30 ) ),
        ),
      } ),
      has_entries( {
        'text': "Create getter and setter for 'testString'...",
        # The edit reported for this is juge and uninteresting really. Manual
        # testing can show that it works. This test is really about the previous
        # FixIt (and nonetheless, the previous tests ensure that we correctly
        # populate the chunks list; the contents all come from jdt.ls)
        'chunks': instance_of( list )
      } ),
    )
  } )

  yield ( RunFixItTest, 'FixIts can change lines as well as add them',
          filepath, 15, 29, fixits )
Example #10
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))
def Subcommands_ServerNotReady_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'AbstractTestWidget.java' )

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

  with patch.object( completer, 'ServerIsReady', return_value = False ):
    RunTest( app, {
      'description': 'Completion works for unicode identifier',
      'request': {
        'filetype'      : 'java',
        'filepath'      : filepath,
        'line_num'      : 16,
        'column_num'    : 35,
        'force_semantic': True
      },
      'expect': {
        'response': requests.codes.ok,
        'data': has_entries( {
          'errors': empty(),
          'completions': empty(),
          'completion_start_column': 6
        } ),
      }
    } )
Example #12
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()
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 )
def GetCompletions_UnicodeIdentifier_test( app ):
  filepath = PathToTestFile( DEFAULT_PROJECT_DIR,
                             'src',
                             'com',
                             'youcompleteme',
                             'Test.java' )
  RunTest( app, {
    'description': 'Completion works for unicode identifier',
    'request': {
      'filetype'      : 'java',
      'filepath'      : filepath,
      'line_num'      : 16,
      'column_num'    : 35,
      'force_semantic': True
    },
    'expect': {
      'response': requests.codes.ok,
      'data': has_entries( {
        'completion_start_column': 35,
        'completions': contains_inanyorder( *WithObjectMethods(
          CompletionEntryMatcher( 'a_test', 'Test.TéstClass', {
            'kind': 'Field',
            'detailed_info': 'a_test : int\n\n',
          } ),
          CompletionEntryMatcher( 'testywesty', 'Test.TéstClass', {
            'kind': 'Field',
          } ),
        ) ),
        'errors': empty(),
      } )
    },
  } )
Example #15
0
def Subcommands_RefactorRename_Unicode_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'youcompleteme',
                             'Test.java' )
  RunTest( app, {
    'description': 'Rename works for unicode identifier',
    'request': {
      'command': 'RefactorRename',
      'arguments': [ 'shorter' ],
      'line_num': 7,
      'column_num': 21,
      'filepath': filepath,
    },
    'expect': {
      'response': requests.codes.ok,
      'data': has_entries ( {
        'fixits': contains( has_entries( {
          'chunks': contains(
            ChunkMatcher(
              'shorter',
              LocationMatcher( filepath, 7, 12 ),
              LocationMatcher( filepath, 7, 25 )
            ),
            ChunkMatcher(
              'shorter',
              LocationMatcher( filepath, 8, 12 ),
              LocationMatcher( filepath, 8, 25 )
            ),
          ),
        } ) ),
      } ),
    },
  } )
Example #16
0
def GetCompletions_ServerNotInitialized_test(app):
    filepath = PathToTestFile('simple_eclipse_project', 'src', 'com', 'test',
                              'AbstractTestWidget.java')

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

    def MockHandleInitializeInPollThread(self, response):
        pass

    with patch.object(completer, '_HandleInitializeInPollThread',
                      MockHandleInitializeInPollThread):
        RunTest(
            app, {
                'description': 'Completion works for unicode identifier',
                'request': {
                    'filetype': 'java',
                    'filepath': filepath,
                    'line_num': 16,
                    'column_num': 35,
                    'force_semantic': True
                },
                'expect': {
                    'response':
                    requests.codes.ok,
                    'data':
                    has_entries({
                        'errors': empty(),
                        'completions': empty(),
                        'completion_start_column': 6
                    }),
                }
            })
Example #17
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 ) )
Example #18
0
def Subcommands_RefactorRename_Simple_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'TestLauncher.java' )
  RunTest( app, {
    'description': 'RefactorRename works within a single scope/file',
    'request': {
      'command': 'RefactorRename',
      'arguments': [ 'renamed_l' ],
      'filepath': filepath,
      'line_num': 28,
      'column_num': 5,
    },
    'expect': {
      'response': requests.codes.ok,
      'data': has_entries ( {
        'fixits': contains( has_entries( {
          'chunks': contains(
              ChunkMatcher( 'renamed_l',
                            LocationMatcher( filepath, 27, 18 ),
                            LocationMatcher( filepath, 27, 19 ) ),
              ChunkMatcher( 'renamed_l',
                            LocationMatcher( filepath, 28, 5 ),
                            LocationMatcher( filepath, 28, 6 ) ),
          ),
          'location': LocationMatcher( filepath, 28, 5 )
        } ) )
      } )
    }
  } )
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)))))
Example #20
0
def Subcommands_GetType_Unicode_test( app ):
  filepath = PathToTestFile( DEFAULT_PROJECT_DIR,
                             'src',
                             'com',
                             'youcompleteme',
                             'Test.java' )
  contents = ReadFile( filepath )

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

  event_data = BuildRequest( filepath = filepath,
                             filetype = 'java',
                             line_num = 7,
                             column_num = 17,
                             contents = contents,
                             command_arguments = [ 'GetType' ],
                             completer_target = 'filetype_default' )

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

  eq_( response, {
         'message': 'String whåtawîdgé - com.youcompleteme.Test.doUnicødeTes()'
  } )
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 ) )
Example #22
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)
Example #23
0
def Subcommands_DifferntFileTypesUpdate_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'youcompleteme',
                             'Test.java' )

  RunTest( app, {
    'description': 'Request error handles the error',
    'request': {
      'command': 'FixIt',
      'line_num': 99,
      'column_num': 99,
      'filepath': filepath,
      'file_data': {
        '!/bin/sh': {
          'filetypes': [],
          'contents': 'this should be ignored by the completer',
        },
        '/path/to/non/project/file': {
          'filetypes': [ 'c' ],
          'contents': 'this should be ignored by the completer',
        },
        PathToTestFile( 'simple_eclipse_project',
                        'src',
                        'com',
                        'test',
                        'TestLauncher.java' ): {
          'filetypes': [ 'some', 'java', 'junk', 'also' ],
          'contents': ReadFile( PathToTestFile( 'simple_eclipse_project',
                                                'src',
                                                'com',
                                                'test',
                                                'TestLauncher.java' ) ),
        },
        '!/usr/bin/sh': {
          'filetypes': [ 'java' ],
          'contents': '\n',
        },
      }
    },
    'expect': {
      'response': requests.codes.ok,
      'data': has_entries( { 'fixits': empty() } ),
    }
  } )
Example #24
0
def DebugInfo_test(app):
    request_data = BuildRequest(filetype='java')
    assert_that(
        app.post_json('/debug_info', request_data).json,
        has_entry(
            'completer',
            has_entries({
                'name':
                'Java',
                'servers':
                contains(
                    has_entries({
                        'name':
                        'jdt.ls Java Language Server',
                        'is_running':
                        instance_of(bool),
                        'executable':
                        instance_of(str),
                        'pid':
                        instance_of(int),
                        'logfiles':
                        contains(instance_of(str), instance_of(str)),
                        'extras':
                        contains(
                            has_entries({
                                'key': 'Startup Status',
                                'value': 'Ready'
                            }),
                            has_entries({
                                'key': 'Java Path',
                                'value': instance_of(str)
                            }),
                            has_entries({
                                'key': 'Launcher Config.',
                                'value': instance_of(str)
                            }),
                            has_entries({
                                'key': 'Workspace Path',
                                'value': instance_of(str)
                            }),
                            has_entries({
                                'key': 'Server State',
                                'value': 'Initialized'
                            }),
                            has_entries({
                                'key':
                                'Project Directory',
                                'value':
                                PathToTestFile(DEFAULT_PROJECT_DIR)
                            }),
                            has_entries({
                                'key': 'Settings',
                                'value': '{}'
                            }),
                        )
                    }))
            })))
Example #25
0
def Subcommands_FixIt_NoDiagnostics_test():
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'TestFactory.java' )

  yield ( RunFixItTest, "no FixIts means you gotta code it yo' self",
          filepath, 1, 1, has_entries( { 'fixits': empty() } ) )
Example #26
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 ) )
Example #27
0
def Subcommands_FixIt_InvalidURI_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'TestFactory.java' )

  fixits = has_entries ( {
    'fixits': contains(
      has_entries( {
        'text': "Change type of 'test' to 'boolean'",
        'chunks': contains(
          # For some reason, eclipse returns modifies as deletes + adds,
          # although overlapping ranges aren't allowed.
          ChunkMatcher( 'boolean',
                        LocationMatcher( '', 14, 12 ),
                        LocationMatcher( '', 14, 12 ) ),
          ChunkMatcher( '',
                        LocationMatcher( '', 14, 12 ),
                        LocationMatcher( '', 14, 15 ) ),
        ),
      } ),
    )
  } )

  contents = ReadFile( filepath )
  # Wait for jdt.ls to have parsed the file and returned some diagnostics
  for tries in range( 0, 60 ):
    results = app.post_json( '/event_notification',
                             BuildRequest( filepath = filepath,
                                           filetype = 'java',
                                           contents = contents,
                                           event_name = 'FileReadyToParse' ) )
    if results.json:
      break

    time.sleep( .25 )

  with patch(
    'ycmd.completers.language_server.language_server_protocol.UriToFilePath',
    side_effect = lsp.InvalidUriException ):
    RunTest( app, {
      'description': 'Invalid URIs do not make us crash',
      'request': {
        'command': 'FixIt',
        'line_num': 27,
        'column_num': 12,
        'filepath': filepath,
      },
      'expect': {
        'response': requests.codes.ok,
        'data': fixits,
      }
    } )
Example #28
0
def GetCompletions_ResolveFailed_test(app):
    filepath = PathToTestFile(DEFAULT_PROJECT_DIR, 'src', 'com',
                              'youcompleteme', 'Test.java')

    from ycmd.completers.language_server import language_server_protocol as lsapi

    def BrokenResolveCompletion(request_id, completion):
        return lsapi.BuildRequest(request_id, 'completionItem/FAIL',
                                  completion)

    with patch(
            'ycmd.completers.language_server.language_server_protocol.'
            'ResolveCompletion',
            side_effect=BrokenResolveCompletion):
        RunTest(
            app, {
                'description': 'Completion works for unicode identifier',
                'request': {
                    'filetype': 'java',
                    'filepath': filepath,
                    'line_num': 16,
                    'column_num': 35,
                    'force_semantic': True
                },
                'expect': {
                    'response':
                    requests.codes.ok,
                    'data':
                    has_entries({
                        'completion_start_column':
                        35,
                        'completions':
                        has_items(
                            CompletionEntryMatcher(
                                'a_test', 'Test.TéstClass.a_test : int', {
                                    'kind': 'Field',
                                    'detailed_info': 'a_test : int\n\n',
                                }),
                            CompletionEntryMatcher(
                                'åtest', 'Test.TéstClass.åtest : boolean', {
                                    'kind': 'Field',
                                    'detailed_info': 'åtest : boolean\n\n',
                                }),
                            CompletionEntryMatcher(
                                'testywesty',
                                'Test.TéstClass.testywesty : String', {
                                    'kind': 'Field',
                                }),
                        ),
                        'errors':
                        empty(),
                    })
                },
            })
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:')),
                    }))
            })))
Example #30
0
def Subcommands_GoToReferences_test( app ):
  filepath = PathToTestFile( 'simple_eclipse_project',
                             'src',
                             'com',
                             'test',
                             'AbstractTestWidget.java' )
  contents = ReadFile( filepath )

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

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

  eq_( response, [
         {
           'filepath': PathToTestFile( 'simple_eclipse_project',
                                       'src',
                                       'com',
                                       'test',
                                       'TestFactory.java' ),
           'column_num': 9,
           'description': "      w.doSomethingVaguelyUseful();",
           'line_num': 28
         },
         {
           'filepath': PathToTestFile( 'simple_eclipse_project',
                                       'src',
                                       'com',
                                       'test',
                                       'TestLauncher.java' ),
           'column_num': 11,
           'description': "        w.doSomethingVaguelyUseful();",
           'line_num': 32
         } ] )