Exemple #1
0
def WorkingDir_Use_ycmd_WD_test():
  # Store the working directory so we can return to it
  wd = os.getcwd()

  test_dir = os.path.join( DATA_DIR, 'include' )
  assert wd != test_dir, "Please run this test from a different directory"

  try:
    options = user_options_store.DefaultOptions()
    options.update( {
      'filepath_completion_use_working_dir': 1
    } )

    completer = FilenameCompleter( options )

    # Change current directory to DATA_DIR/include (path to which we expect
    # results to be relative)
    os.chdir( test_dir )

    # We don't supply working_dir in the request, so the current working
    # directory is used.
    data = sorted( _CompletionResultsForLine( completer, 'ls ./' ) )
    eq_( [
          ( 'Qt',       '[Dir]' ),
          ( 'QtGui',    '[Dir]' ),
        ], data )

  finally:
    os.chdir( wd )
Exemple #2
0
def SetUpApp(custom_options={}):
    bottle.debug(True)
    options = user_options_store.DefaultOptions()
    options.update(custom_options)
    handlers.UpdateUserOptions(options)
    extra_conf_store.Reset()
    return TestApp(handlers.app)
    def setUp(self):
        options = dict(user_options_store.DefaultOptions())
        options.update(DEFAULT_CLIENT_OPTIONS)
        user_options_store.SetAll(options)

        self.server_state = YouCompleteMe(user_options_store.GetAll())
        pass
Exemple #4
0
def WorkingDir_Use_Client_WD_test():
  # Store the working directory so we can return to it
  wd = os.getcwd()

  test_dir = os.path.join( DATA_DIR, 'include' )
  assert wd != test_dir, "Please run this test from a different directory"

  try:
    options = user_options_store.DefaultOptions()
    options.update( {
      'filepath_completion_use_working_dir': 1
    } )

    completer = FilenameCompleter( options )

    # We supply working_dir in the request, so we expect results to be relative
    # to the supplied path
    data = sorted( _CompletionResultsForLine( completer, 'ls ./', {
      'working_dir': os.path.join( DATA_DIR, 'include' )
    } ) )
    eq_( [
          ( 'Qt',       '[Dir]' ),
          ( 'QtGui',    '[Dir]' ),
        ], data )

  finally:
    os.chdir( wd )
Exemple #5
0
def SetupOptions(options_file):
    options = (json.load(open(options_file, 'r'))
               if options_file else user_options_store.DefaultOptions())
    utils.RemoveIfExists(options_file)
    options['hmac_secret'] = base64.b64decode(options['hmac_secret'])
    user_options_store.SetAll(options)
    return options
Exemple #6
0
def LoadJsonDefaultsIntoVim():
    defaults = user_options_store.DefaultOptions()
    vim_defaults = {}
    for key, value in defaults.iteritems():
        vim_defaults['ycm_' + key] = value

    vimsupport.LoadDictIntoVimGlobals(vim_defaults, overwrite=False)
Exemple #7
0
def SetupOptions(options_file):
    options = user_options_store.DefaultOptions()
    if options_file is not None:
        user_options = json.loads(ReadFile(options_file))
        options.update(user_options)
        utils.RemoveIfExists(options_file)
    user_options_store.SetAll(options)
    return options
Exemple #8
0
def SetupOptions( options_file ):
  options = user_options_store.DefaultOptions()
  user_options = json.loads( ReadFile( options_file ) )
  options.update( user_options )
  utils.RemoveIfExists( options_file )
  hmac_secret = ToBytes( base64.b64decode( options[ 'hmac_secret' ] ) )
  del options[ 'hmac_secret' ]
  user_options_store.SetAll( options )
  return options, hmac_secret
Exemple #9
0
def SetUpApp(custom_options={}):
    bottle.debug(True)
    LOGGER.setLevel(logging.DEBUG)
    options = user_options_store.DefaultOptions()
    options.update(TEST_OPTIONS)
    options.update(custom_options)
    handlers.UpdateUserOptions(options)
    extra_conf_store.Reset()
    return TestApp(handlers.app)
Exemple #10
0
def SetupOptions(options_file):
    options = user_options_store.DefaultOptions()
    if options_file:
        user_options = json.load(open(options_file, 'r'))
        options.update(user_options)
    utils.RemoveIfExists(options_file)
    hmac_secret = base64.b64decode(options['hmac_secret'])
    del options['hmac_secret']
    user_options_store.SetAll(options)
    return options, hmac_secret
