|
| 1 | +#!/usr/bin/env python |
| 2 | +# |
| 3 | +# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved. |
| 4 | +# |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from snowflake.connector.auth import AuthByPAT |
| 9 | +from snowflake.connector.auth.by_plugin import AuthType |
| 10 | +from snowflake.connector.network import PROGRAMMATIC_ACCESS_TOKEN |
| 11 | + |
| 12 | + |
| 13 | +def test_auth_pat(): |
| 14 | + """Simple PAT test.""" |
| 15 | + token = "patToken" |
| 16 | + auth = AuthByPAT(token) |
| 17 | + assert auth.type_ == AuthType.PAT |
| 18 | + assert auth.assertion_content == token |
| 19 | + body = {"data": {}} |
| 20 | + auth.update_body(body) |
| 21 | + assert body["data"]["TOKEN"] == token, body |
| 22 | + assert body["data"]["AUTHENTICATOR"] == PROGRAMMATIC_ACCESS_TOKEN, body |
| 23 | + |
| 24 | + auth.reset_secrets() |
| 25 | + assert auth.assertion_content is None |
| 26 | + |
| 27 | + |
| 28 | +def test_auth_pat_reauthenticate(): |
| 29 | + """Test PAT reauthenticate.""" |
| 30 | + token = "patToken" |
| 31 | + auth = AuthByPAT(token) |
| 32 | + result = auth.reauthenticate() |
| 33 | + assert result == {"success": False} |
| 34 | + |
| 35 | + |
| 36 | +def test_pat_authenticator_creates_auth_by_pat(monkeypatch): |
| 37 | + """Test that using PROGRAMMATIC_ACCESS_TOKEN authenticator creates AuthByPAT instance.""" |
| 38 | + import snowflake.connector |
| 39 | + |
| 40 | + # Mock the network request - this prevents actual network calls and connection errors |
| 41 | + def mock_post_request(request, url, headers, json_body, **kwargs): |
| 42 | + return { |
| 43 | + "success": True, |
| 44 | + "message": None, |
| 45 | + "data": { |
| 46 | + "token": "TOKEN", |
| 47 | + "masterToken": "MASTER_TOKEN", |
| 48 | + "idToken": None, |
| 49 | + "parameters": [{"name": "SERVICE_NAME", "value": "FAKE_SERVICE_NAME"}], |
| 50 | + }, |
| 51 | + } |
| 52 | + |
| 53 | + # Apply the mock using monkeypatch |
| 54 | + monkeypatch.setattr( |
| 55 | + snowflake.connector.network.SnowflakeRestful, "_post_request", mock_post_request |
| 56 | + ) |
| 57 | + |
| 58 | + # Create connection with PAT authenticator |
| 59 | + conn = snowflake.connector.connect( |
| 60 | + user="user", |
| 61 | + account="account", |
| 62 | + database="TESTDB", |
| 63 | + warehouse="TESTWH", |
| 64 | + authenticator=PROGRAMMATIC_ACCESS_TOKEN, |
| 65 | + token="test_pat_token", |
| 66 | + ) |
| 67 | + |
| 68 | + # Verify that the auth_class is an instance of AuthByPAT |
| 69 | + assert isinstance(conn.auth_class, AuthByPAT) |
| 70 | + # Note: assertion_content is None after connect() because secrets are cleared for security |
| 71 | + |
| 72 | + conn.close() |
0 commit comments