Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Port to unittest
Browse files Browse the repository at this point in the history
bstaletic committed Sep 12, 2021
1 parent 518275b commit 973ec2b
Showing 24 changed files with 5,827 additions and 5,719 deletions.
7 changes: 0 additions & 7 deletions pytest.ini

This file was deleted.

2 changes: 0 additions & 2 deletions python/test_requirements.txt
Original file line number Diff line number Diff line change
@@ -6,5 +6,3 @@ codecov >= 2.0.5
coverage <5.0
click <8.0.0
covimerage >= 0.2.0
pytest
pytest-cov
126 changes: 125 additions & 1 deletion python/ycm/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -16,9 +16,133 @@
# along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.

import os
from ycm.tests.conftest import * # noqa
from ycm.tests.test_utils import MockVimModule
MockVimModule()

import contextlib
import functools
import time
from urllib.error import HTTPError, URLError

from ycm.client.base_request import BaseRequest
from ycm.tests import test_utils
from ycm.youcompleteme import YouCompleteMe
from ycmd.utils import CloseStandardStreams, WaitUntilProcessIsTerminated


def PathToTestFile( *args ):
dir_of_current_script = os.path.dirname( os.path.abspath( __file__ ) )
return os.path.join( dir_of_current_script, 'testdata', *args )


# The default options which are required for a working YouCompleteMe object.
DEFAULT_CLIENT_OPTIONS = {
# YCM options
'g:ycm_log_level': 'info',
'g:ycm_keep_logfiles': 0,
'g:ycm_extra_conf_vim_data': [],
'g:ycm_server_python_interpreter': '',
'g:ycm_show_diagnostics_ui': 1,
'g:ycm_enable_diagnostic_signs': 1,
'g:ycm_enable_diagnostic_highlighting': 0,
'g:ycm_echo_current_diagnostic': 1,
'g:ycm_filter_diagnostics': {},
'g:ycm_always_populate_location_list': 0,
'g:ycm_collect_identifiers_from_tags_files': 0,
'g:ycm_seed_identifiers_with_syntax': 0,
'g:ycm_goto_buffer_command': 'same-buffer',
'g:ycm_update_diagnostics_in_insert_mode': 1,
# ycmd options
'g:ycm_auto_trigger': 1,
'g:ycm_min_num_of_chars_for_completion': 2,
'g:ycm_semantic_triggers': {},
'g:ycm_filetype_specific_completion_to_disable': { 'gitcommit': 1 },
'g:ycm_max_num_candidates': 50,
'g:ycm_max_diagnostics_to_display': 30,
'g:ycm_disable_signature_help': 0,
}


@contextlib.contextmanager
def UserOptions( options ):
old_vim_options = test_utils.VIM_OPTIONS.copy()
test_utils.VIM_OPTIONS.update( DEFAULT_CLIENT_OPTIONS )
test_utils.VIM_OPTIONS.update( options )
try:
yield
finally:
test_utils.VIM_OPTIONS = old_vim_options


def _IsReady():
return BaseRequest().GetDataFromHandler( 'ready' )


def WaitUntilReady( timeout = 5 ):
expiration = time.time() + timeout
while True:
try:
if time.time() > expiration:
raise RuntimeError( 'Waited for the server to be ready '
f'for { timeout } seconds, aborting.' )
if _IsReady():
return
except ( URLError, HTTPError ):
pass
finally:
time.sleep( 0.1 )


def StopServer( ycm ):
try:
ycm.OnVimLeave()
WaitUntilProcessIsTerminated( ycm._server_popen )
CloseStandardStreams( ycm._server_popen )
except Exception:
pass


def YouCompleteMeInstance( custom_options = {} ):
"""Defines a decorator function for tests that passes a unique YouCompleteMe
instance as a parameter. This instance is initialized with the default options
`DEFAULT_CLIENT_OPTIONS`. Use the optional parameter |custom_options| to give
additional options and/or override the already existing ones.
Example usage:
from ycm.tests import YouCompleteMeInstance
@YouCompleteMeInstance( { 'log_level': 'debug',
'keep_logfiles': 1 } )
def Debug_test( ycm ):
...
"""
def Decorator( test ):
@functools.wraps( test )
def Wrapper( test_case_instance, *args, **kwargs ):
with UserOptions( custom_options ):
ycm = YouCompleteMe()
WaitUntilReady()
ycm.CheckIfServerIsReady()
try:
test_utils.VIM_MATCHES_FOR_WINDOW.clear()
return test( test_case_instance, ycm, *args, **kwargs )
finally:
StopServer( ycm )
return Wrapper
return Decorator


@contextlib.contextmanager
def youcompleteme_instance( custom_options = {} ):
"""Defines a context manager to be used in case a shared YCM state
between subtests is to be avoided, as could be the case with completion
caching."""
with UserOptions( custom_options ):
ycm = YouCompleteMe()
WaitUntilReady()
try:
test_utils.VIM_MATCHES_FOR_WINDOW.clear()
yield ycm
finally:
StopServer( ycm )
360 changes: 181 additions & 179 deletions python/ycm/tests/base_test.py

Large diffs are not rendered by default.

28 changes: 15 additions & 13 deletions python/ycm/tests/client/base_request_test.py
Original file line number Diff line number Diff line change
@@ -19,22 +19,24 @@
MockVimModule()

from hamcrest import assert_that, has_entry
from unittest import TestCase
from unittest.mock import patch
from ycm.client.base_request import BuildRequestData


