dify/api/tests/unit_tests/controllers/openapi/test_chat_messages.py
GareArc 8a62c1d915
chore(api): pyright + ruff cleanup for openapi/cli surface
Type and lint pass over the openapi controllers, auth pipeline, and
oauth bearer/device-flow plumbing. Down from 36 pyright errors and 16
ruff errors to 0/0; 93 openapi unit tests pass.

Logic fixes:
- libs/oauth_bearer.py: drop private-naming on the friend-API methods
  consumed by _VariantResolver (cache_get / cache_set_positive /
  cache_set_negative / hard_expire / session_factory). They were always
  cross-class accessors — leading underscore was misleading. Add public
  registry property on BearerAuthenticator. _hard_expire row_id widened
  to UUID | str (matches the StringUUID column type).
- libs/oauth_bearer.py: type validate_bearer / bearer_feature_required
  with ParamSpec / PEP-695 so wrapped routes preserve their signature.
- libs/rate_limit.py: same — typed rate_limit decorator.
- services/oauth_device_flow.py: mint_oauth_token / _upsert accept
  Session | scoped_session (Flask-SQLAlchemy proxy). Guard row-is-None
  after upsert.
- controllers/openapi/{chat,completion,workflow}_messages.py: tuple-vs-
  Mapping shape narrowing on AppGenerateService.generate return —
  production returns Mapping, tests mock as (body, status). Validate
  through Pydantic Response model in both shapes.
- controllers/openapi/oauth_device.py: replace flask_restx.reqparse (banned)
  with Pydantic Request/Query models — DeviceCodeRequest, DevicePollRequest,
  DeviceLookupQuery, DeviceMutateRequest. Two PEP-695 generic helpers
  (_validate_json / _validate_query) translate ValidationError to BadRequest.
- controllers/openapi/auth/strategies.py: Protocol param-name match
  (subject_type), Optional narrowing on app/tenant/account_id/subject_email.
- controllers/openapi/auth/steps.py: subject_type-is-None guard before
  mounter dispatch.
- core/app/apps/workflow/generate_task_pipeline.py + models/workflow.py:
  add WorkflowAppLogCreatedFrom.OPENAPI + matching match-case branch.
  Fixes match-exhaustiveness and possibly-unbound created_from.
- libs/device_flow_security.py: pyright ignore on flask after_request
  hook (registered by the framework, pyright sees as unused).
- services/oauth_device_flow.py: rename Exceptions to *Error suffix
  (StateNotFoundError / InvalidTransitionError / UserCodeExhaustedError);
  same for libs/oauth_bearer.py (InvalidBearerError / TokenExpiredError).
  Update all callers across openapi controllers.
- controllers/openapi/{oauth_device,oauth_device_sso}.py +
  services/oauth_device_flow.py: switch logger.error in except blocks
  to logger.exception (TRY400) — keeps the traceback for ops.
- configs/feature/__init__.py: OPENAPI_KNOWN_CLIENT_IDS computed_field
  needs an @property alongside for pyright to see it as a value, not a
  method. Matches the existing line-451 pattern.

Plus ruff format + import-sort across the openapi tree (pure formatting).
2026-04-28 21:44:54 -07:00

90 lines
3.0 KiB
Python

from types import SimpleNamespace
from unittest.mock import patch
from flask import Flask
from flask_restx import Api
def _client():
from controllers.openapi import (
chat_messages, # noqa: F401
openapi_ns,
)
app = Flask(__name__)
api = Api(app)
api.add_namespace(openapi_ns, path="/openapi/v1")
return app.test_client()
@patch("controllers.openapi.chat_messages.AppGenerateService")
def test_chat_dispatches_and_returns_response_model(svc, bypass_pipeline):
svc.generate.return_value = (
{
"event": "message",
"task_id": "tk1",
"id": "m1",
"message_id": "m1",
"conversation_id": "c1",
"mode": "chat",
"answer": "hi",
"metadata": {},
"created_at": 1700000000,
},
200,
)
fake = SimpleNamespace(mode="chat", id="app1", tenant_id="t1")
with (
patch("controllers.openapi.chat_messages._unpack_app", return_value=fake),
patch("controllers.openapi.chat_messages._unpack_caller", return_value=SimpleNamespace()),
):
r = _client().post("/openapi/v1/apps/app1/chat-messages", json={"query": "hi", "inputs": {}})
assert r.status_code == 200
body = r.get_json()
assert body["conversation_id"] == "c1"
assert body["answer"] == "hi"
assert svc.generate.call_args.kwargs["invoke_from"].value == "openapi"
@patch("controllers.openapi.chat_messages.AppGenerateService")
def test_chat_strips_user_field_from_body(svc, bypass_pipeline):
svc.generate.return_value = (
{
"event": "message",
"task_id": "tk1",
"id": "m1",
"message_id": "m1",
"conversation_id": "c1",
"mode": "chat",
"answer": "hi",
"metadata": {},
"created_at": 1700000000,
},
200,
)
fake = SimpleNamespace(mode="chat", id="app1", tenant_id="t1")
with (
patch("controllers.openapi.chat_messages._unpack_app", return_value=fake),
patch("controllers.openapi.chat_messages._unpack_caller", return_value=SimpleNamespace()),
):
_client().post(
"/openapi/v1/apps/app1/chat-messages",
json={"query": "hi", "inputs": {}, "user": "spoof@x.com"},
)
args = svc.generate.call_args.kwargs["args"]
assert "user" not in args
def test_chat_rejects_non_chat_mode(bypass_pipeline):
fake = SimpleNamespace(mode="completion")
with patch("controllers.openapi.chat_messages._unpack_app", return_value=fake):
r = _client().post("/openapi/v1/apps/app1/chat-messages", json={"query": "hi", "inputs": {}})
assert r.status_code in (400, 403)
def test_chat_rejects_invalid_body(bypass_pipeline):
fake = SimpleNamespace(mode="chat", id="app1", tenant_id="t1")
with patch("controllers.openapi.chat_messages._unpack_app", return_value=fake):
r = _client().post("/openapi/v1/apps/app1/chat-messages", json={"query": "hi"})
assert r.status_code in (400, 422)