Beispiel #1
0
    def test_get_text_full(self):
        """Text the workspace service's public get_text method when getting the full text of a file"""
        # Set up the service with a file
        workspace_service = WorkspaceService()
        file_uri = 'untitled:Test_file'
        file_text = os.linesep.join(['line1', 'line 2 content', ' line 3 '])
        workspace_service._workspace.open_file(file_uri, file_text)

        # Retrieve the full text of the file and make sure it matches
        result_text = workspace_service.get_text(file_uri, None)
        self.assertEqual(result_text, file_text)
Beispiel #2
0
    def test_get_text_selection(self):
        """Text the workspace service's public get_text method when getting a selection of the text of a file"""
        # Set up the service with a file
        workspace_service = WorkspaceService()
        file_uri = 'untitled:Test_file'
        file_text = os.linesep.join(['line1', 'line 2 content', ' line 3 '])
        workspace_service._workspace.open_file(file_uri, file_text)

        # Retrieve the full text of the file and make sure it matches
        selection_range = Range(Position(1, 1), Position(2, 4))
        result_text = workspace_service.get_text(file_uri, selection_range)
        self.assertEqual(result_text,
                         os.linesep.join(['ine 2 content', ' lin']))
Beispiel #3
0
    def test_handle_text_notification_none(self):
        # Setup:
        # ... Create a workspace service with mock callbacks and a workspace that always returns None
        ws: WorkspaceService = WorkspaceService()
        ws._logger = utils.get_mock_logger()
        ws._text_change_callbacks = [MagicMock()]
        ws._text_open_callbacks = [MagicMock()]
        ws._text_close_callbacks = [MagicMock()]
        ws._workspace, sf = self._get_mock_workspace(all_none=True)

        nc: NotificationContext = utils.get_mock_notification_context()

        # ... Create a list of methods call and parameters to call them with
        test_calls = [
            (ws._handle_did_change_text_doc,
             self._get_change_text_doc_params(), ws._text_change_callbacks[0]),
            (ws._handle_did_open_text_doc, self._get_open_text_doc_params(),
             ws._text_open_callbacks[0]),
            (ws._handle_did_close_text_doc, self._get_close_text_doc_params(),
             ws._text_close_callbacks[0])
        ]

        for call in test_calls:
            # If: The workspace service receives a request to handle a file that shouldn't be processed
            call[0](nc, call[1])

            # Then: The associated notification callback should not have been called
            call[2].assert_not_called()
 def setUp(self):
     """Constructor"""
     self.default_uri = 'file://my.sql'
     self.flow_validator = RequestFlowValidator()
     self.mock_server_set_request = mock.MagicMock()
     self.mock_server = JSONRPCServer(None, None)
     self.mock_server.set_request_handler = self.mock_server_set_request
     self.mock_workspace_service = WorkspaceService()
     self.mock_connection_service = ConnectionService()
     self.mock_service_provider = ServiceProvider(self.mock_server, {},
                                                  PG_PROVIDER_NAME, None)
     self.mock_service_provider._services[
         constants.WORKSPACE_SERVICE_NAME] = self.mock_workspace_service
     self.mock_service_provider._services[
         constants.CONNECTION_SERVICE_NAME] = self.mock_connection_service
     self.mock_service_provider._is_initialized = True
     self.default_text_position = TextDocumentPosition.from_dict({
         'text_document': {
             'uri': self.default_uri
         },
         'position': {
             'line': 3,
             'character': 10
         }
     })
     self.default_text_document_id = TextDocumentIdentifier.from_dict(
         {'uri': self.default_uri})
Beispiel #5
0
    def test_dmp_capabilities_have_backup_options(self):
        """Test that the capabilities returned for a DMP capabilities request include backup options"""
        # Setup: Create a request context with mocked out send_* methods and set up the capabilities service
        rc = utils.MockRequestContext()
        capabilities_service = CapabilitiesService()
        workspace_service = WorkspaceService()
        capabilities_service._service_provider = utils.get_mock_service_provider(
            {constants.WORKSPACE_SERVICE_NAME: workspace_service})

        # If: I request the dmp capabilities of this server
        capabilities_service._handle_dmp_capabilities_request(rc, None)

        # Then: The response should include backup capabilities
        rc.send_response.assert_called_once()
        capabilities_result = rc.send_response.mock_calls[0][1][0]
        features = capabilities_result.capabilities.features
        backup_options_list = [
            feature for feature in features if feature.feature_name == 'backup'
        ]
        # There should be exactly one feature containing backup options
        self.assertEqual(len(backup_options_list), 1)
        backup_options = backup_options_list[0]
        # The backup options should be enabled
        self.assertTrue(backup_options.enabled)
        # And the backup options should contain at least 1 option
        self.assertGreater(len(backup_options.options_metadata), 0)