@patch( 'ycm.client.base_request.GetCurrentDirectory',
return_value = '/some/dir' )
def BuildRequestData_AddWorkingDir_test( *args ):
current_buffer = VimBuffer( 'foo' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( BuildRequestData(), has_entry( 'working_dir', '/some/dir' ) )
class BaseRequestTest( TestCase ):
@patch( 'ycm.client.base_request.GetCurrentDirectory',
return_value = '/some/dir' )
def test_BuildRequestData_AddWorkingDir( self, *args ):
current_buffer = VimBuffer( 'foo' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( BuildRequestData(), has_entry( 'working_dir', '/some/dir' ) )


@patch( 'ycm.client.base_request.GetCurrentDirectory',
return_value = '/some/dir' )
def BuildRequestData_AddWorkingDirWithFileName_test( *args ):
current_buffer = VimBuffer( 'foo' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( BuildRequestData( current_buffer.number ),
has_entry( 'working_dir', '/some/dir' ) )
@patch( 'ycm.client.base_request.GetCurrentDirectory',
return_value = '/some/dir' )
def test_BuildRequestData_AddWorkingDirWithFileName( self, *args ):
current_buffer = VimBuffer( 'foo' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
assert_that( BuildRequestData( current_buffer.number ),
has_entry( 'working_dir', '/some/dir' ) )
123 changes: 65 additions & 58 deletions python/ycm/tests/client/command_request_test.py
Original file line number Diff line number Diff line change
@@ -19,8 +19,8 @@
MockVimModule()

import json
import pytest
from hamcrest import assert_that
from unittest import TestCase
from unittest.mock import patch, call
from ycm.client.command_request import CommandRequest

@@ -87,25 +87,25 @@ def GoToListTest( command, response ):
MULTI_FIXIT_SECOND_CHUNKS = MULTI_FIXIT[ 'fixits' ][ 1 ][ 'chunks' ]


class GoToResponse_QuickFix_test:
class GoToResponse_QuickFixTest( TestCase ):
"""This class tests the generation of QuickFix lists for GoTo responses which
return multiple locations, such as the Python completer and JavaScript
completer. It mostly proves that we use 1-based indexing for the column
number."""

def setup_method( self ):
def setUp( self ):
self._request = CommandRequest( [ 'GoToTest' ] )


def teardown_method( self ):
def tearDown( self ):
self._request = None


def GoTo_EmptyList_test( self ):
def test_GoTo_EmptyList( self ):
self._CheckGoToList( [], [] )


def GoTo_SingleItem_List_test( self ):
def test_GoTo_SingleItem_List( self ):
self._CheckGoToList( [ {
'filepath': 'dummy_file',
'line_num': 10,
@@ -119,7 +119,7 @@ def GoTo_SingleItem_List_test( self ):
} ] )


def GoTo_MultiItem_List_test( self ):
def test_GoTo_MultiItem_List( self ):
self._CheckGoToList( [ {
'filepath': 'dummy_file',
'line_num': 10,
@@ -174,29 +174,26 @@ def _CheckGoToList( self,
set_fitting_height.assert_called_once_with()


class Response_Detection_test:
class Response_Detection_Test( TestCase ):

@pytest.mark.parametrize( 'command,response', [
[ 'AnythingYouLike', True ],
[ 'GoToEvenWorks', 10 ],
[ 'FixItWorks', 'String!' ],
[ 'and8434fd andy garbag!', 10.3 ],
] )
def BasicResponse_test( self, command, response ):
def test_BasicResponse( self ):
def _BasicResponseTest( command, response ):
with patch( 'vim.command' ) as vim_command:
request = CommandRequest( [ command ] )
request._response = response
request.RunPostCommandActionsIfNeeded( 'belowright' )
vim_command.assert_called_with( f"echo '{ response }'" )

_BasicResponseTest( command, response )
for command, response in [
[ 'AnythingYouLike', True ],
[ 'GoToEvenWorks', 10 ],
[ 'FixItWorks', 'String!' ],
[ 'and8434fd andy garbag!', 10.3 ],
]:
with self.subTest( command = command, response = response ):
_BasicResponseTest( command, response )

@pytest.mark.parametrize( 'command', [ 'FixIt',
'Refactor',
'GoToHell',
'any_old_garbade!!!21' ] )
def FixIt_Response_Empty_test( self, command ):
def test_FixIt_Response_Empty( self ):
# Ensures we recognise and handle fixit responses which indicate that there
# are no fixits available
def EmptyFixItTest( command ):
@@ -212,27 +209,13 @@ def EmptyFixItTest( command ):
'No fixits found for current line', warning = False )
replace_chunks.assert_not_called()

EmptyFixItTest( command )
for command in [ 'FixIt', 'Refactor', 'GoToHell', 'any_old_garbade!!!21' ]:
with self.subTest( command = command ):
EmptyFixItTest( command )



@pytest.mark.parametrize( 'command,response,chunks,selection,silent', [
[ 'AnythingYouLike',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'GoToEvenWorks',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'FixItWorks',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'and8434fd andy garbag!',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'Format',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, True ],
[ 'select from multiple 1',
MULTI_FIXIT, MULTI_FIXIT_FIRST_CHUNKS, 0, False ],
[ 'select from multiple 2',
MULTI_FIXIT, MULTI_FIXIT_SECOND_CHUNKS, 1, False ],
] )
def FixIt_Response_test( self, command, response, chunks, selection, silent ):
def test_FixIt_Response( self ):
# Ensures we recognise and handle fixit responses with some dummy chunk data
def FixItTest( command, response, chunks, selection, silent ):
with patch( 'ycm.vimsupport.ReplaceChunks' ) as replace_chunks:
@@ -247,15 +230,31 @@ def FixItTest( command, response, chunks, selection, silent ):
post_vim_message.assert_not_called()


FixItTest( command, response, chunks, selection, silent )
for command, response, chunks, selection, silent in [
[ 'AnythingYouLike',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'GoToEvenWorks',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'FixItWorks',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'and8434fd andy garbag!',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, False ],
[ 'Format',
BASIC_FIXIT, BASIC_FIXIT_CHUNKS, 0, True ],
[ 'select from multiple 1',
MULTI_FIXIT, MULTI_FIXIT_FIRST_CHUNKS, 0, False ],
[ 'select from multiple 2',
MULTI_FIXIT, MULTI_FIXIT_SECOND_CHUNKS, 1, False ],
]:
with self.subTest( command = command,
response = response,
chunks = chunks,
selection = selection,
silent = silent ):
FixItTest( command, response, chunks, selection, silent )


@pytest.mark.parametrize( 'command,message', [
[ '___________', 'This is a message' ],
[ '', 'this is also a message' ],
[ 'GetType', 'std::string' ],
] )
def Message_Response_test( self, command, message ):
def test_Message_Response( self ):
# Ensures we correctly recognise and handle responses with a message to show
# to the user

@@ -266,15 +265,16 @@ def MessageTest( command, message ):
request.RunPostCommandActionsIfNeeded( 'rightbelow' )
post_vim_message.assert_called_with( message, warning = False )

MessageTest( command, message )


@pytest.mark.parametrize( 'command,info', [
for command, message in [
[ '___________', 'This is a message' ],
[ '', 'this is also a message' ],
[ 'GetDoc', 'std::string\netc\netc' ],
] )
def Detailed_Info_test( self, command, info ):
[ 'GetType', 'std::string' ],
]:
with self.subTest( command = command, message = message ):
MessageTest( command, message )


def test_Detailed_Info( self ):
# Ensures we correctly detect and handle detailed_info responses which are
# used to display information in the preview window

@@ -285,17 +285,24 @@ def DetailedInfoTest( command, info ):
request.RunPostCommandActionsIfNeeded( 'topleft' )
write_to_preview.assert_called_with( info )

DetailedInfoTest( command, info )
for command, info in [
[ '___________', 'This is a message' ],
[ '', 'this is also a message' ],
[ 'GetDoc', 'std::string\netc\netc' ],
]:
with self.subTest( command = command, info = info ):
DetailedInfoTest( command, info )


@pytest.mark.parametrize( 'test,command,response', [
def test_GoTo_Single( self ):
for test, command, response in [
[ GoToTest, 'AnythingYouLike', BASIC_GOTO ],
[ GoToTest, 'GoTo', BASIC_GOTO ],
[ GoToTest, 'FindAThing', BASIC_GOTO ],
[ GoToTest, 'FixItGoto', BASIC_GOTO ],
[ GoToListTest, 'AnythingYouLike', [ BASIC_GOTO ] ],
[ GoToListTest, 'GoTo', [] ],
[ GoToListTest, 'FixItGoto', [ BASIC_GOTO, BASIC_GOTO ] ],
] )
def GoTo_Single_test( self, test, command, response ):
test( command, response )
]:
with self.subTest( test = test, command = command, response = response ):
test( command, response )
29 changes: 15 additions & 14 deletions python/ycm/tests/client/completion_request_test.py
Original file line number Diff line number Diff line change
@@ -17,14 +17,15 @@

import json
from hamcrest import assert_that, equal_to
from ycm.tests.conftest import UserOptions
from unittest import TestCase
from ycm.tests import UserOptions
from ycm.tests.test_utils import MockVimModule
vim_mock = MockVimModule()

from ycm.client import completion_request


class ConvertCompletionResponseToVimDatas_test:
class ConvertCompletionResponseToVimDatasTest( TestCase ):
""" This class tests the
completion_request.ConvertCompletionResponseToVimDatas method """

@@ -44,7 +45,7 @@ def _Check( self, completion_data, expected_vim_data ):
raise


def AllFields_test( self ):
def test_AllFields( self ):
extra_data = {
'doc_string': 'DOC STRING',
}
@@ -68,7 +69,7 @@ def AllFields_test( self ):
} )


def OnlyInsertionTextField_test( self ):
def test_OnlyInsertionTextField( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT'
}, {
@@ -84,7 +85,7 @@ def OnlyInsertionTextField_test( self ):
} )


def JustDetailedInfo_test( self ):
def test_JustDetailedInfo( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
@@ -104,7 +105,7 @@ def JustDetailedInfo_test( self ):
} )


def JustDocString_test( self ):
def test_JustDocString( self ):
extra_data = {
'doc_string': 'DOC STRING',
}
@@ -127,7 +128,7 @@ def JustDocString_test( self ):
} )


def ExtraInfoNoDocString_test( self ):
def test_ExtraInfoNoDocString( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
@@ -148,7 +149,7 @@ def ExtraInfoNoDocString_test( self ):
} )


