Best JavaScript code snippet using playwright-internal
subcommands_test.py
Source:subcommands_test.py
1# Copyright (C) 2017-2018 ycmd contributors2# encoding: utf-83#4# This file is part of ycmd.5#6# ycmd is free software: you can redistribute it and/or modify7# it under the terms of the GNU General Public License as published by8# the Free Software Foundation, either version 3 of the License, or9# (at your option) any later version.10#11# ycmd is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# GNU General Public License for more details.15#16# You should have received a copy of the GNU General Public License17# along with ycmd. If not, see <http://www.gnu.org/licenses/>.18from __future__ import absolute_import19from __future__ import unicode_literals20from __future__ import print_function21from __future__ import division22# Not installing aliases from python-future; it's unreliable and slow.23from builtins import * # noqa24import time25from hamcrest import ( assert_that,26 contains,27 contains_inanyorder,28 empty,29 has_entries,30 instance_of )31from nose.tools import eq_32from pprint import pformat33import requests34from ycmd.utils import ReadFile35from ycmd.completers.java.java_completer import NO_DOCUMENTATION_MESSAGE36from ycmd.tests.java import ( DEFAULT_PROJECT_DIR,37 PathToTestFile,38 SharedYcmd )39from ycmd.tests.test_utils import ( BuildRequest,40 ChunkMatcher,41 ErrorMatcher,42 LocationMatcher,43 WithRetry )44from mock import patch45from ycmd.completers.language_server import language_server_protocol as lsp46from ycmd import handlers47from ycmd.completers.language_server.language_server_completer import (48 ResponseTimeoutException,49 ResponseFailedException50)51@WithRetry52@SharedYcmd53def Subcommands_DefinedSubcommands_test( app ):54 subcommands_data = BuildRequest( completer_target = 'java' )55 eq_( sorted( [ 'FixIt',56 'Format',57 'GoToDeclaration',58 'GoToDefinition',59 'GoTo',60 'GetDoc',61 'GetType',62 'GoToReferences',63 'OpenProject',64 'OrganizeImports',65 'RefactorRename',66 'RestartServer' ] ),67 app.post_json( '/defined_subcommands', subcommands_data ).json )68def Subcommands_ServerNotReady_test():69 filepath = PathToTestFile( 'simple_eclipse_project',70 'src',71 'com',72 'test',73 'AbstractTestWidget.java' )74 completer = handlers._server_state.GetFiletypeCompleter( [ 'java' ] )75 @WithRetry76 @SharedYcmd77 @patch.object( completer, 'ServerIsReady', return_value = False )78 def Test( app, cmd, arguments, *args ):79 RunTest( app, {80 'description': 'Subcommand ' + cmd + ' handles server not ready',81 'request': {82 'command': cmd,83 'line_num': 1,84 'column_num': 1,85 'filepath': filepath,86 'arguments': arguments,87 },88 'expect': {89 'response': requests.codes.internal_server_error,90 'data': ErrorMatcher( RuntimeError,91 'Server is initializing. Please wait.' ),92 }93 } )94 yield Test, 'GoTo', []95 yield Test, 'GoToDeclaration', []96 yield Test, 'GoToDefinition', []97 yield Test, 'GoToReferences', []98 yield Test, 'GetType', []99 yield Test, 'GetDoc', []100 yield Test, 'FixIt', []101 yield Test, 'Format', []102 yield Test, 'OrganizeImports', []103 yield Test, 'RefactorRename', [ 'test' ]104def RunTest( app, test, contents = None ):105 if not contents:106 contents = ReadFile( test[ 'request' ][ 'filepath' ] )107 def CombineRequest( request, data ):108 kw = request109 request.update( data )110 return BuildRequest( **kw )111 # Because we aren't testing this command, we *always* ignore errors. This112 # is mainly because we (may) want to test scenarios where the completer113 # throws an exception and the easiest way to do that is to throw from114 # within the FlagsForFile function.115 app.post_json( '/event_notification',116 CombineRequest( test[ 'request' ], {117 'event_name': 'FileReadyToParse',118 'contents': contents,119 'filetype': 'java',120 } ),121 expect_errors = True )122 # We also ignore errors here, but then we check the response code123 # ourself. This is to allow testing of requests returning errors.124 expiry = time.time() + 10125 while True:126 try:127 response = app.post_json(128 '/run_completer_command',129 CombineRequest( test[ 'request' ], {130 'completer_target': 'filetype_default',131 'contents': contents,132 'filetype': 'java',133 'command_arguments': ( [ test[ 'request' ][ 'command' ] ]134 + test[ 'request' ].get( 'arguments', [] ) )135 } ),136 expect_errors = True137 )138 print( 'completer response: {0}'.format( pformat( response.json ) ) )139 eq_( response.status_code, test[ 'expect' ][ 'response' ] )140 assert_that( response.json, test[ 'expect' ][ 'data' ] )141 break142 except AssertionError:143 if time.time() > expiry:144 raise145 time.sleep( 0.25 )146@WithRetry147@SharedYcmd148def Subcommands_GetDoc_NoDoc_test( app ):149 filepath = PathToTestFile( 'simple_eclipse_project',150 'src',151 'com',152 'test',153 'AbstractTestWidget.java' )154 contents = ReadFile( filepath )155 event_data = BuildRequest( filepath = filepath,156 filetype = 'java',157 line_num = 18,158 column_num = 1,159 contents = contents,160 command_arguments = [ 'GetDoc' ],161 completer_target = 'filetype_default' )162 response = app.post_json( '/run_completer_command',163 event_data,164 expect_errors = True )165 eq_( response.status_code, requests.codes.internal_server_error )166 assert_that( response.json,167 ErrorMatcher( RuntimeError, NO_DOCUMENTATION_MESSAGE ) )168@WithRetry169@SharedYcmd170def Subcommands_GetDoc_Method_test( app ):171 filepath = PathToTestFile( 'simple_eclipse_project',172 'src',173 'com',174 'test',175 'AbstractTestWidget.java' )176 contents = ReadFile( filepath )177 event_data = BuildRequest( filepath = filepath,178 filetype = 'java',179 line_num = 17,180 column_num = 17,181 contents = contents,182 command_arguments = [ 'GetDoc' ],183 completer_target = 'filetype_default' )184 response = app.post_json( '/run_completer_command', event_data ).json185 eq_( response, {186 'detailed_info': 'Return runtime debugging info. Useful for finding the '187 'actual code which is useful.'188 } )189@WithRetry190@SharedYcmd191def Subcommands_GetDoc_Class_test( app ):192 filepath = PathToTestFile( 'simple_eclipse_project',193 'src',194 'com',195 'test',196 'TestWidgetImpl.java' )197 contents = ReadFile( filepath )198 event_data = BuildRequest( filepath = filepath,199 filetype = 'java',200 line_num = 11,201 column_num = 7,202 contents = contents,203 command_arguments = [ 'GetDoc' ],204 completer_target = 'filetype_default' )205 response = app.post_json( '/run_completer_command', event_data ).json206 eq_( response, {207 'detailed_info': 'This is the actual code that matters. This concrete '208 'implementation is the equivalent of the main function in '209 'other languages'210 } )211@WithRetry212@SharedYcmd213def Subcommands_GetType_NoKnownType_test( app ):214 filepath = PathToTestFile( 'simple_eclipse_project',215 'src',216 'com',217 'test',218 'TestWidgetImpl.java' )219 contents = ReadFile( filepath )220 event_data = BuildRequest( filepath = filepath,221 filetype = 'java',222 line_num = 28,223 column_num = 1,224 contents = contents,225 command_arguments = [ 'GetType' ],226 completer_target = 'filetype_default' )227 response = app.post_json( '/run_completer_command',228 event_data,229 expect_errors = True )230 eq_( response.status_code, requests.codes.internal_server_error )231 assert_that( response.json,232 ErrorMatcher( RuntimeError, 'Unknown type' ) )233@WithRetry234@SharedYcmd235def Subcommands_GetType_Class_test( app ):236 filepath = PathToTestFile( 'simple_eclipse_project',237 'src',238 'com',239 'test',240 'TestWidgetImpl.java' )241 contents = ReadFile( filepath )242 event_data = BuildRequest( filepath = filepath,243 filetype = 'java',244 line_num = 11,245 column_num = 7,246 contents = contents,247 command_arguments = [ 'GetType' ],248 completer_target = 'filetype_default' )249 response = app.post_json( '/run_completer_command', event_data ).json250 eq_( response, {251 'message': 'com.test.TestWidgetImpl'252 } )253@WithRetry254@SharedYcmd255def Subcommands_GetType_Constructor_test( app ):256 filepath = PathToTestFile( 'simple_eclipse_project',257 'src',258 'com',259 'test',260 'TestWidgetImpl.java' )261 contents = ReadFile( filepath )262 event_data = BuildRequest( filepath = filepath,263 filetype = 'java',264 line_num = 14,265 column_num = 3,266 contents = contents,267 command_arguments = [ 'GetType' ],268 completer_target = 'filetype_default' )269 response = app.post_json( '/run_completer_command', event_data ).json270 eq_( response, {271 'message': 'com.test.TestWidgetImpl.TestWidgetImpl(String info)'272 } )273@WithRetry274@SharedYcmd275def Subcommands_GetType_ClassMemberVariable_test( app ):276 filepath = PathToTestFile( 'simple_eclipse_project',277 'src',278 'com',279 'test',280 'TestWidgetImpl.java' )281 contents = ReadFile( filepath )282 event_data = BuildRequest( filepath = filepath,283 filetype = 'java',284 line_num = 12,285 column_num = 18,286 contents = contents,287 command_arguments = [ 'GetType' ],288 completer_target = 'filetype_default' )289 response = app.post_json( '/run_completer_command', event_data ).json290 eq_( response, {291 'message': 'String info'292 } )293@WithRetry294@SharedYcmd295def Subcommands_GetType_MethodArgument_test( app ):296 filepath = PathToTestFile( 'simple_eclipse_project',297 'src',298 'com',299 'test',300 'TestWidgetImpl.java' )301 contents = ReadFile( filepath )302 event_data = BuildRequest( filepath = filepath,303 filetype = 'java',304 line_num = 16,305 column_num = 17,306 contents = contents,307 command_arguments = [ 'GetType' ],308 completer_target = 'filetype_default' )309 response = app.post_json( '/run_completer_command', event_data ).json310 eq_( response, {311 'message': 'String info - '312 'com.test.TestWidgetImpl.TestWidgetImpl(String)'313 } )314@WithRetry315@SharedYcmd316def Subcommands_GetType_MethodVariable_test( app ):317 filepath = PathToTestFile( 'simple_eclipse_project',318 'src',319 'com',320 'test',321 'TestWidgetImpl.java' )322 contents = ReadFile( filepath )323 event_data = BuildRequest( filepath = filepath,324 filetype = 'java',325 line_num = 15,326 column_num = 9,327 contents = contents,328 command_arguments = [ 'GetType' ],329 completer_target = 'filetype_default' )330 response = app.post_json( '/run_completer_command', event_data ).json331 eq_( response, {332 'message': 'int a - '333 'com.test.TestWidgetImpl.TestWidgetImpl(String)'334 } )335@WithRetry336@SharedYcmd337def Subcommands_GetType_Method_test( app ):338 filepath = PathToTestFile( 'simple_eclipse_project',339 'src',340 'com',341 'test',342 'TestWidgetImpl.java' )343 contents = ReadFile( filepath )344 event_data = BuildRequest( filepath = filepath,345 filetype = 'java',346 line_num = 20,347 column_num = 15,348 contents = contents,349 command_arguments = [ 'GetType' ],350 completer_target = 'filetype_default' )351 response = app.post_json( '/run_completer_command', event_data ).json352 eq_( response, {353 'message': 'void com.test.TestWidgetImpl.doSomethingVaguelyUseful()'354 } )355@WithRetry356@SharedYcmd357def Subcommands_GetType_Unicode_test( app ):358 filepath = PathToTestFile( DEFAULT_PROJECT_DIR,359 'src',360 'com',361 'youcompleteme',362 'Test.java' )363 contents = ReadFile( filepath )364 app.post_json( '/event_notification',365 BuildRequest( filepath = filepath,366 filetype = 'java',367 contents = contents,368 event_name = 'FileReadyToParse' ) )369 event_data = BuildRequest( filepath = filepath,370 filetype = 'java',371 line_num = 7,372 column_num = 17,373 contents = contents,374 command_arguments = [ 'GetType' ],375 completer_target = 'filetype_default' )376 response = app.post_json( '/run_completer_command', event_data ).json377 eq_( response, {378 'message': 'String whåtawîdgé - com.youcompleteme.Test.doUnicødeTes()'379 } )380@WithRetry381@SharedYcmd382def Subcommands_GetType_LiteralValue_test( app ):383 filepath = PathToTestFile( 'simple_eclipse_project',384 'src',385 'com',386 'test',387 'TestWidgetImpl.java' )388 contents = ReadFile( filepath )389 event_data = BuildRequest( filepath = filepath,390 filetype = 'java',391 line_num = 15,392 column_num = 13,393 contents = contents,394 command_arguments = [ 'GetType' ],395 completer_target = 'filetype_default' )396 response = app.post_json( '/run_completer_command',397 event_data,398 expect_errors = True )399 eq_( response.status_code, requests.codes.internal_server_error )400 assert_that( response.json,401 ErrorMatcher( RuntimeError, 'Unknown type' ) )402@WithRetry403@SharedYcmd404def Subcommands_GoTo_NoLocation_test( app ):405 filepath = PathToTestFile( 'simple_eclipse_project',406 'src',407 'com',408 'test',409 'AbstractTestWidget.java' )410 contents = ReadFile( filepath )411 event_data = BuildRequest( filepath = filepath,412 filetype = 'java',413 line_num = 18,414 column_num = 1,415 contents = contents,416 command_arguments = [ 'GoTo' ],417 completer_target = 'filetype_default' )418 response = app.post_json( '/run_completer_command',419 event_data,420 expect_errors = True )421 eq_( response.status_code, requests.codes.internal_server_error )422 assert_that( response.json,423 ErrorMatcher( RuntimeError, 'Cannot jump to location' ) )424@WithRetry425@SharedYcmd426def Subcommands_GoToReferences_NoReferences_test( app ):427 filepath = PathToTestFile( 'simple_eclipse_project',428 'src',429 'com',430 'test',431 'AbstractTestWidget.java' )432 contents = ReadFile( filepath )433 event_data = BuildRequest( filepath = filepath,434 filetype = 'java',435 line_num = 18,436 column_num = 1,437 contents = contents,438 command_arguments = [ 'GoToReferences' ],439 completer_target = 'filetype_default' )440 response = app.post_json( '/run_completer_command',441 event_data,442 expect_errors = True )443 eq_( response.status_code, requests.codes.internal_server_error )444 assert_that( response.json,445 ErrorMatcher( RuntimeError,446 'Cannot jump to location' ) )447@WithRetry448@SharedYcmd449def Subcommands_GoToReferences_test( app ):450 filepath = PathToTestFile( 'simple_eclipse_project',451 'src',452 'com',453 'test',454 'AbstractTestWidget.java' )455 contents = ReadFile( filepath )456 event_data = BuildRequest( filepath = filepath,457 filetype = 'java',458 line_num = 10,459 column_num = 15,460 contents = contents,461 command_arguments = [ 'GoToReferences' ],462 completer_target = 'filetype_default' )463 response = app.post_json( '/run_completer_command', event_data ).json464 eq_( response, [465 {466 'filepath': PathToTestFile( 'simple_eclipse_project',467 'src',468 'com',469 'test',470 'TestFactory.java' ),471 'column_num': 9,472 'description': " w.doSomethingVaguelyUseful();",473 'line_num': 28474 },475 {476 'filepath': PathToTestFile( 'simple_eclipse_project',477 'src',478 'com',479 'test',480 'TestLauncher.java' ),481 'column_num': 11,482 'description': " w.doSomethingVaguelyUseful();",483 'line_num': 32484 } ] )485@WithRetry486@SharedYcmd487def Subcommands_RefactorRename_Simple_test( app ):488 filepath = PathToTestFile( 'simple_eclipse_project',489 'src',490 'com',491 'test',492 'TestLauncher.java' )493 RunTest( app, {494 'description': 'RefactorRename works within a single scope/file',495 'request': {496 'command': 'RefactorRename',497 'arguments': [ 'renamed_l' ],498 'filepath': filepath,499 'line_num': 28,500 'column_num': 5,501 },502 'expect': {503 'response': requests.codes.ok,504 'data': has_entries( {505 'fixits': contains( has_entries( {506 'chunks': contains(507 ChunkMatcher( 'renamed_l',508 LocationMatcher( filepath, 27, 18 ),509 LocationMatcher( filepath, 27, 19 ) ),510 ChunkMatcher( 'renamed_l',511 LocationMatcher( filepath, 28, 5 ),512 LocationMatcher( filepath, 28, 6 ) ),513 ),514 'location': LocationMatcher( filepath, 28, 5 )515 } ) )516 } )517 }518 } )519@WithRetry520@SharedYcmd521def Subcommands_RefactorRename_MultipleFiles_test( app ):522 AbstractTestWidget = PathToTestFile( 'simple_eclipse_project',523 'src',524 'com',525 'test',526 'AbstractTestWidget.java' )527 TestFactory = PathToTestFile( 'simple_eclipse_project',528 'src',529 'com',530 'test',531 'TestFactory.java' )532 TestLauncher = PathToTestFile( 'simple_eclipse_project',533 'src',534 'com',535 'test',536 'TestLauncher.java' )537 TestWidgetImpl = PathToTestFile( 'simple_eclipse_project',538 'src',539 'com',540 'test',541 'TestWidgetImpl.java' )542 RunTest( app, {543 'description': 'RefactorRename works across files',544 'request': {545 'command': 'RefactorRename',546 'arguments': [ 'a-quite-long-string' ],547 'filepath': TestLauncher,548 'line_num': 32,549 'column_num': 13,550 },551 'expect': {552 'response': requests.codes.ok,553 'data': has_entries( {554 'fixits': contains( has_entries( {555 'chunks': contains(556 ChunkMatcher(557 'a-quite-long-string',558 LocationMatcher( AbstractTestWidget, 10, 15 ),559 LocationMatcher( AbstractTestWidget, 10, 39 ) ),560 ChunkMatcher(561 'a-quite-long-string',562 LocationMatcher( TestFactory, 28, 9 ),563 LocationMatcher( TestFactory, 28, 33 ) ),564 ChunkMatcher(565 'a-quite-long-string',566 LocationMatcher( TestLauncher, 32, 11 ),567 LocationMatcher( TestLauncher, 32, 35 ) ),568 ChunkMatcher(569 'a-quite-long-string',570 LocationMatcher( TestWidgetImpl, 20, 15 ),571 LocationMatcher( TestWidgetImpl, 20, 39 ) ),572 ),573 'location': LocationMatcher( TestLauncher, 32, 13 )574 } ) )575 } )576 }577 } )578@WithRetry579@SharedYcmd580def Subcommands_RefactorRename_Missing_New_Name_test( app ):581 filepath = PathToTestFile( 'simple_eclipse_project',582 'src',583 'com',584 'test',585 'TestLauncher.java' )586 RunTest( app, {587 'description': 'RefactorRename raises an error without new name',588 'request': {589 'command': 'RefactorRename',590 'line_num': 15,591 'column_num': 5,592 'filepath': filepath,593 },594 'expect': {595 'response': requests.codes.internal_server_error,596 'data': ErrorMatcher( ValueError,597 'Please specify a new name to rename it to.\n'598 'Usage: RefactorRename <new name>' ),599 }600 } )601@WithRetry602@SharedYcmd603def Subcommands_RefactorRename_Unicode_test( app ):604 filepath = PathToTestFile( 'simple_eclipse_project',605 'src',606 'com',607 'youcompleteme',608 'Test.java' )609 RunTest( app, {610 'description': 'Rename works for unicode identifier',611 'request': {612 'command': 'RefactorRename',613 'arguments': [ 'shorter' ],614 'line_num': 7,615 'column_num': 21,616 'filepath': filepath,617 },618 'expect': {619 'response': requests.codes.ok,620 'data': has_entries( {621 'fixits': contains( has_entries( {622 'chunks': contains(623 ChunkMatcher(624 'shorter',625 LocationMatcher( filepath, 7, 12 ),626 LocationMatcher( filepath, 7, 25 )627 ),628 ChunkMatcher(629 'shorter',630 LocationMatcher( filepath, 8, 12 ),631 LocationMatcher( filepath, 8, 25 )632 ),633 ),634 } ) ),635 } ),636 },637 } )638@WithRetry639@SharedYcmd640def RunFixItTest( app, description, filepath, line, col, fixits_for_line ):641 RunTest( app, {642 'description': description,643 'request': {644 'command': 'FixIt',645 'line_num': line,646 'column_num': col,647 'filepath': filepath,648 },649 'expect': {650 'response': requests.codes.ok,651 'data': fixits_for_line,652 }653 } )654def Subcommands_FixIt_SingleDiag_MultipleOption_Insertion_test():655 filepath = PathToTestFile( 'simple_eclipse_project',656 'src',657 'com',658 'test',659 'TestFactory.java' )660 # Note: The code actions for creating variables are really not very useful.661 # The import is, however, and the FixIt almost exactly matches the one662 # supplied when completing 'CUTHBERT' and auto-inserting.663 fixits_for_line = has_entries( {664 'fixits': contains_inanyorder(665 has_entries( {666 'text': "Import 'Wibble' (com.test.wobble)",667 'chunks': contains(668 # When doing an import, eclipse likes to add two newlines669 # after the package. I suppose this is config in real eclipse,670 # but there's no mechanism to configure this in jdtl afaik.671 ChunkMatcher( '\n\n',672 LocationMatcher( filepath, 1, 18 ),673 LocationMatcher( filepath, 1, 18 ) ),674 # OK, so it inserts the import675 ChunkMatcher( 'import com.test.wobble.Wibble;',676 LocationMatcher( filepath, 1, 18 ),677 LocationMatcher( filepath, 1, 18 ) ),678 # More newlines. Who doesn't like newlines?!679 ChunkMatcher( '\n\n',680 LocationMatcher( filepath, 1, 18 ),681 LocationMatcher( filepath, 1, 18 ) ),682 # For reasons known only to the eclipse JDT developers, it683 # seems to want to delete the lines after the package first.684 ChunkMatcher( '',685 LocationMatcher( filepath, 1, 18 ),686 LocationMatcher( filepath, 3, 1 ) ),687 ),688 } ),689 has_entries( {690 'text': "Create field 'Wibble'",691 'chunks': contains (692 ChunkMatcher( '\n\n',693 LocationMatcher( filepath, 16, 4 ),694 LocationMatcher( filepath, 16, 4 ) ),695 ChunkMatcher( 'private Object Wibble;',696 LocationMatcher( filepath, 16, 4 ),697 LocationMatcher( filepath, 16, 4 ) ),698 ),699 } ),700 has_entries( {701 'text': "Create constant 'Wibble'",702 'chunks': contains (703 ChunkMatcher( '\n\n',704 LocationMatcher( filepath, 16, 4 ),705 LocationMatcher( filepath, 16, 4 ) ),706 ChunkMatcher( 'private static final String Wibble = null;',707 LocationMatcher( filepath, 16, 4 ),708 LocationMatcher( filepath, 16, 4 ) ),709 ),710 } ),711 has_entries( {712 'text': "Create parameter 'Wibble'",713 'chunks': contains (714 ChunkMatcher( ', ',715 LocationMatcher( filepath, 18, 32 ),716 LocationMatcher( filepath, 18, 32 ) ),717 ChunkMatcher( 'Object Wibble',718 LocationMatcher( filepath, 18, 32 ),719 LocationMatcher( filepath, 18, 32 ) ),720 ),721 } ),722 has_entries( {723 'text': "Create local variable 'Wibble'",724 'chunks': contains (725 ChunkMatcher( 'Object Wibble;',726 LocationMatcher( filepath, 19, 5 ),727 LocationMatcher( filepath, 19, 5 ) ),728 ChunkMatcher( '\n ',729 LocationMatcher( filepath, 19, 5 ),730 LocationMatcher( filepath, 19, 5 ) ),731 ),732 } ),733 )734 } )735 yield ( RunFixItTest, 'FixIt works at the first char of the line',736 filepath, 19, 1, fixits_for_line )737 yield ( RunFixItTest, 'FixIt works at the begin of the range of the diag.',738 filepath, 19, 15, fixits_for_line )739 yield ( RunFixItTest, 'FixIt works at the end of the range of the diag.',740 filepath, 19, 20, fixits_for_line )741 yield ( RunFixItTest, 'FixIt works at the end of line',742 filepath, 19, 34, fixits_for_line )743def Subcommands_FixIt_SingleDiag_SingleOption_Modify_test():744 filepath = PathToTestFile( 'simple_eclipse_project',745 'src',746 'com',747 'test',748 'TestFactory.java' )749 # TODO: As there is only one option, we automatically apply it.750 # In Java case this might not be the right thing. It's a code assist, not a751 # FixIt really. Perhaps we should change the client to always ask for752 # confirmation?753 fixits = has_entries( {754 'fixits': contains(755 has_entries( {756 'text': "Change type of 'test' to 'boolean'",757 'chunks': contains(758 # For some reason, eclipse returns modifies as deletes + adds,759 # although overlapping ranges aren't allowed.760 ChunkMatcher( 'boolean',761 LocationMatcher( filepath, 14, 12 ),762 LocationMatcher( filepath, 14, 12 ) ),763 ChunkMatcher( '',764 LocationMatcher( filepath, 14, 12 ),765 LocationMatcher( filepath, 14, 15 ) ),766 ),767 } ),768 )769 } )770 yield ( RunFixItTest, 'FixIts can change lines as well as add them',771 filepath, 27, 12, fixits )772def Subcommands_FixIt_SingleDiag_MultiOption_Delete_test():773 filepath = PathToTestFile( 'simple_eclipse_project',774 'src',775 'com',776 'test',777 'TestFactory.java' )778 fixits = has_entries( {779 'fixits': contains_inanyorder(780 has_entries( {781 'text': "Remove 'testString', keep assignments with side effects",782 'chunks': contains(783 ChunkMatcher( '',784 LocationMatcher( filepath, 14, 21 ),785 LocationMatcher( filepath, 15, 5 ) ),786 ChunkMatcher( '',787 LocationMatcher( filepath, 15, 5 ),788 LocationMatcher( filepath, 15, 30 ) ),789 ),790 } ),791 has_entries( {792 'text': "Create getter and setter for 'testString'...",793 # The edit reported for this is juge and uninteresting really. Manual794 # testing can show that it works. This test is really about the previous795 # FixIt (and nonetheless, the previous tests ensure that we correctly796 # populate the chunks list; the contents all come from jdt.ls)797 'chunks': instance_of( list )798 } ),799 )800 } )801 yield ( RunFixItTest, 'FixIts can change lines as well as add them',802 filepath, 15, 29, fixits )803def Subcommands_FixIt_MultipleDiags_test():804 filepath = PathToTestFile( 'simple_eclipse_project',805 'src',806 'com',807 'test',808 'TestFactory.java' )809 fixits = has_entries( {810 'fixits': contains_inanyorder(811 has_entries( {812 'text': "Change type of 'test' to 'boolean'",813 'chunks': contains(814 # For some reason, eclipse returns modifies as deletes + adds,815 # although overlapping ranges aren't allowed.816 ChunkMatcher( 'boolean',817 LocationMatcher( filepath, 14, 12 ),818 LocationMatcher( filepath, 14, 12 ) ),819 ChunkMatcher( '',820 LocationMatcher( filepath, 14, 12 ),821 LocationMatcher( filepath, 14, 15 ) ),822 ),823 } ),824 has_entries( {825 'text': "Remove argument to match 'doSomethingVaguelyUseful()'",826 'chunks': contains(827 ChunkMatcher( '',828 LocationMatcher( filepath, 30, 48 ),829 LocationMatcher( filepath, 30, 50 ) ),830 ),831 } ),832 has_entries( {833 'text': "Change method 'doSomethingVaguelyUseful()': Add parameter "834 "'Bar'",835 # Again, this produces quite a lot of fussy little changes (that836 # actually lead to broken code, but we can't really help that), and837 # having them in this test would just be brittle without proving838 # anything about our code839 'chunks': instance_of( list ),840 } ),841 has_entries( {842 'text': "Create method 'doSomethingVaguelyUseful(Bar)' in type "843 "'AbstractTestWidget'",844 # Again, this produces quite a lot of fussy little changes (that845 # actually lead to broken code, but we can't really help that), and846 # having them in this test would just be brittle without proving847 # anything about our code848 'chunks': instance_of( list ),849 } ),850 )851 } )852 yield ( RunFixItTest, 'diags are merged in FixIt options - start of line',853 filepath, 30, 1, fixits )854 yield ( RunFixItTest, 'diags are merged in FixIt options - start of diag 1',855 filepath, 30, 10, fixits )856 yield ( RunFixItTest, 'diags are merged in FixIt options - end of diag 1',857 filepath, 30, 15, fixits )858 yield ( RunFixItTest, 'diags are merged in FixIt options - start of diag 2',859 filepath, 30, 23, fixits )860 yield ( RunFixItTest, 'diags are merged in FixIt options - end of diag 2',861 filepath, 30, 46, fixits )862 yield ( RunFixItTest, 'diags are merged in FixIt options - end of line',863 filepath, 30, 55, fixits )864def Subcommands_FixIt_NoDiagnostics_test():865 filepath = PathToTestFile( 'simple_eclipse_project',866 'src',867 'com',868 'test',869 'TestFactory.java' )870 yield ( RunFixItTest, "no FixIts means you gotta code it yo' self",871 filepath, 1, 1, has_entries( { 'fixits': empty() } ) )872def Subcommands_FixIt_Unicode_test():873 filepath = PathToTestFile( 'simple_eclipse_project',874 'src',875 'com',876 'youcompleteme',877 'Test.java' )878 fixits = has_entries( {879 'fixits': contains_inanyorder(880 has_entries( {881 'text': "Remove argument to match 'doUnicødeTes()'",882 'chunks': contains(883 ChunkMatcher( '',884 LocationMatcher( filepath, 13, 24 ),885 LocationMatcher( filepath, 13, 29 ) ),886 ),887 } ),888 has_entries( {889 'text': "Change method 'doUnicødeTes()': Add parameter 'String'",890 'chunks': contains(891 ChunkMatcher( 'String test2',892 LocationMatcher( filepath, 6, 31 ),893 LocationMatcher( filepath, 6, 31 ) ),894 ),895 } ),896 has_entries( {897 'text': "Create method 'doUnicødeTes(String)'",898 'chunks': contains(899 ChunkMatcher( 'private void doUnicødeTes(String test2) {\n}',900 LocationMatcher( filepath, 20, 3 ),901 LocationMatcher( filepath, 20, 3 ) ),902 ChunkMatcher( '\n\n\n',903 LocationMatcher( filepath, 20, 3 ),904 LocationMatcher( filepath, 20, 3 ) ),905 ),906 } ),907 )908 } )909 yield ( RunFixItTest, 'FixIts and diagnostics work with unicode strings',910 filepath, 13, 1, fixits )911@WithRetry912@SharedYcmd913def Subcommands_FixIt_InvalidURI_test( app ):914 filepath = PathToTestFile( 'simple_eclipse_project',915 'src',916 'com',917 'test',918 'TestFactory.java' )919 fixits = has_entries( {920 'fixits': contains(921 has_entries( {922 'text': "Change type of 'test' to 'boolean'",923 'chunks': contains(924 # For some reason, eclipse returns modifies as deletes + adds,925 # although overlapping ranges aren't allowed.926 ChunkMatcher( 'boolean',927 LocationMatcher( '', 14, 12 ),928 LocationMatcher( '', 14, 12 ) ),929 ChunkMatcher( '',930 LocationMatcher( '', 14, 12 ),931 LocationMatcher( '', 14, 15 ) ),932 ),933 } ),934 )935 } )936 contents = ReadFile( filepath )937 # Wait for jdt.ls to have parsed the file and returned some diagnostics938 for tries in range( 0, 60 ):939 results = app.post_json( '/event_notification',940 BuildRequest( filepath = filepath,941 filetype = 'java',942 contents = contents,943 event_name = 'FileReadyToParse' ) )944 if results.json:945 break946 time.sleep( .25 )947 with patch(948 'ycmd.completers.language_server.language_server_protocol.UriToFilePath',949 side_effect = lsp.InvalidUriException ):950 RunTest( app, {951 'description': 'Invalid URIs do not make us crash',952 'request': {953 'command': 'FixIt',954 'line_num': 27,955 'column_num': 12,956 'filepath': filepath,957 },958 'expect': {959 'response': requests.codes.ok,960 'data': fixits,961 }962 } )963@WithRetry964@SharedYcmd965def Subcommands_Format_WholeFile_Spaces_test( app ):966 filepath = PathToTestFile( 'simple_eclipse_project',967 'src',968 'com',969 'youcompleteme',970 'Test.java' )971 RunTest( app, {972 'description': 'Formatting is applied on the whole file '973 'with tabs composed of 4 spaces',974 'request': {975 'command': 'Format',976 'filepath': filepath,977 'options': {978 'tab_size': 4,979 'insert_spaces': True980 }981 },982 'expect': {983 'response': requests.codes.ok,984 'data': has_entries( {985 'fixits': contains( has_entries( {986 'chunks': contains(987 ChunkMatcher( '\n ',988 LocationMatcher( filepath, 3, 20 ),989 LocationMatcher( filepath, 4, 3 ) ),990 ChunkMatcher( '\n\n ',991 LocationMatcher( filepath, 4, 22 ),992 LocationMatcher( filepath, 6, 3 ) ),993 ChunkMatcher( '\n ',994 LocationMatcher( filepath, 6, 34 ),995 LocationMatcher( filepath, 7, 5 ) ),996 ChunkMatcher( '\n ',997 LocationMatcher( filepath, 7, 35 ),998 LocationMatcher( filepath, 8, 5 ) ),999 ChunkMatcher( '',1000 LocationMatcher( filepath, 8, 25 ),1001 LocationMatcher( filepath, 8, 26 ) ),1002 ChunkMatcher( '\n ',1003 LocationMatcher( filepath, 8, 27 ),1004 LocationMatcher( filepath, 9, 3 ) ),1005 ChunkMatcher( '\n\n ',1006 LocationMatcher( filepath, 9, 4 ),1007 LocationMatcher( filepath, 11, 3 ) ),1008 ChunkMatcher( '\n ',1009 LocationMatcher( filepath, 11, 29 ),1010 LocationMatcher( filepath, 12, 5 ) ),1011 ChunkMatcher( '\n ',1012 LocationMatcher( filepath, 12, 26 ),1013 LocationMatcher( filepath, 13, 5 ) ),1014 ChunkMatcher( '',1015 LocationMatcher( filepath, 13, 24 ),1016 LocationMatcher( filepath, 13, 25 ) ),1017 ChunkMatcher( '',1018 LocationMatcher( filepath, 13, 29 ),1019 LocationMatcher( filepath, 13, 30 ) ),1020 ChunkMatcher( '\n\n ',1021 LocationMatcher( filepath, 13, 32 ),1022 LocationMatcher( filepath, 15, 5 ) ),1023 ChunkMatcher( '\n ',1024 LocationMatcher( filepath, 15, 58 ),1025 LocationMatcher( filepath, 16, 5 ) ),1026 ChunkMatcher( '\n ',1027 LocationMatcher( filepath, 16, 42 ),1028 LocationMatcher( filepath, 17, 3 ) ),1029 ChunkMatcher( '\n\n ',1030 LocationMatcher( filepath, 17, 4 ),1031 LocationMatcher( filepath, 20, 3 ) ),1032 ChunkMatcher( '\n ',1033 LocationMatcher( filepath, 20, 28 ),1034 LocationMatcher( filepath, 21, 5 ) ),1035 ChunkMatcher( '\n ',1036 LocationMatcher( filepath, 21, 28 ),1037 LocationMatcher( filepath, 22, 5 ) ),1038 ChunkMatcher( '\n ',1039 LocationMatcher( filepath, 22, 30 ),1040 LocationMatcher( filepath, 23, 5 ) ),1041 ChunkMatcher( '\n ',1042 LocationMatcher( filepath, 23, 23 ),1043 LocationMatcher( filepath, 24, 5 ) ),1044 ChunkMatcher( '\n ',1045 LocationMatcher( filepath, 24, 27 ),1046 LocationMatcher( filepath, 25, 3 ) ),1047 )1048 } ) )1049 } )1050 }1051 } )1052@WithRetry1053@SharedYcmd1054def Subcommands_Format_WholeFile_Tabs_test( app ):1055 filepath = PathToTestFile( 'simple_eclipse_project',1056 'src',1057 'com',1058 'youcompleteme',1059 'Test.java' )1060 RunTest( app, {1061 'description': 'Formatting is applied on the whole file '1062 'with tabs composed of 2 spaces',1063 'request': {1064 'command': 'Format',1065 'filepath': filepath,1066 'options': {1067 'tab_size': 4,1068 'insert_spaces': False1069 }1070 },1071 'expect': {1072 'response': requests.codes.ok,1073 'data': has_entries( {1074 'fixits': contains( has_entries( {1075 'chunks': contains(1076 ChunkMatcher( '\n\t',1077 LocationMatcher( filepath, 3, 20 ),1078 LocationMatcher( filepath, 4, 3 ) ),1079 ChunkMatcher( '\n\n\t',1080 LocationMatcher( filepath, 4, 22 ),1081 LocationMatcher( filepath, 6, 3 ) ),1082 ChunkMatcher( '\n\t\t',1083 LocationMatcher( filepath, 6, 34 ),1084 LocationMatcher( filepath, 7, 5 ) ),1085 ChunkMatcher( '\n\t\t',1086 LocationMatcher( filepath, 7, 35 ),1087 LocationMatcher( filepath, 8, 5 ) ),1088 ChunkMatcher( '',1089 LocationMatcher( filepath, 8, 25 ),1090 LocationMatcher( filepath, 8, 26 ) ),1091 ChunkMatcher( '\n\t',1092 LocationMatcher( filepath, 8, 27 ),1093 LocationMatcher( filepath, 9, 3 ) ),1094 ChunkMatcher( '\n\n\t',1095 LocationMatcher( filepath, 9, 4 ),1096 LocationMatcher( filepath, 11, 3 ) ),1097 ChunkMatcher( '\n\t\t',1098 LocationMatcher( filepath, 11, 29 ),1099 LocationMatcher( filepath, 12, 5 ) ),1100 ChunkMatcher( '\n\t\t',1101 LocationMatcher( filepath, 12, 26 ),1102 LocationMatcher( filepath, 13, 5 ) ),1103 ChunkMatcher( '',1104 LocationMatcher( filepath, 13, 24 ),1105 LocationMatcher( filepath, 13, 25 ) ),1106 ChunkMatcher( '',1107 LocationMatcher( filepath, 13, 29 ),1108 LocationMatcher( filepath, 13, 30 ) ),1109 ChunkMatcher( '\n\n\t\t',1110 LocationMatcher( filepath, 13, 32 ),1111 LocationMatcher( filepath, 15, 5 ) ),1112 ChunkMatcher( '\n\t\t',1113 LocationMatcher( filepath, 15, 58 ),1114 LocationMatcher( filepath, 16, 5 ) ),1115 ChunkMatcher( '\n\t',1116 LocationMatcher( filepath, 16, 42 ),1117 LocationMatcher( filepath, 17, 3 ) ),1118 ChunkMatcher( '\n\n\t',1119 LocationMatcher( filepath, 17, 4 ),1120 LocationMatcher( filepath, 20, 3 ) ),1121 ChunkMatcher( '\n\t\t',1122 LocationMatcher( filepath, 20, 28 ),1123 LocationMatcher( filepath, 21, 5 ) ),1124 ChunkMatcher( '\n\t\t',1125 LocationMatcher( filepath, 21, 28 ),1126 LocationMatcher( filepath, 22, 5 ) ),1127 ChunkMatcher( '\n\t\t',1128 LocationMatcher( filepath, 22, 30 ),1129 LocationMatcher( filepath, 23, 5 ) ),1130 ChunkMatcher( '\n\t\t',1131 LocationMatcher( filepath, 23, 23 ),1132 LocationMatcher( filepath, 24, 5 ) ),1133 ChunkMatcher( '\n\t',1134 LocationMatcher( filepath, 24, 27 ),1135 LocationMatcher( filepath, 25, 3 ) ),1136 )1137 } ) )1138 } )1139 }1140 } )1141@WithRetry1142@SharedYcmd1143def Subcommands_Format_Range_Spaces_test( app ):1144 filepath = PathToTestFile( 'simple_eclipse_project',1145 'src',1146 'com',1147 'youcompleteme',1148 'Test.java' )1149 RunTest( app, {1150 'description': 'Formatting is applied on some part of the file '1151 'with tabs composed of 4 spaces',1152 'request': {1153 'command': 'Format',1154 'filepath': filepath,1155 'range': {1156 'start': {1157 'line_num': 20,1158 'column_num': 1,1159 },1160 'end': {1161 'line_num': 25,1162 'column_num': 41163 }1164 },1165 'options': {1166 'tab_size': 4,1167 'insert_spaces': True1168 }1169 },1170 'expect': {1171 'response': requests.codes.ok,1172 'data': has_entries( {1173 'fixits': contains( has_entries( {1174 'chunks': contains(1175 ChunkMatcher( ' ',1176 LocationMatcher( filepath, 20, 1 ),1177 LocationMatcher( filepath, 20, 3 ) ),1178 ChunkMatcher( '\n ',1179 LocationMatcher( filepath, 20, 28 ),1180 LocationMatcher( filepath, 21, 5 ) ),1181 ChunkMatcher( '\n ',1182 LocationMatcher( filepath, 21, 28 ),1183 LocationMatcher( filepath, 22, 5 ) ),1184 ChunkMatcher( '\n ',1185 LocationMatcher( filepath, 22, 30 ),1186 LocationMatcher( filepath, 23, 5 ) ),1187 ChunkMatcher( '\n ',1188 LocationMatcher( filepath, 23, 23 ),1189 LocationMatcher( filepath, 24, 5 ) ),1190 ChunkMatcher( '\n ',1191 LocationMatcher( filepath, 24, 27 ),1192 LocationMatcher( filepath, 25, 3 ) ),1193 )1194 } ) )1195 } )1196 }1197 } )1198@WithRetry1199@SharedYcmd1200def Subcommands_Format_Range_Tabs_test( app ):1201 filepath = PathToTestFile( 'simple_eclipse_project',1202 'src',1203 'com',1204 'youcompleteme',1205 'Test.java' )1206 RunTest( app, {1207 'description': 'Formatting is applied on some part of the file '1208 'with tabs instead of spaces',1209 'request': {1210 'command': 'Format',1211 'filepath': filepath,1212 'range': {1213 'start': {1214 'line_num': 20,1215 'column_num': 1,1216 },1217 'end': {1218 'line_num': 25,1219 'column_num': 41220 }1221 },1222 'options': {1223 'tab_size': 4,1224 'insert_spaces': False1225 }1226 },1227 'expect': {1228 'response': requests.codes.ok,1229 'data': has_entries( {1230 'fixits': contains( has_entries( {1231 'chunks': contains(1232 ChunkMatcher( '\t',1233 LocationMatcher( filepath, 20, 1 ),1234 LocationMatcher( filepath, 20, 3 ) ),1235 ChunkMatcher( '\n\t\t',1236 LocationMatcher( filepath, 20, 28 ),1237 LocationMatcher( filepath, 21, 5 ) ),1238 ChunkMatcher( '\n\t\t',1239 LocationMatcher( filepath, 21, 28 ),1240 LocationMatcher( filepath, 22, 5 ) ),1241 ChunkMatcher( '\n\t\t',1242 LocationMatcher( filepath, 22, 30 ),1243 LocationMatcher( filepath, 23, 5 ) ),1244 ChunkMatcher( '\n\t\t',1245 LocationMatcher( filepath, 23, 23 ),1246 LocationMatcher( filepath, 24, 5 ) ),1247 ChunkMatcher( '\n\t',1248 LocationMatcher( filepath, 24, 27 ),1249 LocationMatcher( filepath, 25, 3 ) ),1250 )1251 } ) )1252 } )1253 }1254 } )1255@WithRetry1256@SharedYcmd1257def RunGoToTest( app, description, filepath, line, col, cmd, goto_response ):1258 RunTest( app, {1259 'description': description,1260 'request': {1261 'command': cmd,1262 'line_num': line,1263 'column_num': col,1264 'filepath': filepath1265 },1266 'expect': {1267 'response': requests.codes.ok,1268 'data': goto_response,1269 }1270 } )1271def Subcommands_GoTo_test():1272 filepath = PathToTestFile( 'simple_eclipse_project',1273 'src',1274 'com',1275 'test',1276 'TestLauncher.java' )1277 unicode_filepath = PathToTestFile( 'simple_eclipse_project',1278 'src',1279 'com',1280 'youcompleteme',1281 'Test.java' )1282 tests = [1283 # Member function local variable1284 { 'request': { 'line': 28, 'col': 5, 'filepath': filepath },1285 'response': { 'line_num': 27, 'column_num': 18, 'filepath': filepath },1286 'description': 'GoTo works for memeber local variable' },1287 # Member variable1288 { 'request': { 'line': 22, 'col': 7, 'filepath': filepath },1289 'response': { 'line_num': 8, 'column_num': 16, 'filepath': filepath },1290 'description': 'GoTo works for memeber variable' },1291 # Method1292 { 'request': { 'line': 28, 'col': 7, 'filepath': filepath },1293 'response': { 'line_num': 21, 'column_num': 16, 'filepath': filepath },1294 'description': 'GoTo works for method' },1295 # Constructor1296 { 'request': { 'line': 38, 'col': 26, 'filepath': filepath },1297 'response': { 'line_num': 10, 'column_num': 10, 'filepath': filepath },1298 'description': 'GoTo works for jumping to constructor' },1299 # Jump to self - main()1300 { 'request': { 'line': 26, 'col': 22, 'filepath': filepath },1301 'response': { 'line_num': 26, 'column_num': 22, 'filepath': filepath },1302 'description': 'GoTo works for jumping to the same position' },1303 # Static method1304 { 'request': { 'line': 37, 'col': 11, 'filepath': filepath },1305 'response': { 'line_num': 13, 'column_num': 21, 'filepath': filepath },1306 'description': 'GoTo works for static method' },1307 # Static variable1308 { 'request': { 'line': 14, 'col': 11, 'filepath': filepath },1309 'response': { 'line_num': 12, 'column_num': 21, 'filepath': filepath },1310 'description': 'GoTo works for static variable' },1311 # Argument variable1312 { 'request': { 'line': 23, 'col': 5, 'filepath': filepath },1313 'response': { 'line_num': 21, 'column_num': 32, 'filepath': filepath },1314 'description': 'GoTo works for argument variable' },1315 # Class1316 { 'request': { 'line': 27, 'col': 10, 'filepath': filepath },1317 'response': { 'line_num': 6, 'column_num': 7, 'filepath': filepath },1318 'description': 'GoTo works for jumping to class declaration' },1319 # Unicode1320 { 'request': { 'line': 8, 'col': 12, 'filepath': unicode_filepath },1321 'response': { 'line_num': 7, 'column_num': 12, 'filepath':1322 unicode_filepath },1323 'description': 'GoTo works for unicode identifiers' }1324 ]1325 for command in [ 'GoTo', 'GoToDefinition', 'GoToDeclaration' ]:1326 for test in tests:1327 yield ( RunGoToTest,1328 test[ 'description' ],1329 test[ 'request' ][ 'filepath' ],1330 test[ 'request' ][ 'line' ],1331 test[ 'request' ][ 'col' ],1332 command,1333 has_entries( test[ 'response' ] ) )1334@WithRetry1335@SharedYcmd1336def Subcommands_OrganizeImports_test( app ):1337 filepath = PathToTestFile( 'simple_eclipse_project',1338 'src',1339 'com',1340 'test',1341 'TestLauncher.java' )1342 RunTest( app, {1343 'description': 'Imports are resolved and sorted, '1344 'and unused ones are removed',1345 'request': {1346 'command': 'OrganizeImports',1347 'filepath': filepath1348 },1349 'expect': {1350 'response': requests.codes.ok,1351 'data': has_entries( {1352 'fixits': contains( has_entries( {1353 'chunks': contains(1354 ChunkMatcher( 'import com.youcompleteme.Test;',1355 LocationMatcher( filepath, 3, 1 ),1356 LocationMatcher( filepath, 3, 1 ) ),1357 ChunkMatcher( '\n',1358 LocationMatcher( filepath, 3, 1 ),1359 LocationMatcher( filepath, 3, 1 ) ),1360 ChunkMatcher( '',1361 LocationMatcher( filepath, 3, 39 ),1362 LocationMatcher( filepath, 4, 54 ) ),1363 )1364 } ) )1365 } )1366 }1367 } )1368@WithRetry1369@SharedYcmd1370@patch( 'ycmd.completers.language_server.language_server_completer.'1371 'REQUEST_TIMEOUT_COMMAND',1372 5 )1373def Subcommands_RequestTimeout_test( app ):1374 filepath = PathToTestFile( 'simple_eclipse_project',1375 'src',1376 'com',1377 'youcompleteme',1378 'Test.java' )1379 with patch.object(1380 handlers._server_state.GetFiletypeCompleter( [ 'java' ] ).GetConnection(),1381 'WriteData' ):1382 RunTest( app, {1383 'description': 'Request timeout throws an error',1384 'request': {1385 'command': 'FixIt',1386 'line_num': 1,1387 'column_num': 1,1388 'filepath': filepath,1389 },1390 'expect': {1391 'response': requests.codes.internal_server_error,1392 'data': ErrorMatcher( ResponseTimeoutException, 'Response Timeout' )1393 }1394 } )1395@WithRetry1396@SharedYcmd1397def Subcommands_RequestFailed_test( app ):1398 filepath = PathToTestFile( 'simple_eclipse_project',1399 'src',1400 'com',1401 'youcompleteme',1402 'Test.java' )1403 connection = handlers._server_state.GetFiletypeCompleter(1404 [ 'java' ] ).GetConnection()1405 def WriteJunkToServer( data ):1406 junk = data.replace( bytes( b'textDocument/codeAction' ),1407 bytes( b'textDocument/codeFAILED' ) )1408 with connection._stdin_lock:1409 connection._server_stdin.write( junk )1410 connection._server_stdin.flush()1411 with patch.object( connection, 'WriteData', side_effect = WriteJunkToServer ):1412 RunTest( app, {1413 'description': 'Response errors propagate to the client',1414 'request': {1415 'command': 'FixIt',1416 'line_num': 1,1417 'column_num': 1,1418 'filepath': filepath,1419 },1420 'expect': {1421 'response': requests.codes.internal_server_error,1422 'data': ErrorMatcher( ResponseFailedException )1423 }1424 } )1425@WithRetry1426@SharedYcmd1427def Subcommands_IndexOutOfRange_test( app ):1428 filepath = PathToTestFile( 'simple_eclipse_project',1429 'src',1430 'com',1431 'youcompleteme',1432 'Test.java' )1433 RunTest( app, {1434 'description': 'Request error handles the error',1435 'request': {1436 'command': 'FixIt',1437 'line_num': 99,1438 'column_num': 99,1439 'filepath': filepath,1440 },1441 'expect': {1442 'response': requests.codes.ok,1443 'data': has_entries( { 'fixits': empty() } ),1444 }1445 } )1446@WithRetry1447@SharedYcmd1448def Subcommands_DifferentFileTypesUpdate_test( app ):1449 filepath = PathToTestFile( 'simple_eclipse_project',1450 'src',1451 'com',1452 'youcompleteme',1453 'Test.java' )1454 RunTest( app, {1455 'description': 'Request error handles the error',1456 'request': {1457 'command': 'FixIt',1458 'line_num': 99,1459 'column_num': 99,1460 'filepath': filepath,1461 'file_data': {1462 '!/bin/sh': {1463 'filetypes': [],1464 'contents': 'this should be ignored by the completer',1465 },1466 '/path/to/non/project/file': {1467 'filetypes': [ 'c' ],1468 'contents': 'this should be ignored by the completer',1469 },1470 PathToTestFile( 'simple_eclipse_project',1471 'src',1472 'com',1473 'test',1474 'TestLauncher.java' ): {1475 'filetypes': [ 'some', 'java', 'junk', 'also' ],1476 'contents': ReadFile( PathToTestFile( 'simple_eclipse_project',1477 'src',1478 'com',1479 'test',1480 'TestLauncher.java' ) ),1481 },1482 '!/usr/bin/sh': {1483 'filetypes': [ 'java' ],1484 'contents': '\n',1485 },1486 }1487 },1488 'expect': {1489 'response': requests.codes.ok,1490 'data': has_entries( { 'fixits': empty() } ),1491 }...
PandasFileConnector.py
Source:PandasFileConnector.py
1"""2PandasFileConnector script includes loading and writing to file formats for csv, excel, feather, json, txt,3pickle, parquet.4"""5import json6import pandas as pd7from pathlib import Path8from conf import Logger9class PandasFileConnector:10 _logger = Logger().logger11 @classmethod12 def load(cls, filepath, file_type=None, **kwargs):13 """14 Different load methods for respective file format type.15 Args:16 filepath ([str]): [filepath]17 file_type ([str]): [type of files: {'.csv', '.xlsx', '.json', '.txt', '.pkl', '.yaml', '.parquet'}]18 **kwargs ([dict]): [dictionary of extra arguments]19 Returns:20 data_df ([dataframe]): [loaded data]21 """22 try:23 cls._logger.debug(f"[PandasFileConnector] Data loading ({filepath}) initiated...")24 file_type = file_type or cls._check_filetype(filepath)25 file_type = file_type if file_type.startswith('.') else '.' + file_type26 pd_connector = cls._get_connector(file_type)27 data_df = pd_connector.load(filepath=filepath, **kwargs)28 cls._logger.info(f"[PandasFileConnector] Data loaded ({filepath}) successfully.")29 return data_df30 except Exception as error:31 cls._logger.exception(f"[PandasFileConnector] load error: {error}")32 @classmethod33 def save(cls, data_df, filepath, file_type=None, **kwargs):34 """35 Different save methods for respective file format type.36 Args:37 data_df ([dataframe]): [data or table to be saved out]38 filepath ([str]): [file path to save out the dataframe]39 file_type ([str]): [type of files: {'csv', 'xlsx', 'json', 'txt', 'pkl', 'yaml', 'parquet'}]40 **kwargs ([dict]): [dictionary of extra arguments]41 """42 try:43 cls._logger.debug(f"[PandasFileConnector] Data saving ({filepath}) initiated...")44 file_type = file_type or cls._check_filetype(filepath)45 pd_connector = cls._get_connector(file_type)46 pd_connector.save(data_df, filepath, **kwargs)47 cls._logger.info(f"[PandasFileConnector] Data saved ({filepath}) successfully.")48 except Exception as error:49 cls._logger.exception(f"[PandasFileConnector] save error: {error}")50 @staticmethod51 def _connector_list():52 file_connectors = {53 '.csv': CSVFileConnector,54 '.xlsx': ExcelFileConnector,55 '.feather': FeatherFileConnector,56 '.json': JSONFileConnector,57 '.txt': TxtFileConnector,58 '.pkl': PickleFileConnector,59 '.pickle': PickleFileConnector,60 '.parquet': ParquetFileConnector61 }62 return file_connectors63 @classmethod64 def _check_filetype(cls, filepath):65 file_extension = Path(filepath).suffix66 cls._logger.debug(f"[_check_filetype] File extension detected as {file_extension}")67 file_connectors = cls._connector_list()68 assert file_extension in file_connectors.keys(), \69 f"File extension ({file_extension}) not recognised. Only accept .csv, .xlsx, .txt, .json, " \70 f".feather, .pkl, .parquet"71 return file_extension72 @classmethod73 def _get_connector(cls, file_type):74 file_connectors = cls._connector_list()75 assert file_type in file_connectors.keys(), \76 f"File extension ({file_type}) not recognised. Only accept .csv, .xlsx, .txt, .json, .feather, " \77 f".pkl, .parquet"78 return cls._connector_list()[file_type]79class CSVFileConnector:80 @classmethod81 def load(cls, filepath, **kwargs):82 """83 Load csv file as dataframe.84 Args:85 filepath ([str]): [filepath]86 **kwargs ([dict]): [dictionary of extra arguments]87 Returns:88 data_df ([dataframe]): [loaded dataframe]89 """90 data_df = pd.read_csv(filepath, **kwargs)91 return data_df92 @classmethod93 def save(cls, data_df, filepath, **kwargs):94 """95 Save dataframe as csv file.96 Args:97 data_df ([dataframe]): [data to be saved out as csv file]98 filepath ([str]): [filepath]99 **kwargs ([dict]): [dictionary of extra arguments]100 """101 data_df.to_csv(filepath, **kwargs)102class ExcelFileConnector:103 @classmethod104 def load(cls, filepath, **kwargs):105 """106 Load xlsx excel file as dataframe.107 Args:108 filepath ([str]): [filepath]109 **kwargs ([dict]): [dictionary of extra arguments]110 Returns:111 data_df ([dataframe]): [loaded dataframe]112 """113 data_df = pd.read_excel(filepath, **kwargs)114 return data_df115 @classmethod116 def save(cls, data_df, filepath, **kwargs):117 """118 Save dataframe as csv file.119 Args:120 data_df ([dataframe]): [data to be saved out as excel file]121 filepath ([str]): [filepath]122 **kwargs ([dict]): [dictionary of extra arguments]123 """124 data_df.to_excel(filepath, **kwargs)125class FeatherFileConnector:126 @classmethod127 def load(cls, filepath, **kwargs):128 """129 Read a feather file as a dataframe.130 Args:131 filepath ([str]): [filepath]132 **kwargs ([dict]): [dictionary of extra arguments]133 Returns:134 data_df ([dataframe]): [loaded dataframe]135 """136 data_df = pd.read_feather(filepath, **kwargs)137 return data_df138 @classmethod139 def save(cls, data_df, filepath, **kwargs):140 """141 Save out dataframe as feather file format.142 Args:143 data_df ([dataframe]): [data to be saved out as feather file]144 filepath ([str]): [filepath]145 **kwargs ([dict]): [dictionary of extra arguments]146 """147 data_df.to_feather(filepath, **kwargs)148class JSONFileConnector:149 @classmethod150 def load(cls, filepath, **kwargs):151 """152 Load json excel file as dataframe.153 Args:154 filepath ([str]): [filepath]155 **kwargs ([dict]): [dictionary of extra arguments]156 Returns:157 data_df ([dataframe]): [loaded dataframe]158 """159 with open(filepath, mode='r') as fs_file:160 data_df = json.load(fs_file, **kwargs)161 return data_df162 @classmethod163 def save(cls, data_df, filepath, orient='records', **kwargs):164 """165 Save out dataframe as json file format.166 Args:167 data_df ([dataframe]): [data to be saved out as json file]168 filepath ([str]): [filepath]169 orient ([str]): [orient method for pd.DataFrame.to_dict()]170 **kwargs ([dict]): [dictionary of extra arguments]171 """172 if type(data_df) is pd.DataFrame:173 json_data = data_df.to_dict(orient=orient)174 else:175 json_data = data_df176 with open(filepath, 'w') as file:177 json.dump(json_data, file, indent=4, **kwargs)178class TxtFileConnector:179 @classmethod180 def load(cls, filepath, sep=' ', **kwargs):181 """182 Read a text file as a dataframe.183 Args:184 filepath ([str]): [filepath]185 sep ([str]): [text file column seperator]186 **kwargs ([dict]): [dictionary of extra arguments]187 Returns:188 data_df ([dataframe]): [loaded dataframe]189 """190 with open(filepath, mode='r') as fs_file:191 data_df = pd.read_csv(fs_file, sep=sep, **kwargs)192 return data_df193 @classmethod194 def save(cls, data_df, filepath, sep=' ', **kwargs):195 """196 Save out dataframe as text file format.197 Args:198 data_df ([dataframe]): [data to be saved out as text file]199 filepath ([str]): [filepath]200 sep ([str]): [text file column seperator]201 **kwargs ([dict]): [dictionary of extra arguments]202 """203 data_df.to_csv(filepath, sep=sep, **kwargs)204class PickleFileConnector:205 @classmethod206 def load(cls, filepath, **kwargs):207 """208 Read a pickle file as a dataframe.209 Args:210 filepath ([str]): [filepath]211 **kwargs ([dict]): [dictionary of extra arguments]212 Returns:213 data_df ([dataframe]): [loaded dataframe]214 """215 with open(filepath, 'rb') as file:216 data_df = pd.read_pickle(file, **kwargs)217 return data_df218 @classmethod219 def save(cls, data_df, filepath, **kwargs):220 """221 Save out dataframe as pickle file format, the maximum file size of pickle is about 2GB.222 Args:223 data_df ([dataframe]): [data to be saved out as pickle file]224 filepath ([str]): [filepath]225 **kwargs ([dict]): [dictionary of extra arguments]226 """227 data_df.to_pickle(filepath, **kwargs)228class ParquetFileConnector:229 @classmethod230 def load(cls, filepath, **kwargs):231 """232 Read a parquet file as a dataframe.233 Args:234 filepath ([str]): [filepath]235 **kwargs ([dict]): [dictionary of extra arguments]236 Returns:237 data_df ([dataframe]): [loaded dataframe]238 """239 return pd.read_parquet(filepath, **kwargs)240 @classmethod241 def save(cls, data_df, filepath, **kwargs):242 """243 Save out dataframe as parquet file format.244 Args:245 data_df ([dataframe]): [list of dictionaries to be saved out as parquet file]246 filepath ([str]): [filepath]247 """...
exiftool-child.js
Source:exiftool-child.js
1const path = require('path');2const fs = require('fs-extra');3const prettyBytes = require('pretty-bytes');4const { readPsd } = require('ag-psd');5const name = 'exiftool-child';6const log = require('../../lib/log.js')(name);7const timing = require('../../lib/timing.js')(name);8const dcrawBin = require('./dcraw-bin.js');9const { bufferToUrl, urlToBuffer } = require('./bufferToUrl.js');10const metacache = require('./cache-meta.js');11const imagecache = require('./cache-image.js');12const { unknown } = require('./svg.js');13const image = require('../../lib/image.js');14const exiftool = require('../../lib/exiftool.js');15const gprtools = require('../../lib/gprtools.js');16const libheif = require('./libheif.js')(1);17const ROTATION = {18 'Horizontal (normal)': 0,19 'Rotate 90 CW': 90,20 'Rotate 270 CW': 27021};22function extension(filepath) {23 return path.extname(filepath).replace(/^\./, '').toLowerCase();24}25function isPlainImage(filepath) {26 const ext = path.extname(filepath).toLowerCase();27 return ['.jpeg', '.jpg', '.png'].includes(ext);28}29// this can be displayed nativly in Electron, but it is30// a bit difficult to test, so convert it for now31function isPlainConvertable(filepath) {32 const ext = path.extname(filepath).toLowerCase();33 return ['.webp'].includes(ext);34}35function isGpr(filepath) {36 return path.extname(filepath).toLowerCase() === '.gpr';37}38async function readFullMeta(filepath) {39 const name = 'fullmeta';40 const existing = metacache.read(filepath, name);41 if (existing) {42 return existing;43 }44 const result = await timing({45 category: 'read-full-meta-child',46 variable: extension(filepath),47 func: async () => await exiftool.readFullMeta(filepath)48 });49 metacache.add(filepath, name, result);50 return result;51}52async function queryMeta(filepath, keys) {53 return await exiftool.queryMeta(filepath, keys);54}55async function readShortMeta(filepath) {56 const name = 'shortmeta';57 const existing = metacache.read(filepath, name);58 if (existing) {59 return existing;60 }61 const placeholder = {62 disabled: true,63 url: unknown,64 rotation: 0,65 rating: 0,66 filepath67 };68 const stat = await fs.stat(filepath);69 if (stat.isDirectory()) {70 return placeholder;71 }72 let value;73 try {74 value = await timing({75 label: `read short meta ${filepath}`,76 category: 'read-short-meta-child',77 variable: extension(filepath),78 func: async () => await exiftool.readShortMeta(filepath)79 });80 } catch (e) {81 return placeholder;82 }83 const result = Object.assign(value, {84 filepath,85 rotation: value.isHeic ? 0 : ROTATION[value.orientation] || 086 });87 metacache.add(filepath, name, result);88 return result;89}90async function readFilePart({ filepath, start, length }) {91 return timing({92 label: `read file part ${filepath}`,93 func: async () => {94 let buffer = Buffer.alloc(length);95 const fd = await fs.open(filepath, 'r');96 await fs.read(fd, buffer, 0, length, start);97 await fs.close(fd);98 return buffer;99 }100 });101}102async function readFile(filepath) {103 return await timing({104 label: `read file ${filepath}`,105 func: () => fs.readFile(filepath)106 });107}108async function readFilePsd(filepath) {109 return await imagecache.cacheable(filepath, 'psd-render', async () => {110 return await timing({111 label: `read psd ${filepath}`,112 func: async () => {113 const file = await timing({ label: 'psd read', func: () => fs.readFile(filepath) });114 const psd = await timing({115 label: 'psd parse',116 func: () => readPsd(file, {117 skipLayerImageData: true118 })119 });120 const canvas = psd.canvas;121 const imgUrl = await timing({ label: 'psd canvas', func: () => canvas.toDataURL('image/jpeg') });122 const buffer = await timing({ label: 'psd buffer', func: () => urlToBuffer(imgUrl) });123 return buffer;124 }125 });126 });127}128async function readGpr(filepath) {129 return await imagecache.cacheable(filepath, 'gpr-render', async () => {130 return await timing({131 label: `read gpr ${filepath}`,132 func: () => gprtools.jpg(filepath)133 });134 });135}136async function readFileHeic(filepath) {137 return await imagecache.cacheable(filepath, 'heif-render', async () => {138 return await timing({139 label: `read heif ${filepath}`,140 func: () => libheif.jpg(filepath)141 });142 });143}144async function resizeLargeJpeg({ filepath, buffer, length }) {145 const before = buffer.length;146 buffer = await timing({147 label: `resize large jpeg for ${filepath}`,148 func: async () => {149 const { size: filebytes } = await fs.stat(filepath);150 if (filebytes / 2 < length) {151 // this jpeg was more than twice the size of the original152 // raw file... something is off, so resize it... it's too big153 return await image.bufferToJpeg(buffer);154 }155 return buffer;156 }157 });158 const diff = before - buffer.length;159 const pretty = prettyBytes(diff * -1);160 const percent = (1 - (buffer.length / before)) * 100;161 log.info(`change in ${filepath} size: ${pretty}, ${percent.toFixed(1)}%`);162 return buffer;163}164async function readJpegBufferFromMeta({ filepath, start, length }) {165 if (start && length) {166 // we can get a fast jpeg image167 return await timing({168 label: `read preview ${filepath}`,169 func: async () => await readFilePart({ filepath, start, length })170 });171 }172 return await timing({173 label: `dcraw extract preview ${filepath}`,174 func: async () => {175 return await dcrawBin(filepath, { type: 'preview' });176 }177 });178}179async function readJpegFromMeta({ filepath, start, length, url, isPsd, isHeic, rotation }) {180 if (url) {181 return url;182 }183 return await timing({184 label: `read jpeg from meta ${filepath}`,185 category: 'read-jpeg-from-meta',186 variable: extension(filepath),187 func: async () => {188 let buffer;189 if (isPsd) {190 buffer = await readFilePsd(filepath);191 } else if (isHeic) {192 buffer = await readFileHeic(filepath);193 } else if (isPlainImage(filepath)) {194 buffer = await readFile(filepath);195 } else if (isPlainConvertable(filepath)) {196 buffer = await image.pathToJpeg(filepath);197 } else if (isGpr(filepath)) {198 buffer = await readGpr(filepath);199 } else {200 buffer = await readJpegBufferFromMeta({ filepath, start, length });201 }202 if (length && length > 9999999) {203 // this image is probably too big, something suspicious is happening204 // ... it's probably a CR3 file, but I've seen it happen for other205 // formats as well206 buffer = await resizeLargeJpeg({ filepath, buffer, length });207 }208 if (rotation) {209 buffer = await image.resizeJpeg(buffer, { rotation });210 }211 return bufferToUrl(buffer);212 }213 });214}215async function readThumbFromMeta(data) {216 if (data.url) {217 return data.url;218 }219 let buffer;220 await timing({221 category: 'read-thumb-from-meta',222 variable: extension(data.filepath),223 func: async () => {224 if (data.isPsd) {225 buffer = await readFilePsd(data.filepath);226 } else if (data.isHeic) {227 buffer = await readFileHeic(data.filepath);228 } else if (isPlainImage(data.filepath)) {229 buffer = await readFile(data.filepath);230 } else if (isPlainConvertable(data.filepath)) {231 buffer = await image.pathToJpeg(data.filepath);232 } else if (isGpr(data.filepath)) {233 buffer = await readGpr(data.filepath);234 } else if (data.thumbStart && data.thumbLength) {235 // sometimes, the raw file will store a full size preview236 // and a thumbnail, and in those cases, using the smaller237 // image will be faster... though the resize makes large238 // images pretty fast, so maybe it's not worth?239 buffer = await timing({240 label: `read thumb ${data.filepath}`,241 func: async () => await readFilePart({242 filepath: data.filepath,243 start: data.thumbStart,244 length: data.thumbLength245 })246 });247 } else {248 buffer = await readJpegBufferFromMeta(data);249 }250 }251 });252 buffer = await timing({253 label: `resize thumb ${data.filepath}`,254 category: 'resize-thumbnail',255 variable: extension(data.filepath),256 func: async () => await image.resizeJpeg(buffer, { width: 200, rotation: data.rotation })257 });258 return bufferToUrl(buffer);259}260async function setRating(filepath, rating = 0) {261 metacache.remove(filepath);262 return await exiftool.setRating(filepath, rating);263}264async function copyMeta(filepath, targetpath) {265 return await exiftool.copyMeta(filepath, targetpath);266}267async function rawRender(filepath) {268 return imagecache.cacheable(filepath, 'raw', async () => {269 return await timing({270 label: `render ${filepath} from RAW`,271 category: 'raw-render',272 variable: extension(filepath),273 func: async () => {274 const jpeg = await dcrawBin(filepath, { type: 'raw' });275 return bufferToUrl(jpeg);276 }277 });278 });279}280module.exports = {281 readFullMeta,282 readShortMeta,283 queryMeta,284 copyMeta,285 setRating,286 readJpegFromMeta,287 readThumbFromMeta,288 isPlainImage,289 rawRender,290 resetCache: () => metacache.reset()...
loadRc.js
Source:loadRc.js
1// 2'use strict';3const yaml = require('js-yaml');4const requireFromString = require('require-from-string');5const readFile = require('./readFile');6const parseJson = require('./parseJson');7const funcRunner = require('./funcRunner');8module.exports = function loadRc(9 filepath ,10 options 11 12 13 14 15) {16 if (!options.sync) {17 return readFile(filepath)18 .then(parseExtensionlessRcFile)19 .then(checkExtensionlessRcResult);20 } else {21 return checkExtensionlessRcResult(22 parseExtensionlessRcFile(readFile.sync(filepath))23 );24 }25 function checkExtensionlessRcResult(result) {26 if (result) return result;27 if (options.rcExtensions) return loadRcWithExtensions();28 return null;29 }30 function parseExtensionlessRcFile(content ) {31 if (!content) return null;32 const pasedConfig = options.rcStrictJson33 ? parseJson(content, filepath)34 : yaml.safeLoad(content, { filename: filepath });35 return {36 config: pasedConfig,37 filepath,38 };39 }40 function loadRcWithExtensions() {41 let foundConfig = null;42 return funcRunner(readRcFile('json'), [43 (jsonContent ) => {44 // Since this is the first try, config cannot have been found, so don't45 // check `if (foundConfig)`.46 if (jsonContent) {47 const successFilepath = `${filepath}.json`;48 foundConfig = {49 config: parseJson(jsonContent, successFilepath),50 filepath: successFilepath,51 };52 } else {53 return readRcFile('yaml');54 }55 },56 (yamlContent ) => {57 if (foundConfig) {58 return;59 } else if (yamlContent) {60 const successFilepath = `${filepath}.yaml`;61 foundConfig = {62 config: yaml.safeLoad(yamlContent, { filename: successFilepath }),63 filepath: successFilepath,64 };65 } else {66 return readRcFile('yml');67 }68 },69 (ymlContent ) => {70 if (foundConfig) {71 return;72 } else if (ymlContent) {73 const successFilepath = `${filepath}.yml`;74 foundConfig = {75 config: yaml.safeLoad(ymlContent, { filename: successFilepath }),76 filepath: successFilepath,77 };78 } else {79 return readRcFile('js');80 }81 },82 (jsContent ) => {83 if (foundConfig) {84 return;85 } else if (jsContent) {86 const successFilepath = `${filepath}.js`;87 foundConfig = {88 config: requireFromString(jsContent, successFilepath),89 filepath: successFilepath,90 };91 } else {92 return;93 }94 },95 () => foundConfig,96 ]);97 }98 function readRcFile(extension ) {99 const filepathWithExtension = `${filepath}.${extension}`;100 return !options.sync101 ? readFile(filepathWithExtension)102 : readFile.sync(filepathWithExtension);103 }...
index.js
Source:index.js
1/*!2 * detect-file <https://github.com/doowb/detect-file>3 *4 * Copyright (c) 2016-2017, Brian Woodward.5 * Released under the MIT License.6 */7'use strict';8var fs = require('fs');9var path = require('path');10/**11 * Detect the given `filepath` if it exists.12 *13 * ```js14 * var res = detect('package.json');15 * console.log(res);16 * //=> "package.json"17 *18 * var res = detect('fake-file.json');19 * console.log(res)20 * //=> null21 * ```22 *23 * @param {String} `filepath` filepath to detect.24 * @param {Object} `options` Additional options.25 * @param {Boolean} `options.nocase` Set this to `true` to force case-insensitive filename checks. This is useful on case sensitive file systems.26 * @return {String} Returns the detected filepath if it exists, otherwise returns `null`.27 * @api public28 */29module.exports = function detect(filepath, options) {30 if (!filepath || (typeof filepath !== 'string')) {31 return null;32 }33 if (fs.existsSync(filepath)) {34 return path.resolve(filepath);35 }36 options = options || {};37 if (options.nocase === true) {38 return nocase(filepath);39 }40 return null;41};42/**43 * Check if the filepath exists by falling back to reading in the entire directory.44 * Returns the real filepath (for case sensitive file systems) if found.45 *46 * @param {String} `filepath` filepath to check.47 * @return {String} Returns found filepath if exists, otherwise null.48 */49function nocase(filepath) {50 filepath = path.resolve(filepath);51 var res = tryReaddir(filepath);52 if (res === null) {53 return null;54 }55 // "filepath" is a directory, an error would be56 // thrown if it doesn't exist. if we're here, it exists57 if (res.path === filepath) {58 return res.path;59 }60 // "filepath" is not a directory61 // compare against upper case later62 // see https://nodejs.org/en/docs/guides/working-with-different-filesystems/63 var upper = filepath.toUpperCase();64 var len = res.files.length;65 var idx = -1;66 while (++idx < len) {67 var fp = path.resolve(res.path, res.files[idx]);68 if (filepath === fp || upper === fp) {69 return fp;70 }71 var fpUpper = fp.toUpperCase();72 if (filepath === fpUpper || upper === fpUpper) {73 return fp;74 }75 }76 return null;77}78/**79 * Try to read the filepath as a directory first, then fallback to the filepath's dirname.80 *81 * @param {String} `filepath` path of the directory to read.82 * @return {Object} Object containing `path` and `files` if succesful. Otherwise, null.83 */84function tryReaddir(filepath) {85 var ctx = { path: filepath, files: [] };86 try {87 ctx.files = fs.readdirSync(filepath);88 return ctx;89 } catch (err) {}90 try {91 ctx.path = path.dirname(filepath);92 ctx.files = fs.readdirSync(ctx.path);93 return ctx;94 } catch (err) {}95 return null;...
sb-watch.js
Source:sb-watch.js
1'use strict';2const _ = require('lodash');3const chokidar = require('chokidar');4const path = require('path');5const renderAssets = require('./render-assets');6const renderPug = require('./render-pug');7const renderScripts = require('./render-scripts');8const renderSCSS = require('./render-scss');9const watcher = chokidar.watch('src', {10 persistent: true,11});12let READY = false;13process.title = 'pug-watch';14process.stdout.write('Loading');15let allPugFiles = {};16watcher.on('add', filePath => _processFile(filePath, 'add'));17watcher.on('change', filePath => _processFile(filePath, 'change'));18watcher.on('ready', () => {19 READY = true;20 console.log(' READY TO ROLL!');21});22_handleSCSS();23function _processFile(filePath, watchEvent) {24 25 if (!READY) {26 if (filePath.match(/\.pug$/)) {27 if (!filePath.match(/includes/) && !filePath.match(/mixins/) && !filePath.match(/\/pug\/layouts\//)) {28 allPugFiles[filePath] = true;29 } 30 } 31 process.stdout.write('.');32 return;33 }34 console.log(`### INFO: File event: ${watchEvent}: ${filePath}`);35 if (filePath.match(/\.pug$/)) {36 return _handlePug(filePath, watchEvent);37 }38 if (filePath.match(/\.scss$/)) {39 if (watchEvent === 'change') {40 return _handleSCSS(filePath, watchEvent);41 }42 return;43 }44 if (filePath.match(/src\/js\//)) {45 return renderScripts();46 }47 if (filePath.match(/src\/assets\//)) {48 return renderAssets();49 }50}51function _handlePug(filePath, watchEvent) {52 if (watchEvent === 'change') {53 if (filePath.match(/includes/) || filePath.match(/mixins/) || filePath.match(/\/pug\/layouts\//)) {54 return _renderAllPug();55 }56 return renderPug(filePath);57 }58 if (!filePath.match(/includes/) && !filePath.match(/mixins/) && !filePath.match(/\/pug\/layouts\//)) {59 return renderPug(filePath);60 }61}62function _renderAllPug() {63 console.log('### INFO: Rendering All');64 _.each(allPugFiles, (value, filePath) => {65 renderPug(filePath);66 });67}68function _handleSCSS() {69 renderSCSS();...
constants.py
Source:constants.py
1import os2FILE_LIMIT = 53CATEGORIES = ['Electronics', 'Edibles', 'Clothes', 'Skin Care', 'Kitchen', 'Books']4FILE_STORAGE_PATH = 'database/'5PRODUCTS_FILEPATH = FILE_STORAGE_PATH + 'products/'6USERS_FILEPATH = FILE_STORAGE_PATH + 'users/'7HISTORY_FILEPATH = FILE_STORAGE_PATH + 'history/'8SUPPLIER_LOGS_FILEPATH = FILE_STORAGE_PATH + 'supplier_logs/'9CART_FILEPATH = FILE_STORAGE_PATH + 'cart/'10SESSION_FILEPATH = FILE_STORAGE_PATH + 'session/'11PRODUCT_DATA_FILEPATH = PRODUCTS_FILEPATH + 'data/'12PRODUCT_IMAGE_FILEPATH = PRODUCTS_FILEPATH + 'images/'13PRODUCT_COMMENTS_FILEPATH = PRODUCTS_FILEPATH + 'comments/'14CUSTOMERS_FILEPATH = USERS_FILEPATH + 'customers/'15SUPPLIERS_FILEPATH = USERS_FILEPATH + 'suppliers/'16OPERATORS_FILEPATH = USERS_FILEPATH + 'operators/'17def get_path(relative_path):18 if 'core' in os.getcwd() or 'gui' in os.getcwd():19 return os.path.abspath('../' + relative_path)20 return os.path.abspath(relative_path)21def product_data_filepath():22 return get_path(PRODUCT_DATA_FILEPATH)23def product_image_filepath():24 return get_path(PRODUCT_IMAGE_FILEPATH)25def product_comments_filepath():26 return get_path(PRODUCT_COMMENTS_FILEPATH)27def customer_filepath():28 return get_path(CUSTOMERS_FILEPATH)29def supplier_filepath():30 return get_path(SUPPLIERS_FILEPATH)31def operator_filepath():32 return get_path(OPERATORS_FILEPATH)33def history_filepath():34 return get_path(HISTORY_FILEPATH)35def supplier_logs_filepath():36 return get_path(SUPPLIER_LOGS_FILEPATH)37def cart_filepath():38 return get_path(CART_FILEPATH)39def session_filepath():...
Using AI Code Generation
1const path = require('path');2const {chromium} = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: path.join(__dirname, 'google.png') });8 await browser.close();9})();10const path = require('path');11const {chromium} = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.screenshot({ path: path.join(__dirname, 'google.png') });17 await browser.close();18})();19const path = require('path');20const {chromium} = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.screenshot({ path: path.join(__dirname, 'google.png') });26 await browser.close();27})();28const path = require('path');29const {chromium} = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await page.screenshot({ path: path.join(__dirname, 'google.png') });35 await browser.close();36})();37const path = require('path');38const {chromium} = require('playwright');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();42 const page = await context.newPage();43 await page.screenshot({ path: path.join(__dirname, 'google.png') });44 await browser.close();45})();
Using AI Code Generation
1const path = require("path");2const {chromium} = require("playwright");3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({path: path.join(__dirname, "google.png")});8 await browser.close();9})();10const {chromium} = require("playwright");11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.screenshot({path: "google.png"});16 await browser.close();17})();18const {chromium} = require("playwright");19(async () => {20 const browser = await chromium.launch();21 const context = await browser.newContext();22 const page = await context.newPage();23 await page.screenshot({path: "google.png"});24 await browser.close();25})();26const {chromium} = require("playwright");27(async () => {28 const browser = await chromium.launch();29 const context = await browser.newContext();30 const page = await context.newPage();31 await page.screenshot({path: "google.png"});32 await browser.close();33})();34const {chromium} = require("playwright");35(async () => {36 const browser = await chromium.launch();37 const context = await browser.newContext();38 const page = await context.newPage();39 await page.screenshot({path: "google.png"});40 await browser.close();41})();42const {chromium} = require("playwright");43(async () => {44 const browser = await chromium.launch();45 const context = await browser.newContext();
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**/*', route => {7 route.fulfill({8 });9 });10 await browser.close();11})();12const {chromium} = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.route('**/*', route => {18 route.fulfill({19 });20 });21 await browser.close();22})();23const {chromium} = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.route('**/*', route => {29 route.fulfill({30 });31 });32 await browser.close();33})();34const {chromium} = require('playwright');35(async () => {36 const browser = await chromium.launch();37 const context = await browser.newContext();38 const page = await context.newPage();39 await page.route('**/*', route => {40 route.fulfill({41 });42 });43 await browser.close();44})();45const {chromium} = require('playwright');46(async () => {47 const browser = await chromium.launch();48 const context = await browser.newContext();49 const page = await context.newPage();
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({path: page.filePath('screenshot.png')});7 await browser.close();8})();9const {chromium} = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({path: page.filePath('screenshot.png', 'C:\\Users\\User\\Desktop')});15 await browser.close();16})();17page.downloadPath(file, path)18const {chromium} = require('playwright');19(async () => {20 const browser = await chromium.launch();21 const context = await browser.newContext();22 const page = await context.newPage();23 await page.click('a[href="https
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const file = await page.evaluateHandle(() => {7 const input = document.createElement('input');8 input.type = 'file';9 input.onchange = () => {10 window.file = input.files[0];11 };12 document.body.appendChild(input);13 return input;14 });15 await file.evaluateHandle(input => input.click());16 await page.waitForFunction(() => window.file);17 const filePath = await file.evaluateHandle(input => input.files[0].filePath);18 console.log(filePath);19 await browser.close();20})();21from playwright.sync_api import sync_playwright22with sync_playwright() as p:23 browser = p.chromium.launch()24 page = browser.new_page()25 file = page.evaluate_handle("() => { const input = document.createElement('input'); input.type = 'file'; input.onchange = () => { window.file = input.files[0]; }; document.body.appendChild(input); return input; }")26 file.click()27 page.wait_for_function("() => window.file")28 filePath = file.evaluate_handle("input => input.files[0].filePath")29 print(filePath)30 browser.close()31const fs = require('fs');32const {chromium} = require('playwright');33(async () => {34 const browser = await chromium.launch();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const filePath = await page.evaluate(() => window.__playwright__internal__filePath('test.js'));6 console.log(filePath);7 await browser.close();8})();
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.setContent(`<input type="file" id="file" />`);7 const fileInput = await page.$('#file');8 await fileInput.setInputFiles(filePath);9 await browser.close();10})();11const {chromium} = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.setContent(`<input type="file" id="file" />`);17 const fileInput = await page.$('#file');18 await fileInput.setInputFiles(file);19 await browser.close();20})();21const {chromium} = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 await page.setContent(`<input type="file" id="file" />`);27 const fileInput = await page.$('#file');28 await fileInput.setInputFiles(buffer);29 await browser.close();30})();31const {chromium} = require('playwright');32(async () => {33 const browser = await chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();36 await page.setContent(`<input type="file" id="file" />`);37 const fileInput = await page.$('#file');38 await fileInput.setInputFiles([39 ]);
Using AI Code Generation
1const { Playwright } = require('playwright');2const { chromium } = require('playwright');3const playwright = require('playwright');4(async () => {5 const browser = await playwright.chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const input = await page.$('input[name="q"]');9 await input.type('Hello World');10 await page.screenshot({ path: 'screenshot.png' });11 await browser.close();12})();13const { Playwright } = require('playwright');14const { chromium } = require('playwright');15const playwright = require('playwright');16(async () => {17 const browser = await playwright.chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 const input = await page.$('input[name="q"]');21 await input.type('Hello World');22 await page.screenshot({ path: 'screenshot.png' });23 await browser.close();24})();25const { Playwright } = require('playwright');26const { chromium } = require('playwright');27const playwright = require('playwright');28(async () => {29 const browser = await playwright.chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 const input = await page.$('input[name="q"]');33 await input.type('Hello World');34 await page.screenshot({ path: 'screenshot.png' });35 await browser.close();36})();37const { Playwright } = require('playwright');38const { chromium } = require('playwright');39const playwright = require('playwright');40(async () => {41 const browser = await playwright.chromium.launch();42 const context = await browser.newContext();43 const page = await context.newPage();44 const input = await page.$('input[name="q"]');45 await input.type('Hello World');46 await page.screenshot({ path: 'screenshot
Using AI Code Generation
1const { filePath } = require('@playwright/test');2const path = require('path');3const file = filePath(path.join(__dirname, 'file.txt'));4const { file } = require('@playwright/test');5const file = file(path.join(__dirname, 'file.txt'));6const { test } = require('@playwright/test');7test('test', async ({ page }) => {8 await page.setInputFiles('input[type=file]', file);9});10const { file } = require('@playwright/test');11const file = file(path.join(__dirname, 'file.txt'));12const { file } = require('@playwright/test');13const file1 = file(path.join(__dirname, 'file.txt'));14const { file } = require('@playwright/test');15const file1 = file(path.join(__dirname, 'file.txt'));16const { file } = require('@playwright/test');17const file1 = file(path.join(__dirname, 'file.txt'));
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!