Beispiel #6
0
    def setUp(self):
        """Set up the tests with common connection parameters"""
        # Set up the mock connection service and connection info
        self.connection_service = ConnectionService()
        self.connection_service._service_provider = utils.get_mock_service_provider(
            {WORKSPACE_SERVICE_NAME: WorkspaceService()})
        self.owner_uri = 'test_uri'
        self.connection_type = ConnectionType.DEFAULT
        self.connect_params: ConnectRequestParams = ConnectRequestParams.from_dict(
            {
                'ownerUri': self.owner_uri,
                'type': self.connection_type,
                'connection': {
                    'options': {}
                }
            })
        self.mock_psycopg_connection = MockPsycopgConnection(dsn_parameters={
            'host': 'myserver',
            'dbname': 'postgres',
            'user': '******'
        })

        # Mock psycopg2's connect method to store the current cancellation token. This lets us
        # capture the cancellation token state as it would be during a long-running connection.
        self.token_store = []
Beispiel #7
0
    def test_formatter_config_defaults(self):
        # Setup: Create a workspace service
        ws: WorkspaceService = WorkspaceService()

        # Then:
        # ... The config should have sensible default values
        format_options = ws.configuration.pgsql.format
        self.assertIsNotNone(format_options)
        self.assertIsNone(format_options.keyword_case)
        self.assertIsNone(format_options.identifier_case)
        self.assertFalse(format_options.strip_comments)
        self.assertTrue(format_options.reindent)
Beispiel #8
0
    def test_intellisense_config_defaults(self):
        # Setup: Create a workspace service
        ws: WorkspaceService = WorkspaceService()

        # Then:
        # ... The config should have sensible default values
        intellisense: IntellisenseConfiguration = ws.configuration.sql.intellisense
        self.assertIsNotNone(intellisense)
        self.assertTrue(intellisense.enable_intellisense)
        self.assertTrue(intellisense.enable_suggestions)
        self.assertFalse(intellisense.enable_lowercase_suggestions)
        self.assertTrue(intellisense.enable_error_checking)
        self.assertTrue(intellisense.enable_quick_info)
Beispiel #9
0
 def setUp(self):
     """Set up the tests with a connection service"""
     self.connection_service = ConnectionService()
     self.connection_service._service_provider = utils.get_mock_service_provider(
         {WORKSPACE_SERVICE_NAME: WorkspaceService()},
         provider_name=MYSQL_PROVIDER_NAME)
     mock_cursor = MockCursor(results=[['5.7.29-log']])
     # Set up the mock connection for pymysql's connect method to return
     self.mock_pymysql_connection = MockPyMySQLConnection(
         parameters={
             'host': 'myserver',
             'dbname': 'postgres',
             'user': '******'
         },
         cursor=mock_cursor)
Beispiel #10
0
    def test_dmp_capabilities_request(self):
        # Setup: Create a request context with mocked out send_* methods and set up the capabilities service
        rc = utils.MockRequestContext()
        capabilities_service = CapabilitiesService()
        workspace_service = WorkspaceService()
        capabilities_service._service_provider = utils.get_mock_service_provider(
            {constants.WORKSPACE_SERVICE_NAME: workspace_service})

        # If: I request the dmp capabilities of this server
        capabilities_service._handle_dmp_capabilities_request(rc, None)

        # Then: A response should have been sent that is a Capabilities result
        rc.send_notification.assert_not_called()
        rc.send_error.assert_not_called()
        rc.send_response.assert_called_once()
        self.assertIsInstance(rc.send_response.mock_calls[0][1][0],
                              CapabilitiesResult)
Beispiel #11
0
    def test_init(self):
        # If: I create a new workspace service
        ws: WorkspaceService = WorkspaceService()

        # Then:
        # ... The service should have configuration and expose it via the property
        self.assertIsInstance(ws._configuration, Configuration)
        self.assertIs(ws.configuration, ws._configuration)

        # ... The service should have a workspace
        self.assertIsInstance(ws._workspace, Workspace)

        # ... The service should define callback lists
        self.assertListEqual(ws._config_change_callbacks, [])
        self.assertListEqual(ws._text_change_callbacks, [])
        self.assertListEqual(ws._text_open_callbacks, [])
        self.assertListEqual(ws._text_close_callbacks, [])
Beispiel #12
0
    def test_handle_did_change_config(self):
        # Setup: Create a workspace service with two mock config change handlers
        ws: WorkspaceService = WorkspaceService()
        ws._logger = utils.get_mock_logger()
        ws._config_change_callbacks = [MagicMock(), MagicMock()]

        # If: The workspace receives a config change notification
        nc: NotificationContext = utils.get_mock_notification_context()
        params: DidChangeConfigurationParams = DidChangeConfigurationParams.from_dict(
            {
                'settings': {
                    'sql': {
                        'intellisense': {
                            'enable_intellisense': False
                        }
                    },
                    'pgsql': {
                        'format': {
                            'keyword_case': 'upper',
                            'identifier_case': 'lower',
                            'strip_comments': True,
                            'reindent': False,
                        }
                    }
                }
            })
        ws._handle_did_change_config(nc, params)

        # Then:
        # ... No notifications should have been sent
        nc.send_notification.assert_not_called()

        # ... The config should have been updated
        self.assertIs(ws.configuration, params.settings)
        self.assertEqual(ws.configuration.pgsql.format.keyword_case, 'upper')
        self.assertEqual(ws.configuration.pgsql.format.identifier_case,
                         'lower')
        self.assertTrue(ws.configuration.pgsql.format.strip_comments)
        self.assertFalse(ws.configuration.pgsql.format.reindent)
        # ... And default values that weren't specified in the notification are preserved
        self.assertTrue(ws.configuration.sql.intellisense.enable_suggestions)

        # ... The mock config change callbacks should have been called
        for callback in ws._config_change_callbacks:
            callback.assert_called_once_with(params.settings)