Exemple #11
0
def FindGoCodeBinary_test():
  user_options = user_options_store.DefaultOptions()

  eq_( GO_BINARIES.get( "gocode" ), FindBinary( "gocode", user_options ) )

  user_options[ 'gocode_binary_path' ] = DUMMY_BINARY
  eq_( DUMMY_BINARY, FindBinary( "gocode", user_options ) )

  user_options[ 'gocode_binary_path' ] = DATA_DIR
  eq_( None, FindBinary( "gocode", user_options ) )
Exemple #12
0
  def setUp( self ):
    self._filename_completer = FilenameCompleter(
      user_options_store.DefaultOptions() )

    # We cache include flags for test.cpp file for unit testing.
    self._filename_completer._flags.flags_for_file[ PATH_TO_TEST_FILE ] = [
      "-I", os.path.join( DATA_DIR, "include" ),
      "-I", os.path.join( DATA_DIR, "include", "Qt" ),
      "-I", os.path.join( DATA_DIR, "include", "QtGui" ),
    ]
Exemple #13
0
    def FindGoCodeBinary_test(self):
        user_options = user_options_store.DefaultOptions()

        eq_(PATH_TO_GOCODE_BINARY,
            self._completer.FindBinary("gocode", user_options))

        user_options['gocode_binary_path'] = DUMMY_BINARY
        eq_(DUMMY_BINARY, self._completer.FindBinary("gocode", user_options))

        user_options['gocode_binary_path'] = DATA_DIR
        eq_(None, self._completer.FindBinary("gocode", user_options))
def WorkingDir_Use_File_Path_test():
    assert os.getcwd() != DATA_DIR, ("Please run this test from a different "
                                     "directory")

    options = user_options_store.DefaultOptions()
    options.update({'filepath_completion_use_working_dir': 0})
    completer = FilenameCompleter(options)

    data = sorted(_CompletionResultsForLine(completer, 'ls ./include/'))
    eq_([
        ('Qt', '[Dir]'),
        ('QtGui', '[Dir]'),
    ], data)
Exemple #15
0
def MakeUserOptions( custom_options = {} ):
  options = dict( user_options_store.DefaultOptions() )
  options.update( DEFAULT_CLIENT_OPTIONS )
  options.update( custom_options )
  return options
Exemple #16
0
 def setUp(self):
     user_options = user_options_store.DefaultOptions()
     user_options['gocode_binary_path'] = DUMMY_BINARY
     self._completer = GoCodeCompleter(user_options)
Exemple #17
0
def LoadJsonDefaultsIntoVim():
    defaults = user_options_store.DefaultOptions()
    for key, value in iteritems(defaults):
        new_key = 'g:ycm_' + key
        if not vimsupport.VariableExists(new_key):
            vimsupport.SetVariableValue(new_key, value)
        YCMDRequest.shared_hmac_secret = hmac_secret

    def is_server_alive(self):
        """ Test if the server process is alive """
        # When the process hasn't finished yet, poll() returns None.
        return self._server_popen.poll() is None

    def server_shutdown(self):
        """ Shutdown the server """
        if self.is_server_alive():
            self._server_popen.terminate()
            self._keep_alive_thread.stop()


from ycmd import user_options_store  #temporary till the settings module is fleshed out
SERVER_WRAP = SublimeYouCompleteMe(user_options_store.DefaultOptions())


def unload_handler():
    """ This function is called by Sublime Text when this plugin is unloaded
    or reloaded. Unfortunately it is not called when Sublime Text exits.
    """
    SERVER_WRAP.server_shutdown()


class YCMEventListener(sublime_plugin.EventListener):
    """ Listener for events that Sublime Text sends us."""
    def __init__(self):
        self._file_parse_events = []
        self._timer_running = False
 def setUp(self):
     user_options = user_options_store.DefaultOptions()
     self._completer = NimsuggestCompleter(user_options)
     self._completer._StartProc = self._StartProc
     self._completer._EmptyQueue = lambda: None
Exemple #20
0
def _SetupOptions(user_options):
    options = user_options_store.DefaultOptions()
    options.update(user_options)
    user_options_store.SetAll(options)
    return options
