|
| 1 | +"""Importing the connector must not import requests or the OAuth client libraries. |
| 2 | +
|
| 3 | +They are only needed by the auth flows and HTTP paths that use them. Each check runs |
| 4 | +in a fresh interpreter because ``sys.modules`` is process-global. |
| 5 | +""" |
| 6 | + |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import textwrap |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +# Sentinel exit codes, distinct from the 1 of an uncaught exception. |
| 14 | +_CLEAN, _LOADED, _IMPORT_FAILED = 10, 11, 12 |
| 15 | + |
| 16 | +MODULES = [ |
| 17 | + "databricks.sql", |
| 18 | + "databricks.sql.client", |
| 19 | + "databricks.sql.session", |
| 20 | + "databricks.sql.auth.authenticators", |
| 21 | + "databricks.sql.common.http", |
| 22 | +] |
| 23 | +UNWANTED = ["requests", "oauthlib"] |
| 24 | + |
| 25 | + |
| 26 | +@pytest.mark.parametrize("module_name", MODULES) |
| 27 | +def test_module_does_not_import_http_client_libraries(module_name): |
| 28 | + script = f""" |
| 29 | + import sys |
| 30 | + try: |
| 31 | + import {module_name} # noqa: F401 |
| 32 | + except BaseException: |
| 33 | + import traceback |
| 34 | + traceback.print_exc() |
| 35 | + sys.exit({_IMPORT_FAILED}) |
| 36 | + loaded = [m for m in {UNWANTED!r} if m in sys.modules] |
| 37 | + print(loaded) |
| 38 | + sys.exit({_LOADED} if loaded else {_CLEAN}) |
| 39 | + """ |
| 40 | + proc = subprocess.run( |
| 41 | + [sys.executable, "-c", textwrap.dedent(script)], |
| 42 | + capture_output=True, |
| 43 | + text=True, |
| 44 | + ) |
| 45 | + if proc.returncode == _IMPORT_FAILED: |
| 46 | + pytest.skip(f"{module_name} not importable here:\n{proc.stderr}") |
| 47 | + assert proc.returncode != _LOADED, f"importing {module_name} loaded {proc.stdout}" |
| 48 | + assert ( |
| 49 | + proc.returncode == _CLEAN |
| 50 | + ), f"unexpected exit {proc.returncode}:\n{proc.stderr}" |
| 51 | + |
| 52 | + |
| 53 | +def test_oauth_provider_still_builds_its_manager(): |
| 54 | + from unittest.mock import MagicMock, patch |
| 55 | + |
| 56 | + from databricks.sql.auth.authenticators import DatabricksOAuthProvider |
| 57 | + |
| 58 | + with patch("databricks.sql.auth.oauth.OAuthManager") as manager, patch.object( |
| 59 | + DatabricksOAuthProvider, "_initial_get_token" |
| 60 | + ): |
| 61 | + DatabricksOAuthProvider( |
| 62 | + hostname="example.cloud.databricks.com", |
| 63 | + oauth_persistence=None, |
| 64 | + redirect_port_range=[8020], |
| 65 | + client_id="client", |
| 66 | + scopes=["sql"], |
| 67 | + http_client=MagicMock(), |
| 68 | + ) |
| 69 | + manager.assert_called_once() |
0 commit comments