Example #1
0
def RunTest( app, test, contents = None ):
  if not contents:
    contents = ReadFile( test[ 'request' ][ 'filepath' ] )

  # Because we aren't testing this command, we *always* ignore errors. This
  # is mainly because we (may) want to test scenarios where the completer
  # throws an exception and the easiest way to do that is to throw from
  # within the FlagsForFile function.
  app.post_json( '/event_notification',
                 CombineRequest( test[ 'request' ], {
                                 'event_name': 'FileReadyToParse',
                                 'contents': contents,
                                 'filetype': 'javascript',
                                 } ),
                 expect_errors = True )

  # We also ignore errors here, but then we check the response code
  # ourself. This is to allow testing of requests returning errors.
  response = app.post_json(
    '/run_completer_command',
    CombineRequest( test[ 'request' ], {
      'completer_target': 'filetype_default',
      'contents': contents,
      'filetype': 'javascript',
      'command_arguments': ( [ test[ 'request' ][ 'command' ] ]
                             + test[ 'request' ].get( 'arguments', [] ) )
    } ),
    expect_errors = True
  )

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

  eq_( response.status_code, test[ 'expect' ][ 'response' ] )

  assert_that( response.json, test[ 'expect' ][ 'data' ] )
def RunTest( app, test ):
  contents = ReadFile( test[ 'request' ][ 'filepath' ] )
  filetype = test[ 'request' ].get( 'filetype', 'javascriptreact' )
  app.post_json(
    '/event_notification',
    CombineRequest( test[ 'request' ], {
      'contents': contents,
      'filetype': filetype,
      'event_name': 'BufferVisit'
    } )
  )

  response = app.post_json(
    '/completions',
    CombineRequest( test[ 'request' ], {
      'contents': contents,
      'filetype': 'javascriptreact',
      'force_semantic': True
    } )
  )

  print( f'completer response: { pprint.pformat( response.json ) }' )

  assert_that( response.status_code,
               equal_to( test[ 'expect' ][ 'response' ] ) )

  assert_that( response.json, test[ 'expect' ][ 'data' ] )
def RunTest(app, test):
    contents = ReadFile(test['request']['filepath'])

    app.post_json(
        '/event_notification',
        CombineRequest(
            test['request'], {
                'contents': contents,
                'filetype': 'typescript',
                'event_name': 'BufferVisit'
            }))

    response = app.post_json(
        '/completions',
        CombineRequest(test['request'], {
            'contents': contents,
            'filetype': 'typescript',
            'force_semantic': True
        }))

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

    eq_(response.status_code, test['expect']['response'])

    assert_that(response.json, test['expect']['data'])
Example #4
0
def RunTest( app, test ):
  """
  Method to run a simple signature help test and verify the result

  test is a dictionary containing:
    'request': kwargs for BuildRequest
    'expect': {
       'response': server response code (e.g. httplib.OK)
       'data': matcher for the server response json
    }
  """
  contents = ReadFile( test[ 'request' ][ 'filepath' ] )

  app.post_json( '/event_notification',
                 CombineRequest( test[ 'request' ], {
                                 'event_name': 'FileReadyToParse',
                                 'contents': contents,
                                 } ),
                 expect_errors = True )

  # We ignore errors here and we check the response code ourself.
  # This is to allow testing of requests returning errors.
  response = app.post_json( '/signature_help',
                            CombineRequest( test[ 'request' ], {
                              'contents': contents
                            } ),
                            expect_errors = True )

  eq_( response.status_code, test[ 'expect' ][ 'response' ] )

  assert_that( response.json, test[ 'expect' ][ 'data' ] )
