pytest-api/apiclient/config.py

37 lines
1.4 KiB
Python
Raw Normal View History

2024-07-20 10:47:11 +00:00
import os
from dotenv import dotenv_values
2024-07-20 10:47:11 +00:00
from types import MappingProxyType
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Dict to hold values from dotenv files; keys are filenames, values are dictionaries of env vars
_dotenv_values = {}
2024-07-20 10:47:11 +00:00
def get_cfg(env='qa', force_refresh=False):
2024-07-20 10:47:11 +00:00
environment_name = os.getenv('ENV_NAME', env)
dotenv_path = os.path.join(PROJECT_ROOT, f'.env.{environment_name}')
if not os.path.exists(dotenv_path):
raise FileNotFoundError(f"{dotenv_path} does not exist")
if dotenv_path not in _dotenv_values or force_refresh:
# Load the env vars from the dotenv file and store them in the _dotenv_values dict
_dotenv_values[dotenv_path] = dotenv_values(dotenv_path)
# Now, we're sure that _dotenv_values[dotenv_path] contains up-to-date env vars from dotenv_path
dotenv_vars = _dotenv_values[dotenv_path]
2024-07-20 10:47:11 +00:00
config_dict = {
'client_id': dotenv_vars.get('CLIENT_ID'),
'client_secret': dotenv_vars.get('CLIENT_SECRET'),
'token_url': dotenv_vars.get('TOKEN_FETCH_URL'),
'login': dotenv_vars.get('LOGIN'),
'password': dotenv_vars.get('PASSWORD'),
'audience': dotenv_vars.get('AUDIENCE'),
'scopes': dotenv_vars.get('SCOPES', '').split(','),
'api_url': dotenv_vars.get('API_URL')
2024-07-20 10:47:11 +00:00
}
config = MappingProxyType(config_dict) # immutable dict
return config