|
| 1 | +import keyring |
| 2 | + |
| 3 | +from upcloud_api import Credentials |
| 4 | + |
| 5 | + |
| 6 | +class DictBackend(keyring.backend.KeyringBackend): |
| 7 | + priority = 1 |
| 8 | + |
| 9 | + def __init__(self, secrets=None): |
| 10 | + super().__init__() |
| 11 | + self._secrets = secrets or {} |
| 12 | + |
| 13 | + def set_password(self, servicename, username, password): |
| 14 | + pass |
| 15 | + |
| 16 | + def get_password(self, servicename, username): |
| 17 | + return self._secrets.get(servicename, {}).get(username) |
| 18 | + |
| 19 | + def delete_password(self, servicename, username): |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +class TestCredentials: |
| 24 | + def test_precedence(self, monkeypatch): |
| 25 | + param_basic = 'Basic cGFyYW1fdXNlcjpwYXJhbV9wYXNz' |
| 26 | + param_bearer = 'Bearer param_token' |
| 27 | + env_basic = 'Basic ZW52X3VzZXI6ZW52X3Bhc3M=' |
| 28 | + env_bearer = 'Bearer env_token' |
| 29 | + keyring_basic = 'Basic ZW52X3VzZXI6a2V5cmluZ19wYXNz' |
| 30 | + keyring_bearer = 'Bearer keyring_token' |
| 31 | + |
| 32 | + backend = DictBackend( |
| 33 | + { |
| 34 | + "UpCloud": { |
| 35 | + "env_user": "keyring_pass", |
| 36 | + "": "keyring_token", |
| 37 | + } |
| 38 | + } |
| 39 | + ) |
| 40 | + keyring.set_keyring(backend) |
| 41 | + |
| 42 | + credentials = Credentials.parse() |
| 43 | + assert credentials.authorization == keyring_bearer |
| 44 | + |
| 45 | + monkeypatch.setenv("UPCLOUD_USERNAME", 'env_user') |
| 46 | + |
| 47 | + credentials = Credentials.parse() |
| 48 | + assert credentials.authorization == keyring_basic |
| 49 | + |
| 50 | + monkeypatch.setenv("UPCLOUD_PASSWORD", 'env_pass') |
| 51 | + |
| 52 | + credentials = Credentials.parse(username='param_user', password='param_pass') |
| 53 | + assert credentials.authorization == param_basic |
| 54 | + |
| 55 | + credentials = Credentials.parse() |
| 56 | + assert credentials.authorization == env_basic |
| 57 | + |
| 58 | + monkeypatch.setenv("UPCLOUD_TOKEN", 'env_token') |
| 59 | + credentials = Credentials.parse(username='param_user', password='param_pass') |
| 60 | + assert credentials.authorization == param_basic |
| 61 | + |
| 62 | + credentials = Credentials.parse() |
| 63 | + assert credentials.authorization == env_bearer |
| 64 | + |
| 65 | + credentials = Credentials.parse(token='param_token') |
| 66 | + assert credentials.authorization == param_bearer |
0 commit comments