def NullCharactersInExtraInfoAndDocString_test( self ):
def test_NullCharactersInExtraInfoAndDocString( self ):
extra_data = {
'doc_string': 'DOC\x00STRING'
}
@@ -172,7 +173,7 @@ def NullCharactersInExtraInfoAndDocString_test( self ):
} )


def ExtraInfoNoDocStringWithDetailedInfo_test( self ):
def test_ExtraInfoNoDocStringWithDetailedInfo( self ):
self._Check( {
'insertion_text': 'INSERTION TEXT',
'menu_text': 'MENU TEXT',
@@ -194,7 +195,7 @@ def ExtraInfoNoDocStringWithDetailedInfo_test( self ):
} )


def EmptyInsertionText_test( self ):
def test_EmptyInsertionText( self ):
extra_data = {
'doc_string': 'DOC STRING',
}
@@ -218,7 +219,7 @@ def EmptyInsertionText_test( self ):
} )


def TruncateForPopup_test( self, *args ):
def test_TruncateForPopup( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
@@ -244,7 +245,7 @@ def TruncateForPopup_test( self, *args ):
} )


def OnlyTruncateForPopupIfNecessary_test( self, *args ):
def test_OnlyTruncateForPopupIfNecessary( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
@@ -269,7 +270,7 @@ def OnlyTruncateForPopupIfNecessary_test( self, *args ):
} )


def DontTruncateIfNotPopup_test( self, *args ):
def test_DontTruncateIfNotPopup( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'preview,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
@@ -294,7 +295,7 @@ def DontTruncateIfNotPopup_test( self, *args ):
} )


def TruncateForPopupWithoutDuplication_test( self, *args ):
def test_TruncateForPopupWithoutDuplication( self, *args ):
with UserOptions( { '&columns': 60, '&completeopt': b'popup,menuone' } ):
extra_data = {
'doc_string': 'DOC STRING',
195 changes: 99 additions & 96 deletions python/ycm/tests/client/debug_info_request_test.py
Original file line number Diff line number Diff line change
@@ -17,6 +17,7 @@

from copy import deepcopy
from hamcrest import assert_that, contains_string, equal_to
from unittest import TestCase

from ycm.client.debug_info_request import FormatDebugInfoResponse

@@ -66,111 +67,113 @@
}


def FormatDebugInfoResponse_NoResponse_test():
assert_that(
FormatDebugInfoResponse( None ),
equal_to( 'Server errored, no debug info from server\n' )
)
class DebugInfoRequestTest( TestCase ):
def test_FormatDebugInfoResponse_NoResponse( self ):
assert_that(
FormatDebugInfoResponse( None ),
equal_to( 'Server errored, no debug info from server\n' )
)


def FormatDebugInfoResponse_NoExtraConf_test():
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': False,
'path': None
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'No extra configuration file found\n'
def test_FormatDebugInfoResponse_NoExtraConf( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': False,
'path': None
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'No extra configuration file found\n'
)
)
)