Exemple #21
0
def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--host',
                        type=str,
                        default='localhost',
                        help='server hostname')
    # Default of 0 will make the OS pick a free port for us
    parser.add_argument('--port', type=int, default=0, help='server port')
    parser.add_argument('--log',
                        type=str,
                        default='info',
                        help='log level, one of '
                        '[debug|info|warning|error|critical]')
    parser.add_argument('--idle_suicide_seconds',
                        type=int,
                        default=0,
                        help='num idle seconds before server shuts down')
    parser.add_argument('--options_file',
                        type=str,
                        default='',
                        help='file with user options, in JSON format')
    parser.add_argument('--stdout',
                        type=str,
                        default=None,
                        help='optional file to use for stdout')
    parser.add_argument('--stderr',
                        type=str,
                        default=None,
                        help='optional file to use for stderr')
    parser.add_argument('--keep_logfiles',
                        action='store_true',
                        default=None,
                        help='retain logfiles after the server exits')
    args = parser.parse_args()

    if args.stdout is not None:
        sys.stdout = open(args.stdout, "w")
    if args.stderr is not None:
        sys.stderr = open(args.stderr, "w")

    numeric_level = getattr(logging, args.log.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % args.log)

    # Has to be called before any call to logging.getLogger()
    logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
                        level=numeric_level)

    options = (json.load(open(args.options_file, 'r'))
               if args.options_file else user_options_store.DefaultOptions())
    utils.RemoveIfExists(args.options_file)
    options['hmac_secret'] = base64.b64decode(options['hmac_secret'])
    user_options_store.SetAll(options)

    # This ensures that ycm_core is not loaded before extra conf
    # preload was run.
    YcmCoreSanityCheck()
    extra_conf_store.CallGlobalExtraConfYcmCorePreloadIfExists()

    # If not on windows, detach from controlling terminal to prevent
    # SIGINT from killing us.
    if not utils.OnWindows():
        try:
            os.setsid()
        # setsid() can fail if the user started ycmd directly from a shell.
        except OSError:
            pass

    # This can't be a top-level import because it transitively imports
    # ycm_core which we want to be imported ONLY after extra conf
    # preload has executed.
    from ycmd import handlers
    handlers.UpdateUserOptions(options)
    SetUpSignalHandler(args.stdout, args.stderr, args.keep_logfiles)
    handlers.app.install(WatchdogPlugin(args.idle_suicide_seconds))
    handlers.app.install(HmacPlugin(options['hmac_secret']))
    waitress.serve(handlers.app, host=args.host, port=args.port, threads=30)
Exemple #22
0
 def Wrapper( *args, **kwargs ):
   user_options = user_options_store.DefaultOptions()
   user_options[ 'gocode_binary_path' ] = DUMMY_BINARY
   with patch( 'ycmd.utils.SafePopen' ):
     completer = GoCompleter( user_options )
     return test( completer, *args, **kwargs )
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

import os
from nose.tools import eq_
from ycmd.completers.general.filename_completer import FilenameCompleter
from ycmd import user_options_store

test_dir = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(test_dir, "testdata", "filename_completer")
file_path = os.path.join(data_dir, "test.cpp")

fnc = FilenameCompleter(user_options_store.DefaultOptions())
# We cache include flags for test.cpp file for unit testing.
fnc._flags.flags_for_file[file_path] = [
    "-I",
    os.path.join(data_dir, "include"),
    "-I",
    os.path.join(data_dir, "include", "Qt"),
    "-I",
    os.path.join(data_dir, "include", "QtGui"),
]

request_data = {
    'filepath': file_path,
    'file_data': {
        file_path: {
            'filetypes': 'cpp'
Exemple #24
0
import os
import requests

from hamcrest import assert_that, equal_to, calling, has_entries, is_not, raises
from unittest.mock import patch
from unittest import TestCase

from ycmd import handlers, user_options_store
from ycmd.tests.test_utils import BuildRequest, ErrorMatcher
from ycmd.tests.java import setUpModule, tearDownModule  # noqa
from ycmd.tests.java import SharedYcmd
from ycmd.completers.java import java_completer, hook
from ycmd.completers.java.java_completer import NO_DOCUMENTATION_MESSAGE
from ycmd.tests import IsolatedYcmd as IsolatedYcmdWithoutJava

DEFAULT_OPTIONS = user_options_store.DefaultOptions()


class JavaCompleterTest(TestCase):
    @patch('ycmd.completers.java.java_completer.utils.FindExecutable',
           return_value='')
    def test_ShouldEnableJavaCompleter_NoJava(*args):
        assert_that(java_completer.ShouldEnableJavaCompleter(DEFAULT_OPTIONS),
                    equal_to(False))

    @IsolatedYcmdWithoutJava({'java_binary_path': '/this/path/does/not/exist'})
    def test_ShouldEnableJavaCompleter_JavaNotFound(self, app):
        request_data = BuildRequest(filetype='java')
        response = app.post_json('/defined_subcommands',
                                 request_data,
                                 expect_errors=True)
Exemple #25
0
 def setUp( self ):
   self._filename_completer = FilenameCompleter(
     user_options_store.DefaultOptions() )
 def setUp( self ):
   self._completer = GoCodeCompleter(
     user_options_store.DefaultOptions() )
   self._completer._binary = 'THE_BINARY'