Merge branch '3.1' into api-issue-07-x7z6we

This commit is contained in:
Jeremy Grossmann authored and GitHub committed 2026-10-08 19:10:42 +02:00
commit 2dd1652e8a
30 files changed
+549 -72

No files matched your search

@@ -101,3 +101,33 @@ class TestApplianceRoutes:
app.url_path_for("add_appliance_version", appliance_id=appliance_id), json=new_version
)
assert response.status_code == status.HTTP_409_CONFLICT
async def test_add_v8_version_appliance(self, app: FastAPI, client: AsyncClient) -> None:
appliance_id = "1cfdf900-7c30-4cb7-8f03-3f61d2581633" # Empty VM appliance
new_version = {"name": "v8-99G", "category": "guest", "images": {"hda_disk_image": "empty99G.qcow2"}}
response = await client.post(
app.url_path_for("add_appliance_version", appliance_id=appliance_id), json=new_version
)
assert response.status_code == status.HTTP_201_CREATED
assert new_version in response.json()["versions"]
async def test_add_version_appliance_with_registry_version(self, app: FastAPI, client: AsyncClient) -> None:
appliance_id = "1cfdf900-7c30-4cb7-8f03-3f61d2581633" # Empty VM appliance
stored_version = {"name": "explicit-99G", "images": {"hda_disk_image": "empty99G.qcow2"}}
response = await client.post(
app.url_path_for("add_appliance_version", appliance_id=appliance_id),
json=dict(stored_version, registry_version=3),
)
assert response.status_code == status.HTTP_201_CREATED
assert stored_version in response.json()["versions"]
async def test_add_version_appliance_unknown_registry_version(self, app: FastAPI, client: AsyncClient) -> None:
appliance_id = "1cfdf900-7c30-4cb7-8f03-3f61d2581633" # Empty VM appliance
response = await client.post(
app.url_path_for("add_appliance_version", appliance_id=appliance_id),
json={"name": "bad", "registry_version": 7, "images": {"hda_disk_image": "empty99G.qcow2"}},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
@@ -608,6 +608,7 @@ class TestLinkRoutes:
assert result["rhost"] == "127.0.0.1"
assert result["rport"] == 30000
assert result["type"] == "udp"
assert result["kind"] == "udp"
async def test_get_ethernet_interface(self, app: FastAPI, client: AsyncClient, project: Project) -> None:
"""
@@ -638,3 +639,4 @@ class TestLinkRoutes:
assert result["node_id"] == cloud_node.id
assert result["interface"] == "eth0"
assert result["type"] == "ethernet"
assert result["kind"] == "ethernet"
+68
View File
@@ -0,0 +1,68 @@
#
# Copyright (C) 2026 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import pytest
from fastapi import FastAPI
pytestmark = pytest.mark.asyncio
STREAM_AND_BINARY_RESPONSES = [
("/v3/notifications", "get", "200", "application/x-ndjson"),
("/v3/projects/{project_id}/notifications", "get", "200", "application/x-ndjson"),
("/v3/projects/{project_id}/export", "get", "200", "application/zip"),
("/v3/projects/{project_id}/gns3file", "get", "200", "application/json"),
("/v3/projects/{project_id}/files/{file_path}", "get", "200", "application/octet-stream"),
("/v3/projects/{project_id}/nodes/{node_id}/files/{file_path}", "get", "200", "application/octet-stream"),
("/v3/projects/{project_id}/nodes/{node_id}/files/{file_path}", "post", "201", "application/json"),
("/v3/projects/{project_id}/links/{link_id}/capture/stream", "get", "200", "application/vnd.tcpdump.pcap"),
("/v3/symbols/{symbol_id}/raw", "get", "200", "application/octet-stream"),
]
RAW_BODY_REQUESTS = [
("/v3/images/upload/{image_path}", "application/octet-stream"),
("/v3/symbols/{symbol_id}/raw", "application/octet-stream"),
("/v3/projects/{project_id}/files/{file_path}", "application/octet-stream"),
("/v3/projects/{project_id}/nodes/{node_id}/files/{file_path}", "application/octet-stream"),
("/v3/projects/{project_id}/import", "application/zip"),
]
class TestOpenAPIBinaryRoutes:
@pytest.mark.parametrize("path, method, status_code, media_type", STREAM_AND_BINARY_RESPONSES)
async def test_response_content(
self, app: FastAPI, path: str, method: str, status_code: str, media_type: str
) -> None:
content = app.openapi()["paths"][path][method]["responses"][status_code]["content"]
assert media_type in content
assert content[media_type]["schema"] != {}
if media_type != "application/json":
assert "application/json" not in content
@pytest.mark.parametrize("path, media_type", RAW_BODY_REQUESTS)
async def test_request_body(self, app: FastAPI, path: str, media_type: str) -> None:
request_body = app.openapi()["paths"][path]["post"]["requestBody"]
assert request_body["required"] is True
assert request_body["content"][media_type]["schema"] == {"type": "string", "format": "binary"}
async def test_binary_responses_use_binary_schema(self, app: FastAPI) -> None:
paths = app.openapi()["paths"]
for path, method, status_code, media_type in STREAM_AND_BINARY_RESPONSES:
if media_type in ("application/octet-stream", "application/zip", "application/vnd.tcpdump.pcap"):
schema = paths[path][method]["responses"][status_code]["content"][media_type]["schema"]
assert schema == {"type": "string", "format": "binary"}
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python
#
# Copyright (C) 2026 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import pytest
from fastapi import FastAPI
pytestmark = pytest.mark.asyncio
@pytest.fixture
def openapi(app: FastAPI) -> dict:
return app.openapi()
def _ref(name: str) -> str:
return f"#/components/schemas/{name}"
def _assert_discriminated(schema: dict, property_name: str, mapping: dict) -> None:
assert [item["$ref"] for item in schema["oneOf"]] == [_ref(name) for name in dict.fromkeys(mapping.values())]
assert schema["discriminator"]["propertyName"] == property_name
assert schema["discriminator"]["mapping"] == {key: _ref(name) for key, name in mapping.items()}
async def test_link_iface_response_is_discriminated(openapi: dict) -> None:
path = "/v3/projects/{project_id}/links/{link_id}/iface"
schema = openapi["paths"][path]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
_assert_discriminated(schema, "kind", {"udp": "UDPPortInfo", "ethernet": "EthernetPortInfo"})
async def test_appliance_version_request_is_discriminated(openapi: dict) -> None:
schema = openapi["paths"]["/v3/appliances/{appliance_id}/version"]["post"]["requestBody"]["content"][
"application/json"
]["schema"]
mapping = {str(version): "ApplianceVersionCreateV1_6" for version in range(1, 7)}
mapping["8"] = "ApplianceVersionCreateV8"
_assert_discriminated(schema, "registry_version", mapping)
async def test_appliance_settings_are_discriminated(openapi: dict) -> None:
schema = openapi["components"]["schemas"]["ApplianceV8"]["properties"]["settings"]["items"]
_assert_discriminated(
schema,
"template_type",
{
"qemu": "QemuTemplateSetting",
"dynamips": "DynamipsTemplateSetting",
"iou": "IouTemplateSetting",
"docker": "DockerTemplateSetting",
},
)
+114
View File
@@ -0,0 +1,114 @@
#
# Copyright (C) 2026 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
import subprocess
import sys
import pytest
from fastapi import FastAPI
from gns3server.agent import AI_COPILOT_AVAILABLE, MCP_AVAILABLE
from gns3server.version import __api_version__, __version__
pytestmark = pytest.mark.asyncio
AI_PATH_PREFIXES = (
"/v3/copilot",
"/v3/mcp",
"/v3/access/llm",
"/v3/access/users/{user_id}/llm-model-configs",
"/v3/access/groups/{group_id}/llm-model-configs",
)
SPEC_SCRIPT = """
import json
import sys
from gns3server.config import Config
Config.instance(files=[sys.argv[1]])
from gns3server.api.server import app
print(json.dumps(app.openapi()))
"""
def _operation_ids(spec: dict) -> list:
return [
operation["operationId"]
for path_item in spec["paths"].values()
for operation in path_item.values()
if isinstance(operation, dict) and "operationId" in operation
]
def _build_spec(tmp_path, include_ai: bool) -> dict:
config_file = tmp_path / "gns3_server.conf"
config_file.write_text(f"[Server]\nopenapi_include_ai = {str(include_ai).lower()}\n")
result = subprocess.run(
[sys.executable, "-c", SPEC_SCRIPT, str(config_file)],
capture_output=True,
text=True,
check=True,
timeout=120,
)
return json.loads(result.stdout.splitlines()[-1])
class TestOpenAPISpec:
async def test_controller_version_matches_package(self, app: FastAPI) -> None:
spec = app.openapi()
assert spec["info"]["version"] == __api_version__
assert spec["info"]["version"] == __version__.split("+")[0]
assert "+" not in spec["info"]["version"]
async def test_compute_version_matches_package(self, app: FastAPI) -> None:
compute_app = next(route.app for route in app.routes if getattr(route, "path", None) == "/v3/compute")
assert compute_app.openapi()["info"]["version"] == __api_version__
async def test_servers_entry(self, app: FastAPI) -> None:
assert app.openapi()["servers"] == [{"url": "/"}]
async def test_no_catch_all_operations(self, app: FastAPI) -> None:
paths = app.openapi()["paths"]
assert [path for path in paths if "{path}" in path] == []
async def test_operation_ids_are_unique(self, app: FastAPI) -> None:
operation_ids = _operation_ids(app.openapi())
assert len(operation_ids) == len(set(operation_ids))
@pytest.mark.skipif(AI_COPILOT_AVAILABLE or MCP_AVAILABLE, reason="AI extras are installed")
async def test_ai_routes_absent_without_extras(self, app: FastAPI) -> None:
paths = app.openapi()["paths"]
assert [path for path in paths if path.startswith(AI_PATH_PREFIXES)] == []
async def test_setting_hides_ai_routes_and_keeps_the_rest(self, tmp_path) -> None:
with_ai = _build_spec(tmp_path, include_ai=True)
without_ai = _build_spec(tmp_path, include_ai=False)
assert [path for path in without_ai["paths"] if path.startswith(AI_PATH_PREFIXES)] == []
non_ai_paths = {path: item for path, item in with_ai["paths"].items() if not path.startswith(AI_PATH_PREFIXES)}
assert without_ai["paths"] == non_ai_paths
assert len(_operation_ids(without_ai)) == len(set(_operation_ids(without_ai)))