def FormatDebugInfoResponse_ExtraConfFoundButNotLoaded_test():
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': False,
'path': '/path/to/extra/conf'
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Extra configuration file found but not loaded\n'
'Extra configuration path: /path/to/extra/conf\n'
def test_FormatDebugInfoResponse_ExtraConfFoundButNotLoaded( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': False,
'path': '/path/to/extra/conf'
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Extra configuration file found but not loaded\n'
'Extra configuration path: /path/to/extra/conf\n'
)
)
)


def FormatDebugInfoResponse_ExtraConfFoundAndLoaded_test():
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': True,
'path': '/path/to/extra/conf'
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Extra configuration file found and loaded\n'
'Extra configuration path: /path/to/extra/conf\n'
def test_FormatDebugInfoResponse_ExtraConfFoundAndLoaded( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'extra_conf' ].update( {
'is_loaded': True,
'path': '/path/to/extra/conf'
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Extra configuration file found and loaded\n'
'Extra configuration path: /path/to/extra/conf\n'
)
)
)


def FormatDebugInfoResponse_Completer_ServerRunningWithHost_test():
response = deepcopy( GENERIC_RESPONSE )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name running at: http://127.0.0.1:1234\n'
' Server name process ID: 12345\n'
' Server name executable: /path/to/executable\n'
' Server name logfiles:\n'
' /path/to/stdout/logfile\n'
' /path/to/stderr/logfile\n'
' Server name key: value\n'
' Key: value\n'


def test_FormatDebugInfoResponse_Completer_ServerRunningWithHost( self ):
response = deepcopy( GENERIC_RESPONSE )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name running at: http://127.0.0.1:1234\n'
' Server name process ID: 12345\n'
' Server name executable: /path/to/executable\n'
' Server name logfiles:\n'
' /path/to/stdout/logfile\n'
' /path/to/stderr/logfile\n'
' Server name key: value\n'
' Key: value\n'
)
)
)


def FormatDebugInfoResponse_Completer_ServerRunningWithoutHost_test():
response = deepcopy( GENERIC_RESPONSE )
response[ 'completer' ][ 'servers' ][ 0 ].update( {
'address': None,
'port': None
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name running\n'
' Server name process ID: 12345\n'
' Server name executable: /path/to/executable\n'
' Server name logfiles:\n'
' /path/to/stdout/logfile\n'
' /path/to/stderr/logfile\n'
' Server name key: value\n'
' Key: value\n'


def test_FormatDebugInfoResponse_Completer_ServerRunningWithoutHost( self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'completer' ][ 'servers' ][ 0 ].update( {
'address': None,
'port': None
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name running\n'
' Server name process ID: 12345\n'
' Server name executable: /path/to/executable\n'
' Server name logfiles:\n'
' /path/to/stdout/logfile\n'
' /path/to/stderr/logfile\n'
' Server name key: value\n'
' Key: value\n'
)
)
)


def FormatDebugInfoResponse_Completer_ServerNotRunningWithNoLogfiles_test():
response = deepcopy( GENERIC_RESPONSE )
response[ 'completer' ][ 'servers' ][ 0 ].update( {
'is_running': False,
'logfiles': []
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name not running\n'
' Server name executable: /path/to/executable\n'
' No logfiles available\n'
' Server name key: value\n'
' Key: value\n'


def test_FormatDebugInfoResponse_Completer_ServerNotRunningWithNoLogfiles(
self ):
response = deepcopy( GENERIC_RESPONSE )
response[ 'completer' ][ 'servers' ][ 0 ].update( {
'is_running': False,
'logfiles': []
} )
assert_that(
FormatDebugInfoResponse( response ),
contains_string(
'Completer name completer debug information:\n'
' Server name not running\n'
' Server name executable: /path/to/executable\n'
' No logfiles available\n'
' Server name key: value\n'
' Key: value\n'
)
)
)
220 changes: 113 additions & 107 deletions python/ycm/tests/client/messages_request_test.py
Original file line number Diff line number Diff line change
@@ -19,116 +19,122 @@
MockVimModule()

from hamcrest import assert_that, equal_to
from unittest import TestCase
from unittest.mock import patch, call

from ycm.client.messages_request import _HandlePollResponse
from ycm.tests.test_utils import ExtendedMock


def HandlePollResponse_NoMessages_test():
assert_that( _HandlePollResponse( True, None ), equal_to( True ) )

# Other non-False responses mean the same thing
assert_that( _HandlePollResponse( '', None ), equal_to( True ) )
assert_that( _HandlePollResponse( 1, None ), equal_to( True ) )
assert_that( _HandlePollResponse( {}, None ), equal_to( True ) )


def HandlePollResponse_PollingNotSupported_test():
assert_that( _HandlePollResponse( False, None ), equal_to( False ) )

# 0 is not False
assert_that( _HandlePollResponse( 0, None ), equal_to( True ) )


@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def HandlePollResponse_SingleMessage_test( post_vim_message ):
assert_that( _HandlePollResponse( [ { 'message': 'this is a message' } ] ,
None ),
equal_to( True ) )

post_vim_message.assert_has_exact_calls( [
call( 'this is a message', warning=False, truncate=True )
] )


@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def HandlePollResponse_MultipleMessages_test( post_vim_message ):
assert_that( _HandlePollResponse( [ { 'message': 'this is a message' },
{ 'message': 'this is another one' } ] ,
None ),
equal_to( True ) )

post_vim_message.assert_has_exact_calls( [
call( 'this is a message', warning=False, truncate=True ),
call( 'this is another one', warning=False, truncate=True )
] )


def HandlePollResponse_SingleDiagnostic_test():
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER' ] },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [
call( 'foo', [ 'PLACEHOLDER' ] )
] )


def HandlePollResponse_MultipleDiagnostics_test():
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] },
{ 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] },
{ 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] },
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [
call( 'foo', [ 'PLACEHOLDER1' ] ),
call( 'bar', [ 'PLACEHOLDER2' ] ),
call( 'baz', [ 'PLACEHOLDER3' ] ),
call( 'foo', [ 'PLACEHOLDER4' ] )
] )


@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def HandlePollResponse_MultipleMessagesAndDiagnostics_test( post_vim_message ):
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] },
{ 'message': 'On the first day of Christmas, my VimScript gave to me' },
{ 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] },
{ 'message': 'A test file in a Command-T' },
{ 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] },
{ 'message': 'On the second day of Christmas, my VimScript gave to me' },
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] },
{ 'message': 'Two popup menus, and a test file in a Command-T' },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls( [
call( 'foo', [ 'PLACEHOLDER1' ] ),
call( 'bar', [ 'PLACEHOLDER2' ] ),
call( 'baz', [ 'PLACEHOLDER3' ] ),
call( 'foo', [ 'PLACEHOLDER4' ] )
] )

