def RunCompleterCommand_GoToImplementationElseDeclaration_CsCompleter_NoImplementation_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'testy/GotoTestCase.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app ) goto_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GoToImplementationElseDeclaration'], line_num = 17, column_num = 13, contents = contents, filetype = 'cs', filepath = filepath ) eq_( { 'filepath': PathToTestFile( 'testy/GotoTestCase.cs' ), 'line_num': 35, 'column_num': 3 }, app.post_json( '/run_completer_command', goto_data ).json ) StopOmniSharpServer( app )
def RunCompleterCommand_GetType_CsCompleter_Constant_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy/GetTypeTestCase.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) gettype_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GetType'], line_num = 4, column_num = 14, contents = contents, filetype = 'cs', filepath = filepath ) eq_( { u'message': u"System.String" }, app.post_json( '/run_completer_command', gettype_data ).json ) StopOmniSharpServer( app, filepath )
def RunCompleterCommand_GetType_TypescriptCompleter_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'test.ts' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'typescript', contents = contents, event_name = 'BufferVisit' ) app.post_json( '/event_notification', event_data ) gettype_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GetType'], line_num = 12, column_num = 1, contents = contents, filetype = 'typescript', filepath = filepath ) eq_( { 'message': 'var foo: Foo' }, app.post_json( '/run_completer_command', gettype_data ).json )
class Detalle(TestCase): """ NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase """ @classmethod def setUpClass(self): # Cargamos los datos entidad = cargar_datos('usuario')[1] self.uid = entidad['uid'] self.datos = {'corpus': entidad} # Trabajamos en obtener un token self.token = cargar_credenciales() # Creamos nuestro objeto para pruebas from justine import main from webtest import TestApp app = main({}) self.testapp = TestApp(app) res = self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token) @classmethod def tearDownClass(self): res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token) if res.status_int == 200: self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token) def test_detalle_usuario(self): res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token) respuesta = res.json_body['mensaje'][0]['givenName'] datos = self.datos['corpus']['givenName'] self.assertEqual(respuesta, datos) def test_detalle_claves(self): claves = ['dn', 'givenName', 'cn'] res = self.testapp.get('/usuarios/' + self.uid, params={'claves': ','.join(claves)}, headers=self.token) respuesta = res.json_body['mensaje'][0].keys() self.assertListEqual(respuesta, claves) def test_detalle_claves_noexistentes(self): claves = ['dn', 'givenName', 'cn', 'noexistente'] res = self.testapp.get('/usuarios/' + self.uid, params={'claves': ','.join(claves)}, headers=self.token) respuesta = res.json_body['mensaje'][0].keys() del claves[claves.index('noexistente')] self.assertListEqual(respuesta, claves) def test_detalle_noexistente(self): uid = 'fitzcarraldo' self.testapp.get('/usuarios/' + uid, status=404, headers=self.token) def test_detalle_unauth(self): self.testapp.post_json('/usuarios' + self.uid, status=404)
def RunCompleterCommand_GoToImplementationElseDeclaration_CsCompleter_MultipleImplementations_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy', 'GotoTestCase.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) goto_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GoToImplementationElseDeclaration'], line_num = 21, column_num = 13, contents = contents, filetype = 'cs', filepath = filepath ) eq_( [{ 'filepath': PathToTestFile( 'testy', 'GotoTestCase.cs' ), 'line_num': 43, 'column_num': 3 }, { 'filepath': PathToTestFile( 'testy', 'GotoTestCase.cs' ), 'line_num': 48, 'column_num': 3 }], app.post_json( '/run_completer_command', goto_data ).json ) StopOmniSharpServer( app, filepath )
def _RunFixItTest_CsCompleter( line, column, expected_result ): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy/FixItTestCase.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) fixit_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['FixIt'], line_num = line, column_num = column, contents = contents, filetype = 'cs', filepath = filepath ) eq_( expected_result, app.post_json( '/run_completer_command', fixit_data ).json ) StopOmniSharpServer( app, filepath )
def _RunCompleterCommand_StopServer_CsCompleter_KeepLogFiles( keeping_log_files ): ChangeSpecificOptions( { 'server_keep_logfiles': keeping_log_files } ) app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy', 'GotoTestCase.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) event_data = BuildRequest( filetype = 'cs', filepath = filepath ) debuginfo = app.post_json( '/debug_info', event_data ).json log_files_match = re.search( "^OmniSharp logfiles:\n(.*)\n(.*)", debuginfo, re.MULTILINE ) stdout_logfiles_location = log_files_match.group( 1 ) stderr_logfiles_location = log_files_match.group( 2 ) try: assert os.path.exists( stdout_logfiles_location ), "Logfile should exist at " + stdout_logfiles_location assert os.path.exists( stderr_logfiles_location ), "Logfile should exist at " + stderr_logfiles_location finally: StopOmniSharpServer( app, filepath ) if ( keeping_log_files ): assert os.path.exists( stdout_logfiles_location ), "Logfile should still exist at " + stdout_logfiles_location assert os.path.exists( stderr_logfiles_location ), "Logfile should still exist at " + stderr_logfiles_location else: assert not os.path.exists( stdout_logfiles_location ), "Logfile should no longer exist at " + stdout_logfiles_location assert not os.path.exists( stderr_logfiles_location ), "Logfile should no longer exist at " + stderr_logfiles_location
def test_post_task_invalid(): test_app = TestApp(app) assert test_app.post_json('/task', expect_errors=True).status_int == 400 assert test_app.post_json('/task', { 'task_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'test_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'task_type': 'wait', 'task_version': 'invalid_version', 'task_data': { 'wait_time': 3600 } }, expect_errors=True).status_int == 400 assert test_app.post_json('/task', { 'task_id': 'de305d54-75b4-431b-adb2-eb6b9e546013_not_valid', 'test_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'task_type': 'wait', 'task_version': 1, 'task_data': { 'wait_time': 3600 } }, expect_errors=True).status_int == 400 assert test_app.post_json('/task', { 'test_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'task_type': 'wait', 'task_version': 1, 'task_data': { 'wait_time': 3600 } }, expect_errors=True).status_int == 400
def GetCompletions_CsCompleter_StartsWithUnambiguousMultipleSolutions_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( ('testy-multiple-solutions/' 'solution-named-like-folder/' 'testy/Program.cs') ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) # Here the server will raise an exception if it can't start app.post_json( '/event_notification', event_data ) # Now for some cleanup: wait for the server to start then shut it down while True: result = app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['ServerRunning'], filetype = 'cs' ) ).json if result: break time.sleep( 0.2 ) # We need to turn off the CS server so that it doesn't stick around app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = ['StopServer'], filetype = 'cs' ) )
def GetCompletions_TypeScriptCompleter_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'test.ts' ) contents = open ( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'typescript', contents = contents, event_name = 'BufferVisit' ) app.post_json( '/event_notification', event_data ) completion_data = BuildRequest( filepath = filepath, filetype = 'typescript', contents = contents, force_semantic = True, line_num = 11, column_num = 6 ) results = app.post_json( '/completions', completion_data ).json[ 'completions' ] assert_that( results, has_items( CompletionEntryMatcher( 'methodA' ), CompletionEntryMatcher( 'methodB' ), CompletionEntryMatcher( 'methodC' ) ) )
def RunCompleterCommand_GoTo_CsCompleter_Works_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy/GotoTestCase.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app ) goto_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GoTo'], line_num = 9, column_num = 15, contents = contents, filetype = 'cs', filepath = filepath ) eq_( { 'filepath': PathToTestFile( 'testy/Program.cs' ), 'line_num': 7, 'column_num': 3 }, app.post_json( '/run_completer_command', goto_data ).json ) StopOmniSharpServer( app )
def GetCompletions_ClangCompleter_NoCompletionsWhenAutoTriggerOff_test(): ChangeSpecificOptions( { 'auto_trigger': False } ) app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; foo. } """ completion_data = BuildRequest( filepath = '/foo.cpp', filetype = 'cpp', contents = contents, line_num = 11, column_num = 7, compilation_flags = ['-x', 'c++'] ) results = app.post_json( '/completions', completion_data ).json[ 'completions' ] assert_that( results, empty() )
def GetCompletions_ClangCompleter_UnknownExtraConfException_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'basic.cpp' ) completion_data = BuildRequest( filepath = filepath, filetype = 'cpp', contents = open( filepath ).read(), line_num = 11, column_num = 7, force_semantic = True ) response = app.post_json( '/completions', completion_data, expect_errors = True ) eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR ) assert_that( response.json, has_entry( 'exception', has_entry( 'TYPE', UnknownExtraConf.__name__ ) ) ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) response = app.post_json( '/completions', completion_data, expect_errors = True ) eq_( response.status_code, httplib.INTERNAL_SERVER_ERROR ) assert_that( response.json, has_entry( 'exception', has_entry( 'TYPE', NoExtraConfDetected.__name__ ) ) )
def GetCompletions_CsCompleter_DoesntStartWithAmbiguousMultipleSolutions_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( ( 'testy-multiple-solutions/' 'solution-not-named-like-folder/' 'testy/Program.cs' ) ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) exception_caught = False try: app.post_json( '/event_notification', event_data ) except AppError as e: if 'Autodetection of solution file failed' in str( e ): exception_caught = True # the test passes if we caught an exception when trying to start it, # so raise one if it managed to start if not exception_caught: WaitUntilOmniSharpServerReady( app, filepath ) StopOmniSharpServer( app, filepath ) raise Exception( ( 'The Omnisharp server started, despite us not being able ' 'to find a suitable solution file to feed it. Did you ' 'fiddle with the solution finding code in ' 'cs_completer.py? Hopefully you\'ve enhanced it: you need' 'to update this test then :)' ) )
def GetCompletions_CsCompleter_NonForcedReturnsNoResults_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy', 'ContinuousTest.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) completion_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = 9, column_num = 21, force_semantic = False, query = 'Date' ) results = app.post_json( '/completions', completion_data ).json # there are no semantic completions. However, we fall back to identifier # completer in this case. assert_that( results, has_entries( { 'completions' : has_item( has_entries( { 'insertion_text' : 'String', 'extra_menu_info': '[ID]', } ) ), 'errors' : empty(), } ) ) StopOmniSharpServer( app, filepath )
def RunCompleterCommand_GoToImplementation_CsCompleter_InvalidLocation_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'testy/GotoTestCase.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app ) goto_data = BuildRequest( completer_target = 'filetype_default', command_arguments = ['GoToImplementation'], line_num = 2, column_num = 1, contents = contents, filetype = 'cs', filepath = filepath ) try: app.post_json( '/run_completer_command', goto_data ).json raise Exception('Expected a "Can\\\'t jump to implementation" error') except AppError as e: if 'Can\\\'t jump to implementation' in str(e): pass else: raise finally: StopOmniSharpServer( app )
def RunCompleterCommand_GoToImplementationElseDeclaration_CsCompleter_MultipleImplementations_test(): app = TestApp(handlers.app) app.post_json("/ignore_extra_conf_file", {"filepath": PathToTestFile(".ycm_extra_conf.py")}) filepath = PathToTestFile("testy", "GotoTestCase.cs") contents = open(filepath).read() event_data = BuildRequest(filepath=filepath, filetype="cs", contents=contents, event_name="FileReadyToParse") app.post_json("/event_notification", event_data) WaitUntilOmniSharpServerReady(app, filepath) goto_data = BuildRequest( completer_target="filetype_default", command_arguments=["GoToImplementationElseDeclaration"], line_num=21, column_num=13, contents=contents, filetype="cs", filepath=filepath, ) eq_( [ {"filepath": PathToTestFile("testy", "GotoTestCase.cs"), "line_num": 43, "column_num": 3}, {"filepath": PathToTestFile("testy", "GotoTestCase.cs"), "line_num": 48, "column_num": 3}, ], app.post_json("/run_completer_command", goto_data).json, ) StopOmniSharpServer(app, filepath)
class TestUnittest(TestCase): def setUp(self): app = create_app self.client = TestApp(app) @classmethod @autodoc.generate('var/test_unittest.rst') def tearDownClass(cls): pass @autodoc.describe('GET /') def test_get(self): """ GET / """ res = self.client.get('/') self.assertEqual(res.status_code, 200) return res @autodoc.describe('POST /') def test_post(self): """ POST / """ res = self.client.post_json('/', params={'id': 1, 'message': 'foo'}) self.assertEqual(res.status_code, 200) return res @autodoc.describe('POST /foo/bar') def test_foo_bar(self): """ POST /foo/bar """ res = self.client.post_json('/foo/bar', params={'id': 1, 'message': 'foo'}) self.assertEqual(res.status_code, 200) return res
def GetDetailedDiagnostic_CsCompleter_Works_test(): app = TestApp( handlers.app ) filepath = PathToTestFile( 'testy/Program.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app ) app.post_json( '/event_notification', event_data ) diag_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = 10, column_num = 2, start_column = 2 ) results = app.post_json( '/detailed_diagnostic', diag_data ).json assert_that( results, has_entry( 'message', contains_string( "Unexpected symbol `}'', expecting identifier" ) ) ) StopOmniSharpServer( app )
def GetCompletions_ClangCompleter_NoCompletionsWhenAutoTriggerOff_test(): ChangeSpecificOptions({"auto_trigger": False}) app = TestApp(handlers.app) app.post_json("/ignore_extra_conf_file", {"filepath": PathToTestFile(".ycm_extra_conf.py")}) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; foo. } """ completion_data = BuildRequest( filepath="/foo.cpp", filetype="cpp", contents=contents, line_num=11, column_num=7, compilation_flags=["-x", "c++"], ) results = app.post_json("/completions", completion_data).json["completions"] assert_that(results, empty())
def GetCompletions_ClangCompleter_WorksWithExplicitFlags_test(): app = TestApp(handlers.app) app.post_json("/ignore_extra_conf_file", {"filepath": PathToTestFile(".ycm_extra_conf.py")}) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; foo. } """ completion_data = BuildRequest( filepath="/foo.cpp", filetype="cpp", contents=contents, line_num=11, column_num=7, compilation_flags=["-x", "c++"], ) response_data = app.post_json("/completions", completion_data).json assert_that( response_data["completions"], has_items(CompletionEntryMatcher("c"), CompletionEntryMatcher("x"), CompletionEntryMatcher("y")), ) eq_(7, response_data["completion_start_column"])
def GetCompletions_CsCompleter_ReloadSolution_MultipleSolution_Works_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepaths = [ PathToTestFile( 'testy/Program.cs' ), PathToTestFile( 'testy-multiple-solutions/' 'solution-named-like-folder/' 'testy/' 'Program.cs' ) ] for filepath in filepaths: contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) result = app.post_json( '/run_completer_command', BuildRequest( completer_target = 'filetype_default', command_arguments = [ 'ReloadSolution' ], filepath = filepath, filetype = 'cs' ) ).json StopOmniSharpServer( app, filepath ) eq_( result, True )
def GetCompletions_ClangCompleter_WorksWithExplicitFlags_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) contents = """ struct Foo { int x; int y; char c; }; int main() { Foo foo; foo. } """ completion_data = BuildRequest( filepath = '/foo.cpp', filetype = 'cpp', contents = contents, line_num = 11, column_num = 7, compilation_flags = ['-x', 'c++'] ) response_data = app.post_json( '/completions', completion_data ).json assert_that( response_data[ 'completions'], has_items( CompletionEntryMatcher( 'c' ), CompletionEntryMatcher( 'x' ), CompletionEntryMatcher( 'y' ) ) ) eq_( 7, response_data[ 'completion_start_column' ] )
def GetCompletions_CsCompleter_ImportsOrderedAfter_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy/ImportTest.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) completion_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = 9, column_num = 12, force_semantic = True, query = 'Date' ) response_data = app.post_json( '/completions', completion_data ).json min_import_index = min( loc for loc, val in enumerate( response_data[ 'completions' ] ) if val[ 'extra_data' ][ 'required_namespace_import' ] ) max_nonimport_index = max( loc for loc, val in enumerate( response_data[ 'completions' ] ) if not val[ 'extra_data' ][ 'required_namespace_import' ] ) assert_that( min_import_index, greater_than( max_nonimport_index ) ), StopOmniSharpServer( app, filepath )
def GetCompletions_CsCompleter_PathWithSpace_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'неприличное слово/Program.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) completion_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = 9, column_num = 12 ) response_data = app.post_json( '/completions', completion_data ).json assert_that( response_data[ 'completions' ], has_items( CompletionEntryMatcher( 'CursorLeft' ), CompletionEntryMatcher( 'CursorSize' ) ) ) eq_( 12, response_data[ 'completion_start_column' ] ) StopOmniSharpServer( app, filepath )
def GetCompletions_CsCompleter_HasBothImportsAndNonImport_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy/ImportTest.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) completion_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = 9, column_num = 12, force_semantic = True, query = 'Date' ) response_data = app.post_json( '/completions', completion_data ).json assert_that( response_data[ 'completions' ], has_items( CompletionEntryMatcher( 'DateTime' ), CompletionEntryMatcher( 'DateTimeStyles' ) ) ) StopOmniSharpServer( app, filepath )
def GetCompletions_CsCompleter_MultipleSolution_Works_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepaths = [ PathToTestFile( 'testy/Program.cs' ), PathToTestFile( 'testy-multiple-solutions/' 'solution-named-like-folder/' 'testy/' 'Program.cs' ) ] lines = [ 10, 9 ] for filepath, line in zip( filepaths, lines ): contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) completion_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = line, column_num = 12 ) response_data = app.post_json( '/completions', completion_data ).json assert_that( response_data[ 'completions' ], has_items( CompletionEntryMatcher( 'CursorLeft' ), CompletionEntryMatcher( 'CursorSize' ) ) ) eq_( 12, response_data[ 'completion_start_column' ] ) StopOmniSharpServer( app, filepath )
def GetDetailedDiagnostic_ClangCompleter_Works_test(): app = TestApp( handlers.app ) contents = """ struct Foo { int x // semicolon missing here! int y; int c; int d; }; """ diag_data = BuildRequest( compilation_flags = ['-x', 'c++'], line_num = 2, contents = contents, filetype = 'cpp' ) event_data = diag_data.copy() event_data.update( { 'event_name': 'FileReadyToParse', } ) app.post_json( '/event_notification', event_data ) results = app.post_json( '/detailed_diagnostic', diag_data ).json assert_that( results, has_entry( 'message', contains_string( "expected ';'" ) ) )
def GetCompletions_CsCompleter_NonForcedReturnsNoResults_test(): app = TestApp( handlers.app ) app.post_json( '/ignore_extra_conf_file', { 'filepath': PathToTestFile( '.ycm_extra_conf.py' ) } ) filepath = PathToTestFile( 'testy/ContinuousTest.cs' ) contents = open( filepath ).read() event_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ) WaitUntilOmniSharpServerReady( app, filepath ) completion_data = BuildRequest( filepath = filepath, filetype = 'cs', contents = contents, line_num = 9, column_num = 21, force_semantic = False, query = 'Date' ) results = app.post_json( '/completions', completion_data ).json[ 'completions' ] assert_that( results, empty() ) StopOmniSharpServer( app, filepath )
def test_good_gotoassignment_do_not_follow_imports(): app = TestApp(handlers.app) filepath = fixture_filepath('follow_imports', 'importer.py') request_data = { 'source': read_file(filepath), 'line': 3, 'col': 9, 'source_path': filepath } expected_definition = { 'module_path': filepath, 'name': 'imported_function', 'type': 'function', 'in_builtin_module': False, 'line': 1, 'column': 21, 'docstring': 'imported_function()\n\n', 'description': 'def imported_function', 'full_name': 'imported.imported_function', 'is_keyword': False } definitions = app.post_json('/gotoassignment', request_data).json['definitions'] assert_that(definitions, contains(expected_definition)) request_data['follow_imports'] = False definitions = app.post_json('/gotoassignment', request_data).json['definitions'] assert_that(definitions, contains(expected_definition))
def EventNotification_AlwaysJsonResponse_test(): app = TestApp( handlers.app ) event_data = BuildRequest( contents = 'foo foogoo ba', event_name = 'FileReadyToParse' ) app.post_json( '/event_notification', event_data ).json
def DefinedSubcommands_WorksWhenNoExplicitCompleterTargetSpecified_test(): app = TestApp(handlers.app) subcommands_data = BuildRequest(filetype='python') eq_(['GoToDefinition', 'GoToDeclaration', 'GoTo'], app.post_json('/defined_subcommands', subcommands_data).json)
class PyramidPeeweeMarshmallowTestCase(unittest.TestCase): def setUp(self): from webtest import TestApp # Imported here in order to avoid dummy warning from pytest db.drop_tables([User]) db.create_tables([User]) self.app = create_app() self.client = TestApp(self.app) def test_list_users(self): _create_user(first_name='Filipe', last_name='Waitman') response = self.client.get('/api/users/') assert response.status_code == 200 assert response.json_body['count'] == 1 assert response.json_body['next_page'] is None assert response.json_body['prev_page'] is None assert 'id' in response.json_body['results'][0] assert 'created' in response.json_body['results'][0] assert response.json_body['results'][0]['first_name'] == 'Filipe' assert response.json_body['results'][0]['last_name'] == 'Waitman' def test_create(self): data = { 'first_name': 'Filipe', 'last_name': 'Waitman', } response = self.client.post_json('/api/users/', data) assert response.status_code == 201 assert response.json_body['first_name'] == 'Filipe' assert response.json_body['last_name'] == 'Waitman' assert response.json_body.get('id') assert response.json_body.get('created') assert User.select().filter(id=response.json_body['id']).count() == 1 instance = User.select().filter(id=response.json_body['id']).get() assert instance.first_name == 'Filipe' assert instance.last_name == 'Waitman' def test_create_errors(self): data = { 'first_name': 'Filipe', 'last_name': 'Waitman', } response = self.client.post('/api/users/', data, status=400) assert response.status_code == 400 assert response.json_body == {'first_name': ['Missing data for required field.'], 'last_name': ['Missing data for required field.'], 'status_code': 400} # noqa del data['first_name'] response = self.client.post_json('/api/users/', data, status=400) assert response.status_code == 400 assert response.json_body == {'first_name': ['Missing data for required field.'], 'status_code': 400} def test_retrieve(self): user = _create_user(first_name='Filipe', last_name='Waitman') response = self.client.get('/api/users/{}/'.format(user.id)) assert response.status_code == 200 assert 'id' in response.json_body assert 'created' in response.json_body assert response.json_body['first_name'] == 'Filipe' assert response.json_body['last_name'] == 'Waitman' def test_retrieve_errors(self): response = self.client.get('/api/users/999/', status=404) assert response.status_code == 404 assert response.json_body == {'status_code': 404} def test_update(self): user = _create_user(first_name='Filipe', last_name='Waitman') data = { 'last_name': 'New', } response = self.client.patch_json('/api/users/{}/'.format(user.id), data) assert response.status_code == 200 assert 'id' in response.json_body assert 'created' in response.json_body assert response.json_body['first_name'] == 'Filipe' assert response.json_body['last_name'] == 'New' instance = User.select().filter(id=response.json_body['id']).get() assert instance.last_name == 'New' def test_update_errors(self): user = _create_user(first_name='Filipe', last_name='Waitman') data = { 'last_name': '', } response = self.client.patch_json('/api/users/{}/'.format(user.id), data, status=400) assert response.status_code == 400 assert response.json_body == {'last_name': ['Shorter than minimum length 1.'], 'status_code': 400} instance = User.select().filter(id=user.id).get() assert instance.last_name == 'Waitman' def test_delete(self): user = _create_user(first_name='Filipe', last_name='Waitman') response = self.client.delete('/api/users/{}/'.format(user.id)) assert response.status_code == 204 assert User.select().filter(id=user.id).count() == 0 def test_doublename(self): user = _create_user(first_name='Filipe', last_name='Waitman') response = self.client.get('/api/users/{}/doublename/'.format(user.id)) assert response.status_code == 200 assert response.json_body == {'doubled': 'FilipeFilipe'} assert response.headers['header-passed-in'] == '1' def test_pagination(self): _create_user(first_name='Filipe', last_name='Waitman') _create_user(first_name='John', last_name='Doe') response = self.client.get('/api/users/') assert response.status_code == 200 assert response.json_body['count'] == 2 assert response.json_body['next_page'] is None assert response.json_body['prev_page'] is None assert len(response.json_body['results']) == 2 response = self.client.get('/api/users/?per_page=1&x=y') assert response.status_code == 200 assert response.json_body['count'] == 2 assert response.json_body['next_page'] is not None assert response.json_body['prev_page'] is None assert len(response.json_body['results']) == 1 assert 'http' in response.json_body['next_page'] assert 'localhost' in response.json_body['next_page'] assert '/api/users/' in response.json_body['next_page'] assert 'x=y' in response.json_body['next_page'] assert 'per_page=1' in response.json_body['next_page'] assert 'page=2' in response.json_body['next_page'] response = self.client.get('/api/users/?per_page=1&page=2') assert response.status_code == 200 assert response.json_body['count'] == 2 assert response.json_body['next_page'] is None assert response.json_body['prev_page'] is not None assert len(response.json_body['results']) == 1 @mock.patch.object(MyBaseAPI, 'get_current_user', return_value=None) def test_permissions(self, *mocks): user = _create_user(first_name='Filipe', last_name='Waitman') # User API response = self.client.get('/api/users/', status=401) assert response.status_code == 401 response = self.client.post('/api/users/', status=401) assert response.status_code == 401 response = self.client.get('/api/users/{}/'.format(user.id), status=401) assert response.status_code == 401 response = self.client.patch('/api/users/{}/'.format(user.id), status=401) assert response.status_code == 401 response = self.client.delete('/api/users/{}/'.format(user.id), status=401) assert response.status_code == 401 response = self.client.get('/api/users/{}/doublename/'.format(user.id), status=401) assert response.status_code == 401 # UserOpen API response = self.client.get('/api/users/{}/doublename_open/'.format(user.id)) assert response.status_code == 200 # UserReadOnly API response = self.client.get('/api/users/read_only/') assert response.status_code == 200 response = self.client.post('/api/users/read_only/', status=403) assert response.status_code == 403 def test_form_data_create(self): data = { 'first_name': 'Filipe', 'last_name': 'Waitman', } response = self.client.post_json('/api/users/form_data/', data, status=400) assert response.status_code == 400 assert response.json_body == {'first_name': ['Missing data for required field.'], 'last_name': ['Missing data for required field.'], 'status_code': 400} # noqa response = self.client.post('/api/users/form_data/', data) assert response.status_code == 201 def test_no_pagination_list(self): _create_user(first_name='Filipe', last_name='Waitman') response = self.client.get('/api/users/no_pagination/') assert response.status_code == 200 assert len(response.json_body) == 1 assert 'next_page' not in response.json_body assert 'prev_page' not in response.json_body assert 'id' in response.json_body[0] assert 'created' in response.json_body[0] assert response.json_body[0]['first_name'] == 'Filipe' assert response.json_body[0]['last_name'] == 'Waitman' def test_no_pagination_list_via_query_params(self): _create_user(first_name='Filipe', last_name='Waitman') response = self.client.get('/api/users/?paginate=f') assert response.status_code == 200 assert len(response.json_body) == 1 assert 'next_page' not in response.json_body assert 'prev_page' not in response.json_body assert 'id' in response.json_body[0] assert 'created' in response.json_body[0] assert response.json_body[0]['first_name'] == 'Filipe' assert response.json_body[0]['last_name'] == 'Waitman' def test_exception_behavior(self): response = self.client.get('/api/users/exception/handled/', status=499) assert response.status_code == 499 assert response.json_body == {'detail': 'Now this is a weird HTTP code', 'status_code': 499} with pytest.raises(ZeroDivisionError): self.client.get('/api/users/exception/unhandled/') response = self.client.get('/api/users', status=404) # Missing trailing slash (out of wrf scope) assert response.status_code == 404
class TestHttpHandler(TestCaseWithDatabasePerTest): def setUp(self): super(TestHttpHandler, self).setUp() bottle.debug(True) handler = WimHandler(db=self.db) self.engine = handler.engine self.addCleanup(self.engine.stop_threads) self.app = TestApp(handler.wsgi_app) def populate(self, seeds=None): super(TestHttpHandler, self).populate(seeds or eg.consistent_set()) def test_list_wims(self): # Given some wims are registered in the database self.populate() # when a GET /<tenant_id>/wims request arrives tenant_id = uuid('tenant0') response = self.app.get('/{}/wims'.format(tenant_id)) # then the request should be well succeeded self.assertEqual(response.status_code, OK) # and all the registered wims should be present retrieved_wims = {v['name']: v for v in response.json['wims']} for name in retrieved_wims: identifier = int(name.replace('wim', '')) self.assertDictContainsSubset(eg.wim(identifier), retrieved_wims[name]) def test_show_wim(self): # Given some wims are registered in the database self.populate() # when a GET /<tenant_id>/wims/<wim_id> request arrives tenant_id = uuid('tenant0') wim_id = uuid('wim1') response = self.app.get('/{}/wims/{}'.format(tenant_id, wim_id)) # then the request should be well succeeded self.assertEqual(response.status_code, OK) # and the registered wim (wim1) should be present self.assertDictContainsSubset(eg.wim(1), response.json['wim']) # Moreover, it also works with tenant_id = all response = self.app.get('/any/wims/{}'.format(wim_id)) self.assertEqual(response.status_code, OK) self.assertDictContainsSubset(eg.wim(1), response.json['wim']) def test_show_wim__wim_doesnt_exists(self): # Given wim_id does not refer to any already registered wim self.populate() # when a GET /<tenant_id>/wims/<wim_id> request arrives tenant_id = uuid('tenant0') wim_id = uuid('wim999') response = self.app.get('/{}/wims/{}'.format(tenant_id, wim_id), expect_errors=True) # then the result should not be well succeeded self.assertEqual(response.status_code, Not_Found) def test_show_wim__tenant_doesnt_exists(self): # Given wim_id does not refer to any already registered wim self.populate() # when a GET /<tenant_id>/wims/<wim_id> request arrives tenant_id = uuid('tenant999') wim_id = uuid('wim0') response = self.app.get('/{}/wims/{}'.format(tenant_id, wim_id), expect_errors=True) # then the result should not be well succeeded self.assertEqual(response.status_code, Not_Found) def test_edit_wim(self): # Given a WIM exists in the database self.populate() # when a PUT /wims/<wim_id> request arrives wim_id = uuid('wim1') response = self.app.put_json('/wims/{}'.format(wim_id), {'wim': { 'name': 'My-New-Name' }}) # then the request should be well succeeded self.assertEqual(response.status_code, OK) # and the registered wim (wim1) should be present self.assertDictContainsSubset( merge_dicts(eg.wim(1), name='My-New-Name'), response.json['wim']) def test_edit_wim__port_mappings(self): # Given a WIM exists in the database self.populate() # when a PUT /wims/<wim_id> request arrives wim_id = uuid('wim1') response = self.app.put_json( '/wims/{}'.format(wim_id), { 'wim': dict(name='My-New-Name', config={ 'wim_port_mapping': [{ 'datacenter_name': 'dc0', 'pop_wan_mappings': [{ 'device_id': '00:AA:11:BB:22:CC:33:DD', 'device_interface_id': 1, 'service_mapping_info': { 'mapping_type': 'dpid-port', 'wan_switch_dpid': 'BB:BB:BB:BB:BB:BB:BB:0A', 'wan_switch_port': 1 } }] }] }) }) # then the request should be well succeeded self.assertEqual(response.status_code, OK) # and the registered wim (wim1) should be present self.assertDictContainsSubset( merge_dicts(eg.wim(1), name='My-New-Name'), response.json['wim']) # and the port mappings hould be updated mappings = response.json['wim']['config']['wim_port_mapping'] self.assertEqual(len(mappings), 1) self.assertEqual(mappings[0]['pop_wan_mappings'][0]['device_id'], '00:AA:11:BB:22:CC:33:DD') def test_delete_wim(self): # Given a WIM exists in the database self.populate() num_accounts = self.count('wim_accounts') num_associations = self.count('wim_nfvo_tenants') num_mappings = self.count('wim_port_mappings') with self.engine.threads_running(): num_threads = len(self.engine.threads) # when a DELETE /wims/<wim_id> request arrives wim_id = uuid('wim1') response = self.app.delete('/wims/{}'.format(wim_id)) num_threads_after = len(self.engine.threads) # then the request should be well succeeded self.assertEqual(response.status_code, OK) self.assertIn('deleted', response.json['result']) # and the registered wim1 should be deleted response = self.app.get('/any/wims/{}'.format(wim_id), expect_errors=True) self.assertEqual(response.status_code, Not_Found) # and all the dependent records in other tables should be deleted: # wim_accounts, wim_nfvo_tenants, wim_port_mappings self.assertEqual(self.count('wim_nfvo_tenants'), num_associations - eg.NUM_TENANTS) self.assertLess(self.count('wim_port_mappings'), num_mappings) self.assertEqual(self.count('wim_accounts'), num_accounts - eg.NUM_TENANTS) # And the threads associated with the wim accounts should be stopped self.assertEqual(num_threads_after, num_threads - eg.NUM_TENANTS) def test_create_wim(self): # Given no WIM exists yet # when a POST /wims request arrives with the right payload response = self.app.post_json('/wims', {'wim': eg.wim(999)}) # then the request should be well succeeded self.assertEqual(response.status_code, OK) self.assertEqual(response.json['wim']['name'], 'wim999') def test_create_wim__port_mappings(self): self.populate() # when a POST /wims request arrives with the right payload response = self.app.post_json( '/wims', { 'wim': merge_dicts(eg.wim(999), config={ 'wim_port_mapping': [{ 'datacenter_name': 'dc0', 'pop_wan_mappings': [{ 'device_id': 'AA:AA:AA:AA:AA:AA:AA:01', 'device_interface_id': 1, 'service_mapping_info': { 'mapping_type': 'dpid-port', 'wan_switch_dpid': 'BB:BB:BB:BB:BB:BB:BB:01', 'wan_switch_port': 1 } }] }] }) }) # then the request should be well succeeded self.assertEqual(response.status_code, OK) self.assertEqual(response.json['wim']['name'], 'wim999') self.assertEqual( len(response.json['wim']['config']['wim_port_mapping']), 1) def test_create_wim_account(self): # Given a WIM and a NFVO tenant exist but are not associated self.populate([{ 'wims': [eg.wim(0)] }, { 'nfvo_tenants': [eg.tenant(0)] }]) with self.engine.threads_running(): num_threads = len(self.engine.threads) # when a POST /<tenant_id>/wims/<wim_id> arrives response = self.app.post_json( '/{}/wims/{}'.format(uuid('tenant0'), uuid('wim0')), {'wim_account': eg.wim_account(0, 0)}) num_threads_after = len(self.engine.threads) # then a new thread should be created self.assertEqual(num_threads_after, num_threads + 1) # and the request should be well succeeded self.assertEqual(response.status_code, OK) self.assertEqual(response.json['wim_account']['name'], 'wim-account00') # and a new association record should be created association = self.db.get_rows(FROM='wim_nfvo_tenants') assert association self.assertEqual(len(association), 1) self.assertEqual(association[0]['wim_id'], uuid('wim0')) self.assertEqual(association[0]['nfvo_tenant_id'], uuid('tenant0')) self.assertEqual(association[0]['wim_account_id'], response.json['wim_account']['uuid']) def test_create_wim_account__existing_account(self): # Given a WIM, a WIM account and a NFVO tenants exist # But the NFVO and the WIM are not associated self.populate([{ 'wims': [eg.wim(0)] }, { 'nfvo_tenants': [eg.tenant(0)] }, { 'wim_accounts': [eg.wim_account(0, 0)] }]) # when a POST /<tenant_id>/wims/<wim_id> arrives # and it refers to an existing wim account response = self.app.post_json( '/{}/wims/{}'.format(uuid('tenant0'), uuid('wim0')), {'wim_account': { 'name': 'wim-account00' }}) # then the request should be well succeeded self.assertEqual(response.status_code, OK) # and the association should be created association = self.db.get_rows(FROM='wim_nfvo_tenants', WHERE={ 'wim_id': uuid('wim0'), 'nfvo_tenant_id': uuid('tenant0') }) assert association self.assertEqual(len(association), 1) # but no new wim_account should be created wim_accounts = self.db.get_rows(FROM='wim_accounts') self.assertEqual(len(wim_accounts), 1) self.assertEqual(wim_accounts[0]['name'], 'wim-account00') def test_create_wim_account__existing_account__differing(self): # Given a WIM, a WIM account and a NFVO tenants exist # But the NFVO and the WIM are not associated self.populate([{ 'wims': [eg.wim(0)] }, { 'nfvo_tenants': [eg.tenant(0)] }, { 'wim_accounts': [eg.wim_account(0, 0)] }]) # when a POST /<tenant_id>/wims/<wim_id> arrives # and it refers to an existing wim account, # but with different fields response = self.app.post_json('/{}/wims/{}'.format( uuid('tenant0'), uuid('wim0')), { 'wim_account': { 'name': 'wim-account00', 'user': '******', 'password': '******' } }, expect_errors=True) # then the request should not be well succeeded self.assertEqual(response.status_code, Conflict) # some useful message should be displayed response.mustcontain('attempt to overwrite', 'user', 'password') # and the association should not be created association = self.db.get_rows(FROM='wim_nfvo_tenants', WHERE={ 'wim_id': uuid('wim0'), 'nfvo_tenant_id': uuid('tenant0') }) assert not association def test_create_wim_account__association_already_exists(self): # Given a WIM, a WIM account and a NFVO tenants exist # and are correctly associated self.populate() num_assoc_before = self.count('wim_nfvo_tenants') # when a POST /<tenant_id>/wims/<wim_id> arrives trying to connect a # WIM and a tenant for the second time response = self.app.post_json( '/{}/wims/{}'.format(uuid('tenant0'), uuid('wim0')), {'wim_account': { 'user': '******', 'password': '******' }}, expect_errors=True) # then the request should not be well succeeded self.assertEqual(response.status_code, Conflict) # the message should be useful response.mustcontain('There is already', uuid('wim0'), uuid('tenant0')) num_assoc_after = self.count('wim_nfvo_tenants') # and the number of association record should not be increased self.assertEqual(num_assoc_before, num_assoc_after) def test_create_wim__tenant_doesnt_exist(self): # Given a tenant not exists self.populate() # But the user tries to create a wim_account anyway response = self.app.post_json( '/{}/wims/{}'.format(uuid('tenant999'), uuid('wim0')), {'wim_account': { 'user': '******', 'password': '******' }}, expect_errors=True) # then the request should not be well succeeded self.assertEqual(response.status_code, Not_Found) # the message should be useful response.mustcontain('No record was found', uuid('tenant999')) def test_create_wim__wim_doesnt_exist(self): # Given a tenant not exists self.populate() # But the user tries to create a wim_account anyway response = self.app.post_json( '/{}/wims/{}'.format(uuid('tenant0'), uuid('wim999')), {'wim_account': { 'user': '******', 'password': '******' }}, expect_errors=True) # then the request should not be well succeeded self.assertEqual(response.status_code, Not_Found) # the message should be useful response.mustcontain('No record was found', uuid('wim999')) def test_update_wim_account(self): # Given a WIM account connecting a tenant and a WIM exists self.populate() with self.engine.threads_running(): num_threads = len(self.engine.threads) thread = self.engine.threads[uuid('wim-account00')] reload = MagicMock(wraps=thread.reload) with patch.object(thread, 'reload', reload): # when a PUT /<tenant_id>/wims/<wim_id> arrives response = self.app.put_json( '/{}/wims/{}'.format(uuid('tenant0'), uuid('wim0')), {'wim_account': { 'name': 'account888', 'user': '******' }}) num_threads_after = len(self.engine.threads) # then the wim thread should be restarted reload.assert_called_once() # and no thread should be added or removed self.assertEqual(num_threads_after, num_threads) # and the request should be well succeeded self.assertEqual(response.status_code, OK) self.assertEqual(response.json['wim_account']['name'], 'account888') self.assertEqual(response.json['wim_account']['user'], 'user888') def test_update_wim_account__multiple(self): # Given a WIM account connected to several tenants self.populate() with self.engine.threads_running(): # when a PUT /any/wims/<wim_id> arrives response = self.app.put_json( '/any/wims/{}'.format(uuid('wim0')), {'wim_account': { 'user': '******', 'config': { 'x': 888 } }}) # then the request should be well succeeded self.assertEqual(response.status_code, OK) self.assertEqual(len(response.json['wim_accounts']), eg.NUM_TENANTS) for account in response.json['wim_accounts']: self.assertEqual(account['user'], 'user888') self.assertEqual(account['config']['x'], 888) def test_delete_wim_account(self): # Given a WIM account exists and it is connected to a tenant self.populate() num_accounts_before = self.count('wim_accounts') with self.engine.threads_running(): thread = self.engine.threads[uuid('wim-account00')] exit = MagicMock(wraps=thread.exit) num_threads = len(self.engine.threads) with patch.object(thread, 'exit', exit): # when a PUT /<tenant_id>/wims/<wim_id> arrives response = self.app.delete_json('/{}/wims/{}'.format( uuid('tenant0'), uuid('wim0'))) num_threads_after = len(self.engine.threads) # then the wim thread should exit self.assertEqual(num_threads_after, num_threads - 1) exit.assert_called_once() # and the request should be well succeeded self.assertEqual(response.status_code, OK) response.mustcontain('account `wim-account00` deleted') # and the number of wim_accounts should decrease num_accounts_after = self.count('wim_accounts') self.assertEqual(num_accounts_after, num_accounts_before - 1) def test_delete_wim_account__multiple(self): # Given a WIM account exists and it is connected to several tenants self.populate() num_accounts_before = self.count('wim_accounts') with self.engine.threads_running(): # when a PUT /<tenant_id>/wims/<wim_id> arrives response = self.app.delete_json('/any/wims/{}'.format( uuid('wim0'))) # then the request should be well succeeded self.assertEqual(response.status_code, OK) response.mustcontain('account `wim-account00` deleted') response.mustcontain('account `wim-account10` deleted') # and the number of wim_accounts should decrease num_accounts_after = self.count('wim_accounts') self.assertEqual(num_accounts_after, num_accounts_before - eg.NUM_TENANTS) def test_delete_wim_account__doesnt_exist(self): # Given we have a tenant that is not connected to a WIM self.populate() tenant = {'uuid': uuid('tenant888'), 'name': 'tenant888'} self.populate([{'nfvo_tenants': [tenant]}]) num_accounts_before = self.count('wim_accounts') # when a PUT /<tenant_id>/wims/<wim_id> arrives response = self.app.delete('/{}/wims/{}'.format( uuid('tenant888'), uuid('wim0')), expect_errors=True) # then the request should not succeed self.assertEqual(response.status_code, Not_Found) # and the number of wim_accounts should not decrease num_accounts_after = self.count('wim_accounts') self.assertEqual(num_accounts_after, num_accounts_before) def test_create_port_mappings(self): # Given we have a wim and datacenter without any port mappings self.populate([{ 'nfvo_tenants': eg.tenant(0) }] + eg.datacenter_set(888, 0) + eg.wim_set(999, 0)) # when a POST /<tenant_id>/wims/<wim_id>/port_mapping arrives response = self.app.post_json( '/{}/wims/{}/port_mapping'.format(uuid('tenant0'), uuid('wim999')), { 'wim_port_mapping': [{ 'datacenter_name': 'dc888', 'pop_wan_mappings': [{ 'device_id': 'AA:AA:AA:AA:AA:AA:AA:AA', 'device_interface_id': 1, 'service_mapping_info': { 'mapping_type': 'dpid-port', 'wan_switch_dpid': 'BB:BB:BB:BB:BB:BB:BB:BB', 'wan_switch_port': 1 } }] }] }) # the request should be well succeeded self.assertEqual(response.status_code, OK) # and port mappings should be stored in the database port_mapping = self.db.get_rows(FROM='wim_port_mappings') self.assertEqual(len(port_mapping), 1) def test_get_port_mappings(self): # Given WIMS and datacenters exist with port mappings between them self.populate() # when a GET /<tenant_id>/wims/<wim_id>/port_mapping arrives response = self.app.get('/{}/wims/{}/port_mapping'.format( uuid('tenant0'), uuid('wim0'))) # the request should be well succeeded self.assertEqual(response.status_code, OK) # and we should see port mappings for each WIM, datacenter pair mappings = response.json['wim_port_mapping'] self.assertEqual(len(mappings), eg.NUM_DATACENTERS) # ^ In the fixture set all the datacenters are connected to all wims def test_delete_port_mappings(self): # Given WIMS and datacenters exist with port mappings between them self.populate() num_mappings_before = self.count('wim_port_mappings') # when a DELETE /<tenant_id>/wims/<wim_id>/port_mapping arrives response = self.app.delete('/{}/wims/{}/port_mapping'.format( uuid('tenant0'), uuid('wim0'))) # the request should be well succeeded self.assertEqual(response.status_code, OK) # and the number of port mappings should decrease num_mappings_after = self.count('wim_port_mappings') self.assertEqual(num_mappings_after, num_mappings_before - eg.NUM_DATACENTERS)
def test_poll_tasks_invalid_data(): test_app = TestApp(app) # Invalid protocol assert test_app.post_json('/tasks', { 'protocol': 'invalid', 'agent_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 } }, 'max_tasks': 1 }, expect_errors=True).status_int == 400 # Another invalid protocol - so far only protocol version 1 is supported assert test_app.post_json('/tasks', { 'protocol': 5, 'agent_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 } }, 'max_tasks': 1 }, expect_errors=True).status_int == 400 # Invalid agent_id assert test_app.post_json('/tasks', { 'protocol': 1, 'agent_id': 'invalid_agent', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 } }, 'max_tasks': 1 }, expect_errors=True).status_int == 400 assert test_app.post_json('/tasks', { 'protocol': 1, 'agent_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 } }, 'max_tasks': 'many_tasks' }, expect_errors=True).status_int == 400 # Extra fields assert test_app.post_json('/tasks', { 'protocol': 1, 'agent_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 } }, 'max_tasks': 'many_tasks', 'extra_field': 1234 }, expect_errors=True).status_int == 400 # Extra fields assert test_app.post_json('/tasks', { 'protocol': 1, 'agent_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18', 'somewhere': 'else' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 } }, 'max_tasks': 'many_tasks' }, expect_errors=True).status_int == 400
def SemanticCompletionAvailable_Works_test(): app = TestApp( handlers.app ) request_data = BuildRequest( filetype = 'python' ) ok_( app.post_json( '/semantic_completion_available', request_data ).json )
def test_preload_module(): app = TestApp(handlers.app) request_data = {'modules': ['os', 'sys']} ok_(app.post_json('/preload_module', request_data))
def test_email_field(self): app = TestApp(main({})) content = {'email': '*****@*****.**'} app.post_json('/newsletter', params=content)
class BaseTestAPI(unittest.TestCase): """ Test login, logout, and session handling """ @classmethod def setUpClass(cls): """Set up resources to be shared within a test class""" #TODO: refactor into a pytest class fixtures and inject as necessary # Create an empty session ID cls.session_id = "" # update application's db config options so unittests # run against test databases suite = cls.__name__.lower() config = dataactcore.config.CONFIG_DB cls.num = randint(1, 9999) config['error_db_name'] = 'unittest{}_{}_error_data'.format( cls.num, suite) config['job_db_name'] = 'unittest{}_{}_job_tracker'.format( cls.num, suite) config['user_db_name'] = 'unittest{}_{}_user_manager'.format( cls.num, suite) config['validator_db_name'] = 'unittest{}_{}_validator'.format( cls.num, suite) config['staging_db_name'] = 'unittest{}_{}_staging'.format( cls.num, suite) dataactcore.config.CONFIG_DB = config # drop and re-create test user db/tables setupUserDB() # drop and re-create test job db/tables setupJobTrackerDB() # drop and re-create test error db/tables setupErrorDB() # drop and re-create test validation db/tables setupValidationDB() # load e-mail templates setupEmails() #get test users try: with open('test.json') as test_users_file: test_users = json.load(test_users_file) test_users = test_users except: #if no test.json, provide some default e-mail accounts for tests test_users = {} test_users['admin_email'] = '*****@*****.**' test_users['change_user_email'] = '*****@*****.**' test_users['password_reset_email'] = '*****@*****.**' test_users['inactive_email'] = '*****@*****.**' test_users['password_lock_email'] = '*****@*****.**' test_users['expired_lock_email'] = '*****@*****.**' test_users['agency_admin_email'] = '*****@*****.**' # This email is for a regular agency_user email that is to be used for testing functionality # expected by a normal, base user test_users['agency_user'] = '******' if 'approved_email' not in test_users: test_users['approved_email'] = '*****@*****.**' if 'submission_email' not in test_users: test_users['submission_email'] = '*****@*****.**' user_password = '******' admin_password = '******' #setup test users userEmails = [ "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**", test_users["admin_email"], test_users["approved_email"], "*****@*****.**" ] userStatus = [ "awaiting_confirmation", "email_confirmed", "awaiting_approval", "awaiting_approval", "awaiting_approval", "approved", "approved", "denied" ] userPermissions = [ 0, AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.WEBSITE_ADMIN + AccountType.AGENCY_USER, AccountType.AGENCY_USER, AccountType.AGENCY_USER ] # Add new users userDb = UserHandler() userDb.createUserWithPassword(test_users["submission_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["change_user_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["password_reset_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["inactive_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users["password_lock_email"], user_password, Bcrypt()) userDb.createUserWithPassword(test_users['expired_lock_email'], user_password, Bcrypt()) userDb.createUserWithPassword(test_users['agency_admin_email'], admin_password, Bcrypt(), permission=4) userDb.createUserWithPassword(test_users['agency_user'], user_password, Bcrypt()) # Set the Agency for the agency user agencyUser = userDb.getUserByEmail(test_users['agency_user']) userDb.session.commit() cls.agency_user_id = agencyUser.user_id # Set the specified account to be expired expiredUser = userDb.getUserByEmail(test_users['expired_lock_email']) today = parse(time.strftime("%c")) expiredUser.last_login_date = (today - timedelta(days=120)).strftime("%c") userDb.session.commit() # Create users for status testing for index in range(len(userEmails)): email = userEmails[index] userDb.addUnconfirmedEmail(email) user = userDb.getUserByEmail(email) userDb.changeStatus(user, userStatus[index]) userDb.setPermission(user, userPermissions[index]) #set up approved user user = userDb.getUserByEmail(test_users['approved_email']) user.username = "******" userDb.setPassword(user, user_password, Bcrypt()) cls.approved_user_id = user.user_id #set up admin user admin = userDb.getUserByEmail(test_users['admin_email']) userDb.setPassword(admin, admin_password, Bcrypt()) admin.name = "Mr. Manager" admin.cgac_code = "SYS" userDb.session.commit() #set up status changed user statusChangedUser = userDb.getUserByEmail( test_users["change_user_email"]) cls.status_change_user_id = statusChangedUser.user_id statusChangedUser.name = "Test User" statusChangedUser.user_status_id = userDb.getUserStatusId( "email_confirmed") userDb.session.commit() #set up deactivated user user = userDb.getUserByEmail(test_users["inactive_email"]) user.last_login_date = time.strftime("%c") user.is_active = False userDb.session.commit() #set up info needed by the individual test classes cls.test_users = test_users cls.user_password = user_password cls.admin_password = admin_password cls.interfaces = InterfaceHolder() cls.jobTracker = cls.interfaces.jobDb cls.errorDatabase = cls.interfaces.errorDb cls.userDb = cls.interfaces.userDb cls.local = CONFIG_BROKER['local'] def setUp(self): """Set up broker unit tests.""" app = createApp() app.config['TESTING'] = True self.app = TestApp(app) @classmethod def tearDownClass(cls): """Tear down class-level resources.""" cls.interfaces.close() dropDatabase(cls.interfaces.userDb.dbName) dropDatabase(cls.interfaces.jobDb.dbName) dropDatabase(cls.interfaces.errorDb.dbName) def tearDown(self): """Tear down broker unit tests.""" def login_approved_user(self): """Log an agency user (non-admin) into broker.""" #TODO: put user data in pytest fixture; put credentials in config file user = { "username": self.test_users['approved_email'], "password": self.user_password } response = self.app.post_json( "/v1/login/", user, headers={"x-session-id": self.session_id}) self.session_id = response.headers["x-session-id"] return response def login_agency_user(self): """Log an agency user (non-admin) into broker.""" #TODO: put user data in pytest fixture; put credentials in config file user = { "username": self.test_users['agency_user'], "password": self.user_password } response = self.app.post_json( "/v1/login/", user, headers={"x-session-id": self.session_id}) self.session_id = response.headers["x-session-id"] return response def login_admin_user(self): """Log an admin user into broker.""" #TODO: put user data in pytest fixture; put credentials in config file user = { "username": self.test_users['admin_email'], "password": self.admin_password } response = self.app.post_json( "/v1/login/", user, headers={"x-session-id": self.session_id}) self.session_id = response.headers["x-session-id"] return response def login_agency_admin_user(self): """ Log an agency admin user into broker. """ # TODO: put user data in pytest fixture; put credentials in config file user = { "username": self.test_users['agency_admin_email'], "password": self.admin_password } response = self.app.post_json( "/v1/login/", user, headers={"x-session-id": self.session_id}) self.session_id = response.headers["x-session-id"] return response def login_inactive_user(self): """Attempt to log in an inactive user""" #TODO: put user data in pytest fixture; put credentials in config file user = { "username": self.test_users['inactive_email'], "password": self.user_password } response = self.app.post_json( "/v1/login/", user, expect_errors=True, headers={"x-session-id": self.session_id}) try: self.session_id = response.headers["x-session-id"] except KeyError: # Session ID doesn't come back for inactive user, set to empty self.session_id = "" return response def login_expired_locked_user(self): """Force user to have their account locked then attempt to login again""" # TODO: put user data in pytest fixture; put credentials in config file user = { "username": self.test_users['expired_lock_email'], "password": self.user_password } response = self.app.post_json( "/v1/login/", user, expect_errors=True, headers={"x-session-id": self.session_id}) try: self.session_id = response.headers["x-session-id"] except KeyError: # Session ID doesn't come back for inactive user, set to empty self.session_id = "" return response def login_password_locked_user(self): """Force user to have their account locked then attempt to login again""" # TODO: put user data in pytest fixture; put credentials in config file user = { "username": self.test_users['password_lock_email'], "password": "******" } response = self.app.post_json( "/v1/login/", user, expect_errors=True, headers={"x-session-id": self.session_id}) try: self.session_id = response.headers["x-session-id"] except KeyError: # Session ID doesn't come back for inactive user, set to empty self.session_id = "" return response def login_other_user(self, username, password): """Log a specific user into broker.""" user = {"username": username, "password": password} response = self.app.post_json( "/v1/login/", user, headers={"x-session-id": self.session_id}) self.session_id = response.headers["x-session-id"] return response def logout(self): """Log user out of broker.""" return self.app.post("/v1/logout/", {}, headers={"x-session-id": self.session_id}) def session_route(self): """Get session.""" return self.app.get("/v1/session/", headers={"x-session-id": self.session_id}) def check_response(self, response, status, message=None): """Perform common tests on API responses.""" self.assertEqual(response.status_code, status) self.assertEqual(response.headers.get("Content-Type"), "application/json") try: self.assertIsInstance(response.json, dict) except AttributeError: self.fail("Response is missing JSON component") json = response.json if message: self.assertEqual(message, json["message"])
def test_poll_task_capability_change(): test_app = TestApp(app) test_app.post_json( '/tasks', { 'protocol': 1, 'agent_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 } }, 'max_tasks': 5 }) test_app.post_json( '/tasks', { 'protocol': 1, 'agent_id': 'de305d54-75b4-431b-adb2-eb6b9e546013', 'agent_name': 'Agent 007', 'agent_location': { 'country': 'FI', 'region': '18' }, 'agent_time': '2012-04-23T18:25:43.511Z', 'agent_capabilities': { 'task-type-1': { 'version': 1 }, 'task-type-2': { 'version': 2 }, 'task-type-3': { 'version': 3 }, 'task-type-4': { 'version': 4 } }, 'max_tasks': 5 }) session = create_session() agent = session.query(Agent).filter( Agent.uuid == 'de305d54-75b4-431b-adb2-eb6b9e546013').one() try: session.query(AgentCapability).filter(AgentCapability.agent_uuid == agent.uuid).\ filter(AgentCapability.type == 'task-type-1').one() session.query(AgentCapability).filter(AgentCapability.agent_uuid == agent.uuid).\ filter(AgentCapability.type == 'task-type-2').one() session.query(AgentCapability).filter(AgentCapability.agent_uuid == agent.uuid).\ filter(AgentCapability.type == 'task-type-3').one() session.query(AgentCapability).filter(AgentCapability.agent_uuid == agent.uuid).\ filter(AgentCapability.type == 'task-type-4').one() finally: session.close()
def GetCompletions_IdentifierCompleter_StartColumn_AfterWord_test(): app = TestApp(handlers.app) completion_data = BuildRequest(contents='oo foo foogoo ba', column_num=11) response_data = app.post_json('/completions', completion_data).json eq_(8, response_data['completion_start_column'])
def test_usages(): app = TestApp(handlers.app) filepath = fixture_filepath('usages.py') request_data = { 'source': read_file(filepath), 'line': 8, 'col': 5, 'source_path': filepath } definitions = app.post_json('/usages', request_data).json['definitions'] assert_that( definitions, contains_inanyorder( { 'module_path': filepath, 'name': 'f', 'type': 'function', 'in_builtin_module': False, 'line': 1, 'column': 4, 'docstring': 'f()\n\nModule method docs\n' 'Are dedented, like you might expect', 'description': 'def f', 'full_name': '__main__.f', 'is_keyword': False }, { 'module_path': filepath, 'name': 'f', 'type': 'statement', 'in_builtin_module': False, 'line': 6, 'column': 4, 'description': 'f', 'docstring': '', 'full_name': '__main__.f', 'is_keyword': False }, { 'module_path': filepath, 'name': 'f', 'type': 'statement', 'in_builtin_module': False, 'line': 7, 'column': 4, 'description': 'f', 'docstring': '', 'full_name': '__main__.f', 'is_keyword': False }, { 'module_path': filepath, 'name': 'f', 'type': 'statement', 'in_builtin_module': False, 'line': 8, 'column': 4, 'description': 'f', 'docstring': '', 'full_name': '__main__.f', 'is_keyword': False }))
class Cs_Subcommands_test(Cs_Handlers_test): def GoTo_Basic_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GoTo'], line_num=9, column_num=15, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'Program.cs'), 'line_num': 7, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementation_Basic_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementation'], line_num=13, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 30, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementation_NoImplementation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementation'], line_num=17, column_num=13, contents=contents, filetype='cs', filepath=filepath) try: self._app.post_json('/run_completer_command', goto_data).json raise Exception("Expected a 'No implementations found' error") except AppError as e: if 'No implementations found' in str(e): pass else: raise finally: self._StopOmniSharpServer(filepath) def CsCompleter_InvalidLocation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementation'], line_num=2, column_num=1, contents=contents, filetype='cs', filepath=filepath) try: self._app.post_json('/run_completer_command', goto_data).json raise Exception( 'Expected a "Can\\\'t jump to implementation" error') except AppError as e: if 'Can\\\'t jump to implementation' in str(e): pass else: raise finally: self._StopOmniSharpServer(filepath) def GoToImplementationElseDeclaration_NoImplementation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementationElseDeclaration'], line_num=17, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 35, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementationElseDeclaration_SingleImplementation_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementationElseDeclaration'], line_num=13, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_( { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 30, 'column_num': 3 }, self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GoToImplementationElseDeclaration_MultipleImplementations_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) goto_data = self._BuildRequest( completer_target='filetype_default', command_arguments=['GoToImplementationElseDeclaration'], line_num=21, column_num=13, contents=contents, filetype='cs', filepath=filepath) eq_([{ 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 43, 'column_num': 3 }, { 'filepath': self._PathToTestFile('testy', 'GotoTestCase.cs'), 'line_num': 48, 'column_num': 3 }], self._app.post_json('/run_completer_command', goto_data).json) self._StopOmniSharpServer(filepath) def GetType_EmptyMessage_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=1, column_num=1, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u""}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_VariableDeclaration_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=4, column_num=5, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u"string"}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_VariableUsage_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=5, column_num=5, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u"string str"}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_Constant_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=4, column_num=14, contents=contents, filetype='cs', filepath=filepath) eq_({u'message': u"System.String"}, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetType_DocsIgnored_test(self): filepath = self._PathToTestFile('testy', 'GetTypeTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) gettype_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetType'], line_num=9, column_num=34, contents=contents, filetype='cs', filepath=filepath) eq_({ u'message': u"int GetTypeTestCase.an_int_with_docs;", }, self._app.post_json('/run_completer_command', gettype_data).json) self._StopOmniSharpServer(filepath) def GetDoc_Variable_test(self): filepath = self._PathToTestFile('testy', 'GetDocTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) getdoc_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetDoc'], line_num=13, column_num=28, contents=contents, filetype='cs', filepath=filepath) eq_( { 'detailed_info': 'int GetDocTestCase.an_int;\n' 'an integer, or something', }, self._app.post_json('/run_completer_command', getdoc_data).json) self._StopOmniSharpServer(filepath) def GetDoc_Function_test(self): filepath = self._PathToTestFile('testy', 'GetDocTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) getdoc_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['GetDoc'], line_num=33, column_num=27, contents=contents, filetype='cs', filepath=filepath) # It seems that Omnisharp server eats newlines eq_( { 'detailed_info': 'int GetDocTestCase.DoATest();\n' ' Very important method. With multiple lines of ' 'commentary And Format- -ting', }, self._app.post_json('/run_completer_command', getdoc_data).json) self._StopOmniSharpServer(filepath) def _RunFixIt(self, line, column, expected_result): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) fixit_data = self._BuildRequest(completer_target='filetype_default', command_arguments=['FixIt'], line_num=line, column_num=column, contents=contents, filetype='cs', filepath=filepath) eq_(expected_result, self._app.post_json('/run_completer_command', fixit_data).json) self._StopOmniSharpServer(filepath) def FixIt_RemoveSingleLine_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 11, 1, { u'fixits': [{ u'location': { u'line_num': 11, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': '', u'range': { u'start': { u'line_num': 10, u'column_num': 20, u'filepath': filepath }, u'end': { u'line_num': 11, u'column_num': 30, u'filepath': filepath }, } }] }] }) def FixIt_MultipleLines_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 19, 1, { u'fixits': [{ u'location': { u'line_num': 19, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': "return On", u'range': { u'start': { u'line_num': 20, u'column_num': 13, u'filepath': filepath }, u'end': { u'line_num': 21, u'column_num': 35, u'filepath': filepath }, } }] }] }) def FixIt_SpanFileEdge_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 1, 1, { u'fixits': [{ u'location': { u'line_num': 1, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': 'System', u'range': { u'start': { u'line_num': 1, u'column_num': 7, u'filepath': filepath }, u'end': { u'line_num': 3, u'column_num': 18, u'filepath': filepath }, } }] }] }) def FixIt_AddTextInLine_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 9, 1, { u'fixits': [{ u'location': { u'line_num': 9, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': ', StringComparison.Ordinal', u'range': { u'start': { u'line_num': 9, u'column_num': 29, u'filepath': filepath }, u'end': { u'line_num': 9, u'column_num': 29, u'filepath': filepath }, } }] }] }) def FixIt_ReplaceTextInLine_test(self): filepath = self._PathToTestFile('testy', 'FixItTestCase.cs') self._RunFixIt( 10, 1, { u'fixits': [{ u'location': { u'line_num': 10, u'column_num': 1, u'filepath': filepath }, u'chunks': [{ u'replacement_text': 'const int', u'range': { u'start': { u'line_num': 10, u'column_num': 13, u'filepath': filepath }, u'end': { u'line_num': 10, u'column_num': 16, u'filepath': filepath }, } }] }] }) def StopServer_NoErrorIfNotStarted_test(self): filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') self._StopOmniSharpServer(filepath) # Success = no raise def StopServer_KeepLogFiles_test(self): yield self._StopServer_KeepLogFiles, True yield self._StopServer_KeepLogFiles, False def _StopServer_KeepLogFiles(self, keeping_log_files): self._ChangeSpecificOptions( {'server_keep_logfiles': keeping_log_files}) self._app = TestApp(handlers.app) self._app.post_json( '/ignore_extra_conf_file', {'filepath': self._PathToTestFile('.ycm_extra_conf.py')}) filepath = self._PathToTestFile('testy', 'GotoTestCase.cs') contents = open(filepath).read() event_data = self._BuildRequest(filepath=filepath, filetype='cs', contents=contents, event_name='FileReadyToParse') self._app.post_json('/event_notification', event_data) self._WaitUntilOmniSharpServerReady(filepath) event_data = self._BuildRequest(filetype='cs', filepath=filepath) debuginfo = self._app.post_json('/debug_info', event_data).json log_files_match = re.search("^OmniSharp logfiles:\n(.*)\n(.*)", debuginfo, re.MULTILINE) stdout_logfiles_location = log_files_match.group(1) stderr_logfiles_location = log_files_match.group(2) try: ok_(os.path.exists(stdout_logfiles_location), "Logfile should exist at {0}".format(stdout_logfiles_location)) ok_(os.path.exists(stderr_logfiles_location), "Logfile should exist at {0}".format(stderr_logfiles_location)) finally: self._StopOmniSharpServer(filepath) if keeping_log_files: ok_( os.path.exists(stdout_logfiles_location), "Logfile should still exist at " "{0}".format(stdout_logfiles_location)) ok_( os.path.exists(stderr_logfiles_location), "Logfile should still exist at " "{0}".format(stderr_logfiles_location)) else: ok_( not os.path.exists(stdout_logfiles_location), "Logfile should no longer exist at " "{0}".format(stdout_logfiles_location)) ok_( not os.path.exists(stderr_logfiles_location), "Logfile should no longer exist at " "{0}".format(stderr_logfiles_location))
class DiffFileTests(unittest.TestCase): def setUp(self): self.testapp = TestApp(application) def tearDown(self): try: shutil.rmtree(FILE_DB_SETTINGS['folder']) except: pass def test_diff_without_data(self): res = self.testapp.get('/v1/diff/1', status=400) self.assertEqual(400, res.status_code) self.assertEqual('400 Bad Request', res.status) self.assertEqual( '{"error": "File with id = 1 and side = left is not provided"}', res.body) def test_diff_without_right_data(self): self.testapp.post_json('/v1/diff/1/left', {'payload': 'sds21'}, headers={'Content-Type': 'application/json'}, status=200) res = self.testapp.get('/v1/diff/1', status=400) self.assertEqual(400, res.status_code) self.assertEqual('400 Bad Request', res.status) self.assertEqual( '{"error": "File with id = 1 and side = right is not provided"}', res.body) def test_diff_without_left_data(self): self.testapp.post_json('/v1/diff/1/right', {'payload': 'sds21'}, headers={'Content-Type': 'application/json'}, status=200) res = self.testapp.get('/v1/diff/1', status=400) self.assertEqual(400, res.status_code) self.assertEqual('400 Bad Request', res.status) self.assertEqual( '{"error": "File with id = 1 and side = left is not provided"}', res.body) def test_diff_with_diffrent_length_data(self): self.testapp.post_json('/v1/diff/1/left', {'payload': 'sds21d'}, headers={'Content-Type': 'application/json'}, status=200) self.testapp.post_json('/v1/diff/1/right', {'payload': 'sds21'}, headers={'Content-Type': 'application/json'}, status=200) res = self.testapp.get('/v1/diff/1', status=200) self.assertEqual(200, res.status_code) self.assertEqual('200 OK', res.status) self.assertEqual('{"payload": "Different length"}', res.body) def test_diff_with_equal_data(self): self.testapp.post_json('/v1/diff/1/left', {'payload': 'sds21'}, headers={'Content-Type': 'application/json'}, status=200) self.testapp.post_json('/v1/diff/1/right', {'payload': 'sds21'}, headers={'Content-Type': 'application/json'}, status=200) res = self.testapp.get('/v1/diff/1', status=200) self.assertEqual(200, res.status_code) self.assertEqual('200 OK', res.status) self.assertEqual('{"payload": "Equal"}', res.body) def test_diff_with_equal_length_diff_data(self): self.testapp.post_json('/v1/diff/1/left', {'payload': 'sas21'}, headers={'Content-Type': 'application/json'}, status=200) self.testapp.post_json('/v1/diff/1/right', {'payload': 'sds21'}, headers={'Content-Type': 'application/json'}, status=200) res = self.testapp.get('/v1/diff/1', status=200) self.assertEqual(200, res.status_code) self.assertEqual('200 OK', res.status) self.assertDictEqual({"payload": [{ "length": 1, "offset": 1 }]}, json.loads(res.body))
class TestUpdateTable(unittest.TestCase): @mock.patch("ddbmock.database.table.time") # Brrr def setUp(self, m_time): from ddbmock.database.db import dynamodb from ddbmock.database.table import Table from ddbmock.database.key import PrimaryKey from ddbmock import main app = main({}) from webtest import TestApp self.app = TestApp(app) m_time.time.return_value = NOW dynamodb.hard_reset() hash_key = PrimaryKey(TABLE_HK_NAME, TABLE_HK_TYPE) range_key = PrimaryKey(TABLE_RK_NAME, TABLE_RK_TYPE) t1 = Table(TABLE_NAME, TABLE_RT, TABLE_WT, hash_key, range_key, status="ACTIVE") dynamodb.data[TABLE_NAME] = t1 def tearDown(self): from ddbmock.database.db import dynamodb dynamodb.hard_reset() @mock.patch("ddbmock.database.table.time") def test_update(self, m_time): from ddbmock.database.db import dynamodb m_time.time.return_value = NOW2 self.maxDiff = None request = { "TableName": TABLE_NAME, "ProvisionedThroughput": { "ReadCapacityUnits": TABLE_RT2, "WriteCapacityUnits": TABLE_WT2, }, } expected = { u'TableDescription': { u'CreationDateTime': NOW, u'ItemCount': 0, u'KeySchema': { u'HashKeyElement': { u'AttributeName': u'hash_key', u'AttributeType': u'N', }, u'RangeKeyElement': { u'AttributeName': u'range_key', u'AttributeType': u'S', }, }, u'ProvisionedThroughput': { u'LastDecreaseDateTime': NOW2, u'ReadCapacityUnits': TABLE_RT2, u'WriteCapacityUnits': TABLE_WT2, }, u'TableName': TABLE_NAME, u'TableSizeBytes': 0, u'TableStatus': u'UPDATING' } } # Protocol check res = self.app.post_json('/', request, headers=HEADERS, status=200) self.assertEqual(expected, json.loads(res.body)) self.assertEqual('application/x-amz-json-1.0; charset=UTF-8', res.headers['Content-Type']) # Live data check data = dynamodb.data assert TABLE_NAME in data table = data[TABLE_NAME] self.assertEqual(TABLE_RT2, table.rt) self.assertEqual(TABLE_WT2, table.wt)
class Client(object): def __init__(self): self.test_core = TestApp(Core().execute_wsgi()) def get_api(self, api_url, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.get(__api_url) response.json = test_core_response.json response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body response.content_type = test_core_response.content_type return response def post_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.post_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def patch_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.patch_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def put_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.put_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response def delete_api(self, api_url, data, *auth): response = APIResponse() __api_url = str(api_url) if auth: self.test_core.set_authorization(auth) test_core_response = self.test_core.delete_json(__api_url, params=data) response.json = json.dumps(test_core_response.json) response.status = test_core_response.status response.status_code = test_core_response.status_code response.body = test_core_response.body return response