fix: authenticate WeKnora API client

This commit is contained in:
Administrator committed 2026-08-13 17:41:30 +08:00
1 parent 56044d9cb7
commit 3aeb6ac5ce
4 files changed
+200 -24

No files matched your search

@@ -230,7 +230,7 @@ async def test_weknora_session_endpoint_sets_cookie_and_returns_platform_path(mo
@pytest.mark.asyncio
async def test_weknora_client_sends_no_credentials_and_normalizes_search() -> None:
async def test_weknora_client_keeps_anonymous_mode_without_admin_credentials() -> None:
requests: list[httpx.Request] = []
async def handler(request: httpx.Request) -> httpx.Response:
@@ -270,6 +270,77 @@ async def test_weknora_client_sends_no_credentials_and_normalizes_search() -> No
assert results[0]["title"] == "Guide"
@pytest.mark.asyncio
async def test_weknora_client_uses_admin_token_when_credentials_are_configured() -> None:
requests: list[httpx.Request] = []
async def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
if request.url.path == "/api/v1/auth/login":
assert json.loads(request.content) == {"email": "admin@example.test", "password": "secret"}
return httpx.Response(
200,
json={
"success": True,
"data": {
"token": "token-one",
"tenant": {"id": "tenant-one"},
},
},
)
assert request.headers["Authorization"] == "Bearer token-one"
assert request.headers["X-Tenant-ID"] == "tenant-one"
return httpx.Response(200, json={"success": True, "data": []})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:
client = WeKnoraClient(
base_url="http://weknora.local:8080",
http_client=http_client,
admin_email="admin@example.test",
admin_password="secret",
)
results = await client.search("deployment guide", ["kb-one"])
assert results == []
assert [request.url.path for request in requests] == [
"/api/v1/auth/login",
"/api/v1/knowledge-search",
]
@pytest.mark.asyncio
async def test_weknora_client_refreshes_admin_token_after_rejection() -> None:
login_count = 0
search_count = 0
async def handler(request: httpx.Request) -> httpx.Response:
nonlocal login_count, search_count
if request.url.path == "/api/v1/auth/login":
login_count += 1
return httpx.Response(
200,
json={"success": True, "data": {"token": f"token-{login_count}"}},
)
search_count += 1
if search_count == 1:
assert request.headers["Authorization"] == "Bearer token-1"
return httpx.Response(401, json={"message": "expired"})
assert request.headers["Authorization"] == "Bearer token-2"
return httpx.Response(200, json={"success": True, "data": []})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:
client = WeKnoraClient(
base_url="http://weknora.local:8080",
http_client=http_client,
admin_email="admin@example.test",
admin_password="secret",
)
await client.search("deployment guide", ["kb-one"])
assert login_count == 2
assert search_count == 2
@pytest.mark.asyncio
async def test_weknora_client_merges_required_name_for_description_update() -> None:
requests: list[httpx.Request] = []