|
| 1 | +import os |
| 2 | +from typing import Dict |
| 3 | + |
| 4 | +import responses |
| 5 | +from posit.connect import Client |
| 6 | +from posit.connect.external.databricks import ( |
| 7 | + CredentialsProvider, |
| 8 | + PositCredentialsProvider, |
| 9 | + PositCredentialsStrategy, |
| 10 | +) |
| 11 | + |
| 12 | + |
| 13 | +def register_mocks(): |
| 14 | + responses.post( |
| 15 | + "https://connect.example/__api__/v1/oauth/integrations/credentials", |
| 16 | + match=[ |
| 17 | + responses.matchers.urlencoded_params_matcher( |
| 18 | + { |
| 19 | + "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", |
| 20 | + "subject_token_type": "urn:posit:connect:user-session-token", |
| 21 | + "subject_token": "cit", |
| 22 | + } |
| 23 | + ) |
| 24 | + ], |
| 25 | + json={ |
| 26 | + "access_token": "dynamic-viewer-access-token", |
| 27 | + "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", |
| 28 | + "token_type": "Bearer", |
| 29 | + }, |
| 30 | + ) |
| 31 | + |
| 32 | +class TestPositCredentialsHelpers: |
| 33 | + @responses.activate |
| 34 | + def test_posit_credentials_provider(self): |
| 35 | + register_mocks() |
| 36 | + |
| 37 | + client = Client(api_key="12345", url="https://connect.example/") |
| 38 | + cp = PositCredentialsProvider(posit_oauth=client.oauth, user_session_token="cit") |
| 39 | + assert cp() == {"Authorization": f"Bearer dynamic-viewer-access-token"} |
| 40 | + |
| 41 | + @responses.activate |
| 42 | + def test_posit_credentials_strategy(self): |
| 43 | + register_mocks() |
| 44 | + |
| 45 | + class local_strategy: |
| 46 | + def auth_type(self) -> str: |
| 47 | + return "local" |
| 48 | + def __call__(self) -> CredentialsProvider: |
| 49 | + def inner() -> Dict[str,str]: |
| 50 | + return {"Authorization": "Bearer static-pat-token"} |
| 51 | + return inner |
| 52 | + |
| 53 | + # local_strategy is used when the content is running locally |
| 54 | + client = Client(api_key="12345", url="https://connect.example/") |
| 55 | + cs = PositCredentialsStrategy(local_strategy=local_strategy(), |
| 56 | + user_session_token="cit", |
| 57 | + client=client) |
| 58 | + cp = cs() |
| 59 | + assert cs.auth_type() == "local" |
| 60 | + assert cp() == {"Authorization": "Bearer static-pat-token"} |
| 61 | + |
| 62 | + # posit_strategy is used when the content is running on Connect |
| 63 | + os.environ["RSTUDIO_PRODUCT"] = "CONNECT" |
| 64 | + cs = PositCredentialsStrategy(local_strategy=local_strategy(), |
| 65 | + user_session_token="cit", |
| 66 | + client=client) |
| 67 | + cp = cs() |
| 68 | + assert cs.auth_type() == "posit-oauth-integration" |
| 69 | + assert cp() == {"Authorization": "Bearer dynamic-viewer-access-token"} |
| 70 | + del os.environ["RSTUDIO_PRODUCT"] |
| 71 | + |
0 commit comments