|
| 1 | +"""Tests for RESTful sandbox endpoints on sandbox_router.""" |
| 2 | + |
| 3 | +from unittest.mock import AsyncMock, MagicMock |
| 4 | + |
| 5 | +import pytest |
| 6 | +from fastapi import FastAPI |
| 7 | +from fastapi.exceptions import RequestValidationError |
| 8 | +from httpx import ASGITransport, AsyncClient |
| 9 | + |
| 10 | +from rock.admin.entrypoints.sandbox_api import sandbox_router, set_sandbox_manager |
| 11 | +from rock.common.exception import request_validation_exception_handler |
| 12 | + |
| 13 | + |
| 14 | +@pytest.fixture |
| 15 | +def sandbox_app(): |
| 16 | + mock_manager = MagicMock() |
| 17 | + mock_manager.rock_config = MagicMock() |
| 18 | + mock_manager.rock_config.nacos_provider = None |
| 19 | + set_sandbox_manager(mock_manager) |
| 20 | + app = FastAPI() |
| 21 | + app.add_exception_handler(RequestValidationError, request_validation_exception_handler) |
| 22 | + app.include_router(sandbox_router, prefix="/apis/envs/sandbox/v1") |
| 23 | + return app, mock_manager |
| 24 | + |
| 25 | + |
| 26 | +BASE = "/apis/envs/sandbox/v1" |
| 27 | + |
| 28 | + |
| 29 | +@pytest.mark.asyncio |
| 30 | +async def test_archive_allowed(sandbox_app): |
| 31 | + app, mock_manager = sandbox_app |
| 32 | + mock_manager.rock_config.lifecycle.archive.is_allowed.return_value = True |
| 33 | + mock_manager.archive_sandbox = AsyncMock() |
| 34 | + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: |
| 35 | + resp = await client.post(f"{BASE}/sandboxes/sb-1/archive") |
| 36 | + assert resp.status_code == 200 |
| 37 | + assert resp.json()["status"] == "Success" |
| 38 | + mock_manager.archive_sandbox.assert_called_once_with("sb-1") |
| 39 | + |
| 40 | + |
| 41 | +@pytest.mark.asyncio |
| 42 | +async def test_archive_forbidden(sandbox_app): |
| 43 | + """Unauthorised key: handle_exceptions returns HTTP 200 with status=Failed.""" |
| 44 | + app, mock_manager = sandbox_app |
| 45 | + mock_manager.rock_config.lifecycle.archive.is_allowed.return_value = False |
| 46 | + mock_manager.archive_sandbox = AsyncMock() |
| 47 | + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: |
| 48 | + resp = await client.post(f"{BASE}/sandboxes/sb-1/archive", headers={"X-Key": "bad-key"}) |
| 49 | + assert resp.status_code == 200 |
| 50 | + assert resp.json()["status"] == "Failed" |
| 51 | + mock_manager.archive_sandbox.assert_not_called() |
0 commit comments