Example #5
0
def RunTest( app, test ):
  """
  Method to run a simple completion test and verify the result

  Note: by default uses the .ycm_extra_conf from general_fallback/ which:
   - supports cpp, c and objc
   - requires extra_conf_data containing 'filetype&' = the filetype

  This should be sufficient for many standard test cases. If not, specify
  a path (as a list of path items) in 'extra_conf' member of |test|.

  test is a dictionary containing:
    'request': kwargs for BuildRequest
    'expect': {
       'response': server response code (e.g. requests.codes.ok)
       'data': matcher for the server response json
    }
    'extra_conf': [ optional list of path items to extra conf file ]
  """

  extra_conf = ( test[ 'extra_conf' ] if 'extra_conf' in test
                                      else [ 'general_fallback',
                                             '.ycm_extra_conf.py' ] )

  app.post_json( '/load_extra_conf_file', {
    'filepath': PathToTestFile( *extra_conf ) } )


  request = test[ 'request' ]
  contents = ( request[ 'contents' ] if 'contents' in request else
               ReadFile( request[ 'filepath' ] ) )

  # Because we aren't testing this command, we *always* ignore errors. This
  # is mainly because we (may) want to test scenarios where the completer
  # throws an exception and the easiest way to do that is to throw from
  # within the Settings function.
  app.post_json( '/event_notification',
                 CombineRequest( request, {
                   'event_name': 'FileReadyToParse',
                   'contents': contents,
                 } ),
                 expect_errors = True )

  # We also ignore errors here, but then we check the response code ourself.
  # This is to allow testing of requests returning errors.
  response = app.post_json( '/completions',
                            CombineRequest( request, {
                              'contents': contents
                            } ),
                            expect_errors = True )

  eq_( response.status_code, test[ 'expect' ][ 'response' ] )

  print( 'Completer response: {0}'.format( json.dumps(
    response.json, indent = 2 ) ) )

  assert_that( response.json, test[ 'expect' ][ 'data' ] )
Example #6
0
def RunAfterInitialized(app, test):
    """Performs initialization of clangd server for the file contents specified in
  the |test| and optionally can run a test and check for its response.
  Since LSP servers do not start until initialization we need to send a
  FileReadyToParse request prior to any other request we will make.

  |test| consists of two parts a 'request' to be made and an optional 'expect'
  to perform a check on server's response.
  Request part must contain either a 'content' or 'filepath' element which
  either contains or points to the source code that will be sent to the server.
  In addition to that, if |test| also contain a 'route' element, then a
  follow-up request will be made to the server, with the same file contents and
  response of that request will be returned.
  Expect part, if specified, must contain two elements named 'response' and
  'data' which are used to check status code and data of the result received
  from server before returning them to the caller.

  Example usage:
    filepath = PathToTestFile( 'foo.cc' )
    request = { 'filepath': filepath,
                'filetype': 'cpp' }

    test = { 'request': request }
    RunAfterInitialized( app, test )
    ...
  """
    request = test['request']
    contents = (request['contents']
                if 'contents' in request else ReadFile(request['filepath']))
    response = app.post_json('/event_notification',
                             CombineRequest(
                                 request, {
                                     'event_name': 'FileReadyToParse',
                                     'contents': contents,
                                 }),
                             expect_errors=True)
    WaitUntilCompleterServerReady(app, 'cpp')

    if 'route' in test:
        expect_errors = 'expect' in test
        response = app.post_json(test['route'],
                                 CombineRequest(request,
                                                {'contents': contents}),
                                 expect_errors=expect_errors)

    if 'expect' in test:
        print("Completer response: {}".format(
            json.dumps(response.json, indent=2)))
        eq_(response.status_code, test['expect']['response'])
        assert_that(response.json, test['expect']['data'])
    return response.json
Example #7
0
def RunTest(app, test):
    """
  Method to run a simple completion test and verify the result

  Note: Compile commands are extracted from a compile_flags.txt file by clangd
  by iteratively looking at the directory containing the source file and its
  ancestors.

  test is a dictionary containing:
    'request': kwargs for BuildRequest
    'expect': {
       'response': server response code (e.g. requests.codes.ok)
       'data': matcher for the server response json
    }
  """

    request = test['request']
    filetype = request.get('filetype', 'cpp')
    if 'contents' not in request:
        contents = ReadFile(request['filepath'])
        request['contents'] = contents
        request['filetype'] = filetype

    # Because we aren't testing this command, we *always* ignore errors. This
    # is mainly because we (may) want to test scenarios where the completer
    # throws an exception and the easiest way to do that is to throw from
    # within the Settings function.
    app.post_json('/event_notification',
                  CombineRequest(request, {
                      'event_name': 'FileReadyToParse',
                      'filetype': filetype
                  }),
                  expect_errors=True)
    WaitUntilCompleterServerReady(app, filetype)

    for i in range(10):
        try:
            # We also ignore errors here, but then we check the response code ourself.
            # This is to allow testing of requests returning errors.
            response = app.post_json('/completions',
                                     BuildRequest(**request),
                                     expect_errors=True)

            assert_that(response.status_code,
                        equal_to(test['expect']['response']))

            print('Completer response: '
                  f'{ json.dumps( response.json, indent = 2 ) }')

            assert_that(response.json, test['expect']['data'])
            break
        except Exception:
            if i == 9:
                raise
            else:
                completer = handlers._server_state.GetFiletypeCompleter(
                    ['cpp'])
                completer._completions_cache.Invalidate()
                sleep(0.1)
                pass