Beispiel #13
0
    def test_handle_text_notification_success(self):
        # Setup:
        # ... Create a workspace service with a mock callback and a workspace that returns a mock script file
        ws: WorkspaceService = WorkspaceService()
        ws._logger = utils.get_mock_logger()
        ws._workspace, sf = self._get_mock_workspace(False)
        ws._text_change_callbacks = [MagicMock()]
        ws._text_open_callbacks = [MagicMock()]
        ws._text_close_callbacks = [MagicMock()]

        # ... Create a mock notification context
        nc: NotificationContext = utils.get_mock_notification_context()

        # ... Create a list of method calls and parameters to call them with
        test_calls = [
            (ws._handle_did_change_text_doc, ws._text_change_callbacks[0],
             self._get_change_text_doc_params(),
             self._test_handle_text_change_helper),
            (ws._handle_did_open_text_doc, ws._text_open_callbacks[0],
             self._get_open_text_doc_params(), None),
            (ws._handle_did_close_text_doc, ws._text_close_callbacks[0],
             self._get_close_text_doc_params(), None)
        ]

        for call in test_calls:
            # If: The workspace service receives a notification
            call[0](nc, call[2])

            # Then:
            # ... The callback should have been called with the script file
            call[1].assert_called_once_with(sf)

            # ... The notification sender should not have not been called
            nc.send_notification.assert_not_called()

            # ... Any additional validation should pass
            if call[3] is not None:
                call[3](call[2], sf)

        # ... Get, Open, and Close file should all have been called
        ws._workspace.get_file.assert_called_once()
        ws._workspace.open_file.assert_called_once()
        ws._workspace.close_file.assert_called_once()
Beispiel #14
0
    def test_register(self):
        # Setup:
        # ... Create a mock service provider
        server: JSONRPCServer = JSONRPCServer(None, None)
        server.set_notification_handler = MagicMock()
        server.set_request_handler = MagicMock()
        sp: ServiceProvider = ServiceProvider(server, {}, PG_PROVIDER_NAME,
                                              utils.get_mock_logger())

        # If: I register a workspace service
        ws: WorkspaceService = WorkspaceService()
        ws.register(sp)

        # Then:
        # ... The notifications should have been registered
        server.set_notification_handler.assert_called()
        server.set_request_handler.assert_not_called()

        # ... The service provider should have been stored
        self.assertIs(ws._service_provider, sp)
Beispiel #15
0
    def test_register_callbacks(self):
        # Setup:
        # ... Create a workspace service
        ws: WorkspaceService = WorkspaceService()
        ws._logger = utils.get_mock_logger()

        # ... Create the list of methods to test and the list of handlers to check
        test_methods = [
            (ws.register_config_change_callback, ws._config_change_callbacks),
            (ws.register_text_change_callback, ws._text_change_callbacks),
            (ws.register_text_close_callback, ws._text_close_callbacks),
            (ws.register_text_open_callback, ws._text_open_callbacks)
        ]
        test_callback = MagicMock()

        for test_param in test_methods:
            # If: I register a callback with the workspace service
            test_param[0](test_callback)

            # Then: The callback list should be updated
            self.assertListEqual(test_param[1], [test_callback])
Beispiel #16
0
    def test_handle_text_notification_exception(self):
        # Setup:
        # ... Create a workspace service with a workspace that always raises an exception
        ws: WorkspaceService = WorkspaceService()
        ws._logger = utils.get_mock_logger()
        ws._workspace, exp = self._get_mock_workspace(exception=True)

        # ... Create a mock notification context
        nc: NotificationContext = utils.get_mock_notification_context()

        # ... Create a list of method calls and parameters to call them with
        test_calls = [
            (ws._handle_did_change_text_doc,
             self._get_change_text_doc_params()),
            (ws._handle_did_open_text_doc, self._get_open_text_doc_params()),
            (ws._handle_did_close_text_doc, self._get_close_text_doc_params())
        ]

        for call in test_calls:
            # If: The workspace service gets an exception while handling the notification
            call[0](nc, call[1])
Beispiel #17
0
 def setUp(self):
     """Set up the tests with a connection service"""
     self.connection_service = ConnectionService()
     self.connection_service._service_provider = utils.get_mock_service_provider(
         {WORKSPACE_SERVICE_NAME: WorkspaceService()})