post_vim_message.assert_has_exact_calls( [
call( 'On the first day of Christmas, my VimScript gave to me',
warning=False,
truncate=True ),
call( 'A test file in a Command-T', warning=False, truncate=True ),
call( 'On the second day of Christmas, my VimScript gave to me',
warning=False,
truncate=True ),
call( 'Two popup menus, and a test file in a Command-T',
warning=False,
truncate=True ),
] )
class MessagesRequestTest( TestCase ):
def test_HandlePollResponse_NoMessages( self ):
assert_that( _HandlePollResponse( True, None ), equal_to( True ) )

# Other non-False responses mean the same thing
assert_that( _HandlePollResponse( '', None ), equal_to( True ) )
assert_that( _HandlePollResponse( 1, None ), equal_to( True ) )
assert_that( _HandlePollResponse( {}, None ), equal_to( True ) )


def test_HandlePollResponse_PollingNotSupported( self ):
assert_that( _HandlePollResponse( False, None ), equal_to( False ) )

# 0 is not False
assert_that( _HandlePollResponse( 0, None ), equal_to( True ) )


@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def test_HandlePollResponse_SingleMessage( self, post_vim_message ):
assert_that( _HandlePollResponse( [ { 'message': 'this is a message' } ] ,
None ),
equal_to( True ) )

post_vim_message.assert_has_exact_calls( [
call( 'this is a message', warning=False, truncate=True )
] )


@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def test_HandlePollResponse_MultipleMessages( self, post_vim_message ):
assert_that( _HandlePollResponse( [ { 'message': 'this is a message' },
{ 'message': 'this is another one' } ] ,
None ),
equal_to( True ) )

post_vim_message.assert_has_exact_calls( [
call( 'this is a message', warning=False, truncate=True ),
call( 'this is another one', warning=False, truncate=True )
] )


def test_HandlePollResponse_SingleDiagnostic( self ):
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER' ] },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls(
[
call( 'foo', [ 'PLACEHOLDER' ] )
] )


def test_HandlePollResponse_MultipleDiagnostics( self ):
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] },
{ 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] },
{ 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] },
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls(
[
call( 'foo', [ 'PLACEHOLDER1' ] ),
call( 'bar', [ 'PLACEHOLDER2' ] ),
call( 'baz', [ 'PLACEHOLDER3' ] ),
call( 'foo', [ 'PLACEHOLDER4' ] )
] )


@patch( 'ycm.client.messages_request.PostVimMessage',
new_callable = ExtendedMock )
def test_HandlePollResponse_MultipleMessagesAndDiagnostics(
self, post_vim_message ):
diagnostics_handler = ExtendedMock()
messages = [
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER1' ] },
{ 'message': 'On the first day of Christmas, my VimScript gave to me' },
{ 'filepath': 'bar', 'diagnostics': [ 'PLACEHOLDER2' ] },
{ 'message': 'A test file in a Command-T' },
{ 'filepath': 'baz', 'diagnostics': [ 'PLACEHOLDER3' ] },
{ 'message': 'On the second day of Christmas, my VimScript gave to me' },
{ 'filepath': 'foo', 'diagnostics': [ 'PLACEHOLDER4' ] },
{ 'message': 'Two popup menus, and a test file in a Command-T' },
]
assert_that( _HandlePollResponse( messages, diagnostics_handler ),
equal_to( True ) )
diagnostics_handler.UpdateWithNewDiagnosticsForFile.assert_has_exact_calls(
[
call( 'foo', [ 'PLACEHOLDER1' ] ),
call( 'bar', [ 'PLACEHOLDER2' ] ),
call( 'baz', [ 'PLACEHOLDER3' ] ),
call( 'foo', [ 'PLACEHOLDER4' ] )
] )

post_vim_message.assert_has_exact_calls( [
call( 'On the first day of Christmas, my VimScript gave to me',
warning=False,
truncate=True ),
call( 'A test file in a Command-T', warning=False, truncate=True ),
call( 'On the second day of Christmas, my VimScript gave to me',
warning=False,
truncate=True ),
call( 'Two popup menus, and a test file in a Command-T',
warning=False,
truncate=True ),
] )
26 changes: 14 additions & 12 deletions python/ycm/tests/client/omni_completion_request_test.py
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@
# You should have received a copy of the GNU General Public License
# along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>.

from unittest import TestCase
from unittest.mock import MagicMock
from hamcrest import assert_that, has_entries

@@ -36,19 +37,20 @@ def BuildOmnicompletionRequest( results, start_column = 1 ):
return request


def Done_AlwaysTrue_test():
request = BuildOmnicompletionRequest( [] )
class OmniCompletionRequestTest( TestCase ):
def test_Done_AlwaysTrue( self ):
request = BuildOmnicompletionRequest( [] )

assert_that( request.Done() )
assert_that( request.Done() )


def Response_FromOmniCompleter_test():
results = [ { "word": "test" } ]
request = BuildOmnicompletionRequest( results )
def test_Response_FromOmniCompleter( self ):
results = [ { "word": "test" } ]
request = BuildOmnicompletionRequest( results )

assert_that( request.Response(), has_entries( {
'line': 1,
'column': 1,
'completion_start_column': 1,
'completions': results
} ) )
assert_that( request.Response(), has_entries( {
'line': 1,
'column': 1,
'completion_start_column': 1,
'completions': results
} ) )
225 changes: 114 additions & 111 deletions python/ycm/tests/command_test.py
Original file line number Diff line number Diff line change
@@ -20,142 +20,145 @@

from hamcrest import assert_that, contains_exactly, has_entries
from unittest.mock import patch
from unittest import TestCase

from ycm.tests import YouCompleteMeInstance


