def create_database_objects(self, metadata: dict, connection: 'psycopg2.connection', **kwargs): for key, metadata_value in metadata.items(): create_script: str = CREATE_SCRIPTS.get(key) if create_script is not None: kwargs[key + '_Name'] = metadata_value['Name'] if key == 'Databases': dbname = create_extra_test_database() metadata_value['Name'] = dbname kwargs[key + '_Name'] = dbname connection_details = get_connection_details() connection_details['dbname'] = dbname connection = psycopg2.connect(**connection_details) connection.autocommit = True else: self.execute_script(create_script.format(**kwargs), connection) get_oid_script = GET_OID_SCRIPTS.get(key) if get_oid_script is not None: cursor = self.execute_script( get_oid_script.format(**kwargs), connection) kwargs[key + '_OID'] = cursor.fetchone()[0] children = metadata_value.get('Children') if children is not None: object_names = self.create_database_objects( children, connection, **kwargs) kwargs.update(object_names) return kwargs
def test_list_databases(self): """Test that the list databases handler correctly lists the connection's databases""" connection_service = ConnectionService() connection_uri = 'someuri' request_context = MockRequestContext() params = ListDatabasesParams() params.owner_uri = connection_uri connection = psycopg2.connect(**get_connection_details()) connection_service.get_connection = mock.Mock(return_value=connection) # If I call the list database handler connection_service.handle_list_databases(request_context, params) # Then a response is returned that lists all the databases database_names = request_context.last_response_params.database_names self.assertGreater(len(database_names), 0) self.assertIn(connection.get_dsn_parameters()['dbname'], database_names)
def test_get_database_info_request_integration(self): # Set up the request parameters params = GetDatabaseInfoParameters() params.owner_uri = 'test_uri' request_context = MockRequestContext() # Set up the connection service to return our connection connection = psycopg2.connect(**get_connection_details()) self.connection_service.get_connection = mock.Mock(return_value=connection) # If I send a get_database_info request self.admin_service._handle_get_database_info_request(request_context, params) # Then the service responded with a valid database owner owner = request_context.last_response_params.database_info.options['owner'] cursor = connection.cursor() cursor.execute('select usename from pg_catalog.pg_user') usernames = [row[0] for row in cursor.fetchall()] self.assertIn(owner, usernames)
def test_connection_fails(self): # If I set up a connection request with incorrect connection parameters owner_uri = 'test_uri' connection_details = get_connection_details() connection_details['dbname'] += '_fail' connection_request, language_flavor_notification = DefaultRPCTestMessages.connection_request(owner_uri, connection_details) # Then when the connection request is made, a connection failed response notification will be returned def verify_connection_complete(notification): params = notification['params'] self.assertIsNone(params['connectionSummary']) self.assertIsNotNone(params['errorMessage']) self.assertIsNotNone(params['messages']) self.assertIsNone(params['serverInfo']) connection_request.notification_verifiers[0] = (connection_request.notification_verifiers[0][0], verify_connection_complete) language_flavor_notification.notification_verifiers = None # Run the test with the incorrect connection parameters and failure response verifier test_case = JSONRPCTestCase([connection_request, language_flavor_notification]) test_case.run()
def test_connection_successful(self): # If I set up a connection request with valid connection parameters owner_uri = 'test_uri' connection_details = get_connection_details() connection_request, language_flavor_notification = DefaultRPCTestMessages.connection_request(owner_uri, connection_details) # Then when the connection request is made, a successful response notification will be returned def verify_connection_complete(notification): params = notification['params'] self.assertIn('connectionSummary', params) connection_summary = params['connectionSummary'] self.assertEqual(connection_summary['databaseName'], connection_details['dbname']) self.assertEqual(connection_summary['serverName'], connection_details['host']) self.assertEqual(connection_summary['userName'], connection_details['user']) self.assertIsNone(params['errorMessage']) self.assertIn('serverInfo', params) connection_request.notification_verifiers[0] = (connection_request.notification_verifiers[0][0], verify_connection_complete) # Run the test with the valid connection request and response verifier test_case = JSONRPCTestCase([connection_request, language_flavor_notification]) test_case.run()
def test_scripting(self): connection_details = get_connection_details() connection = psycopg2.connect(**connection_details) connection.autocommit = True args = self.create_database_objects(META_DATA, connection) created_object_names = {} for key, value in args.items(): if key[-5:] == "_Name": created_object_names[key] = value owner_uri = 'test_uri' connection_details['dbname'] = args["Databases_Name"] connection_messages = DefaultRPCTestMessages.connection_request( owner_uri, connection_details) test_messages = [connection_messages[0], connection_messages[1]] def generate_scripting_requests(metadata): scripting_requests = [] for key, metadata_value in metadata.items(): for operation in metadata_value: scripting_object = {} scripting_object['name'] = created_object_names[key + 's_Name'] if key == 'Function': scripting_object['name'] = created_object_names[ key + 's_Name'] + ScriptingJSONRPCTests.CREATED_FUNCTION_PARAMETER_LIST scripting_object['schema'] = 'public' if key in [ 'Table', 'View', 'Function' ] else None scripting_object['type'] = key scripting_objects = [scripting_object] params = {} params['connectionString'] = None params['filePath'] = None params['scriptingObjects'] = scripting_objects params['scriptDestination'] = 'ToEditor' params['includeObjectCriteria'] = None params['excludeObjectCriteria'] = None params['includeSchemas'] = None params['excludeSchemas'] = None params['includeTypes'] = None params['excludeTypes'] = None params['scriptOptions'] = None params['connectionDetails'] = None params['ownerURI'] = 'test_uri' params['operation'] = operation.value scripting_request = RPCTestMessage( 'scripting/script', json.dumps(params), JSONRPCMessageType.Request, response_verifier=lambda response: self. assertIsNotNone(response['result']['script']), notification_verifiers=None) scripting_requests.append(scripting_request) return scripting_requests # create requests based on metadata: scripting_requests = generate_scripting_requests(SCRIPT_META_DATA) test_messages += scripting_requests JSONRPCTestCase(test_messages).run()
def test_object_explorer(self): connection_details = get_connection_details() connection = psycopg2.connect(**connection_details) connection.autocommit = True self.args = self.create_database_objects(META_DATA, connection) owner_uri = 'test_uri' connection_details['dbname'] = self.args["Databases_Name"] connection_messages = DefaultRPCTestMessages.connection_request( owner_uri, connection_details) test_messages = [connection_messages[0], connection_messages[1]] expected_session_id = f'objectexplorer://{quote(connection_details["user"])}' + \ f'@{quote(connection_details["host"])}:{connection_details["port"]}:{quote(connection_details["dbname"])}/' def session_created_verifier(notification): params = notification['params'] self.assertIsNone(params['errorMessage']) self.assertTrue(params['success']) self.assertIn('rootNode', params) root_node = params['rootNode'] self.assertEqual(root_node['label'], connection_details['dbname']) self.assertEqual(root_node['nodeType'], 'Database') self.assertIn('metadata', root_node) metadata = root_node['metadata'] self.assertEqual(metadata['metadataTypeName'], 'Database') self.assertEqual(metadata['name'], connection_details['dbname']) create_session_request = RPCTestMessage( 'objectexplorer/createsession', '{{"options":{}}}'.format(json.dumps(connection_details)), JSONRPCMessageType.Request, response_verifier=lambda response: self.assertEqual( response['result']['sessionId'], expected_session_id), notification_verifiers=[(lambda notification: notification[ 'method'] == 'objectexplorer/sessioncreated', session_created_verifier)]) def expand_completed_verifier(node_path, expected_nodes, exact_node_match, notification): params = notification['params'] self.assertIsNone(params['errorMessage']) self.assertEqual(params['nodePath'], node_path) nodes = params['nodes'] self.assertGreater(len(nodes), 0) found_nodes = set() for node in nodes: self.assertIsNone(node['errorMessage']) found_nodes.add(node['label']) if exact_node_match: self.assertEqual(found_nodes, expected_nodes) else: for node in expected_nodes: self.assertIn(node, found_nodes) def create_expand_test_message(node_path, expected_nodes, exact_node_match): return RPCTestMessage( 'objectexplorer/expand', '{{"sessionId":"{}","nodePath":"{}"}}'.format( expected_session_id, node_path), JSONRPCMessageType.Request, response_verifier=lambda response: self.assertTrue(response[ 'result']), notification_verifiers=[ (lambda notification: notification['method'] == 'objectexplorer/expandCompleted' and notification[ 'params']['nodePath'] == node_path, functools.partial(expand_completed_verifier, node_path, expected_nodes, exact_node_match)) ]) test_messages += [create_session_request] self.create_expand_messages(META_DATA, '/{0}/', create_expand_test_message, test_messages, **self.args) JSONRPCTestCase(test_messages).run() # Delete the created test role role_name = self.args['Roles_Name'] self.delete_role(connection, role_name)