aaron-y-chen commented on code in PR #71350:
URL: https://github.com/apache/airflow/pull/71350#discussion_r3834956935


##########
providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_analysis_services.py:
##########
@@ -0,0 +1,388 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+from unittest import mock
+
+import pytest
+import requests
+from azure.core.credentials import AccessToken
+from azure.core.exceptions import ClientAuthenticationError
+
+from airflow.models import Connection
+from airflow.providers.microsoft.azure.hooks.analysis_services import (
+    TOKEN_SCOPE,
+    VALID_REFRESH_TYPES,
+    AzureAnalysisServicesHook,
+    AzureAnalysisServicesRefreshException,
+    AzureAnalysisServicesRefreshStatus,
+)
+
+CONN_ID = "azure_analysis_services_test"
+HOST = "westus.asazure.windows.net"
+SERVER_NAME = "testserver"
+DATABASE = "Adventure Works"
+REFRESH_ID = "refresh-id"
+REQUEST_TIMEOUT = 30
+HEADERS = {"Authorization": "Bearer token", "Content-Type": "application/json"}
+MODULE = "airflow.providers.microsoft.azure.hooks.analysis_services"
+
+
+def build_response(
+    *, headers: dict[str, str] | None = None, body: object | None = None, 
text: str = ""
+) -> mock.Mock:
+    """Build a response mock with the requested headers and JSON body."""
+    response = mock.Mock(spec=requests.Response)
+    response.headers = headers or {}
+    response.json.return_value = body
+    response.text = text
+    return response
+
+
+class TestAzureAnalysisServicesHook:
+    @pytest.fixture(autouse=True)
+    def setup_connection(self, create_mock_connection):
+        create_mock_connection(
+            Connection(
+                conn_id=CONN_ID,
+                conn_type="azure_analysis_services",
+                host=HOST,
+                login="client-id",
+                password="client-secret",
+                extra={"tenantId": "tenant-id"},
+            )
+        )
+
+    @pytest.mark.parametrize("request_timeout", [0, -1])
+    def test_rejects_invalid_request_timeout(self, request_timeout):
+        with pytest.raises(ValueError, match="request_timeout must be greater 
than zero"):
+            AzureAnalysisServicesHook(CONN_ID, request_timeout=request_timeout)
+
+    def test_defines_connection_form_widget(self):
+        pytest.importorskip("flask_appbuilder")
+        assert set(AzureAnalysisServicesHook.get_connection_form_widgets()) == 
{"tenantId"}
+
+    def test_defines_connection_ui_field_behaviour(self):
+        assert AzureAnalysisServicesHook.get_ui_field_behaviour() == {
+            "hidden_fields": ["schema", "port", "extra"],
+            "relabeling": {
+                "host": "Region Endpoint",
+                "login": "Client ID",
+                "password": "Client Secret",
+            },
+            "placeholders": {"host": "westus.asazure.windows.net"},
+        }
+
+    @mock.patch(f"{MODULE}.ClientSecretCredential", autospec=True)
+    def test_get_conn_creates_and_caches_credential(self, credential_class):
+        hook = AzureAnalysisServicesHook(CONN_ID)
+
+        first_credential = hook.get_conn()
+        second_credential = hook.get_conn()
+
+        credential_class.assert_called_once_with(
+            tenant_id="tenant-id",
+            client_id="client-id",
+            client_secret="client-secret",
+        )
+        assert first_credential is credential_class.return_value
+        assert second_credential is first_credential
+
+    @mock.patch(f"{MODULE}.BaseHook.get_connection", autospec=True)
+    def test_caches_connection(self, get_connection):
+        get_connection.return_value = Connection(
+            conn_id=CONN_ID,
+            conn_type="azure_analysis_services",
+            host=HOST,
+            login="client-id",
+            password="client-secret",
+            extra={"tenantId": "tenant-id"},
+        )
+        hook = AzureAnalysisServicesHook(CONN_ID)
+
+        first_connection = hook.connection
+        second_connection = hook.connection
+
+        get_connection.assert_called_once_with(CONN_ID)
+        assert second_connection is first_connection
+
+    @pytest.mark.parametrize(
+        ("login", "password", "extra", "message"),
+        [
+            (None, "secret", {"tenantId": "tenant"}, "Client ID is required"),
+            ("client", None, {"tenantId": "tenant"}, "Client secret is 
required"),
+            ("client", "secret", {}, "Tenant ID is required"),
+            ("client", "secret", {"tenantId": 123}, "Tenant ID is required"),
+        ],
+    )
+    def test_get_conn_requires_service_principal_fields(
+        self, create_mock_connection, login, password, extra, message
+    ):
+        create_mock_connection(
+            Connection(
+                conn_id="invalid-auth",
+                conn_type="azure_analysis_services",
+                host=HOST,
+                login=login,
+                password=password,
+                extra=extra,
+            )
+        )
+
+        with pytest.raises(ValueError, match=message):
+            AzureAnalysisServicesHook("invalid-auth").get_conn()
+
+    @mock.patch(f"{MODULE}.ClientSecretCredential", autospec=True)
+    def test_get_headers_uses_literal_token_scope(self, credential_class):
+        credential_class.return_value.get_token.return_value = 
AccessToken("token", 0)
+
+        headers = AzureAnalysisServicesHook(CONN_ID)._get_headers()
+
+        
credential_class.return_value.get_token.assert_called_once_with(TOKEN_SCOPE)
+        assert TOKEN_SCOPE == "https://*.asazure.windows.net/.default";
+        assert headers == HEADERS
+
+    @mock.patch(f"{MODULE}.ClientSecretCredential", autospec=True)
+    def test_get_headers_wraps_authentication_errors(self, credential_class):
+        credential_class.return_value.get_token.side_effect = 
ClientAuthenticationError("bad credential")
+
+        with pytest.raises(AzureAnalysisServicesRefreshException, 
match="Failed to authenticate"):
+            AzureAnalysisServicesHook(CONN_ID)._get_headers()

Review Comment:
   Nice suggestion, thanks! I added additional cases like `host:abc` and 
`evil.example:0`. I hope this makes the tests more comprehensive than before :)
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to