2021-02-15 08:42:16 +00:00
|
|
|
import os
|
2024-01-13 18:38:05 +00:00
|
|
|
from unittest.mock import patch
|
2023-11-30 15:55:51 +00:00
|
|
|
|
2024-01-07 12:03:33 +00:00
|
|
|
from moto import mock_aws
|
2021-02-15 08:42:16 +00:00
|
|
|
|
|
|
|
KEY = "AWS_ACCESS_KEY_ID"
|
|
|
|
|
|
|
|
|
2023-12-14 21:35:36 +00:00
|
|
|
def test_aws_keys_are_patched() -> None:
|
2024-01-07 12:03:33 +00:00
|
|
|
with mock_aws():
|
2024-01-13 18:38:05 +00:00
|
|
|
assert os.environ[KEY] == "FOOBARKEY"
|
|
|
|
|
|
|
|
|
|
|
|
def test_aws_keys_are_not_patched_when_user_configured() -> None:
|
|
|
|
with patch.dict(os.environ, {"AWS_ACCESS_KEY_ID": "diff_value"}):
|
|
|
|
# Sanity check
|
|
|
|
assert os.environ["AWS_ACCESS_KEY_ID"] == "diff_value"
|
|
|
|
|
|
|
|
# Moto will not mock the credentials, and we see the 'original' value
|
|
|
|
with mock_aws(config={"core": {"mock_credentials": False}}):
|
|
|
|
assert os.environ[KEY] == "diff_value"
|
|
|
|
|
|
|
|
# Nested mocks are possible
|
|
|
|
# For the duration of the inner mock, Moto will patch the credentials
|
|
|
|
with mock_aws(config={"core": {"mock_credentials": True}}):
|
|
|
|
assert os.environ[KEY] == "FOOBARKEY"
|
|
|
|
|
|
|
|
# The moment the inner patch ends, we're back to the 'original' value
|
|
|
|
assert os.environ[KEY] == "diff_value"
|
2021-02-15 08:42:16 +00:00
|
|
|
|
|
|
|
|
2023-12-14 21:35:36 +00:00
|
|
|
def test_aws_keys_can_be_none() -> None:
|
2021-02-15 08:42:16 +00:00
|
|
|
"""
|
|
|
|
Verify that the os.environ[KEY] can be None
|
|
|
|
Patching the None-value shouldn't be an issue
|
|
|
|
"""
|
|
|
|
original = os.environ.get(KEY, "value-set-by-user")
|
|
|
|
# Delete the original value by the user
|
|
|
|
try:
|
|
|
|
del os.environ[KEY]
|
|
|
|
except KeyError:
|
|
|
|
pass # Value might not be set on this system in the first place
|
|
|
|
try:
|
|
|
|
# Verify that the os.environ[KEY] is patched
|
2024-01-07 12:03:33 +00:00
|
|
|
with mock_aws():
|
2024-01-13 18:38:05 +00:00
|
|
|
assert os.environ[KEY] == "FOOBARKEY"
|
2021-02-15 08:42:16 +00:00
|
|
|
# Verify that the os.environ[KEY] is unpatched, and reverts to None
|
|
|
|
assert os.environ.get(KEY) is None
|
|
|
|
finally:
|
|
|
|
# Reset the value original - don't want to change the users system
|
|
|
|
os.environ[KEY] = original
|