chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,23 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
from werkzeug.exceptions import HTTPException
|
||||
|
||||
|
||||
def raised_error(call: Callable[[], object]) -> tuple[dict[str, object], int]:
|
||||
"""Run a handler call that must fail and return its error ``(body, status)``.
|
||||
|
||||
Controllers raise ``BaseHTTPException`` subclasses whose body carries the standard
|
||||
``status`` field. It is checked against the HTTP status here and left out of the
|
||||
returned body, so assertions compare only the fields that vary per error.
|
||||
"""
|
||||
try:
|
||||
call()
|
||||
except HTTPException as error:
|
||||
body = vars(error).get("data")
|
||||
if not isinstance(body, dict):
|
||||
raise AssertionError(f"{error!r} carries no error body") from error
|
||||
status = error.code
|
||||
assert status is not None
|
||||
assert body.get("status") == status, f"body status {body.get('status')!r} != HTTP status {status}"
|
||||
return {key: value for key, value in body.items() if key != "status"}, status
|
||||
raise AssertionError("expected the handler to raise an HTTP error")
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Check error responses served in controller tests against the API's own OpenAPI document.
|
||||
|
||||
Declarations are written by hand, so nothing checks them against the code. This check
|
||||
compares them with what is actually served, on every path a test exercises: each
|
||||
4xx/5xx JSON response served by an ``ExternalApi`` must carry the standard error body,
|
||||
and its ``code`` must be one the operation documents for that status or one of the
|
||||
surface's generic codes (``ExternalApi.implicit_error_codes``). The body must also satisfy
|
||||
the status's complete documented schema and, for a documented code, that code's component
|
||||
(fixed ``status`` and any ``details`` model). Operations that relay downstream errors admit
|
||||
any code. On APIs that do not document business errors
|
||||
(``/openapi/v1``, test-built APIs) only statuses that document a code are checked.
|
||||
"""
|
||||
|
||||
import sys
|
||||
from collections.abc import Iterator, Mapping
|
||||
from typing import cast, override
|
||||
from weakref import WeakKeyDictionary, WeakSet
|
||||
|
||||
from flask import Flask, Response, current_app, request
|
||||
from flask_restx.swagger import Swagger, extract_path
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
from libs.external_api import RELAYS_ERRORS_EXTENSION, ExternalApi
|
||||
|
||||
STANDARD_KEYS = frozenset({"code", "message", "status"})
|
||||
_MODULE_APIS = ("controllers.console", "controllers.web", "controllers.service_api", "controllers.openapi")
|
||||
# Surfaces whose operations document their business errors (the error lint covers them): a code
|
||||
# they serve must be documented or generic. Other APIs only have the codes a status documents checked.
|
||||
_DOCUMENTED_APIS = ("controllers.console", "controllers.web", "controllers.service_api")
|
||||
|
||||
_created: WeakSet[ExternalApi] = WeakSet()
|
||||
_documents: WeakKeyDictionary[ExternalApi, dict[str, object]] = WeakKeyDictionary()
|
||||
|
||||
|
||||
def track_external_apis() -> None:
|
||||
"""Record every ``ExternalApi`` built from now on (module-level surfaces are found by import)."""
|
||||
if vars(ExternalApi.__init__).get("_tracked"):
|
||||
return
|
||||
original = ExternalApi.__init__
|
||||
|
||||
def tracking_init(self: ExternalApi, *args: object, **kwargs: object) -> None:
|
||||
original(self, *args, **kwargs) # type: ignore[arg-type]
|
||||
_created.add(self)
|
||||
|
||||
tracking_init._tracked = True # type: ignore[attr-defined]
|
||||
ExternalApi.__init__ = tracking_init # type: ignore[method-assign]
|
||||
|
||||
|
||||
def _candidate_apis() -> Iterator[ExternalApi]:
|
||||
yield from _created
|
||||
yield from _module_apis()
|
||||
|
||||
|
||||
def _serving_api(app: Flask) -> ExternalApi | None:
|
||||
"""The ExternalApi that routed this request, whether mounted on a blueprint or on the app."""
|
||||
blueprint = app.blueprints.get(request.blueprint) if request.blueprint else None
|
||||
for api in _candidate_apis():
|
||||
if blueprint is not None and api.blueprint is blueprint:
|
||||
return api
|
||||
if blueprint is None and api.blueprint is None and api.app is app:
|
||||
return api
|
||||
return None
|
||||
|
||||
|
||||
def _module_apis(names: tuple[str, ...] = _MODULE_APIS) -> Iterator[ExternalApi]:
|
||||
for name in names:
|
||||
module = sys.modules.get(name)
|
||||
api = vars(module).get("api") if module is not None else None
|
||||
if isinstance(api, ExternalApi):
|
||||
yield api
|
||||
|
||||
|
||||
def _documents_business_errors(api: ExternalApi) -> bool:
|
||||
return any(api is surface for surface in _module_apis(_DOCUMENTED_APIS))
|
||||
|
||||
|
||||
# Flask-RESTX types ``Api.models`` as ``dict``, so the fallback mapping must be one.
|
||||
class _BorrowedModels(dict[str, object]): # noqa: FURB189
|
||||
"""An API's own models whose lookups by name fall back to the real surfaces' models.
|
||||
|
||||
Swagger resolves models only through ``in`` and ``[]``, while document finalization
|
||||
iterates every registered model. Iterating only the API's own models keeps a test API's
|
||||
document to the borrowed models its operations reference, instead of every surface model.
|
||||
"""
|
||||
|
||||
def __init__(self, own: Mapping[str, object], fallbacks: tuple[Mapping[str, object], ...]) -> None:
|
||||
super().__init__(own)
|
||||
self._fallbacks = fallbacks
|
||||
|
||||
@override
|
||||
def __contains__(self, key: object, /) -> bool:
|
||||
return super().__contains__(key) or any(key in fallback for fallback in self._fallbacks)
|
||||
|
||||
def __missing__(self, key: str) -> object:
|
||||
found = [fallback[key] for fallback in self._fallbacks if key in fallback]
|
||||
if not found:
|
||||
raise KeyError(key)
|
||||
return found[0]
|
||||
|
||||
|
||||
def _document(api: ExternalApi) -> dict[str, object]:
|
||||
"""The OpenAPI document of ``api``, built once per API and cached.
|
||||
|
||||
Test apps often mount a few resources on a fresh ExternalApi without the namespace that
|
||||
registers their models; those models are borrowed from the real surfaces for the build,
|
||||
without being copied into ``api.models``. ``api.models`` is the same mapping afterwards,
|
||||
whether the build succeeds or raises.
|
||||
"""
|
||||
if api not in _documents:
|
||||
surfaces = tuple(surface.models for surface in _module_apis() if surface is not api)
|
||||
own_models = api.models
|
||||
api.models = _BorrowedModels(own_models, surfaces)
|
||||
try:
|
||||
_documents[api] = cast(dict[str, object], Swagger(api).as_dict())
|
||||
finally:
|
||||
api.models = own_models
|
||||
return _documents[api]
|
||||
|
||||
|
||||
def _resolve(schema: object, components: Mapping[str, object]) -> Mapping[str, object]:
|
||||
if isinstance(schema, Mapping) and isinstance(ref := schema.get("$ref"), str):
|
||||
resolved = components.get(ref.rsplit("/", 1)[-1])
|
||||
return resolved if isinstance(resolved, Mapping) else {}
|
||||
return schema if isinstance(schema, Mapping) else {}
|
||||
|
||||
|
||||
def _documented_code(schema: Mapping[str, object]) -> str | None:
|
||||
"""The fixed ``code`` a per-code error component declares, or ``None`` for the open body."""
|
||||
parts = schema.get("allOf")
|
||||
for part in parts if isinstance(parts, list) else []:
|
||||
if isinstance(part, Mapping):
|
||||
code = (part.get("properties") or {}).get("code")
|
||||
if isinstance(code, Mapping) and isinstance(code.get("const"), str):
|
||||
return code["const"]
|
||||
return None
|
||||
|
||||
|
||||
def _mapping(value: object) -> Mapping[str, object]:
|
||||
return cast(Mapping[str, object], value) if isinstance(value, Mapping) else {}
|
||||
|
||||
|
||||
def _is_error_body(schema: Mapping[str, object], error_models: set[str]) -> bool:
|
||||
return schema.get("title") in error_models or bool(schema.get("allOf"))
|
||||
|
||||
|
||||
def _schema_errors(schema: Mapping[str, object], components: Mapping[str, object], body: object) -> list[str]:
|
||||
"""How ``body`` fails ``schema``, resolving ``$ref`` against the document's components."""
|
||||
validator = Draft202012Validator({**schema, "components": {"schemas": dict(components)}})
|
||||
return [
|
||||
f"{'/'.join(str(part) for part in error.absolute_path) or 'body'}: {error.message}"
|
||||
for error in validator.iter_errors(body)
|
||||
]
|
||||
|
||||
|
||||
def violation(api: ExternalApi, response: Response) -> str | None:
|
||||
"""Why ``response`` contradicts the operation's documented error contract, if it does."""
|
||||
document = _document(api)
|
||||
components = _mapping(_mapping(document.get("components")).get("schemas"))
|
||||
rule = request.url_rule
|
||||
if rule is None:
|
||||
return None
|
||||
prefix = (api.blueprint.url_prefix if api.blueprint is not None else "") or ""
|
||||
path = extract_path(rule.rule).removeprefix(prefix).removeprefix(api.prefix or "") or "/"
|
||||
operation = _mapping(_mapping(document.get("paths")).get(path)).get(request.method.lower())
|
||||
if not isinstance(operation, Mapping):
|
||||
return None
|
||||
|
||||
where = f"{request.method} {path} -> {response.status_code}"
|
||||
body = response.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
return f"{where}: error body is not a JSON object: {response.get_data(as_text=True)[:200]!r}"
|
||||
|
||||
responses = _mapping(operation.get("responses"))
|
||||
declared = _mapping(responses.get(str(response.status_code)) or responses.get("default"))
|
||||
schema = _mapping(_mapping(declared.get("content")).get("application/json")).get("schema")
|
||||
error_model = api.error_response_model.__name__
|
||||
alternatives = schema.get("anyOf") if isinstance(schema, Mapping) else None
|
||||
raw_options = [_mapping(option) for option in (alternatives or ([schema] if schema is not None else []))]
|
||||
options = [(option, _resolve(option, components)) for option in raw_options]
|
||||
error_options = [raw for raw, resolved in options if _is_error_body(resolved, {error_model})]
|
||||
legacy_options = [raw for raw, resolved in options if not _is_error_body(resolved, {error_model})]
|
||||
|
||||
# A body that matches a legacy model the status also declares is documented as is.
|
||||
if any(not _schema_errors(option, components, body) for option in legacy_options):
|
||||
return None
|
||||
if legacy_options and not error_options:
|
||||
return f"{where}: error body matches none of the declared models: {body!r}"
|
||||
|
||||
standard = {"$ref": f"#/components/schemas/{error_model}"} if error_model in components else None
|
||||
problems: list[str] = _schema_errors(standard, components, body) if standard else []
|
||||
if not body.keys() >= STANDARD_KEYS:
|
||||
return f"{where}: error body lacks {sorted(STANDARD_KEYS - body.keys())}: {body!r}"
|
||||
if problems:
|
||||
return f"{where}: error body does not match {error_model} ({'; '.join(problems)}): {body!r}"
|
||||
if body["status"] != response.status_code:
|
||||
return f"{where}: body status {body['status']!r} differs from the HTTP status"
|
||||
if schema is not None and (problems := _schema_errors(_mapping(schema), components, body)):
|
||||
# The status's own schema must admit the body: the open error body must stay beside
|
||||
# the per-code components, or a generic error on this status contradicts the document.
|
||||
return (
|
||||
f"{where}: error body does not match the documented {response.status_code} schema "
|
||||
f"({'; '.join(problems)}): {body!r}"
|
||||
)
|
||||
components_by_code = {
|
||||
code: option for option in error_options if (code := _documented_code(_resolve(option, components)))
|
||||
}
|
||||
documented = set(components_by_code)
|
||||
if operation.get(RELAYS_ERRORS_EXTENSION) is True and body["code"] not in documented:
|
||||
# The operation relays downstream errors, whose codes the document cannot know.
|
||||
return None
|
||||
if (component := components_by_code.get(body["code"])) is not None:
|
||||
if problems := _schema_errors(component, components, body):
|
||||
return (
|
||||
f"{where}: error body does not match its {body['code']!r} component ({'; '.join(problems)}): {body!r}"
|
||||
)
|
||||
return None
|
||||
if not documented and not _documents_business_errors(api):
|
||||
return None
|
||||
generic = api.implicit_error_codes(response.status_code)
|
||||
if not _documents_business_errors(api):
|
||||
# A test harness mounts a surface's resources on a fresh ExternalApi that declares none
|
||||
# of the surface's generic errors (``document_generic_errors``); admit what the
|
||||
# documented surfaces treat as generic, since the resources under test are theirs.
|
||||
for surface in _module_apis(_DOCUMENTED_APIS):
|
||||
generic |= surface.implicit_error_codes(response.status_code)
|
||||
if body["code"] not in documented | generic:
|
||||
return (
|
||||
f"{where}: code {body['code']!r} is not documented for this status "
|
||||
f"(documented: {sorted(documented)}, generic: {sorted(generic)})"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def check_response(sender: Flask, response: Response, violations: list[str]) -> None:
|
||||
if response.status_code < 400 or not response.is_json:
|
||||
return
|
||||
api = _serving_api(sender)
|
||||
if api is None:
|
||||
return
|
||||
with current_app.app_context():
|
||||
try:
|
||||
found = violation(api, response)
|
||||
except Exception as exc:
|
||||
# The checker never changes the response under test, but a response it cannot check
|
||||
# (e.g. a test app missing a model the document needs) must not pass silently.
|
||||
found = (
|
||||
f"{request.method} {request.path} -> {response.status_code}: cannot check the error contract: {exc!r}"
|
||||
)
|
||||
if found is not None:
|
||||
violations.append(found)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Typed recording fakes shared by the KnowledgeFS controller tests.
|
||||
|
||||
Controllers reach KnowledgeFS through a runtime object whose components expose
|
||||
plain methods. These fakes replace those components without mock objects:
|
||||
``Recorder`` stores every call in a list and returns or raises what the test
|
||||
configured, and ``FakeComponent`` exposes only the operations a test declares,
|
||||
so an unexpected delegation fails with ``AttributeError``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RecordedCall:
|
||||
args: tuple[object, ...] = ()
|
||||
kwargs: dict[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
def invocation(*args: object, **kwargs: object) -> RecordedCall:
|
||||
return RecordedCall(args=args, kwargs=kwargs)
|
||||
|
||||
|
||||
class Recorder:
|
||||
"""Callable test double that records calls and returns, raises or delegates.
|
||||
|
||||
``raises`` is raised on every call, ``results`` is consumed one value per
|
||||
call (exceptions in it are raised), and ``effect`` computes the result from
|
||||
the call arguments. Otherwise ``return_value`` is returned.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
return_value: object = None,
|
||||
*,
|
||||
raises: BaseException | None = None,
|
||||
results: Iterable[object] | None = None,
|
||||
effect: Callable[..., object] | None = None,
|
||||
) -> None:
|
||||
self.return_value = return_value
|
||||
self.raises = raises
|
||||
self.effect = effect
|
||||
self._results: Iterator[object] | None = iter(results) if results is not None else None
|
||||
self.calls: list[RecordedCall] = []
|
||||
|
||||
def __call__(self, *args: object, **kwargs: object) -> object:
|
||||
self.calls.append(RecordedCall(args=args, kwargs=kwargs))
|
||||
if self.raises is not None:
|
||||
raise self.raises
|
||||
if self._results is not None:
|
||||
result = next(self._results)
|
||||
if isinstance(result, BaseException):
|
||||
raise result
|
||||
return result
|
||||
if self.effect is not None:
|
||||
return self.effect(*args, **kwargs)
|
||||
return self.return_value
|
||||
|
||||
@property
|
||||
def last_call(self) -> RecordedCall:
|
||||
assert self.calls, "expected at least one call"
|
||||
return self.calls[-1]
|
||||
|
||||
@property
|
||||
def only_call(self) -> RecordedCall:
|
||||
assert len(self.calls) == 1, f"expected exactly one call, got {len(self.calls)}"
|
||||
return self.calls[0]
|
||||
|
||||
|
||||
class FakeComponent:
|
||||
"""Runtime component exposing exactly the named operations given to it."""
|
||||
|
||||
def __init__(self, **operations: Recorder) -> None:
|
||||
self._operations = operations
|
||||
|
||||
def __getattr__(self, name: str) -> Recorder:
|
||||
operations = self.__dict__.get("_operations", {})
|
||||
if name not in operations:
|
||||
raise AttributeError(name)
|
||||
return operations[name]
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeRuntime:
|
||||
"""The subset of ``KnowledgeFSRuntime`` that controllers resolve per request."""
|
||||
|
||||
facade: FakeComponent = field(default_factory=FakeComponent)
|
||||
application: FakeComponent = field(default_factory=FakeComponent)
|
||||
control_plane: FakeComponent = field(default_factory=FakeComponent)
|
||||
app_bindings: FakeComponent = field(default_factory=FakeComponent)
|
||||
broker: FakeComponent = field(default_factory=FakeComponent)
|
||||
service_api_authorization: FakeComponent = field(default_factory=FakeComponent)
|
||||
|
||||
|
||||
def narrowed[T](value: object, kind: type[T]) -> T:
|
||||
"""Assert a recorded argument is ``kind`` and return it typed as such."""
|
||||
|
||||
assert isinstance(value, kind), f"expected {kind.__name__}, got {type(value).__name__}"
|
||||
return value
|
||||
|
||||
|
||||
def raising(error: BaseException) -> Callable[..., object]:
|
||||
"""Return a plain callable that raises ``error`` when invoked."""
|
||||
|
||||
def operation(*_args: object, **_kwargs: object) -> object:
|
||||
raise error
|
||||
|
||||
return operation
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Shared mode lists for the openapi app-list query tests.
|
||||
|
||||
Single source so adding/removing a listable app type is a one-line change
|
||||
across every query-validator test.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
LISTABLE_MODES = ["completion", "chat", "advanced-chat", "workflow", "agent-chat"]
|
||||
NON_LISTABLE_MODES = ["rag-pipeline", "channel", "agent"]
|
||||
@@ -0,0 +1,131 @@
|
||||
"""The rows, tokens and subjects the auth-layer tests build their worlds from.
|
||||
|
||||
One copy: every module under `auth/` was carrying its own identical `App`,
|
||||
`Tenant`, `Account` and `AuthContext` builders, so a column added to any of
|
||||
those models had to be chased through six files.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import NoReturn
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from constants.oauth_bearer import SubjectType, TokenType
|
||||
from controllers.openapi.auth.context import Context
|
||||
from controllers.openapi.auth.subjects import AccountSubject, ExternalSsoSubject, Subject
|
||||
from enums import DeploymentEdition
|
||||
from libs.oauth_bearer import AuthContext
|
||||
from models import Account, App, Tenant, TenantAccountJoin
|
||||
from models.account import AccountStatus, TenantAccountRole, TenantStatus
|
||||
from models.enums import AppStatus
|
||||
from models.model import AppMode, IconType
|
||||
from services.enterprise.enterprise_service import WebAppSettings
|
||||
from services.entities.feature_entities import (
|
||||
LicenseStatus,
|
||||
LicenseStatusModel,
|
||||
SystemFeatureModel,
|
||||
WebAppAuthModel,
|
||||
)
|
||||
|
||||
APP_ID = "00000000-0000-0000-0000-000000000001"
|
||||
TENANT_ID = "00000000-0000-0000-0000-000000000002"
|
||||
ACCOUNT_ID = "00000000-0000-0000-0000-000000000003"
|
||||
TOKEN_ID = "00000000-0000-0000-0000-000000000004"
|
||||
SESSION_ID = "00000000-0000-0000-0000-000000000005"
|
||||
OTHER_TENANT_ID = "00000000-0000-0000-0000-000000000006"
|
||||
CLIENT_ID = "openapi-client"
|
||||
ACCOUNT_EMAIL = "account@example.com"
|
||||
SSO_EMAIL = "user@sso.com"
|
||||
SSO_ISSUER = "https://idp.example"
|
||||
|
||||
|
||||
def make_auth(token_type: TokenType, **overrides: object) -> AuthContext:
|
||||
"""A live token of either kind. `overrides` names the one field a test varies."""
|
||||
is_account = token_type.subject is SubjectType.ACCOUNT
|
||||
fields: dict[str, object] = {
|
||||
"token_type": token_type,
|
||||
"subject_email": None if is_account else SSO_EMAIL,
|
||||
"subject_issuer": None if is_account else SSO_ISSUER,
|
||||
"account_id": uuid.UUID(ACCOUNT_ID) if is_account else None,
|
||||
"client_id": CLIENT_ID,
|
||||
"token_id": uuid.UUID(TOKEN_ID),
|
||||
"expires_at": None,
|
||||
}
|
||||
fields.update(overrides)
|
||||
return AuthContext(**fields) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def account_subject(**overrides: object) -> AccountSubject:
|
||||
return AccountSubject(make_auth(TokenType.OAUTH_ACCOUNT, **overrides))
|
||||
|
||||
|
||||
def sso_subject(**overrides: object) -> ExternalSsoSubject:
|
||||
return ExternalSsoSubject(make_auth(TokenType.OAUTH_EXTERNAL_SSO, **overrides))
|
||||
|
||||
|
||||
def make_app(
|
||||
*, app_id: str = APP_ID, tenant_id: str = TENANT_ID, enable_api: bool = True, mode: AppMode = AppMode.CHAT
|
||||
) -> App:
|
||||
return App(
|
||||
id=app_id,
|
||||
tenant_id=tenant_id,
|
||||
name="OpenAPI app",
|
||||
description="",
|
||||
mode=mode,
|
||||
icon_type=IconType.EMOJI,
|
||||
icon="robot",
|
||||
icon_background="#FFFFFF",
|
||||
status=AppStatus.NORMAL,
|
||||
enable_site=True,
|
||||
enable_api=enable_api,
|
||||
max_active_requests=None,
|
||||
)
|
||||
|
||||
|
||||
def make_tenant(*, tenant_id: str = TENANT_ID, status: TenantStatus = TenantStatus.NORMAL) -> Tenant:
|
||||
tenant = Tenant(name="OpenAPI tenant", status=status)
|
||||
tenant.id = tenant_id
|
||||
return tenant
|
||||
|
||||
|
||||
def make_account(*, status: AccountStatus = AccountStatus.ACTIVE, email: str = ACCOUNT_EMAIL) -> Account:
|
||||
account = Account(name="OpenAPI account", email=email, status=status)
|
||||
account.id = ACCOUNT_ID
|
||||
return account
|
||||
|
||||
|
||||
def make_membership(role: TenantAccountRole = TenantAccountRole.NORMAL) -> TenantAccountJoin:
|
||||
return TenantAccountJoin(tenant_id=TENANT_ID, account_id=ACCOUNT_ID, current=True, role=role)
|
||||
|
||||
|
||||
def persist(session: Session, *models: object) -> None:
|
||||
session.add_all(models)
|
||||
session.commit()
|
||||
|
||||
|
||||
def make_ctx(session: Session, subject: Subject | None = None, **view_args: str) -> Context:
|
||||
return Context(subject or account_subject(), session, dict(view_args))
|
||||
|
||||
|
||||
def system_features(
|
||||
*,
|
||||
license_status: LicenseStatus = LicenseStatus.ACTIVE,
|
||||
webapp_auth: bool = False,
|
||||
) -> SystemFeatureModel:
|
||||
return SystemFeatureModel(
|
||||
agent_tracing_api_collection_enabled=False,
|
||||
deployment_edition=DeploymentEdition.ENTERPRISE,
|
||||
license=LicenseStatusModel(status=license_status),
|
||||
webapp_auth=WebAppAuthModel(enabled=webapp_auth),
|
||||
)
|
||||
|
||||
|
||||
def webapp_settings(access_mode: str) -> WebAppSettings:
|
||||
return WebAppSettings.model_validate({"accessMode": access_mode})
|
||||
|
||||
|
||||
def never_reached(*_args: object, **_kwargs: object) -> NoReturn:
|
||||
"""Stand-in for anything a test's own setup says the code under test must not reach."""
|
||||
raise AssertionError("reached a call this test's setup says nothing should have made")
|
||||
@@ -0,0 +1,26 @@
|
||||
from collections.abc import Callable
|
||||
|
||||
from controllers.common.rbac import RBAC_CHECKS_ATTR, RBACCheck
|
||||
|
||||
|
||||
def rbac_checks(view: Callable[..., object]) -> tuple[RBACCheck, ...]:
|
||||
current = view
|
||||
while RBAC_CHECKS_ATTR not in current.__dict__:
|
||||
wrapped = current.__dict__.get("__wrapped__")
|
||||
if wrapped is None:
|
||||
raise AssertionError(f"no decorator layer of {view!r} carries an rbac_checks bundle")
|
||||
current = wrapped
|
||||
return current.__dict__[RBAC_CHECKS_ATTR]
|
||||
|
||||
|
||||
def all_rbac_checks(view: Callable[..., object]) -> list[RBACCheck]:
|
||||
found: list[RBACCheck] = []
|
||||
seen_bundle_ids: set[int] = set()
|
||||
current: Callable[..., object] | None = view
|
||||
while current is not None:
|
||||
bundle = current.__dict__.get(RBAC_CHECKS_ATTR)
|
||||
if bundle is not None and id(bundle) not in seen_bundle_ids:
|
||||
seen_bundle_ids.add(id(bundle))
|
||||
found.extend(bundle)
|
||||
current = current.__dict__.get("__wrapped__")
|
||||
return found
|
||||
Reference in new issue
Block a user