Skip to content

Commit

Permalink
add support for embedded variables in headers
Browse files Browse the repository at this point in the history
  • Loading branch information
zyv committed Feb 11, 2025
1 parent 11bfe35 commit d11a770
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
12 changes: 7 additions & 5 deletions ariadne_codegen/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import enum
import os
import re
from dataclasses import dataclass, field
from keyword import iskeyword
from pathlib import Path
Expand Down Expand Up @@ -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


Expand Down
30 changes: 30 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit d11a770

Please sign in to comment.