def Subcommands_FixIt_AlreadyResolved_test( app ):
  filename = PathToTestFile( 'FixIt_Clang_cpp11.cpp' )
  request = {
    'completer_target' : 'filetype_default',
    'contents'         : ReadFile( filename ),
    'filepath'         : filename,
    'command_arguments': [ 'FixIt' ],
    'line_num'         : 16,
    'column_num'       : 1,
    'filetype'         : 'cpp'
  }
  app.post_json( '/event_notification',
                 CombineRequest( request, {
                   'event_name': 'FileReadyToParse',
                 } ),
                 expect_errors = True )
  WaitUntilCompleterServerReady( app, 'cpp' )
  expected = app.post_json( '/run_completer_command',
                            BuildRequest( **request ) ).json
  print( 'expected = ' )
  print( expected )
  request[ 'fixit' ] = expected[ 'fixits' ][ 0 ]
  actual = app.post_json( '/resolve_fixit',
                          BuildRequest( **request ) ).json
  print( 'actual = ' )
  print( actual )
  assert_that( actual, equal_to( expected ) )
Example #9
0
def GetCompletions_IgoreNonJSFiles_test(app):
    trivial1 = {
        'filetypes': ['python'],
        'contents': ReadFile(PathToTestFile('trivial.js')),
    }
    trivial2 = {
        'filetypes': ['javascript'],
        'contents': ReadFile(PathToTestFile('trivial2.js')),
    }

    request = {
        'line_num': 1,
        'column_num': 3,
        'file_data': {
            PathToTestFile('trivial.js'): trivial1,
            PathToTestFile('trivial2.js'): trivial2,
        },
    }

    app.post_json(
        '/event_notification',
        CombineRequest(
            request, {
                'filepath': PathToTestFile('trivial2.js'),
                'event_name': 'FileReadyToParse',
            }))

    response = app.post_json(
        '/completions',
        CombineRequest(request, {
            'filepath': PathToTestFile('trivial2.js'),
        })).json

    print('completer response: {0}'.format(pformat(response, indent=2)))

    assert_that(
        response,
        has_entries({
            'completion_start_column': 3,
            # Note: we do *not* see X.y and X.z because tern is not told about
            # the trivial.js file because we pretended it was Python
            'completions': empty(),
            'errors': empty(),
        }))
Example #10
0
def RunTest(app, test):
    contents = ReadFile(test['request']['filepath'])

    app.post_json(
        '/event_notification',
        CombineRequest(
            test['request'], {
                'contents': contents,
                'filetype': 'typescript',
                'event_name': 'BufferVisit'
            }))

    app.post_json(
        '/event_notification',
        CombineRequest(
            test['request'], {
                'contents': contents,
                'filetype': 'typescript',
                'event_name': 'FileReadyToParse'
            }))

    # We ignore errors here and check the response code ourself.
    # This is to allow testing of requests returning errors.
    response = app.post_json('/run_completer_command',
                             CombineRequest(
                                 test['request'], {
                                     'contents':
                                     contents,
                                     'filetype':
                                     'typescript',
                                     'command_arguments':
                                     ([test['request']['command']] +
                                      test['request'].get('arguments', []))
                                 }),
                             expect_errors=True)

    print(f'completer response: { pprint.pformat( response.json ) }')

    assert_that(response.status_code, equal_to(test['expect']['response']))

    assert_that(response.json, test['expect']['data'])
Example #11
0
def Signature_Help_Available_Disabled_By_User_test(app, *args):
    request = {'filepath': PathToTestFile('goto.cc')}
    app.post_json('/event_notification',
                  CombineRequest(request, {
                      'event_name': 'FileReadyToParse',
                      'filetype': 'cpp'
                  }),
                  expect_errors=True)
    WaitUntilCompleterServerReady(app, 'cpp')

    response = app.get('/signature_help_available', {'subserver': 'cpp'}).json
    assert_that(response, SignatureAvailableMatcher('NO'))