@YouCompleteMeInstance( { 'g:ycm_extra_conf_vim_data': [ 'tempname()' ] } )
def SendCommandRequest_ExtraConfVimData_Works_test( ycm ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'aboveleft', False, 1, 1 )
assert_that(
# Positional arguments passed to SendCommandRequest.
send_request.call_args[ 0 ],
contains_exactly(
contains_exactly( 'GoTo' ),
'aboveleft',
'same-buffer',
has_entries( {
'options': has_entries( {
'tab_size': 2,
'insert_spaces': True,
} ),
'extra_conf_data': has_entries( {
'tempname()': '_TEMP_FILE_'
} ),
} )
class CommandTest( TestCase ):
@YouCompleteMeInstance( { 'g:ycm_extra_conf_vim_data': [ 'tempname()' ] } )
def test_SendCommandRequest_ExtraConfVimData_Works( self, ycm ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'aboveleft', False, 1, 1 )
assert_that(
# Positional arguments passed to SendCommandRequest.
send_request.call_args[ 0 ],
contains_exactly(
contains_exactly( 'GoTo' ),
'aboveleft',
'same-buffer',
has_entries( {
'options': has_entries( {
'tab_size': 2,
'insert_spaces': True,
} ),
'extra_conf_data': has_entries( {
'tempname()': '_TEMP_FILE_'
} ),
} )
)
)


@YouCompleteMeInstance( {
'g:ycm_extra_conf_vim_data': [ 'undefined_value' ] } )
def test_SendCommandRequest_ExtraConfData_UndefinedValue( self, ycm ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'belowright', False, 1, 1 )
assert_that(
# Positional arguments passed to SendCommandRequest.
send_request.call_args[ 0 ],
contains_exactly(
contains_exactly( 'GoTo' ),
'belowright',
'same-buffer',
has_entries( {
'options': has_entries( {
'tab_size': 2,
'insert_spaces': True,
} )
} )
)
)
)


@YouCompleteMeInstance( { 'g:ycm_extra_conf_vim_data': [ 'undefined_value' ] } )
def SendCommandRequest_ExtraConfData_UndefinedValue_test( ycm ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'belowright', False, 1, 1 )
assert_that(
# Positional arguments passed to SendCommandRequest.
send_request.call_args[ 0 ],
contains_exactly(
contains_exactly( 'GoTo' ),
'belowright',
@YouCompleteMeInstance()
def test_SendCommandRequest_BuildRange_NoVisualMarks( self, ycm, *args ):
current_buffer = VimBuffer( 'buffer', contents = [ 'first line',
'second line' ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], '', True, 1, 2 )
send_request.assert_called_once_with(
[ 'GoTo' ],
'',
'same-buffer',
has_entries( {
'options': has_entries( {
{
'options': {
'tab_size': 2,
'insert_spaces': True,
} )
} )
'insert_spaces': True
},
'range': {
'start': {
'line_num': 1,
'column_num': 1
},
'end': {
'line_num': 2,
'column_num': 12
}
}
}
)
)


@YouCompleteMeInstance()
def SendCommandRequest_BuildRange_NoVisualMarks_test( ycm, *args ):
current_buffer = VimBuffer( 'buffer', contents = [ 'first line',
'second line' ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], '', True, 1, 2 )
send_request.assert_called_once_with(
[ 'GoTo' ],
'',
'same-buffer',
{
'options': {
'tab_size': 2,
'insert_spaces': True
},
'range': {
'start': {
'line_num': 1,
'column_num': 1
@YouCompleteMeInstance()
def test_SendCommandRequest_BuildRange_VisualMarks( self, ycm, *args ):
current_buffer = VimBuffer( 'buffer',
contents = [ 'first line',
'second line' ],
visual_start = [ 1, 4 ],
visual_end = [ 2, 8 ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'tab', True, 1, 2 )
send_request.assert_called_once_with(
[ 'GoTo' ],
'tab',
'same-buffer',
{
'options': {
'tab_size': 2,
'insert_spaces': True
},
'end': {
'line_num': 2,
'column_num': 12
'range': {
'start': {
'line_num': 1,
'column_num': 5
},
'end': {
'line_num': 2,
'column_num': 9
}
}
}
}
)
)


@YouCompleteMeInstance()
def SendCommandRequest_BuildRange_VisualMarks_test( ycm, *args ):
current_buffer = VimBuffer( 'buffer',
contents = [ 'first line',
'second line' ],
visual_start = [ 1, 4 ],
visual_end = [ 2, 8 ] )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo' ], 'tab', True, 1, 2 )
send_request.assert_called_once_with(
@YouCompleteMeInstance()
def test_SendCommandRequest_IgnoreFileTypeOption( self, ycm, *args ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
expected_args = (
[ 'GoTo' ],
'tab',
'',
'same-buffer',
{
'options': {
'tab_size': 2,
'insert_spaces': True
},
'range': {
'start': {
'line_num': 1,
'column_num': 5
},
'end': {
'line_num': 2,
'column_num': 9
}
}
}
)

with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'ft=ycm:ident', 'GoTo' ], '', False, 1, 1 )
send_request.assert_called_once_with( *expected_args )

@YouCompleteMeInstance()
def SendCommandRequest_IgnoreFileTypeOption_test( ycm, *args ):
current_buffer = VimBuffer( 'buffer' )
with MockVimBuffers( [ current_buffer ], [ current_buffer ] ):
expected_args = (
[ 'GoTo' ],
'',
'same-buffer',
{
'options': {
'tab_size': 2,
'insert_spaces': True
},
}
)

with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'ft=ycm:ident', 'GoTo' ], '', False, 1, 1 )
send_request.assert_called_once_with( *expected_args )

with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo', 'ft=python' ], '', False, 1, 1 )
send_request.assert_called_once_with( *expected_args )
with patch( 'ycm.youcompleteme.SendCommandRequest' ) as send_request:
ycm.SendCommandRequest( [ 'GoTo', 'ft=python' ], '', False, 1, 1 )
send_request.assert_called_once_with( *expected_args )
789 changes: 398 additions & 391 deletions python/ycm/tests/completion_test.py

Large diffs are not rendered by default.

143 changes: 0 additions & 143 deletions python/ycm/tests/conftest.py

This file was deleted.

118 changes: 60 additions & 58 deletions python/ycm/tests/diagnostic_filter_test.py
Original file line number Diff line number Diff line change
@@ -19,6 +19,7 @@
MockVimModule()

from hamcrest import assert_that, equal_to
from unittest import TestCase
from ycm.diagnostic_filter import DiagnosticFilter


@@ -45,91 +46,92 @@ def _CreateFilterForTypes( opts, types ):
return DiagnosticFilter.CreateFromOptions( opts ).SubsetForTypes( types )


def RegexFilter_test():
opts = _JavaFilter( { 'regex' : 'taco' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
class DiagnosticFilterTest( TestCase ):
def test_RegexFilter( self ):
opts = _JavaFilter( { 'regex' : 'taco' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )

_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )


def RegexSingleList_test():
opts = _JavaFilter( { 'regex' : [ 'taco' ] } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
def test_RegexSingleList( self ):
opts = _JavaFilter( { 'regex' : [ 'taco' ] } )
f = _CreateFilterForTypes( opts, [ 'java' ] )

_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )


def RegexMultiList_test():
opts = _JavaFilter( { 'regex' : [ 'taco', 'burrito' ] } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
def test_RegexMultiList( self ):
opts = _JavaFilter( { 'regex' : [ 'taco', 'burrito' ] } )
f = _CreateFilterForTypes( opts, [ 'java' ] )

_assert_rejects( f, 'This is a Taco' )
_assert_rejects( f, 'This is a Burrito' )
_assert_rejects( f, 'This is a Taco' )
_assert_rejects( f, 'This is a Burrito' )


def RegexNotFiltered_test():
opts = _JavaFilter( { 'regex' : 'taco' } )
f = _CreateFilterForTypes( opts, [ 'cs' ] )
def test_RegexNotFiltered( self ):
opts = _JavaFilter( { 'regex' : 'taco' } )
f = _CreateFilterForTypes( opts, [ 'cs' ] )

_assert_accepts( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
_assert_accepts( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )


def LevelWarnings_test():
opts = _JavaFilter( { 'level' : 'warning' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
def test_LevelWarnings( self ):
opts = _JavaFilter( { 'level' : 'warning' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )

_assert_rejects( f, { 'text' : 'This is an unimportant taco',
'kind' : 'WARNING' } )
_assert_accepts( f, { 'text' : 'This taco will be shown',
'kind' : 'ERROR' } )
_assert_rejects( f, { 'text' : 'This is an unimportant taco',
'kind' : 'WARNING' } )
_assert_accepts( f, { 'text' : 'This taco will be shown',
'kind' : 'ERROR' } )


def LevelErrors_test():
opts = _JavaFilter( { 'level' : 'error' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
def test_LevelErrors( self ):
opts = _JavaFilter( { 'level' : 'error' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )

_assert_accepts( f, { 'text' : 'This is an IMPORTANT taco',
'kind' : 'WARNING' } )
_assert_rejects( f, { 'text' : 'This taco will NOT be shown',
'kind' : 'ERROR' } )
_assert_accepts( f, { 'text' : 'This is an IMPORTANT taco',
'kind' : 'WARNING' } )
_assert_rejects( f, { 'text' : 'This taco will NOT be shown',
'kind' : 'ERROR' } )


def MultipleFilterTypesTypeTest_test():
def test_MultipleFilterTypesTypeTest( self ):

opts = _JavaFilter( { 'regex' : '.*taco.*',
'level' : 'warning' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )
opts = _JavaFilter( { 'regex' : '.*taco.*',
'level' : 'warning' } )
f = _CreateFilterForTypes( opts, [ 'java' ] )

_assert_rejects( f, { 'text' : 'This is an unimportant taco',
'kind' : 'WARNING' } )
_assert_rejects( f, { 'text' : 'This taco will NOT be shown',
'kind' : 'ERROR' } )
_assert_accepts( f, { 'text' : 'This burrito WILL be shown',
'kind' : 'ERROR' } )
_assert_rejects( f, { 'text' : 'This is an unimportant taco',
'kind' : 'WARNING' } )
_assert_rejects( f, { 'text' : 'This taco will NOT be shown',
'kind' : 'ERROR' } )
_assert_accepts( f, { 'text' : 'This burrito WILL be shown',
'kind' : 'ERROR' } )


def MergeMultipleFiletypes_test():
def test_MergeMultipleFiletypes( self ):

opts = { 'filter_diagnostics' : {
'java' : { 'regex' : '.*taco.*' },
'xml' : { 'regex' : '.*burrito.*' } } }
opts = { 'filter_diagnostics' : {
'java' : { 'regex' : '.*taco.*' },
'xml' : { 'regex' : '.*burrito.*' } } }

f = _CreateFilterForTypes( opts, [ 'java', 'xml' ] )
f = _CreateFilterForTypes( opts, [ 'java', 'xml' ] )

_assert_rejects( f, 'This is a Taco' )
_assert_rejects( f, 'This is a Burrito' )
_assert_accepts( f, 'This is some Nachos' )
_assert_rejects( f, 'This is a Taco' )
_assert_rejects( f, 'This is a Burrito' )
_assert_accepts( f, 'This is some Nachos' )


def CommaSeparatedFiletypes_test():
def test_CommaSeparatedFiletypes( self ):

opts = { 'filter_diagnostics' : {
'java,c,cs' : { 'regex' : '.*taco.*' } } }
opts = { 'filter_diagnostics' : {
'java,c,cs' : { 'regex' : '.*taco.*' } } }

f = _CreateFilterForTypes( opts, [ 'cs' ] )
f = _CreateFilterForTypes( opts, [ 'cs' ] )

_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
_assert_rejects( f, 'This is a Taco' )
_assert_accepts( f, 'This is a Burrito' )
693 changes: 349 additions & 344 deletions python/ycm/tests/event_notification_test.py

Large diffs are not rendered by default.

1,765 changes: 886 additions & 879 deletions python/ycm/tests/omni_completer_test.py

Large diffs are not rendered by default.

45 changes: 24 additions & 21 deletions python/ycm/tests/paths_test.py
Original file line number Diff line number Diff line change
@@ -18,8 +18,8 @@
from ycm.tests.test_utils import MockVimModule
MockVimModule()

import pytest
from hamcrest import assert_that
from unittest import TestCase
from ycm.paths import _EndsWithPython


@@ -33,23 +33,26 @@ def EndsWithPython_Bad( path ):
f'Path { path } does end with a Python name.' )


@pytest.mark.parametrize( 'path', [
'python3',
'/usr/bin/python3.6',
'/home/user/.pyenv/shims/python3.6',
r'C:\Python36\python.exe'
] )
def EndsWithPython_Python3Paths_test( path ):
EndsWithPython_Good( path )


@pytest.mark.parametrize( 'path', [
None,
'',
'/opt/local/bin/vim',
r'C:\Program Files\Vim\vim74\gvim.exe',
'/usr/bin/python2.7',
'/home/user/.pyenv/shims/python3.2',
] )
def EndsWithPython_BadPaths_test( path ):
EndsWithPython_Bad( path )
class PathTest( TestCase ):
def test_EndsWithPython_Python3Paths( self ):
for path in [
'python3',
'/usr/bin/python3.6',
'/home/user/.pyenv/shims/python3.6',
r'C:\Python36\python.exe'
]:
with self.subTest( path = path ):
EndsWithPython_Good( path )


def test_EndsWithPython_BadPaths( self ):
for path in [
None,
'',
'/opt/local/bin/vim',
r'C:\Program Files\Vim\vim74\gvim.exe',
'/usr/bin/python2.7',
'/home/user/.pyenv/shims/python3.2',
]:
with self.subTest( path = path ):
EndsWithPython_Bad( path )
559 changes: 285 additions & 274 deletions python/ycm/tests/postcomplete_test.py

Large diffs are not rendered by default.

30 changes: 16 additions & 14 deletions python/ycm/tests/signature_help_test.py
Original file line number Diff line number Diff line change
@@ -17,20 +17,22 @@

from hamcrest import ( assert_that,
empty )
from unittest import TestCase
from ycm import signature_help as sh


def MakeSignatureHelpBuffer_Empty_test():
assert_that( sh._MakeSignatureHelpBuffer( {} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'activeSignature': 0,
'activeParameter': 0,
'signatures': []
} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'activeSignature': 0,
'activeParameter': 0,
} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'signatures': []
} ), empty() )
class SignatureHelpTest( TestCase ):
def test_MakeSignatureHelpBuffer_Empty( self ):
assert_that( sh._MakeSignatureHelpBuffer( {} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'activeSignature': 0,
'activeParameter': 0,
'signatures': []
} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'activeSignature': 0,
'activeParameter': 0,
} ), empty() )
assert_that( sh._MakeSignatureHelpBuffer( {
'signatures': []
} ), empty() )
455 changes: 232 additions & 223 deletions python/ycm/tests/syntax_parse_test.py

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions python/ycm/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -17,11 +17,11 @@

from collections import defaultdict, namedtuple
from unittest.mock import DEFAULT, MagicMock, patch
from unittest import skip
from hamcrest import assert_that, equal_to
import contextlib
import functools
import json
import pytest
import os
import re
import sys
@@ -712,7 +712,7 @@ def Wrapper( *args, **kwargs ):
raise test_exception

# Failed for the right reason
pytest.skip( reason )
skip( reason )
else:
raise AssertionError( f'Test was expected to fail: { reason }' )
return Wrapper
3,561 changes: 1,794 additions & 1,767 deletions python/ycm/tests/vimsupport_test.py

Large diffs are not rendered by default.

1,998 changes: 1,015 additions & 983 deletions python/ycm/tests/youcompleteme_test.py

Large diffs are not rendered by default.

45 changes: 25 additions & 20 deletions run_tests.py
Original file line number Diff line number Diff line change
@@ -20,13 +20,7 @@
#
# Pip knows how to install this correctly so that it doesn't matter where in
# sys.path the path is.
python_path = [ p.join( DIR_OF_THIRD_PARTY, 'pythonfutures' ),
p.join( DIR_OF_THIRD_PARTY, 'requests-futures' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'chardet' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'certifi' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'idna' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'requests' ),
p.join( DIR_OF_THIRD_PARTY, 'requests_deps', 'urllib3', 'src' ),
python_path = [ p.join( DIR_OF_THIS_SCRIPT, 'python' ),
p.join( DIR_OF_THIRD_PARTY, 'ycmd' ) ]
if os.environ.get( 'PYTHONPATH' ):
python_path.append( os.environ[ 'PYTHONPATH' ] )
@@ -56,38 +50,49 @@ def ParseArguments():
help = 'Dump the PYTHONPATH required to run tests '
'manually, then exit.' )

parsed_args, pytests_args = parser.parse_known_args()
parsed_args, unittest_args = parser.parse_known_args()

if 'COVERAGE' in os.environ:
parsed_args.coverage = ( os.environ[ 'COVERAGE' ] == 'true' )

return parsed_args, pytests_args
return parsed_args, unittest_args


def BuildYcmdLibs( args ):
if not args.skip_build:
subprocess.check_call( [
sys.executable,
p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' )
p.join( DIR_OF_THIS_SCRIPT, 'third_party', 'ycmd', 'build.py' ),
'--quiet'
] )


def PytestTests( parsed_args, extra_pytests_args ):
pytests_args = []
def UnittestTests( parsed_args, extra_unittest_args ):
unittest_args = [ '-cb' ]
prefer_regular = any( p.isfile( arg ) for arg in extra_unittest_args )
if not prefer_regular:
unittest_args += [ '-p', '*_test.py' ]

if parsed_args.coverage:
pytests_args += [ '--cov=ycm' ]
if extra_unittest_args:
unittest_args.extend( extra_unittest_args )
if not ( prefer_regular and extra_unittest_args ):
unittest_args.append( '-s' )
test_directory = p.join( DIR_OF_THIS_SCRIPT, 'python', 'ycm', 'tests' )
unittest_args.append( test_directory )

if extra_pytests_args:
pytests_args.extend( extra_pytests_args )
if parsed_args.coverage:
executable = [ sys.executable, '-We', '-m', 'coverage', 'run' ]
else:
pytests_args.append( p.join( DIR_OF_THIS_SCRIPT, 'python' ) )
executable = [ sys.executable, '-We' ]

subprocess.check_call( [ sys.executable, '-m', 'pytest' ] + pytests_args )
unittest = [ '-m', 'unittest' ]
if not prefer_regular:
unittest.append( 'discover' )
subprocess.check_call( executable + unittest + unittest_args )


def Main():
( parsed_args, pytests_args ) = ParseArguments()
( parsed_args, unittest_args ) = ParseArguments()
if parsed_args.dump_path:
print( os.environ[ 'PYTHONPATH' ] )
sys.exit()
@@ -96,7 +101,7 @@ def Main():
RunFlake8()

BuildYcmdLibs( parsed_args )
PytestTests( parsed_args, pytests_args )
UnittestTests( parsed_args, unittest_args )


if __name__ == "__main__":

0 comments on commit 973ec2b

Please sign in to comment.