File: test_credentials.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (72 lines) | stat: -rw-r--r-- 2,122 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# coding: utf-8

#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import time
try:
    from unittest import mock
except ImportError:
    import mock

import pytest

from azure.common.credentials import _CliCredentials
import azure.common.credentials


class MockCliCredentials:
    def _token_retriever(self):
        return "NOTUSED", "TOKEN", {'expiresIn': 42}

    def signed_session(self, session=None):
        return session


class MockCliProfile:
    def __init__(self):
        self.received_resource = None

    def get_login_credentials(self, resource):
        self.received_resource = resource
        return MockCliCredentials(), "NOTUSED", "NOTUSED"


def test_cli_credentials_mgmt():

    cli_profile = MockCliProfile()

    cred = _CliCredentials(cli_profile, "http://resource.id")

    # Mgmt scenario
    session = cred.signed_session("session")
    assert cli_profile.received_resource == "http://resource.id"
    assert session == "session"

    # Trying to mock azure-core not here
    with mock.patch('azure.common.credentials._AccessToken', None):
        # Should not crash
        cred.signed_session("session")


def test_cli_credentials_accesstoken():

    cli_profile = MockCliProfile()

    cred = _CliCredentials(cli_profile, "http://resource.id")

    # Track2 scenario
    access_token = cred.get_token("http://resource.id/.default")
    assert cli_profile.received_resource == "http://resource.id"
    assert access_token.token == "TOKEN"
    assert access_token.expires_on <= int(time.time() + 42)

    access_token = cred.get_token("http://resource.newid")
    assert cli_profile.received_resource == "http://resource.newid"

    # Trying to mock azure-core not here
    with mock.patch('azure.common.credentials._AccessToken', None):
        with pytest.raises(ImportError):
            cred.get_token("http://resource.yetid")