Example #12
0
def Signature_Help_Available_test(app):
    request = {'filepath': PathToTestFile('common', 'src', 'main.rs')}
    app.post_json('/event_notification',
                  CombineRequest(request, {
                      'event_name': 'FileReadyToParse',
                      'filetype': 'rust'
                  }),
                  expect_errors=True)
    WaitUntilCompleterServerReady(app, 'rust')

    response = app.get('/signature_help_available', {'subserver': 'rust'}).json
    assert_that(response, SignatureAvailableMatcher('YES'))
def GetCompletions_PythonInterpreter_ExtraConfData_test( app ):
  filepath = PathToTestFile( 'project', '__main__.py' )
  contents = ReadFile( filepath )
  request = {
    'filetype'  : 'python',
    'filepath'  : filepath,
    'contents'  : contents,
    'line_num'  : 3,
    'column_num': 8
  }

  # Complete with a sys.path specified by the client that contains the path to a
  # third-party module.
  completion_request = CombineRequest( request, {
    'extra_conf_data': {
      'sys_path': [ PathToTestFile( 'project', 'third_party' ) ]
    }
  } )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': has_item(
        CompletionEntryMatcher( 'SOME_CONSTANT', 'SOME_CONSTANT = 1' )
      ),
      'errors': empty()
    } )
  )

  # Complete at the same position but no sys.path from the client.
  completion_request = CombineRequest( request, {} )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': empty(),
      'errors': empty()
    } )
  )
Example #14
0
    def test_Signature_Help_Available(self, app):
        request = {'filepath': ProjectPath('SignatureHelp.java')}
        app.post_json('/event_notification',
                      CombineRequest(request, {
                          'event_name': 'FileReadyToParse',
                          'filetype': 'java'
                      }),
                      expect_errors=True)
        WaitUntilCompleterServerReady(app, 'java')

        response = app.get('/signature_help_available', {
            'subserver': 'java'
        }).json
        assert_that(response, SignatureAvailableMatcher('YES'))
Example #15
0
def RunTest( app, test ):
  """
  Method to run a simple completion test and verify the result

  test is a dictionary containing:
    'request': kwargs for BuildRequest
    'expect': {
       'response': server response code (e.g. requests.codes.ok)
       'data': matcher for the server response json
    }
  """

  request = test[ 'request' ]
  filetype = request.get( 'filetype', 'python' )
  if 'contents' not in request:
    contents = ReadFile( request[ 'filepath' ] )
    request[ 'contents' ] = contents
    request[ 'filetype' ] = filetype

  # Because we aren't testing this command, we *always* ignore errors. This
  # is mainly because we (may) want to test scenarios where the completer
  # throws an exception and the easiest way to do that is to throw from
  # within the Settings function.
  app.post_json( '/event_notification',
                 CombineRequest( request, {
                   'event_name': 'FileReadyToParse',
                   'filetype': filetype
                 } ),
                 expect_errors = True )
  WaitUntilCompleterServerReady( app, filetype )

  # We also ignore errors here, but then we check the response code ourself.
  # This is to allow testing of requests returning errors.
  response = app.post_json( '/semantic_tokens',
                            BuildRequest( **request ),
                            expect_errors = True )

  assert_that( response.status_code,
               equal_to( test[ 'expect' ][ 'response' ] ) )

  print( f'Completer response: { json.dumps( response.json, indent = 2 ) }' )

  assert_that( response.json, test[ 'expect' ][ 'data' ] )
def RunTest( app, test ):
  contents = ReadFile( test[ 'request' ][ 'filepath' ] )

  # We ignore errors here and check the response code ourself.
  # This is to allow testing of requests returning errors.
  response = app.post_json(
    '/run_completer_command',
    CombineRequest( test[ 'request' ], {
      'contents': contents,
      'filetype': 'python',
      'command_arguments': ( [ test[ 'request' ][ 'command' ] ]
                             + test[ 'request' ].get( 'arguments', [] ) )
    } ),
    expect_errors = True
  )

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

  eq_( response.status_code, test[ 'expect' ][ 'response' ] )

  assert_that( response.json, test[ 'expect' ][ 'data' ] )
