From 06a41bde23fa1aabdec49a4d38baa763a81ebd11 Mon Sep 17 00:00:00 2001 From: Boris Staletic Date: Sat, 7 Oct 2023 21:10:30 +0200 Subject: [PATCH] Useful pylint fixes After combing through all the stuff pylint has found, this seems to me the useful part. The only questionable thing here, I think, could be the stuff related to `open()` and explicit encoding argument. This changes behaviour! Without specifying, the encoding is platform dependent. See https://docs.python.org/3/library/functions.html#open for details. Fixes #1672 --- .ycm_extra_conf.py | 4 +--- build.py | 13 ++++++------- run_tests.py | 4 ++-- update_clang_headers.py | 2 +- update_unicode.py | 4 ++-- ycmd/__main__.py | 2 +- ycmd/completers/cpp/clang_completer.py | 4 ++-- ycmd/completers/cpp/flags.py | 3 +-- ycmd/completers/cs/cs_completer.py | 2 +- .../language_server/generic_lsp_completer.py | 19 +++++++++---------- .../language_server_completer.py | 12 ++++++------ ycmd/completers/python/python_completer.py | 9 --------- .../typescript/typescript_completer.py | 5 ++--- ycmd/tests/clang/flags_test.py | 2 +- ycmd/tests/clang/include_cache_test.py | 4 ++-- ycmd/tests/clangd/debug_info_test.py | 2 +- ycmd/tests/clangd/diagnostics_test.py | 12 ++++++------ ycmd/tests/clangd/utilities_test.py | 2 +- ycmd/tests/cs/debug_info_test.py | 4 ++-- ycmd/tests/identifier_completer_test.py | 8 ++++---- ycmd/tests/java/diagnostics_test.py | 8 ++++---- ycmd/tests/java/get_completions_test.py | 4 ++-- ycmd/tests/java/java_completer_test.py | 4 ++-- ycmd/tests/java/server_management_test.py | 2 +- ycmd/tests/java/subcommands_test.py | 2 +- .../language_server_completer_test.py | 3 +-- ycmd/tests/rust/diagnostics_test.py | 6 +++--- ycmd/tests/test_utils.py | 4 ++-- ycmd/utils.py | 4 ++-- 29 files changed, 69 insertions(+), 85 deletions(-) diff --git a/.ycm_extra_conf.py b/.ycm_extra_conf.py index d97014841c..36cf6cca4e 100644 --- a/.ycm_extra_conf.py +++ b/.ycm_extra_conf.py @@ -29,9 +29,7 @@ # For more information, please refer to from sysconfig import get_path -import platform import os.path as p -import subprocess DIR_OF_THIS_SCRIPT = p.abspath( p.dirname( __file__ ) ) DIR_OF_THIRD_PARTY = p.join( DIR_OF_THIS_SCRIPT, 'third_party' ) @@ -120,7 +118,7 @@ def FindCorrespondingSourceFile( filename ): def PathToPythonUsedDuringBuild(): try: filepath = p.join( DIR_OF_THIS_SCRIPT, 'PYTHON_USED_DURING_BUILDING' ) - with open( filepath ) as f: + with open( filepath, encoding = 'utf8' ) as f: return f.read().strip() except OSError: return None diff --git a/build.py b/build.py index f4a95deee8..70f6897366 100755 --- a/build.py +++ b/build.py @@ -130,7 +130,7 @@ def FindLatestMSVC( quiet ): ).strip().decode() if '.' in latest_full_v: try: - latest_v = int( latest_full_v.split( '.' )[ 0 ] ) + latest_v = int( latest_full_v.split( '.', 1 )[ 0 ] ) except ValueError: raise ValueError( f"{ latest_full_v } is not a version number." ) @@ -464,10 +464,10 @@ def ParseArguments(): DEFAULT_RUST_TOOLCHAIN + '" is tested/' 'supported by the maintainers of YCM/ycmd' ) parser.add_argument( '--java-completer', action = 'store_true', - help = 'Enable Java semantic completion engine.' ), + help = 'Enable Java semantic completion engine.' ) parser.add_argument( '--ts-completer', action = 'store_true', help = 'Enable JavaScript and TypeScript semantic ' - 'completion engine.' ), + 'completion engine.' ) parser.add_argument( '--system-libclang', action = 'store_true', help = 'Use system libclang instead of downloading one ' 'from llvm.org. NOT RECOMMENDED OR SUPPORTED!' ) @@ -834,7 +834,6 @@ def CleanCsCompleter( build_dir, version ): if os.path.isfile( file_path ): os.remove( file_path ) elif os.path.isdir( file_path ): - import shutil shutil.rmtree( file_path ) @@ -953,14 +952,14 @@ def EnableGoCompleter( args ): def WriteToolchainVersion( version ): path = p.join( RUST_ANALYZER_DIR, 'TOOLCHAIN_VERSION' ) - with open( path, 'w' ) as f: + with open( path, 'w', encoding = 'utf8' ) as f: f.write( version ) def ReadToolchainVersion(): try: filepath = p.join( RUST_ANALYZER_DIR, 'TOOLCHAIN_VERSION' ) - with open( filepath ) as f: + with open( filepath, encoding = 'utf8' ) as f: return f.read().strip() except OSError: return None @@ -1234,7 +1233,7 @@ def Print( msg ): def WritePythonUsedDuringBuild(): path = p.join( DIR_OF_THIS_SCRIPT, 'PYTHON_USED_DURING_BUILDING' ) - with open( path, 'w' ) as f: + with open( path, 'w', encoding = 'utf8' ) as f: f.write( sys.executable ) diff --git a/run_tests.py b/run_tests.py index 8e9bc6b834..bd5db344b0 100755 --- a/run_tests.py +++ b/run_tests.py @@ -195,9 +195,9 @@ def BuildYcmdLibs( args ): '--core-tests' ] - for key in COMPLETERS: + for key, value in COMPLETERS.items(): if key in args.completers: - build_cmd.extend( COMPLETERS[ key ][ 'build' ] ) + build_cmd.extend( value[ 'build' ] ) if args.msvc and platform.system() == 'Windows': build_cmd.extend( [ '--msvc', str( args.msvc ) ] ) diff --git a/update_clang_headers.py b/update_clang_headers.py index 56c7a41903..6daaf76676 100755 --- a/update_clang_headers.py +++ b/update_clang_headers.py @@ -39,7 +39,7 @@ def ExtractTar( uncompressed_data, destination ): tar_file.extractall( destination ) # Determine the directory name - return os.path.join( destination, a_member.name.split( '/' )[ 0 ] ) + return os.path.join( destination, a_member.name.split( '/', 1 )[ 0 ] ) def ExtractLZMA( compressed_data, destination ): diff --git a/update_unicode.py b/update_unicode.py index 9cbb0876a2..aa4133df8b 100755 --- a/update_unicode.py +++ b/update_unicode.py @@ -580,7 +580,7 @@ def GenerateNormalizationTestCases( output_file ): JoinUnicodeToUtf8( captures[ 4 ].split() ) + '"},\n' ) res[ -1 ] = res[ -1 ].rstrip( ',\n' ) - with open( output_file, 'w' ) as f: + with open( output_file, 'w', encoding = 'utf8' ) as f: f.writelines( res ) @@ -602,7 +602,7 @@ def GenerateGraphemeBreakTestCases( output_file ): for x in split_data ] ).rstrip( ',' ) + '}},\n' ) res[ -1 ] = res[ -1 ].rstrip( ',\n' ) - with open( output_file, 'w' ) as f: + with open( output_file, 'w', encoding = 'utf8' ) as f: f.writelines( res ) diff --git a/ycmd/__main__.py b/ycmd/__main__.py index 512c5974c8..3da0f98725 100644 --- a/ycmd/__main__.py +++ b/ycmd/__main__.py @@ -142,7 +142,7 @@ def ParseArguments(): def SetupLogging( log_level ): numeric_level = getattr( logging, log_level.upper(), None ) if not isinstance( numeric_level, int ): - raise ValueError( 'Invalid log level: %s' % log_level ) + raise ValueError( f'Invalid log level: { log_level }' ) # Has to be called before any call to logging.getLogger() logging.basicConfig( format = '%(asctime)s - %(levelname)s - %(message)s', diff --git a/ycmd/completers/cpp/clang_completer.py b/ycmd/completers/cpp/clang_completer.py index 7a2d2cac0c..8003b87219 100644 --- a/ycmd/completers/cpp/clang_completer.py +++ b/ycmd/completers/cpp/clang_completer.py @@ -436,9 +436,9 @@ def DebugInfo( self, request_data ): database_item = responses.DebugInfoItem( key = 'compilation database path', - value = '{0}'.format( database_directory ) ) + value = f'{ database_directory }' ) flags_item = responses.DebugInfoItem( - key = 'flags', value = '{0}'.format( list( flags ) ) ) + key = 'flags', value = f'{ list( flags ) }' ) filename_item = responses.DebugInfoItem( key = 'translation unit', value = filename ) diff --git a/ycmd/completers/cpp/flags.py b/ycmd/completers/cpp/flags.py index eb9f1427bc..7360e7bf2a 100644 --- a/ycmd/completers/cpp/flags.py +++ b/ycmd/completers/cpp/flags.py @@ -673,13 +673,12 @@ def UserIncludePaths( user_flags, filename ): it = iter( user_flags ) for user_flag in it: user_flag_len = len( user_flag ) - for flag in include_flags: + for flag, container in include_flags.items(): if user_flag.startswith( flag ): flag_len = len( flag ) include_path = ( next( it ) if user_flag_len == flag_len else user_flag[ flag_len: ] ) if include_path: - container = include_flags[ flag ] container.append( ToUnicode( include_path ) ) break except StopIteration: diff --git a/ycmd/completers/cs/cs_completer.py b/ycmd/completers/cs/cs_completer.py index b20b7d94a8..879510e95d 100644 --- a/ycmd/completers/cs/cs_completer.py +++ b/ycmd/completers/cs/cs_completer.py @@ -387,7 +387,7 @@ def _GetSolutionFile( self, filepath ): return self._solution_for_file[ filepath ] -class CsharpSolutionCompleter( object ): +class CsharpSolutionCompleter: def __init__( self, solution_path, keep_logfiles, diff --git a/ycmd/completers/language_server/generic_lsp_completer.py b/ycmd/completers/language_server/generic_lsp_completer.py index 4859ba8837..17485bf579 100644 --- a/ycmd/completers/language_server/generic_lsp_completer.py +++ b/ycmd/completers/language_server/generic_lsp_completer.py @@ -48,18 +48,17 @@ def __init__( self, user_options, server_settings ): cmd = utils.FindExecutable( self._command_line[ 0 ] ) if cmd is None: - utils.LOGGER.warn( "Unable to find any executable with the path %s. " - "Cannot use %s completer.", - self._command_line[ 0 ], - self._name ) - raise RuntimeError( f"Invalid cmdline: { str( self._command_line ) }" ) + utils.LOGGER.warning( "Unable to find any executable with the path %s. " + "Cannot use %s completer.", + self._command_line[ 0 ], + self._name ) + raise RuntimeError( f"Invalid cmdline: { self._command_line }" ) self._command_line[ 0 ] = cmd - for idx in range( len( self._command_line ) ): - self._command_line[ idx ] = string.Template( - self._command_line[ idx ] ).safe_substitute( { - 'port': self._port - } ) + for arg in self._command_line: + arg = string.Template( arg ).safe_substitute( { + 'port': self._port + } ) super().__init__( user_options, connection_type ) diff --git a/ycmd/completers/language_server/language_server_completer.py b/ycmd/completers/language_server/language_server_completer.py index 2a088db933..0ffce0271d 100644 --- a/ycmd/completers/language_server/language_server_completer.py +++ b/ycmd/completers/language_server/language_server_completer.py @@ -564,8 +564,8 @@ def _ReadHeaders( self, data ): key, value = utils.ToUnicode( line ).split( ':', 1 ) headers[ key.strip() ] = value.strip() except Exception: - LOGGER.exception( 'Received invalid protocol data from server: ' - + str( line ) ) + LOGGER.exception( 'Received invalid protocol data from server: ', + line ) raise read_bytes += 1 @@ -1096,7 +1096,7 @@ def _StartServerNoLock( self, request_data ): self._project_directory, lambda globs: WatchdogHandler( self, globs ), self._port, - lambda request: self.WorkspaceConfigurationResponse( request ), + self.WorkspaceConfigurationResponse, self.GetDefaultNotificationHandler() ) else: self._stderr_file = utils.CreateLogfile( @@ -1116,7 +1116,7 @@ def _StartServerNoLock( self, request_data ): lambda globs: WatchdogHandler( self, globs ), self._server_handle.stdin, self._server_handle.stdout, - lambda request: self.WorkspaceConfigurationResponse( request ), + self.WorkspaceConfigurationResponse, self.GetDefaultNotificationHandler() ) ) @@ -2865,7 +2865,7 @@ def ExecuteCommand( self, request_data, args ): if response is not None: return response - if len( edits ): + if edits: fixits = [ WorkspaceEditToFixIt( request_data, e[ 'edit' ], @@ -3190,7 +3190,7 @@ def _SymbolInfoListToGoTo( request_data, symbols ): """Convert a list of LSP SymbolInformation into a YCM GoTo response""" def BuildGoToLocationFromSymbol( symbol ): - location, line_value = _LspLocationToLocationAndDescription( + location, _ = _LspLocationToLocationAndDescription( request_data, symbol[ 'location' ] ) diff --git a/ycmd/completers/python/python_completer.py b/ycmd/completers/python/python_completer.py index d2c62ea215..7e6dbad0c8 100644 --- a/ycmd/completers/python/python_completer.py +++ b/ycmd/completers/python/python_completer.py @@ -650,12 +650,3 @@ def _OffsetToPosition( start_end, filename, text, newlines ): if len( loc ) == 2: break return loc - - # Invalid position - it's outside of the text. Just return the last - # position in the text. This is an internal error. - LOGGER.error( "Invalid offset %s in file %s with text %s and newlines %s", - offset, - filename, - text, - newlines ) - raise RuntimeError( "Invalid file offset in diff" ) diff --git a/ycmd/completers/typescript/typescript_completer.py b/ycmd/completers/typescript/typescript_completer.py index 99439421da..af06c085e3 100644 --- a/ycmd/completers/typescript/typescript_completer.py +++ b/ycmd/completers/typescript/typescript_completer.py @@ -373,9 +373,8 @@ def _Reload( self, request_data ): filename = request_data[ 'filepath' ] contents = request_data[ 'file_data' ][ filename ][ 'contents' ] - tmpfile = NamedTemporaryFile( delete = False ) - tmpfile.write( utils.ToBytes( contents ) ) - tmpfile.close() + with NamedTemporaryFile( delete = False ) as tmpfile: + tmpfile.write( utils.ToBytes( contents ) ) self._SendRequest( 'reload', { 'file': filename, 'tmpfile': tmpfile.name diff --git a/ycmd/tests/clang/flags_test.py b/ycmd/tests/clang/flags_test.py index 61c54aeb24..2827c1bb5f 100644 --- a/ycmd/tests/clang/flags_test.py +++ b/ycmd/tests/clang/flags_test.py @@ -99,7 +99,7 @@ def Settings( **kwargs ): assert_that( filename, equal_to( '/foo' ) ) - def test_FlagsForFile_BadNonUnicodeFlagsAreAlsoRemoved( *args ): + def test_FlagsForFile_BadNonUnicodeFlagsAreAlsoRemoved( self, *args ): flags_object = flags.Flags() def Settings( **kwargs ): diff --git a/ycmd/tests/clang/include_cache_test.py b/ycmd/tests/clang/include_cache_test.py index 7fe1762c6c..db58c75a60 100644 --- a/ycmd/tests/clang/include_cache_test.py +++ b/ycmd/tests/clang/include_cache_test.py @@ -102,7 +102,7 @@ def test_IncludeCache_Cached_NewMtime( self ): include_cache = IncludeCache() assert_that( include_cache._cache, equal_to( {} ) ) foo_path = os.path.join( tmp_dir, 'foo' ) - with open( foo_path, 'w' ) as foo_file: + with open( foo_path, 'w', encoding = 'utf8' ) as foo_file: foo_file.write( 'foo' ) old_includes = include_cache.GetIncludes( tmp_dir ) @@ -124,7 +124,7 @@ def test_IncludeCache_Cached_NewMtime( self ): sleep( 2 ) bar_path = os.path.join( tmp_dir, 'bar' ) - with open( bar_path, 'w' ) as bar_file: + with open( bar_path, 'w', encoding = 'utf8' ) as bar_file: bar_file.write( 'bar' ) new_includes = include_cache.GetIncludes( tmp_dir ) diff --git a/ycmd/tests/clangd/debug_info_test.py b/ycmd/tests/clangd/debug_info_test.py index 7c2aa44c8e..22adf79078 100644 --- a/ycmd/tests/clangd/debug_info_test.py +++ b/ycmd/tests/clangd/debug_info_test.py @@ -336,7 +336,7 @@ def test_DebugInfo_ExtraConf_UseLocalOverDatabase( self, app ): with TemporaryClangProject( tmp_dir, database ): extra_conf = os.path.join( tmp_dir, '.ycm_extra_conf.py' ) - with open( extra_conf, 'w' ) as f: + with open( extra_conf, 'w', encoding = 'utf8' ) as f: f.write( ''' def Settings( **kwargs ): return { 'flags': [ '-x', 'c++', '-I', 'ycm' ] } diff --git a/ycmd/tests/clangd/diagnostics_test.py b/ycmd/tests/clangd/diagnostics_test.py index 452e69062a..b5d8367746 100644 --- a/ycmd/tests/clangd/diagnostics_test.py +++ b/ycmd/tests/clangd/diagnostics_test.py @@ -474,19 +474,19 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ): source_contents = """#include "header.h" int main() {return S::h();} """ - with open( source_file, 'w' ) as sf: + with open( source_file, 'w', encoding = 'utf8' ) as sf: sf.write( source_contents ) header_file = os.path.join( tmp_dir, 'header.h' ) old_header_content = """#pragma once struct S{static int h();}; """ - with open( header_file, 'w' ) as hf: + with open( header_file, 'w', encoding = 'utf8' ) as hf: hf.write( old_header_content ) flags_file = os.path.join( tmp_dir, 'compile_flags.txt' ) flags_content = """-xc++""" - with open( flags_file, 'w' ) as ff: + with open( flags_file, 'w', encoding = 'utf8' ) as ff: ff.write( flags_content ) messages_request = { 'contents': source_contents, @@ -502,7 +502,7 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ): new_header_content = """#pragma once static int h(); """ - with open( header_file, 'w' ) as f: + with open( header_file, 'w', encoding = 'utf8' ) as f: f.write( new_header_content ) # Send BufferSaved notification for the header @@ -548,7 +548,7 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ): break # Restore original content - with open( header_file, 'w' ) as f: + with open( header_file, 'w', encoding = 'utf8' ) as f: f.write( old_header_content ) # Send BufferSaved notification for the header @@ -571,5 +571,5 @@ def test_Diagnostics_UpdatedOnBufferVisit( self, app ): break # Assert no dirty files - with open( header_file, 'r' ) as f: + with open( header_file, 'r', encoding = 'utf8' ) as f: assert_that( f.read(), equal_to( old_header_content ) ) diff --git a/ycmd/tests/clangd/utilities_test.py b/ycmd/tests/clangd/utilities_test.py index 7f0f51fb26..cd34f8b6ea 100644 --- a/ycmd/tests/clangd/utilities_test.py +++ b/ycmd/tests/clangd/utilities_test.py @@ -104,7 +104,7 @@ def test_ClangdCompleter_GetClangdCommand_CustomBinary( self ): ( 13, 0, 0 ), ( 13, 10, 10 ), ( 100, 100, 100 ) ] ) - def test_ClangdCompleter_CheckClangdVersion( *args ): + def test_ClangdCompleter_CheckClangdVersion( self, *args ): assert_that( clangd_completer.CheckClangdVersion( 'clangd' ), equal_to( True ) ) assert_that( clangd_completer.CheckClangdVersion( 'clangd' ), diff --git a/ycmd/tests/cs/debug_info_test.py b/ycmd/tests/cs/debug_info_test.py index 8f6258ffbd..070935af62 100644 --- a/ycmd/tests/cs/debug_info_test.py +++ b/ycmd/tests/cs/debug_info_test.py @@ -193,14 +193,14 @@ def test_GetCompleter_RoslynFound( self ): @patch( 'ycmd.completers.cs.cs_completer.PATH_TO_OMNISHARP_ROSLYN_BINARY', None ) - def test_GetCompleter_RoslynNotFound( *args ): + def test_GetCompleter_RoslynNotFound( self, *args ): assert_that( not GetCompleter( user_options_store.GetAll() ) ) @patch( 'ycmd.completers.cs.cs_completer.FindExecutableWithFallback', wraps = lambda x, fb: x if x == 'roslyn' else fb ) @patch( 'os.path.isfile', return_value = True ) - def test_GetCompleter_RoslynFromUserOption( *args ): + def test_GetCompleter_RoslynFromUserOption( self, *args ): user_options = user_options_store.GetAll().copy( roslyn_binary_path = 'roslyn' ) assert_that( GetCompleter( user_options )._roslyn_path, diff --git a/ycmd/tests/identifier_completer_test.py b/ycmd/tests/identifier_completer_test.py index c1c0c020ab..76b309368e 100644 --- a/ycmd/tests/identifier_completer_test.py +++ b/ycmd/tests/identifier_completer_test.py @@ -121,7 +121,7 @@ def test_GetCursorIdentifier_IgnoreIdentifierFromCommentsAndStrings( self ): 4 ) ) ) ) assert_that( '', equal_to( ic._GetCursorIdentifier( False, - BuildRequestWrap( '/*\n' ' * foobar\n' ' */', + BuildRequestWrap( '/*\n * foobar\n */', 5, 2 ) ) ) ) @@ -133,7 +133,7 @@ def test_GetCursorIdentifier_CollectIdentifierFromCommentsAndStrings( self ): 4 ) ) ) ) assert_that( 'foobar', equal_to( ic._GetCursorIdentifier( True, - BuildRequestWrap( '/*\n' ' * foobar\n' ' */', + BuildRequestWrap( '/*\n * foobar\n */', 5, 2 ) ) ) ) @@ -254,7 +254,7 @@ def test_PreviousIdentifier_IgnoreIdentifierFromCommentsAndStrings( self ): assert_that( '', equal_to( ic._PreviousIdentifier( 2, False, - BuildRequestWrap( '/*\n' ' * foo\n' ' */', + BuildRequestWrap( '/*\n * foo\n */', column_num = 2, line_num = 3 ) ) ) ) @@ -269,7 +269,7 @@ def test_PreviousIdentifier_CollectIdentifierFromCommentsAndStrings( self ): assert_that( 'foo', equal_to( ic._PreviousIdentifier( 2, True, - BuildRequestWrap( '/*\n' ' * foo\n' ' */', + BuildRequestWrap( '/*\n * foo\n */', column_num = 2, line_num = 3 ) ) ) ) diff --git a/ycmd/tests/java/diagnostics_test.py b/ycmd/tests/java/diagnostics_test.py index 642290cdee..db3c347a90 100644 --- a/ycmd/tests/java/diagnostics_test.py +++ b/ycmd/tests/java/diagnostics_test.py @@ -450,7 +450,7 @@ def test_FileReadyToParse_ServerNotReady( self, app ): completer = handlers._server_state.GetFiletypeCompleter( [ 'java' ] ) # It can take a while for the diagnostics to be ready - for tries in range( 0, 60 ): + for _ in range( 0, 60 ): event_data = BuildRequest( event_name = 'FileReadyToParse', contents = contents, filepath = filepath, @@ -486,7 +486,7 @@ def test_FileReadyToParse_ChangeFileContents( self, app ): StartJavaCompleterServerInDirectory( app, ProjectPath() ) # It can take a while for the diagnostics to be ready - for tries in range( 0, 60 ): + for _ in range( 0, 60 ): event_data = BuildRequest( event_name = 'FileReadyToParse', contents = contents, filepath = filepath, @@ -641,7 +641,7 @@ def test_PollForMessages_InvalidUri( self, app ): 'ycmd.completers.language_server.language_server_protocol.UriToFilePath', side_effect = lsp.InvalidUriException ): - for tries in range( 0, 5 ): + for _ in range( 0, 5 ): response = app.post_json( '/receive_messages', BuildRequest( filetype = 'java', @@ -701,7 +701,7 @@ def test_PollForMessages_AbortedWhenServerDies( self, app ): def AwaitMessages(): max_tries = 20 - for tries in range( 0, max_tries ): + for _ in range( 0, max_tries ): response = app.post_json( '/receive_messages', BuildRequest( filetype = 'java', diff --git a/ycmd/tests/java/get_completions_test.py b/ycmd/tests/java/get_completions_test.py index fb4d1ad078..6e1e12886b 100644 --- a/ycmd/tests/java/get_completions_test.py +++ b/ycmd/tests/java/get_completions_test.py @@ -209,7 +209,7 @@ def test_GetCompletions_WithQuery( self, app ): @WithRetry() @SharedYcmd def test_GetCompletions_DetailFromCache( self, app ): - for i in range( 0, 2 ): + for _ in range( 0, 2 ): RunTest( app, { 'description': 'completion works when the elements come from the cache', 'request': { @@ -617,7 +617,7 @@ def test_GetCompletions_MoreThan10_NoResolve_ThenResolve( self, app ): request[ 'resolve' ] = resolve # Do this twice to prove that the request is idempotent - for i in range( 2 ): + for _ in range( 2 ): response = app.post_json( '/resolve_completion', request ).json print( f"Resolve response: { pformat( response ) }" ) diff --git a/ycmd/tests/java/java_completer_test.py b/ycmd/tests/java/java_completer_test.py index 4dc7a91b44..50375f1ae5 100644 --- a/ycmd/tests/java/java_completer_test.py +++ b/ycmd/tests/java/java_completer_test.py @@ -37,7 +37,7 @@ class JavaCompleterTest( TestCase ): @patch( 'ycmd.completers.java.java_completer.utils.FindExecutable', return_value = '' ) - def test_ShouldEnableJavaCompleter_NoJava( *args ): + def test_ShouldEnableJavaCompleter_NoJava( self, *args ): assert_that( java_completer.ShouldEnableJavaCompleter( DEFAULT_OPTIONS ), equal_to( False ) ) @@ -238,5 +238,5 @@ def test_JavaCompleter_GetDoc( self, app ): @patch( 'ycmd.completers.java.hook.ShouldEnableJavaCompleter', return_value = False ) - def test_JavaHook_JavaNotEnabled( *args ): + def test_JavaHook_JavaNotEnabled( self, *args ): assert_that( hook.GetCompleter( {} ), equal_to( None ) ) diff --git a/ycmd/tests/java/server_management_test.py b/ycmd/tests/java/server_management_test.py index 4e9f586d98..cf568dc63d 100644 --- a/ycmd/tests/java/server_management_test.py +++ b/ycmd/tests/java/server_management_test.py @@ -432,7 +432,7 @@ def test_ServerManagement_ServerDies( self, app ): process = psutil.Process( pid ) process.terminate() - for tries in range( 0, 10 ): + for _ 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' ]: diff --git a/ycmd/tests/java/subcommands_test.py b/ycmd/tests/java/subcommands_test.py index 02af0ae03f..f638fd971e 100644 --- a/ycmd/tests/java/subcommands_test.py +++ b/ycmd/tests/java/subcommands_test.py @@ -1645,7 +1645,7 @@ def test_Subcommands_FixIt_InvalidURI( self, app ): contents = ReadFile( filepath ) # Wait for jdt.ls to have parsed the file and returned some diagnostics - for tries in range( 0, 60 ): + for _ in range( 0, 60 ): results = app.post_json( '/event_notification', BuildRequest( filepath = filepath, filetype = 'java', diff --git a/ycmd/tests/language_server/language_server_completer_test.py b/ycmd/tests/language_server/language_server_completer_test.py index db5259a248..c3e26a3b21 100644 --- a/ycmd/tests/language_server/language_server_completer_test.py +++ b/ycmd/tests/language_server/language_server_completer_test.py @@ -55,8 +55,7 @@ def __init__( self, custom_options = {} ): user_options.update( custom_options ) super().__init__( user_options ) - self._connection = MockConnection( - lambda request: self.WorkspaceConfigurationResponse( request ) ) + self._connection = MockConnection( self.WorkspaceConfigurationResponse ) self._started = False def Language( self ): diff --git a/ycmd/tests/rust/diagnostics_test.py b/ycmd/tests/rust/diagnostics_test.py index 5daafb8e4e..e9e35c4b6c 100644 --- a/ycmd/tests/rust/diagnostics_test.py +++ b/ycmd/tests/rust/diagnostics_test.py @@ -61,7 +61,7 @@ class DiagnosticsTest( TestCase ): def test_Diagnostics_DetailedDiags( self, app ): filepath = PathToTestFile( 'common', 'src', 'main.rs' ) contents = ReadFile( filepath ) - with open( filepath, 'w' ) as f: + with open( filepath, 'w', encoding = 'utf8' ) as f: f.write( contents ) event_data = BuildRequest( event_name = 'FileSave', contents = contents, @@ -87,7 +87,7 @@ def test_Diagnostics_DetailedDiags( self, app ): def test_Diagnostics_FileReadyToParse( self, app ): filepath = PathToTestFile( 'common', 'src', 'main.rs' ) contents = ReadFile( filepath ) - with open( filepath, 'w' ) as f: + with open( filepath, 'w', encoding = 'utf8' ) as f: f.write( contents ) event_data = BuildRequest( event_name = 'FileSave', contents = contents, @@ -107,7 +107,7 @@ def test_Diagnostics_Poll( self, app ): project_dir = PathToTestFile( 'common' ) filepath = os.path.join( project_dir, 'src', 'main.rs' ) contents = ReadFile( filepath ) - with open( filepath, 'w' ) as f: + with open( filepath, 'w', encoding = 'utf8' ) as f: f.write( contents ) event_data = BuildRequest( event_name = 'FileSave', contents = contents, diff --git a/ycmd/tests/test_utils.py b/ycmd/tests/test_utils.py index e7b725db4a..6ae4ad0d19 100644 --- a/ycmd/tests/test_utils.py +++ b/ycmd/tests/test_utils.py @@ -463,7 +463,7 @@ def TemporaryClangProject( tmp_dir, compile_commands ): """ path = os.path.join( tmp_dir, 'compile_commands.json' ) - with open( path, 'w' ) as f: + with open( path, 'w', encoding = 'utf8' ) as f: f.write( ToUnicode( json.dumps( compile_commands, indent = 2 ) ) ) try: @@ -474,7 +474,7 @@ def TemporaryClangProject( tmp_dir, compile_commands ): def WaitForDiagnosticsToBeReady( app, filepath, contents, filetype, **kwargs ): results = None - for tries in range( 0, 60 ): + for _ in range( 0, 60 ): event_data = BuildRequest( event_name = 'FileReadyToParse', contents = contents, filepath = filepath, diff --git a/ycmd/utils.py b/ycmd/utils.py index ce2775452e..0aa482e880 100644 --- a/ycmd/utils.py +++ b/ycmd/utils.py @@ -91,7 +91,7 @@ def OpenForStdHandle( filepath ): # Since this function is used for logging purposes, we don't want the output # to be delayed. This means line buffering for text mode. # See https://docs.python.org/2/library/io.html#io.open - return open( filepath, mode = 'w', buffering = 1 ) + return open( filepath, mode = 'w', buffering = 1, encoding = 'utf8' ) def MakeSafeFileNameString( s ): @@ -490,7 +490,7 @@ def LoadYcmCoreDependencies(): def ImportCore(): """Imports and returns the ycm_core module. This function exists for easily mocking this import in tests.""" - import ycm_core as ycm_core + import ycm_core return ycm_core