Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from __future__ import annotations

import copy
import logging
import re
from typing import Any
from typing import Dict
from typing import List
Expand Down Expand Up @@ -46,6 +48,46 @@

_SCHEMA_CONTAINER_KEYS: Set[str] = frozenset({"schema", "schemas"})

logger = logging.getLogger("google_adk." + __name__)


def _server_url(server: Dict[str, Any]) -> str:
"""Returns a Server Object's URL with each variable set to its default.

A server URL such as ``https://{region}.example.com`` is a template, and
OpenAPI requires the default value to be used when no other is supplied.
A placeholder that has no variable, or whose variable is not an object with
a non-null ``default``, is left as is and a warning is logged, since requests to
that URL will fail.
"""
url = server.get("url", "")
variables = server.get("variables")
if not isinstance(variables, dict):
variables = {}

def _default(match: re.Match[str]) -> str:
name = match.group(1)
variable = variables.get(name)
default = variable.get("default") if isinstance(variable, dict) else None
if default is not None:
return str(default)
if variable is None:
reason = "no server variable defines it"
elif not isinstance(variable, dict):
reason = "its server variable is not an object"
else:
reason = "its server variable has no default"
logger.warning(
"Cannot fill placeholder {%s} in server URL %r: %s. Requests will be"
" sent to the URL with the placeholder unfilled.",
name,
url,
reason,
)
return match.group(0)

return re.sub(r"\{([^{}]+)\}", _default, url)


class OperationEndpoint(BaseModel):
base_url: str
Expand Down Expand Up @@ -177,10 +219,12 @@ def _collect_operations(
"""Collects operations from an OpenAPI spec."""
operations = []

# Taking first server url, or default to empty string if not present
# Use the first server's URL, with its server variables replaced by their
# defaults, or an empty string if no server is defined. Path-level and
# operation-level `servers` overrides are not supported yet.
base_url = ""
if openapi_spec.get("servers"):
base_url = openapi_spec["servers"][0].get("url", "")
base_url = _server_url(openapi_spec["servers"][0])

# Get global security scheme (if any).
global_scheme_name = _required_scheme_name(openapi_spec.get("security"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
from typing import Any
from typing import Dict

Expand Down Expand Up @@ -294,6 +295,112 @@ def test_parse_spec_with_servers(openapi_spec_generator):
assert parsed_operations[0].endpoint.base_url == "https://api.example.com"


def test_parse_spec_with_server_variables(openapi_spec_generator):
"""Server URL variables are replaced with their default values."""
openapi_spec = create_minimal_openapi_spec()
openapi_spec["servers"] = [{
"url": "https://{region}.api.example.com/{basePath}",
"variables": {
"region": {"default": "us", "enum": ["us", "eu"]},
"basePath": {"default": "v2"},
},
}]

parsed_operations = openapi_spec_generator.parse(openapi_spec)

assert len(parsed_operations) == 1
assert (
parsed_operations[0].endpoint.base_url == "https://us.api.example.com/v2"
)


@pytest.mark.parametrize(
("url", "variables", "expected_url", "placeholder", "reason"),
[
pytest.param(
"https://{region}.api.example.com/{basePath}",
{"region": {"enum": ["us", "eu"]}, "basePath": {"default": "v2"}},
"https://{region}.api.example.com/v2",
"region",
"has no default",
id="missing_default",
),
pytest.param(
"https://{region}.api.example.com",
{"region": {"default": None}},
"https://{region}.api.example.com",
"region",
"has no default",
id="null_default",
),
pytest.param(
"https://{region}.api.example.com/{version}",
{"region": {"default": "us"}},
"https://us.api.example.com/{version}",
"version",
"no server variable defines it",
id="unknown_placeholder",
),
pytest.param(
"https://{region}.api.example.com",
{"region": "us"},
"https://{region}.api.example.com",
"region",
"is not an object",
id="invalid_variable",
),
pytest.param(
"https://{region}.api.example.com",
["region"],
"https://{region}.api.example.com",
"region",
"no server variable defines it",
id="invalid_variables",
),
],
)
def test_parse_spec_with_unfillable_server_variable(
openapi_spec_generator,
caplog,
url,
variables,
expected_url,
placeholder,
reason,
):
"""A placeholder that can't be filled stays in the URL and is logged."""
openapi_spec = create_minimal_openapi_spec()
openapi_spec["servers"] = [{"url": url, "variables": variables}]

with caplog.at_level(logging.WARNING):
parsed_operations = openapi_spec_generator.parse(openapi_spec)

assert parsed_operations[0].endpoint.base_url == expected_url
warnings = [
r.getMessage() for r in caplog.records if r.levelno == logging.WARNING
]
assert len(warnings) == 1
assert f"{{{placeholder}}}" in warnings[0]
assert reason in warnings[0]


def test_parse_spec_with_server_variables_logs_nothing(
openapi_spec_generator, caplog
):
"""Filling every placeholder logs no warning."""
openapi_spec = create_minimal_openapi_spec()
openapi_spec["servers"] = [{
"url": "https://{region}.api.example.com",
"variables": {"region": {"default": "eu"}},
}]

with caplog.at_level(logging.WARNING):
parsed_operations = openapi_spec_generator.parse(openapi_spec)

assert parsed_operations[0].endpoint.base_url == "https://eu.api.example.com"
assert not [r for r in caplog.records if r.levelno == logging.WARNING]


def test_parse_spec_with_no_servers(openapi_spec_generator):
"""Test with no servers defined (should default to empty string)."""
openapi_spec = create_minimal_openapi_spec()
Expand Down