def RunRangedFixItTest( app, rng, expected ):
  contents = ReadFile( PathToTestFile( 'FixIt_Clang_cpp11.cpp' ) )
  args = {
    'completer_target' : 'filetype_default',
    'contents'         : contents,
    'filepath'         : PathToTestFile( 'FixIt_Clang_cpp11.cpp' ),
    'command_arguments': [ 'FixIt' ],
    'range'            : rng,
    'filetype'         : 'cpp'
  }
  app.post_json( '/event_notification',
                 CombineRequest( args, {
                   'event_name': 'FileReadyToParse',
                 } ),
                 expect_errors = True )
  WaitUntilCompleterServerReady( app, 'cpp' )
  response = app.post_json( '/run_completer_command',
                            BuildRequest( **args ) ).json
  args[ 'fixit' ] = response[ 'fixits' ][ 0 ]
  response = app.post_json( '/resolve_fixit',
                            BuildRequest( **args ) ).json
  print( 'Resolved fixit response = ' )
  print( response )
  expected( response )
Example #18
0
def GetCompletions_IncludeMultiFileType_test(app):
    trivial1 = {
        'filetypes': ['python', 'javascript'],
        'contents': ReadFile(PathToTestFile('trivial.js')),
    }
    trivial2 = {
        'filetypes': ['javascript'],
        'contents': ReadFile(PathToTestFile('trivial2.js')),
    }

    request = {
        'line_num': 1,
        'column_num': 3,
        'file_data': {
            PathToTestFile('trivial.js'): trivial1,
            PathToTestFile('trivial2.js'): trivial2,
        },
    }

    app.post_json(
        '/event_notification',
        CombineRequest(
            request, {
                'filepath': PathToTestFile('trivial2.js'),
                'event_name': 'FileReadyToParse',
            }))

    response = app.post_json(
        '/completions',
        CombineRequest(
            request,
            {
                'filepath': PathToTestFile('trivial2.js'),
                # We must force the use of semantic engine because the previous test would
                # have entered 'empty' results into the completion cache.
                'force_semantic': True,
            })).json

    print('completer response: {0}'.format(pformat(response, indent=2)))

    assert_that(
        response,
        has_entries({
            'completion_start_column':
            3,
            # Note: This time, we *do* see the completions, becuase one of the 2
            # filetypes for trivial.js is javascript.
            'completions':
            contains_inanyorder(
                CompletionEntryMatcher('y', 'string'),
                CompletionEntryMatcher('z', 'string'),
                CompletionEntryMatcher('toString', 'fn() -> string'),
                CompletionEntryMatcher('toLocaleString', 'fn() -> string'),
                CompletionEntryMatcher('valueOf', 'fn() -> number'),
                CompletionEntryMatcher('hasOwnProperty',
                                       'fn(prop: string) -> bool'),
                CompletionEntryMatcher('isPrototypeOf', 'fn(obj: ?) -> bool'),
                CompletionEntryMatcher('propertyIsEnumerable',
                                       'fn(prop: string) -> bool'),
            ),
            'errors':
            empty(),
        }))
Example #19
0
def GetCompletions_ClientDataGivenToExtraConf_Cache_test( app ):
  app.post_json(
    '/load_extra_conf_file',
    { 'filepath': PathToTestFile( 'client_data', '.ycm_extra_conf.py' ) } )

  filepath = PathToTestFile( 'client_data', 'macro.cpp' )
  contents = ReadFile( filepath )
  request = {
    'filetype'  : 'cpp',
    'filepath'  : filepath,
    'contents'  : contents,
    'line_num'  : 11,
    'column_num': 8
  }

  # Complete with flags from the client.
  completion_request = CombineRequest( request, {
    'extra_conf_data': {
      'flags': [ '-DSOME_MACRO' ]
    }
  } )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': has_item(
        CompletionEntryMatcher( 'macro_defined' )
      ),
      'errors': empty()
    } )
  )

  # Complete at the same position but for a different set of flags from the
  # client.
  completion_request = CombineRequest( request, {
    'extra_conf_data': {
      'flags': [ '-Wall' ]
    }
  } )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': has_item(
        CompletionEntryMatcher( 'macro_not_defined' )
      ),
      'errors': empty()
    } )
  )

  # Finally, complete once again at the same position but no flags are given by
  # the client. An empty list of flags is returned by the extra conf file in
  # that case.
  completion_request = CombineRequest( request, {} )

  assert_that(
    app.post_json( '/completions', completion_request ).json,
    has_entries( {
      'completions': empty(),
      'errors': contains(
        ErrorMatcher( RuntimeError, NO_COMPILE_FLAGS_MESSAGE )
      )
    } )
  )