diff --git a/ariadne_codegen/settings.py b/ariadne_codegen/settings.py index 808397ba..7cefa221 100644 --- a/ariadne_codegen/settings.py +++ b/ariadne_codegen/settings.py @@ -1,5 +1,6 @@ import enum import os +import re from dataclasses import dataclass, field from keyword import iskeyword from pathlib import Path @@ -278,16 +279,17 @@ def resolve_headers(headers: Dict) -> Dict: def get_header_value(value: str) -> str: - env_var_prefix = "$" - if value.startswith(env_var_prefix): - env_var_name = value.lstrip(env_var_prefix) + replacements = {} + for env_var_name in re.findall(r"\$([A-z][A-z0-9_]*)", value): var_value = os.environ.get(env_var_name) if not var_value: raise InvalidConfiguration( f"Environment variable {env_var_name} not found." ) - return var_value - + replacements[f"${env_var_name}"] = var_value + if replacements: + pattern = re.compile("|".join(map(re.escape, replacements.keys()))) + return pattern.sub(lambda match: replacements[match.group(0)], value) return value diff --git a/tests/test_settings.py b/tests/test_settings.py index 11d03523..51c4aac7 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -148,6 +148,36 @@ def test_client_settings_resolves_env_variable_for_remote_schema_header_with_pre assert settings.remote_schema_headers["Authorization"] == "test_value" +def test_client_settings_resolves_env_variable_for_remote_schema_header_with_prefix_inside( + tmp_path, mocker +): + queries_path = tmp_path / "queries.graphql" + queries_path.touch() + mocker.patch.dict(os.environ, {"TEST_VAR": "test_value"}) + + settings = ClientSettings( + queries_path=queries_path, + remote_schema_url="https://test", + remote_schema_headers={"Authorization": "Bearer $TEST_VAR"}, + ) + + assert settings.remote_schema_headers["Authorization"] == "Bearer test_value" + +def test_client_settings_resolves_env_variable_for_remote_schema_header_with_prefix_multiple( + tmp_path, mocker +): + queries_path = tmp_path / "queries.graphql" + queries_path.touch() + mocker.patch.dict(os.environ, {"TEST_FOO": "test_foo"}) + mocker.patch.dict(os.environ, {"TEST_BAR": "test_bar"}) + + settings = ClientSettings( + queries_path=queries_path, + remote_schema_url="https://test", + remote_schema_headers={"Authorization": "Bearer $TEST_FOO$TEST_BAR suffix"}, + ) + + assert settings.remote_schema_headers["Authorization"] == "Bearer test_footest_bar suffix" def test_client_settings_doesnt_resolve_remote_schema_header_without_prefix(tmp_path): queries_path = tmp_path / "queries.graphql"