chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Test suite root package (enables ``import tests.e2e_tests.middleware...`` with ``pythonpath = .``)."""
+28
View File
@@ -0,0 +1,28 @@
import gc
import os
from collections.abc import Iterator
import pytest
from core.app.workflow.file_runtime import create_dify_workflow_file_runtime
from graphon.file.runtime import use_workflow_file_runtime
# Tests select an explicit deployment event transport.
os.environ.setdefault("HUMAN_INPUT_IM_EVENT_TRANSPORT_MODE", "WEBHOOK")
def pytest_collection_finish(session: pytest.Session) -> None:
"""Move everything loaded during collection out of the garbage collector's reach.
Collection imports the whole application, so every automatic full collection afterwards
rescanned those long-lived objects and stalled whichever test triggered it. Objects created
by tests themselves are still collected normally.
"""
gc.collect()
gc.freeze()
@pytest.fixture(autouse=True)
def _bind_workflow_file_runtime() -> Iterator[None]:
with use_workflow_file_runtime(create_dify_workflow_file_runtime()):
yield
Whitespace-only changes.
@@ -0,0 +1,91 @@
extend = "../../../.ruff.toml"
src = ["../../.."]
[lint]
extend-select = ["ANN401", "ARG"]
# Existing strict-mode debt. Remove a file entry when bringing it under strict checking.
[lint.per-file-ignores]
"controllers/console/test_apikey.py" = ["ARG002"]
"controllers/openapi/test_app_dsl.py" = ["ARG002"]
"controllers/service_api/dataset/test_dataset.py" = ["ARG002"]
"controllers/web/test_conversation.py" = ["ARG002"]
"controllers/web/test_human_input_form.py" = ["ARG001"]
"controllers/web/test_wraps.py" = ["ARG002"]
"core/app/layers/test_pause_state_persist_layer.py" = ["ARG002"]
"core/rag/pipeline/test_queue_integration.py" = ["ARG002", "TID251"]
"core/rag/retrieval/test_dataset_retrieval_integration.py" = ["ARG002"]
"models/test_conversation_message_inputs.py" = ["ARG001"]
"models/test_types_enum_text.py" = ["ANN401", "TID251"]
"repositories/test_sqlalchemy_api_workflow_run_repository.py" = ["ARG002", "ARG005"]
"repositories/test_workflow_run_repository.py" = ["ARG002"]
"services/auth/test_auth_integration.py" = ["ARG002"]
"services/dataset_collection_binding.py" = ["ARG002"]
"services/document_service_status.py" = ["ARG002"]
"services/rag_pipeline/test_rag_pipeline_service_db.py" = ["ARG002"]
"services/test_advanced_prompt_template_service.py" = ["ARG002"]
"services/test_app_dsl_service.py" = ["ANN401", "ARG001", "ARG002", "ARG005", "TID251"]
"services/test_app_service.py" = ["ARG002"]
"services/test_attachment_service.py" = ["ARG002"]
"services/test_conversation_variable_updater.py" = ["ARG002"]
"services/test_dataset_service_batch_update_document_status.py" = ["ARG002"]
"services/test_delete_archived_workflow_run.py" = ["ARG002"]
"services/test_document_service_rename_document.py" = ["ARG001"]
"services/test_end_user_service.py" = ["ARG002"]
"services/test_feature_service.py" = ["ARG002"]
"services/test_file_service.py" = ["ARG002"]
"services/test_file_service_zip_and_lookup.py" = ["TID251"]
"services/test_messages_clean_service.py" = ["ARG002", "S110"]
"services/test_metadata_partial_update.py" = ["ARG002"]
"services/test_metadata_service.py" = ["ARG002"]
"services/test_model_load_balancing_service.py" = ["ARG002"]
"services/test_model_provider_service.py" = ["ARG002"]
"services/test_webapp_auth_service.py" = ["ARG002"]
"services/test_webhook_service.py" = ["ARG002"]
"services/test_workflow_draft_variable_service.py" = ["ARG002"]
"services/test_workflow_run_service.py" = ["ARG002"]
"services/test_workflow_service.py" = ["ARG002"]
"services/tools/test_api_tools_manage_service.py" = ["ARG002"]
"services/tools/test_mcp_tools_manage_service.py" = ["ARG002", "ARG005"]
"services/tools/test_tools_transform_service.py" = ["ARG002"]
"services/workflow/test_workflow_converter.py" = ["ARG002"]
"tasks/test_add_document_to_index_task.py" = ["ARG002"]
"tasks/test_batch_clean_document_task.py" = ["ARG002"]
"tasks/test_batch_create_segment_to_index_task.py" = ["ARG001", "ARG002"]
"tasks/test_clean_dataset_task.py" = ["T201"]
"tasks/test_clean_notion_document_task.py" = ["ARG002"]
"tasks/test_create_segment_to_index_task.py" = ["ARG002"]
"tasks/test_dataset_indexing_task.py" = ["ARG002"]
"tasks/test_deal_dataset_vector_index_task.py" = ["ARG002"]
"tasks/test_delete_segment_from_index_task.py" = ["ARG002"]
"tasks/test_disable_segment_from_index_task.py" = ["ARG002"]
"tasks/test_disable_segments_from_index_task.py" = ["ARG002"]
"tasks/test_document_indexing_sync_task.py" = ["ARG002"]
"tasks/test_document_indexing_task.py" = ["ARG002"]
"tasks/test_document_indexing_update_task.py" = ["ARG002"]
"tasks/test_duplicate_document_indexing_task.py" = ["ARG002"]
"tasks/test_enable_segments_to_index_task.py" = ["ARG002"]
"tasks/test_mail_change_mail_task.py" = ["ARG002"]
"tasks/test_mail_email_code_login_task.py" = ["ARG002"]
"tasks/test_mail_human_input_delivery_task.py" = ["ARG001"]
"tasks/test_mail_inner_task.py" = ["ARG002"]
"tasks/test_mail_invite_member_task.py" = ["ARG002"]
"tasks/test_mail_owner_transfer_task.py" = ["ARG002"]
"tasks/test_mail_register_task.py" = ["ARG002"]
"tasks/test_rag_pipeline_run_tasks.py" = ["ARG002"]
"test_workflow_pause_integration.py" = ["T201"]
"trigger/conftest.py" = ["ANN401", "TID251"]
"trigger/test_trigger_e2e.py" = ["ANN401", "ARG001", "TID251"]
"workflow/nodes/code_executor/test_code_javascript.py" = ["ARG002"]
"workflow/nodes/code_executor/test_code_jinja2.py" = ["ARG002"]
"workflow/nodes/code_executor/test_code_python3.py" = ["ARG002"]
"workflow/nodes/code_executor/test_utils.py" = ["T201"]
[lint.flake8-tidy-imports.banned-api."flask_restx.reqparse"]
msg = "Use Pydantic payload/query models instead of reqparse."
[lint.flake8-tidy-imports.banned-api."flask_restx.reqparse.RequestParser"]
msg = "Use Pydantic payload/query models instead of reqparse."
[lint.flake8-tidy-imports.banned-api."typing.Any"]
msg = "Use object, Protocol, TypedDict, TypeVar, ParamSpec, or a localized cast instead."
Whitespace-only changes.
@@ -0,0 +1,412 @@
from __future__ import annotations
import importlib
import io
import json
from collections.abc import Generator
from datetime import datetime, timedelta
import pytest
import sqlalchemy as sa
from tests.helpers.legacy_model_type_migration import (
assert_tenant_rows_use_only_canonical_model_types,
count_rows,
fetch_table_rows,
seed_legacy_model_type_dirty_data,
)
def _parse_json_lines(output: io.StringIO) -> list[dict[str, object]]:
return [json.loads(line) for line in output.getvalue().splitlines() if line.strip()]
def _json_key(value: object) -> str:
return json.dumps(value, sort_keys=True)
def _lb_processing_signatures(lines: list[dict[str, object]]) -> set[tuple[object, ...]]:
signatures: set[tuple[object, ...]] = set()
for line in lines:
attrs = line.get("attrs")
if not isinstance(attrs, dict):
continue
if attrs.get("table_name") != "load_balancing_model_configs":
continue
event = line.get("event")
if event == "row_updated":
signatures.add(
(
event,
attrs.get("id"),
_json_key(attrs.get("old_values")),
_json_key(attrs.get("new_values")),
)
)
elif event == "row_deleted":
signatures.add(
(
event,
attrs.get("id"),
attrs.get("merge_winner_id"),
)
)
elif event == "group_processed":
signatures.add(
(
event,
attrs.get("table_name"),
_json_key(attrs.get("business_key")),
tuple(attrs.get("group_row_ids", [])),
)
)
return signatures
def _insert_load_balancing_model_config(
engine: sa.Engine,
*,
row_id: str,
tenant_id: str,
provider_name: str,
model_name: str,
model_type: str,
name: str,
encrypted_config: str,
credential_id: str,
enabled: bool,
created_at: datetime,
updated_at: datetime,
) -> None:
with engine.begin() as conn:
conn.execute(
sa.text(
"""
INSERT INTO load_balancing_model_configs
(
id, tenant_id, provider_name, model_name, model_type, name,
encrypted_config, credential_id, credential_source_type, enabled, created_at, updated_at
)
VALUES
(
:id, :tenant_id, :provider_name, :model_name, :model_type, :name,
:encrypted_config, :credential_id, :credential_source_type, :enabled, :created_at, :updated_at
)
"""
),
{
"id": row_id,
"tenant_id": tenant_id,
"provider_name": provider_name,
"model_name": model_name,
"model_type": model_type,
"name": name,
"encrypted_config": encrypted_config,
"credential_id": credential_id,
"credential_source_type": "custom_model",
"enabled": enabled,
"created_at": created_at,
"updated_at": updated_at,
},
)
@pytest.fixture(autouse=True)
def reset_legacy_schema(container_engine: tuple[str, sa.Engine]) -> None:
from tests.helpers.legacy_model_type_migration import drop_minimal_legacy_model_type_schema
_, engine = container_engine
drop_minimal_legacy_model_type_schema(engine)
@pytest.fixture(scope="session")
def migration_module():
try:
return importlib.import_module("services.legacy_model_type_migration")
except ModuleNotFoundError: # pragma: no cover - explicit TDD failure path
pytest.fail(
"services.legacy_model_type_migration is missing. "
"Implement LegacyModelTypeMigrationService before running these tests."
)
@pytest.fixture(params=("postgresql", "mysql"), scope="session")
def container_engine(request: pytest.FixtureRequest) -> Generator[tuple[str, sa.Engine]]:
backend_name = request.param
if backend_name == "postgresql":
testcontainers_postgres = pytest.importorskip("testcontainers.postgres")
container = testcontainers_postgres.PostgresContainer("postgres:15-alpine")
else:
testcontainers_mysql = pytest.importorskip("testcontainers.mysql")
container = testcontainers_mysql.MySqlContainer("mysql:8.0")
container.start()
raw_url = container.get_connection_url()
engine_url = raw_url.replace("mysql://", "mysql+pymysql://", 1)
engine = sa.create_engine(engine_url)
try:
yield backend_name, engine
finally:
engine.dispose()
container.stop()
def test_legacy_model_type_migration_end_to_end_across_supported_backends(
migration_module,
container_engine: tuple[str, sa.Engine],
monkeypatch: pytest.MonkeyPatch,
) -> None:
backend_name, engine = container_engine
fixture = seed_legacy_model_type_dirty_data(engine)
deleted_cache_keys: list[str] = []
def _record_delete(self) -> None:
deleted_cache_keys.append(self.cache_key)
monkeypatch.setattr(migration_module.ProviderCredentialsCache, "delete", _record_delete)
dry_run_output = io.StringIO()
migration_module.LegacyModelTypeMigrationService(
engine=engine,
apply=False,
output=dry_run_output,
tenant_ids=(fixture.primary.tenant_id,),
).migrate()
assert count_rows(engine, "provider_model_credentials", tenant_id=fixture.primary.tenant_id) == 3
assert deleted_cache_keys == []
apply_output = io.StringIO()
migration_module.LegacyModelTypeMigrationService(
engine=engine,
apply=True,
output=apply_output,
tenant_ids=(fixture.primary.tenant_id,),
).migrate()
first_apply_state = {
table_name: fetch_table_rows(engine, table_name, tenant_id=fixture.primary.tenant_id)
for table_name in (
"provider_models",
"tenant_default_models",
"provider_model_settings",
"load_balancing_model_configs",
"provider_model_credentials",
)
}
assert_tenant_rows_use_only_canonical_model_types(engine, fixture.primary.tenant_id)
assert count_rows(engine, "provider_model_credentials", tenant_id=fixture.primary.tenant_id) == 2
provider_model_row = next(
row for row in first_apply_state["provider_models"] if row["id"] == fixture.primary.provider_model_id
)
assert provider_model_row["credential_id"] == fixture.primary.winner_credential_id
credential_ids = {str(row["id"]) for row in first_apply_state["provider_model_credentials"]}
assert credential_ids == {
fixture.primary.winner_credential_id,
fixture.primary.distinct_credential_id,
}
lb_row = next(
row
for row in first_apply_state["load_balancing_model_configs"]
if row["id"] == fixture.primary.load_balancing_config_id
)
assert lb_row["credential_id"] == fixture.primary.winner_credential_id
assert lb_row["encrypted_config"] == fixture.primary.winner_encrypted_config
assert deleted_cache_keys, f"{backend_name} apply run should clear cache keys"
migration_module.LegacyModelTypeMigrationService(
engine=engine,
apply=True,
output=io.StringIO(),
tenant_ids=(fixture.primary.tenant_id,),
).migrate()
second_apply_state = {
table_name: fetch_table_rows(engine, table_name, tenant_id=fixture.primary.tenant_id)
for table_name in first_apply_state
}
assert second_apply_state == first_apply_state
def test_load_balancing_inherit_deduplication_is_applied_consistently_across_supported_backends(
migration_module,
container_engine: tuple[str, sa.Engine],
monkeypatch: pytest.MonkeyPatch,
) -> None:
_, engine = container_engine
fixture = seed_legacy_model_type_dirty_data(engine)
tenant_id = fixture.primary.tenant_id
older_inherit_row_id = "00000000-0000-0000-0000-00000000ee01"
newer_inherit_row_id = "00000000-0000-0000-0000-00000000ee02"
canonical_non_inherit_row_id = "00000000-0000-0000-0000-00000000ee03"
created_at = datetime(2025, 1, 1, 8, 0, 0)
_insert_load_balancing_model_config(
engine,
row_id=older_inherit_row_id,
tenant_id=tenant_id,
provider_name="openai",
model_name="gpt-4o-mini",
model_type="llm",
name="__inherit__",
encrypted_config='{"api_key":"older-inherit"}',
credential_id=fixture.primary.winner_credential_id,
enabled=True,
created_at=created_at,
updated_at=created_at + timedelta(minutes=15),
)
_insert_load_balancing_model_config(
engine,
row_id=newer_inherit_row_id,
tenant_id=tenant_id,
provider_name="openai",
model_name="gpt-4o-mini",
model_type="text-generation",
name="__inherit__",
encrypted_config='{"api_key":"newer-inherit"}',
credential_id=fixture.primary.distinct_credential_id,
enabled=True,
created_at=created_at,
updated_at=created_at + timedelta(minutes=30),
)
_insert_load_balancing_model_config(
engine,
row_id=canonical_non_inherit_row_id,
tenant_id=tenant_id,
provider_name="openai",
model_name="gpt-4o-mini",
model_type="llm",
name=f"{tenant_id}-second-shared",
encrypted_config='{"api_key":"non-inherit-canonical"}',
credential_id=fixture.primary.distinct_credential_id,
enabled=True,
created_at=created_at,
updated_at=created_at + timedelta(minutes=45),
)
before_dry_run = fetch_table_rows(engine, "load_balancing_model_configs", tenant_id=tenant_id)
deleted_cache_keys: list[str] = []
def _record_delete(self) -> None:
deleted_cache_keys.append(self.cache_key)
monkeypatch.setattr(migration_module.ProviderCredentialsCache, "delete", _record_delete)
dry_run_output = io.StringIO()
migration_module.LegacyModelTypeMigrationService(
engine=engine,
apply=False,
output=dry_run_output,
tables=("load_balancing_model_configs",),
model_types=(migration_module.ModelType.LLM,),
tenant_ids=(tenant_id,),
).migrate()
after_dry_run = fetch_table_rows(engine, "load_balancing_model_configs", tenant_id=tenant_id)
dry_run_lines = _parse_json_lines(dry_run_output)
dry_run_cache_events = [line["event"] for line in dry_run_lines if str(line.get("event")).startswith("cache_")]
dry_run_row_updates = {
str(attrs["id"])
for line in dry_run_lines
if line.get("event") == "row_updated"
and isinstance((attrs := line.get("attrs")), dict)
and attrs.get("table_name") == "load_balancing_model_configs"
}
dry_run_row_deletes = {
str(attrs["id"])
for line in dry_run_lines
if line.get("event") == "row_deleted"
and isinstance((attrs := line.get("attrs")), dict)
and attrs.get("table_name") == "load_balancing_model_configs"
}
dry_run_group_processed = [
attrs
for line in dry_run_lines
if line.get("event") == "group_processed"
and isinstance((attrs := line.get("attrs")), dict)
and attrs.get("table_name") == "load_balancing_model_configs"
]
assert after_dry_run == before_dry_run
assert deleted_cache_keys == []
assert dry_run_row_deletes == {older_inherit_row_id}
assert dry_run_row_updates == {
fixture.primary.load_balancing_config_id,
newer_inherit_row_id,
}
assert canonical_non_inherit_row_id not in dry_run_row_updates
assert "cache_delete_planned" in dry_run_cache_events
assert "cache_deleted" not in dry_run_cache_events
assert len(dry_run_group_processed) == 1
assert dry_run_group_processed[0]["table_name"] == "load_balancing_model_configs"
assert dry_run_group_processed[0]["business_key"] == {
"tenant_id": tenant_id,
"provider_name": "openai",
"model_name": "gpt-4o-mini",
"model_type": "llm",
}
assert set(dry_run_group_processed[0]["group_row_ids"]) == {
older_inherit_row_id,
newer_inherit_row_id,
}
apply_output = io.StringIO()
migration_module.LegacyModelTypeMigrationService(
engine=engine,
apply=True,
output=apply_output,
tables=("load_balancing_model_configs",),
model_types=(migration_module.ModelType.LLM,),
tenant_ids=(tenant_id,),
).migrate()
apply_lines = _parse_json_lines(apply_output)
apply_cache_events = [line["event"] for line in apply_lines if str(line.get("event")).startswith("cache_")]
apply_group_processed = [
attrs
for line in apply_lines
if line.get("event") == "group_processed"
and isinstance((attrs := line.get("attrs")), dict)
and attrs.get("table_name") == "load_balancing_model_configs"
]
assert _lb_processing_signatures(apply_lines) == _lb_processing_signatures(dry_run_lines)
assert "cache_deleted" in apply_cache_events
assert deleted_cache_keys
assert len(apply_group_processed) == len(dry_run_group_processed)
assert [
(
attrs["table_name"],
_json_key(attrs["business_key"]),
tuple(attrs["group_row_ids"]),
)
for attrs in apply_group_processed
] == [
(
attrs["table_name"],
_json_key(attrs["business_key"]),
tuple(attrs["group_row_ids"]),
)
for attrs in dry_run_group_processed
]
lb_rows = fetch_table_rows(engine, "load_balancing_model_configs", tenant_id=tenant_id)
surviving_inherit_rows = [row for row in lb_rows if row["name"] == "__inherit__"]
surviving_non_inherit_rows = [row for row in lb_rows if row["name"] != "__inherit__"]
assert {str(row["id"]) for row in surviving_inherit_rows} == {newer_inherit_row_id}
assert surviving_inherit_rows[0]["model_type"] == "llm"
assert surviving_inherit_rows[0]["credential_id"] == fixture.primary.distinct_credential_id
assert {
str(row["id"])
for row in surviving_non_inherit_rows
if str(row["id"]) in {fixture.primary.load_balancing_config_id, canonical_non_inherit_row_id}
} == {fixture.primary.load_balancing_config_id, canonical_non_inherit_row_id}
assert all(
row["model_type"] == "llm"
for row in surviving_non_inherit_rows
if str(row["id"]) in {fixture.primary.load_balancing_config_id, canonical_non_inherit_row_id}
)
assert count_rows(engine, "load_balancing_model_configs", tenant_id=tenant_id) == len(before_dry_run) - 1
@@ -0,0 +1,547 @@
"""
TestContainers-based integration test configuration for Dify API.
This module provides containerized test infrastructure using TestContainers library
to spin up real database and service instances for integration testing. This approach
ensures tests run against actual service implementations rather than mocks, providing
more reliable and realistic test scenarios.
"""
import logging
import os
from collections.abc import Generator
from contextlib import ExitStack, closing
from dataclasses import dataclass
from pathlib import Path
import psycopg2
import pytest
from flask import Flask
from flask.testing import FlaskClient
from sqlalchemy import Engine, text
from sqlalchemy.orm import Session
from testcontainers.core.container import DockerContainer
from testcontainers.core.network import Network
from testcontainers.core.wait_strategies import HttpWaitStrategy, LogMessageWaitStrategy
from testcontainers.postgres import PostgresContainer
from testcontainers.redis import RedisContainer
from app_factory import create_app
from extensions.ext_database import db
# Configure logging for test containers
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
DEFAULT_SANDBOX_TEST_IMAGE = "langgenius/dify-sandbox:0.2.14"
SANDBOX_TEST_IMAGE_ENV = "DIFY_SANDBOX_TEST_IMAGE"
def _wait_for_log_message(message: str, timeout: int) -> LogMessageWaitStrategy:
return LogMessageWaitStrategy(message).with_startup_timeout(timeout)
@dataclass(frozen=True, slots=True)
class DifyTestContainerEnvironment:
postgres: PostgresContainer
redis: RedisContainer
dify_sandbox: DockerContainer
dify_plugin_daemon: DockerContainer | None
@pytest.fixture(scope="session")
def testcontainers_network() -> Generator[Network]:
"""Provide the shared network after all dependent containers have stopped."""
logger.info("Creating Docker network for test container communication")
with Network() as network:
logger.info("Docker network created successfully with name: %s", network.name)
yield network
@pytest.fixture(scope="session")
def postgres_container(testcontainers_network: Network) -> Generator[PostgresContainer]:
"""Provide PostgreSQL and clean it up if any later setup step fails."""
# This per-worker database is discarded after the session. Keep its data
# in bounded tmpfs to reduce I/O from full-schema TRUNCATE cleanup.
postgres = (
PostgresContainer(image="postgres:14-alpine")
.with_tmpfs_mount("/var/lib/postgresql/data", size="rw,size=2g")
.with_network(testcontainers_network)
)
postgres.waiting_for(_wait_for_log_message("is ready to accept connections", 30))
with ExitStack() as stack:
postgres = stack.enter_context(postgres)
environment = stack.enter_context(pytest.MonkeyPatch.context())
db_host = postgres.get_container_host_ip()
db_port = postgres.get_exposed_port(5432)
environment.setenv("DB_HOST", db_host)
environment.setenv("DB_PORT", str(db_port))
environment.setenv("DB_USERNAME", postgres.username)
environment.setenv("DB_PASSWORD", postgres.password)
environment.setenv("DB_DATABASE", postgres.dbname)
logger.info(
"PostgreSQL container started successfully - Host: %s, Port: %s User: %s, Database: %s",
db_host,
db_port,
postgres.username,
postgres.dbname,
)
connection = psycopg2.connect(
host=db_host,
port=db_port,
user=postgres.username,
password=postgres.password,
database=postgres.dbname,
)
connection.autocommit = True
with closing(connection):
with connection.cursor() as cursor:
cursor.execute('CREATE EXTENSION IF NOT EXISTS "uuid-ossp";')
# CREATE DATABASE cannot run inside a transaction block.
with closing(connection.cursor()) as cursor:
cursor.execute("CREATE DATABASE dify_plugin;")
yield postgres
@pytest.fixture(scope="session")
def redis_container(testcontainers_network: Network) -> Generator[RedisContainer]:
"""Provide Redis with its process environment scoped to the fixture."""
redis = RedisContainer(image="redis:6-alpine", port=6379).with_network(testcontainers_network)
redis.waiting_for(_wait_for_log_message("Ready to accept connections", 30))
with ExitStack() as stack:
redis = stack.enter_context(redis)
environment = stack.enter_context(pytest.MonkeyPatch.context())
redis_host = redis.get_container_host_ip()
redis_port = redis.get_exposed_port(6379)
environment.setenv("REDIS_HOST", redis_host)
environment.setenv("REDIS_PORT", str(redis_port))
environment.setenv("REDIS_USERNAME", "")
environment.setenv("REDIS_PASSWORD", "")
logger.info("Redis container started successfully - Host: %s, Port: %s", redis_host, redis_port)
yield redis
@pytest.fixture(scope="session")
def dify_sandbox_container(testcontainers_network: Network) -> Generator[DockerContainer]:
"""Provide Dify Sandbox with its endpoint environment."""
sandbox_image = os.getenv(SANDBOX_TEST_IMAGE_ENV, DEFAULT_SANDBOX_TEST_IMAGE)
sandbox = DockerContainer(image=sandbox_image).with_network(testcontainers_network)
sandbox.with_exposed_ports(8194)
sandbox.waiting_for(HttpWaitStrategy(8194, "/health").with_startup_timeout(180))
sandbox.env = {
"API_KEY": "test_api_key",
# Match Docker Compose: the image's 5-second limit can expire during
# Python/Jinja2 startup under parallel CI load.
"WORKER_TIMEOUT": "15",
}
with ExitStack() as stack:
sandbox = stack.enter_context(sandbox)
environment = stack.enter_context(pytest.MonkeyPatch.context())
sandbox_host = sandbox.get_container_host_ip()
sandbox_port = sandbox.get_exposed_port(8194)
environment.setenv("CODE_EXECUTION_ENDPOINT", f"http://{sandbox_host}:{sandbox_port}")
environment.setenv("CODE_EXECUTION_API_KEY", "test_api_key")
logger.info(
"Dify Sandbox container started successfully - Image: %s Host: %s, Port: %s",
sandbox_image,
sandbox_host,
sandbox_port,
)
yield sandbox
@pytest.fixture(scope="session")
def dify_plugin_daemon_container(
testcontainers_network: Network,
postgres_container: PostgresContainer,
redis_container: RedisContainer,
) -> Generator[DockerContainer | None]:
"""Provide the optional plugin daemon without swallowing consumer failures."""
postgres_container_name = postgres_container.get_wrapped_container().name
redis_container_name = redis_container.get_wrapped_container().name
assert postgres_container_name is not None
assert redis_container_name is not None
plugin_daemon = DockerContainer(image="langgenius/dify-plugin-daemon:0.6.14-local").with_network(
testcontainers_network
)
plugin_daemon.with_exposed_ports(5002)
plugin_daemon.waiting_for(_wait_for_log_message("start plugin manager daemon", 60))
plugin_daemon.env = {
"DB_HOST": postgres_container_name,
"DB_PORT": "5432",
"DB_USERNAME": postgres_container.username,
"DB_PASSWORD": postgres_container.password,
"DB_DATABASE": "dify_plugin",
"REDIS_HOST": redis_container_name,
"REDIS_PORT": "6379",
"REDIS_PASSWORD": "",
"SERVER_PORT": "5002",
"SERVER_KEY": "test_plugin_daemon_key",
"MAX_PLUGIN_PACKAGE_SIZE": "52428800",
"PPROF_ENABLED": "false",
"DIFY_INNER_API_URL": f"http://{postgres_container_name}:5001",
"DIFY_INNER_API_KEY": "test_inner_api_key",
"PLUGIN_REMOTE_INSTALLING_HOST": "0.0.0.0",
"PLUGIN_REMOTE_INSTALLING_PORT": "5003",
"PLUGIN_WORKING_PATH": "/app/storage/cwd",
"FORCE_VERIFYING_SIGNATURE": "false",
"PYTHON_ENV_INIT_TIMEOUT": "120",
"PLUGIN_MAX_EXECUTION_TIMEOUT": "600",
"PLUGIN_STDIO_BUFFER_SIZE": "1024",
"PLUGIN_STDIO_MAX_BUFFER_SIZE": "5242880",
"PLUGIN_STORAGE_TYPE": "local",
"PLUGIN_STORAGE_LOCAL_ROOT": "/app/storage",
"PLUGIN_INSTALLED_PATH": "plugin",
"PLUGIN_PACKAGE_CACHE_PATH": "plugin_packages",
"PLUGIN_MEDIA_CACHE_PATH": "assets",
}
stack = ExitStack()
try:
plugin_daemon = stack.enter_context(plugin_daemon)
plugin_daemon_host = plugin_daemon.get_container_host_ip()
plugin_daemon_port = plugin_daemon.get_exposed_port(5002)
except Exception:
logger.exception("Failed to start Dify Plugin Daemon container")
stack.close()
logger.info("Continuing without plugin daemon - some tests may be limited")
yield None
return
with stack:
environment = stack.enter_context(pytest.MonkeyPatch.context())
environment.setenv("PLUGIN_DAEMON_URL", f"http://{plugin_daemon_host}:{plugin_daemon_port}")
environment.setenv("PLUGIN_DAEMON_KEY", "test_plugin_daemon_key")
logger.info(
"Dify Plugin Daemon container started successfully - Host: %s, Port: %s",
plugin_daemon_host,
plugin_daemon_port,
)
yield plugin_daemon
@pytest.fixture(scope="session")
def storage_environment() -> Generator[None]:
"""Provide default storage settings without overwriting caller overrides."""
defaults = {
"STORAGE_TYPE": "opendal",
"OPENDAL_SCHEME": "fs",
"OPENDAL_FS_ROOT": "/tmp/dify-storage",
}
with pytest.MonkeyPatch.context() as environment:
for name, value in defaults.items():
if name not in os.environ:
environment.setenv(name, value)
yield
def _get_migration_dir() -> Path:
conftest_dir = Path(__file__).parent
return conftest_dir.parent.parent.parent / "migrations"
def _get_engine_url(engine: Engine) -> str:
try:
return engine.url.render_as_string(hide_password=False).replace("%", "%%")
except AttributeError:
return str(engine.url).replace("%", "%%")
_UUIDv7SQL = r"""
/* Main function to generate a uuidv7 value with millisecond precision */
CREATE FUNCTION uuidv7() RETURNS uuid
AS
$$
-- Replace the first 48 bits of a uuidv4 with the current
-- number of milliseconds since 1970-01-01 UTC
-- and set the "ver" field to 7 by setting additional bits
SELECT encode(
set_bit(
set_bit(
overlay(uuid_send(gen_random_uuid()) placing
substring(int8send((extract(epoch from clock_timestamp()) * 1000)::bigint) from
3)
from 1 for 6),
52, 1),
53, 1), 'hex')::uuid;
$$ LANGUAGE SQL VOLATILE PARALLEL SAFE;
COMMENT ON FUNCTION uuidv7 IS
'Generate a uuid-v7 value with a 48-bit timestamp (millisecond precision) and 74 bits of randomness';
CREATE FUNCTION uuidv7_boundary(timestamptz) RETURNS uuid
AS
$$
/* uuid fields: version=0b0111, variant=0b10 */
SELECT encode(
overlay('\x00000000000070008000000000000000'::bytea
placing substring(int8send(floor(extract(epoch from $1) * 1000)::bigint) from 3)
from 1 for 6),
'hex')::uuid;
$$ LANGUAGE SQL STABLE STRICT PARALLEL SAFE;
COMMENT ON FUNCTION uuidv7_boundary(timestamptz) IS
'Generate a non-random uuidv7 with the given timestamp (first 48 bits) and all random bits to 0.
As the smallest possible uuidv7 for that timestamp, it may be used as a boundary for partitions.';
"""
def _create_app_with_containers() -> Flask:
"""
Create Flask application configured to use test containers.
This function creates a Flask application instance that is configured
to connect to the test containers instead of the default development
or production databases.
Returns:
Flask: Configured Flask application for containerized testing
"""
logger.info("Creating Flask application with test container configuration...")
# Ensure Redis client reconnects to the containerized Redis (no auth)
from extensions import ext_redis
ext_redis.redis_client._client = None
# Re-create the config after environment variables have been set
from configs import dify_config
# Force re-creation of config with new environment variables
dify_config.__dict__.clear()
dify_config.__init__()
# Create and configure the Flask application
logger.info("Initializing Flask application...")
sio_app, app = create_app()
logger.info("Flask application created successfully")
# Initialize database schema
logger.info("Creating database schema...")
with app.app_context():
with db.engine.connect() as conn, conn.begin():
conn.execute(text(_UUIDv7SQL))
db.create_all()
# migration_dir = _get_migration_dir()
# alembic_config = Config()
# alembic_config.config_file_name = str(migration_dir / "alembic.ini")
# alembic_config.set_main_option("sqlalchemy.url", _get_engine_url(db.engine))
# alembic_config.set_main_option("script_location", str(migration_dir))
# alembic_command.upgrade(revision="head", config=alembic_config)
logger.info("Database schema created successfully")
logger.info("Flask application configured and ready for testing")
return app
@pytest.fixture(scope="session")
def set_up_containers_and_env(
postgres_container: PostgresContainer,
redis_container: RedisContainer,
dify_sandbox_container: DockerContainer,
dify_plugin_daemon_container: DockerContainer | None,
storage_environment: None,
) -> DifyTestContainerEnvironment:
"""
Compose the independently managed test container fixtures.
Pytest owns the dependency graph and finalizes every resource fixture in
reverse order, including when a later fixture fails during setup.
Returns:
DifyTestContainerEnvironment: Handles for the started containers
"""
assert storage_environment is None
logger.info("Test containers ready for session")
return DifyTestContainerEnvironment(
postgres=postgres_container,
redis=redis_container,
dify_sandbox=dify_sandbox_container,
dify_plugin_daemon=dify_plugin_daemon_container,
)
@pytest.fixture(scope="session")
def flask_app_with_containers(set_up_containers_and_env: DifyTestContainerEnvironment) -> Flask:
"""
Session-scoped Flask application fixture using test containers.
This fixture provides a Flask application instance that is configured
to use the test containers for all database and service connections.
Args:
set_up_containers_and_env: Composed test container environment
Returns:
Flask: Configured Flask application
"""
assert set_up_containers_and_env.postgres is not None
logger.info("=== Creating session-scoped Flask application ===")
app = _create_app_with_containers()
logger.info("Session-scoped Flask application created successfully")
return app
@pytest.fixture
def flask_req_ctx_with_containers(flask_app_with_containers: Flask) -> Generator[None]:
"""
Request context fixture for containerized Flask application.
This fixture provides a Flask request context for tests that need
to interact with the Flask application within a request scope.
Args:
flask_app_with_containers: Flask application fixture
Yields:
None: Request context is active during yield
"""
logger.debug("Creating Flask request context...")
with flask_app_with_containers.test_request_context():
logger.debug("Flask request context active")
yield
logger.debug("Flask request context closed")
@pytest.fixture
def test_client_with_containers(flask_app_with_containers: Flask) -> Generator[FlaskClient]:
"""
Test client fixture for containerized Flask application.
This fixture provides a Flask test client that can be used to make
HTTP requests to the containerized application for integration testing.
Args:
flask_app_with_containers: Flask application fixture
Yields:
FlaskClient: Test client instance
"""
logger.debug("Creating Flask test client...")
with flask_app_with_containers.test_client() as client:
logger.debug("Flask test client ready")
yield client
logger.debug("Flask test client closed")
@pytest.fixture
def db_session_with_containers(flask_app_with_containers: Flask) -> Generator[Session]:
"""
Database session fixture for containerized testing.
This fixture provides a SQLAlchemy database session that is connected
to the test PostgreSQL container, allowing tests to interact with
the database directly.
Args:
flask_app_with_containers: Flask application fixture
Yields:
Session: Database session instance
"""
logger.debug("Creating database session...")
with flask_app_with_containers.app_context():
session = db.session()
logger.debug("Database session created and ready")
try:
yield session
finally:
session.close()
logger.debug("Database session closed")
def _truncate_container_database(app: Flask) -> None:
"""
Reset application tables after a container integration test.
Tests in this package share one PostgreSQL container for performance, while
application code may commit through db.session, Session(db.engine), or
session_factory-created sessions. Truncating after each test gives the suite
a central DB isolation contract that does not depend on which session a test used.
This only covers SQLAlchemy application tables in db.metadata for now;
object storage and custom ad hoc metadata still need their own cleanup.
"""
with app.app_context():
db.session.remove()
tables = db.metadata.sorted_tables
if not tables:
return
preparer = db.engine.dialect.identifier_preparer
table_names = ", ".join(preparer.format_table(table) for table in tables)
with db.engine.begin() as conn:
conn.execute(text("SET LOCAL lock_timeout = '5s'"))
conn.execute(text(f"TRUNCATE TABLE {table_names} RESTART IDENTITY CASCADE"))
db.session.remove()
def _flush_container_redis(app: Flask) -> None:
"""
Reset Redis after a container integration test.
Tests in this package share one Redis container for performance. Application
code stores temporary tokens, rate-limit counters, locks, and cache entries
there, so flushing after each test gives Redis-backed state the same
isolation contract as the PostgreSQL container.
"""
with app.app_context():
app.extensions["redis"].flushdb()
@pytest.fixture(autouse=True)
def isolate_container_database(request: pytest.FixtureRequest) -> Generator[None]:
"""
Clean DB and Redis state after tests that use the containerized Flask app.
This fixture intentionally does not depend on flask_app_with_containers so
tests under this package do not start the full app/container stack just to
run state cleanup.
"""
yield
if "flask_app_with_containers" not in request.fixturenames:
return
app = request.getfixturevalue("flask_app_with_containers")
assert isinstance(app, Flask)
try:
_truncate_container_database(app)
finally:
_flush_container_redis(app)
@pytest.fixture(scope="package", autouse=True)
def mock_ssrf_proxy_requests() -> Generator[None]:
"""
Avoid outbound network during containerized tests by stubbing SSRF proxy helpers.
"""
from unittest.mock import patch
import httpx
def _fake_request(method: str, url: str, **_kwargs: object) -> httpx.Response:
request = httpx.Request(method=method, url=url)
return httpx.Response(200, request=request, content=b"")
with (
patch("core.helper.ssrf_proxy.make_request", side_effect=_fake_request),
patch("core.helper.ssrf_proxy.get", side_effect=lambda url, **kw: _fake_request("GET", url, **kw)),
patch("core.helper.ssrf_proxy.post", side_effect=lambda url, **kw: _fake_request("POST", url, **kw)),
patch("core.helper.ssrf_proxy.put", side_effect=lambda url, **kw: _fake_request("PUT", url, **kw)),
patch("core.helper.ssrf_proxy.patch", side_effect=lambda url, **kw: _fake_request("PATCH", url, **kw)),
patch("core.helper.ssrf_proxy.delete", side_effect=lambda url, **kw: _fake_request("DELETE", url, **kw)),
patch("core.helper.ssrf_proxy.head", side_effect=lambda url, **kw: _fake_request("HEAD", url, **kw)),
):
yield
Whitespace-only changes.
@@ -0,0 +1,336 @@
"""Real HTTP, PostgreSQL, Redis and Celery publication for annotation import jobs.
Workers are not executed: admission and publication are exercised without vector I/O.
"""
from __future__ import annotations
import time
from collections.abc import Iterator
from dataclasses import dataclass, replace
from io import BytesIO
from queue import Empty
from uuid import UUID, uuid4
import pytest
from celery import Celery, Task
from celery.signals import before_task_publish
from flask import Flask
from kombu.simple import SimpleQueue
from sqlalchemy import Connection, event, update
from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
from werkzeug.test import TestResponse
from constants import COOKIE_NAME_CSRF_TOKEN, HEADER_NAME_CSRF_TOKEN
from controllers.console.wraps import _is_setup_completed
from enums import DeploymentEdition
from enums.account import TenantAccountRole
from extensions.ext_application_services import ApplicationServices, _get_annotation_import_quota
from extensions.ext_database import db
from extensions.ext_redis import RedisClientWrapper
from libs.datetime_utils import naive_utc_now
from libs.passport import PassportService
from libs.token import generate_csrf_token
from models import Account, App, Tenant
from models.account import TenantAccountJoin
from models.model import DifySetup
from repositories.annotation_import_job_repository import (
RedisAnnotationImportJobRepository,
annotation_import_job_owner_key,
)
from repositories.annotation_repository import AnnotationRepository
from services.annotation_import_service import AnnotationImportLimits, AnnotationImportService
from tasks.annotation.batch_import_annotations_task import batch_import_annotations_task
from tests.helpers.unit.config_override import config_overrides_context
from tests.helpers.unit.model_factories import make_account, make_app
_CSV = b"question,answer\n Question , Answer \nNA,N/A\n"
_RECORDS = [{"question": "Question", "answer": "Answer"}, {"question": "NA", "answer": "N/A"}]
@dataclass(frozen=True)
class _Harness:
app: Flask
account: Account
target: App
other: App
factory: sessionmaker[Session]
redis: RedisClientWrapper
celery: Celery
task: Task[..., None]
queue: str
sessions: list[Session]
publications: list[bool]
def request(
self,
*,
app_id: str | None = None,
job_id: str | None = None,
content: bytes = _CSV,
filename: str = "annotations.CSV",
) -> TestResponse:
client = self.app.test_client()
token = generate_csrf_token(self.account.id)
headers = {
HEADER_NAME_CSRF_TOKEN: token,
"Authorization": f"Bearer {PassportService().issue({'user_id': self.account.id})}",
}
client.set_cookie(COOKIE_NAME_CSRF_TOKEN, token)
path = f"/console/api/apps/{app_id or self.target.id}/annotations/batch-import"
if job_id is None:
response = client.post(
path,
data={"file": (BytesIO(content), filename)},
content_type="multipart/form-data",
headers=headers,
)
else:
response = client.get(f"{path}-status/{job_id}", headers=headers)
assert response.headers["Content-Type"] == "application/json"
assert int(response.headers["Content-Length"]) == len(response.data)
assert all(not session.in_transaction() and not session.identity_map for session in self.sessions)
return response
@pytest.fixture
def harness(flask_app_with_containers: Flask) -> Iterator[_Harness]:
app = flask_app_with_containers
services = app.extensions["application_services"]
assert isinstance(services, ApplicationServices)
redis = app.extensions["redis"]
assert isinstance(redis, RedisClientWrapper)
with app.app_context():
factory = sessionmaker(bind=db.engine, expire_on_commit=False)
workspace = Tenant(name="Annotation import workspace")
account = make_account(account_id=str(uuid4()), email=f"{uuid4()}@example.com")
account.last_active_at = naive_utc_now()
target = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
other = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
with factory.begin() as session:
session.add_all(
[
workspace,
account,
target,
other,
TenantAccountJoin(
tenant_id=workspace.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True
),
DifySetup(version="test"),
]
)
queue = f"annotation-import-{uuid4()}"
celery = Celery(queue, broker="memory://", set_as_current=False)
celery.conf.update(task_default_queue=queue, task_ignore_result=True, task_publish_retry=False)
task = celery.task(name=batch_import_annotations_task.name, shared=False)(batch_import_annotations_task.run)
service = AnnotationImportService(
apps=AnnotationRepository(session_factory=factory),
jobs=RedisAnnotationImportJobRepository(redis=redis),
publish=task.delay,
quota=_get_annotation_import_quota,
limits=AnnotationImportLimits(
min_records=1, max_records=2, requests_per_minute=5, requests_per_hour=20, max_concurrent=3
),
)
app.extensions["application_services"] = replace(services, annotation_imports=service)
sessions: list[Session] = []
publications: list[bool] = []
def track(session: Session, _transaction: SessionTransaction, _connection: Connection) -> None:
sessions.append(session)
def observe_publish(**_kwargs: object) -> None:
publications.append(all(not session.in_transaction() and not session.identity_map for session in sessions))
event.listen(Session, "after_begin", track)
before_task_publish.connect(observe_publish, weak=True)
_is_setup_completed.reset_success()
try:
with config_overrides_context(
DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
SECRET_KEY="annotation-import-passport-test-key-32-bytes",
LOGIN_DISABLED=False,
INIT_PASSWORD="",
CONSOLE_API_URL="http://localhost",
CONSOLE_WEB_URL="http://localhost",
COOKIE_DOMAIN="",
RBAC_ENABLED=False,
):
with app.app_context():
assert _is_setup_completed()
db.session.remove()
yield _Harness(app, account, target, other, factory, redis, celery, task, queue, sessions, publications)
finally:
app.extensions["application_services"] = services
del observe_publish
event.remove(Session, "after_begin", track)
with celery.connection_for_read() as connection, SimpleQueue(connection, queue) as messages:
messages.clear()
celery.close()
_is_setup_completed.reset_success()
with app.app_context():
db.session.remove()
def _assert_no_task(harness: _Harness) -> None:
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
with pytest.raises(Empty):
messages.get(block=False)
@pytest.mark.parametrize("role", [TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR])
def test_import_publishes_scoped_records_after_sql_sessions_close(harness: _Harness, role: TenantAccountRole) -> None:
with harness.factory.begin() as session:
session.execute(
update(TenantAccountJoin).where(TenantAccountJoin.account_id == harness.account.id).values(role=role)
)
response = harness.request()
assert response.status_code == 200
body = response.get_json()
job_id = body["job_id"]
assert str(UUID(job_id)) == job_id
assert body == {"job_id": job_id, "job_status": "waiting", "record_count": 2, "error_msg": None}
assert harness.redis.get(f"app_annotation_batch_import_{job_id}") == b"waiting"
assert harness.redis.get(annotation_import_job_owner_key(job_id=job_id)) == (
f"{harness.target.tenant_id}:{harness.target.id}".encode()
)
assert harness.redis.zscore(f"annotation_import_active:{harness.target.tenant_id}", job_id) is not None
assert harness.publications == [True]
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
message = messages.get(block=False)
assert message.headers["task"] == batch_import_annotations_task.name
assert message.payload[0] == []
assert message.payload[1] == {
"job_id": job_id,
"content_list": _RECORDS,
"app_id": harness.target.id,
"tenant_id": harness.target.tenant_id,
"user_id": harness.account.id,
}
message.ack()
_assert_no_task(harness)
status = harness.request(job_id=job_id)
assert status.status_code == 200
assert status.get_json() == {"job_id": job_id, "job_status": "waiting", "error_msg": ""}
@pytest.mark.parametrize(
("content", "message"),
[
(b"question\nQuestion\n", "at least 2 columns"),
(b"question,answer\n", "at least 1 valid annotation record"),
(b"question,answer", "appears to be empty or invalid"),
(b"question,answer\nQ1,A1\nQ2,A2\nQ3,A3\n", "Maximum 2 records"),
(b"question,answer\n" + b"Q" * 2001 + b",Answer\n", "Maximum 2000 characters"),
(b"question,answer\nQuestion," + b"A" * 10001 + b"\n", "Maximum 10000 characters"),
(b"question,answer\n\xff,Answer\n", "can't decode byte"),
],
ids=["one-column", "header-only", "no-newline", "too-many-records", "long-question", "long-answer", "bad-encoding"],
)
def test_invalid_csv_preserves_error_message_response_without_creating_a_job(
harness: _Harness, content: bytes, message: str
) -> None:
response = harness.request(content=content)
assert response.status_code == 200
body = response.get_json()
assert body == {"job_id": None, "job_status": None, "record_count": None, "error_msg": body["error_msg"]}
assert message in body["error_msg"]
for window in ("1min", "1hour"):
assert harness.redis.zcard(f"annotation_import_rate_limit:{harness.target.tenant_id}:{window}") == 1
assert harness.redis.zcard(f"annotation_import_active:{harness.target.tenant_id}") == 0
assert list(harness.redis.scan_iter(match="app_annotation_batch_import_owner_*")) == []
assert harness.publications == []
_assert_no_task(harness)
@pytest.mark.parametrize(("window", "limit"), [("1min", 5), ("1hour", 20)])
def test_rate_limit_returns_429_without_registering_or_publishing_job(
harness: _Harness, window: str, limit: int
) -> None:
now_ms = int(time.time() * 1000)
harness.redis.zadd(
f"annotation_import_rate_limit:{harness.target.tenant_id}:{window}",
{f"prior-{index}": now_ms for index in range(limit)},
)
response = harness.request()
assert response.status_code == 429
assert response.get_json()["code"] == "too_many_requests"
assert harness.redis.zcard(f"annotation_import_active:{harness.target.tenant_id}") == 0
assert harness.publications == []
_assert_no_task(harness)
def test_concurrency_limit_returns_429_and_preserves_existing_jobs(harness: _Harness) -> None:
active_key = f"annotation_import_active:{harness.target.tenant_id}"
existing = {str(uuid4()) for _ in range(3)}
now_ms = int(time.time() * 1000)
harness.redis.zadd(active_key, dict.fromkeys(existing, now_ms))
response = harness.request()
assert response.status_code == 429
assert response.get_json()["code"] == "too_many_requests"
assert {job.decode() for job in harness.redis.zrange(active_key, 0, -1)} == existing
assert harness.publications == []
_assert_no_task(harness)
@pytest.mark.parametrize("mismatch", ["app", "tenant", "legacy", "missing", "status_missing"])
def test_job_status_requires_complete_owner_and_status(harness: _Harness, mismatch: str) -> None:
job_id = str(uuid4())
requested_app = harness.other.id if mismatch == "app" else harness.target.id
if mismatch not in {"missing", "status_missing"}:
harness.redis.set(f"app_annotation_batch_import_{job_id}", "completed")
if mismatch not in {"legacy", "missing"}:
tenant_id = str(uuid4()) if mismatch == "tenant" else harness.target.tenant_id
harness.redis.set(annotation_import_job_owner_key(job_id=job_id), f"{tenant_id}:{harness.target.id}")
response = harness.request(app_id=requested_app, job_id=job_id)
assert response.status_code == 404
assert response.get_json()["code"] == "not_found"
assert response.get_json()["message"] == "The job does not exist."
assert harness.publications == []
@pytest.mark.parametrize(
("status", "error", "expected"),
[
("waiting", None, ""),
("completed", "Old error", ""),
("error", "Worker failed", "Worker failed"),
("error", None, ""),
],
)
def test_status_preserves_worker_error_and_handles_expired_error_key(
harness: _Harness, status: str, error: str | None, expected: str
) -> None:
job_id = str(uuid4())
harness.redis.set(annotation_import_job_owner_key(job_id=job_id), f"{harness.target.tenant_id}:{harness.target.id}")
harness.redis.set(f"app_annotation_batch_import_{job_id}", status)
if error is not None:
harness.redis.set(f"app_annotation_batch_import_error_msg_{job_id}", error)
response = harness.request(job_id=job_id)
assert response.status_code == 200
assert response.get_json() == {"job_id": job_id, "job_status": status, "error_msg": expected}
def test_publish_failure_returns_500_and_removes_pending_job(harness: _Harness) -> None:
harness.task.serializer = "not-installed"
response = harness.request()
assert response.status_code == 500
assert response.get_json()["code"] == "internal_server_error"
assert "error_msg" not in response.get_json()
assert harness.redis.zcard(f"annotation_import_active:{harness.target.tenant_id}") == 0
assert list(harness.redis.scan_iter(match="app_annotation_batch_import_*")) == []
_assert_no_task(harness)
@@ -0,0 +1,452 @@
"""Real HTTP admission, PostgreSQL, Redis and Celery memory transport for reply jobs.
Exercises admission, publication and worker cleanup without embedding/vector I/O.
"""
from __future__ import annotations
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, replace
from queue import Empty
from threading import Barrier, Event
from typing import Literal
from uuid import UUID, uuid4
import pytest
from celery import Celery, Task
from celery.signals import before_task_publish
from flask import Flask
from kombu.exceptions import SerializerNotInstalled
from kombu.simple import SimpleQueue
from sqlalchemy import Connection, delete, event, select, update
from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
from werkzeug.test import TestResponse
from constants import COOKIE_NAME_CSRF_TOKEN, HEADER_NAME_CSRF_TOKEN
from controllers.console.wraps import _is_setup_completed
from enums import DeploymentEdition
from enums.account import TenantAccountRole
from extensions.ext_application_services import ApplicationServices
from extensions.ext_database import db
from extensions.ext_redis import RedisClientWrapper
from libs.datetime_utils import naive_utc_now
from libs.passport import PassportService
from libs.token import generate_csrf_token
from models import Account, App, Tenant
from models.account import TenantAccountJoin
from models.model import AppAnnotationSetting, DifySetup
from repositories.annotation_reply_job_repository import (
RedisAnnotationReplyJobRepository,
annotation_reply_job_owner_key,
)
from repositories.annotation_repository import AnnotationRepository
from services.annotation_reply_service import AnnotationReplyAction, AnnotationReplyService
from tasks.annotation.disable_annotation_reply_task import disable_annotation_reply_task
from tasks.annotation.enable_annotation_reply_task import enable_annotation_reply_task
from tests.helpers.unit.config_override import config_overrides_context
from tests.helpers.unit.model_factories import make_account, make_app
_PAYLOAD: dict[str, object] = {
"score_threshold": 0.75,
"embedding_provider_name": "openai",
"embedding_model_name": "text-embedding-3-small",
}
@dataclass(frozen=True)
class _Harness:
app: Flask
account: Account
target: App
other: App
factory: sessionmaker[Session]
redis: RedisClientWrapper
service: AnnotationReplyService
celery: Celery
tasks: tuple[Task[..., None], ...]
queue: str
sessions: list[Session]
publications: list[bool]
def request(
self,
action: AnnotationReplyAction,
*,
app_id: str | None = None,
job_id: str | None = None,
) -> TestResponse:
client = self.app.test_client()
token = generate_csrf_token(self.account.id)
headers = {
HEADER_NAME_CSRF_TOKEN: token,
"Authorization": f"Bearer {PassportService().issue({'user_id': self.account.id})}",
}
client.set_cookie(COOKIE_NAME_CSRF_TOKEN, token)
path = f"/console/api/apps/{app_id or self.target.id}/annotation-reply/{action}"
if job_id is None:
response = client.post(path, json=_PAYLOAD, headers=headers)
else:
response = client.get(f"{path}/status/{job_id}", headers=headers)
assert response.headers["Content-Type"] == "application/json"
assert all(not session.in_transaction() and not session.identity_map for session in self.sessions)
return response
@pytest.fixture
def harness(flask_app_with_containers: Flask) -> Iterator[_Harness]:
app = flask_app_with_containers
services = app.extensions["application_services"]
assert isinstance(services, ApplicationServices)
redis = app.extensions["redis"]
assert isinstance(redis, RedisClientWrapper)
with app.app_context():
factory = sessionmaker(bind=db.engine, expire_on_commit=False)
workspace = Tenant(name="Annotation reply workspace")
account = make_account(account_id=str(uuid4()), email=f"{uuid4()}@example.com")
account.last_active_at = naive_utc_now()
target = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
other = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
with factory.begin() as session:
session.add_all(
[
workspace,
account,
target,
other,
TenantAccountJoin(
tenant_id=workspace.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True
),
DifySetup(version="test"),
]
)
queue = f"annotation-reply-{uuid4()}"
celery = Celery(queue, broker="memory://", set_as_current=False)
celery.conf.update(task_default_queue=queue, task_ignore_result=True, task_publish_retry=False)
tasks = (
celery.task(name=enable_annotation_reply_task.name, shared=False)(enable_annotation_reply_task.run),
celery.task(name=disable_annotation_reply_task.name, shared=False)(disable_annotation_reply_task.run),
)
service = AnnotationReplyService(
apps=AnnotationRepository(session_factory=factory),
jobs=RedisAnnotationReplyJobRepository(redis=redis),
enable_task=tasks[0].delay,
disable_task=tasks[1].delay,
)
app.extensions["application_services"] = replace(services, annotation_reply=service)
sessions: list[Session] = []
publications: list[bool] = []
def track(session: Session, _transaction: SessionTransaction, _connection: Connection) -> None:
sessions.append(session)
def observe_publish(**_kwargs: object) -> None:
publications.append(all(not session.in_transaction() and not session.identity_map for session in sessions))
event.listen(Session, "after_begin", track)
before_task_publish.connect(observe_publish, weak=True)
_is_setup_completed.reset_success()
try:
with config_overrides_context(
DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
SECRET_KEY="annotation-reply-passport-test-key-32-bytes",
LOGIN_DISABLED=False,
INIT_PASSWORD="",
CONSOLE_API_URL="http://localhost",
CONSOLE_WEB_URL="http://localhost",
COOKIE_DOMAIN="",
RBAC_ENABLED=False,
):
with app.app_context():
assert _is_setup_completed()
db.session.remove()
yield _Harness(
app, account, target, other, factory, redis, service, celery, tasks, queue, sessions, publications
)
finally:
app.extensions["application_services"] = services
del observe_publish
event.remove(Session, "after_begin", track)
with celery.connection_for_read() as connection, SimpleQueue(connection, queue) as messages:
messages.clear()
celery.close()
_is_setup_completed.reset_success()
with app.app_context():
db.session.remove()
def _consume_task(harness: _Harness, action: AnnotationReplyAction, job_id: str) -> None:
expected: dict[str, object] = {
"job_id": job_id,
"app_id": harness.target.id,
"tenant_id": harness.target.tenant_id,
}
if action == "enable":
expected.update(_PAYLOAD, user_id=harness.account.id)
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
message = messages.get(block=False)
assert message.headers["task"] == harness.tasks[0 if action == "enable" else 1].name
assert message.payload[0] == []
assert message.payload[1] == expected
message.ack()
with pytest.raises(Empty):
messages.get(block=False)
@pytest.mark.parametrize("action", ["enable", "disable"])
@pytest.mark.parametrize("role", [TenantAccountRole.OWNER, TenantAccountRole.ADMIN, TenantAccountRole.EDITOR])
def test_reply_actions_publish_scoped_task_after_sql_sessions_close(
harness: _Harness, action: AnnotationReplyAction, role: TenantAccountRole
) -> None:
with harness.factory.begin() as session:
session.execute(
update(TenantAccountJoin).where(TenantAccountJoin.account_id == harness.account.id).values(role=role)
)
response = harness.request(action)
assert response.status_code == 200
body = response.get_json()
job_id = body["job_id"]
assert str(UUID(job_id)) == job_id
assert body == {"job_id": job_id, "job_status": "waiting"}
assert harness.redis.get(f"{action}_app_annotation_job_{job_id}") == b"waiting"
assert harness.redis.get(annotation_reply_job_owner_key(action=action, job_id=job_id)) == (
f"{harness.target.tenant_id}:{harness.target.id}".encode()
)
assert harness.publications == [True]
_consume_task(harness, action, job_id)
status = harness.request(action, job_id=job_id)
assert status.status_code == 200
assert status.get_json() == {"job_id": job_id, "job_status": "waiting", "error_msg": ""}
@pytest.mark.parametrize("action", ["enable", "disable"])
def test_cached_owned_job_returns_decoded_identifier_without_duplicate_publish(
harness: _Harness, action: AnnotationReplyAction
) -> None:
started = harness.request(action).get_json()
job_id = started["job_id"]
_consume_task(harness, action, job_id)
response = harness.request(action)
assert response.status_code == 200
assert response.get_json() == {"job_id": job_id, "job_status": "processing"}
assert harness.publications == [True]
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
with pytest.raises(Empty):
messages.get(block=False)
@pytest.mark.parametrize("action", ["enable", "disable"])
@pytest.mark.parametrize("mismatch", ["app", "tenant", "action", "legacy", "missing"])
def test_job_status_rejects_missing_or_unverifiable_ownership(
harness: _Harness, action: AnnotationReplyAction, mismatch: Literal["app", "tenant", "action", "legacy", "missing"]
) -> None:
job_id = str(uuid4())
requested_app = harness.target.id
stored_action: AnnotationReplyAction = (
("disable" if action == "enable" else "enable") if mismatch == "action" else action
)
if mismatch != "missing":
harness.redis.set(f"{stored_action}_app_annotation_job_{job_id}", "completed")
if mismatch not in {"legacy", "missing"}:
tenant_id = str(uuid4()) if mismatch == "tenant" else harness.target.tenant_id
harness.redis.set(
annotation_reply_job_owner_key(action=stored_action, job_id=job_id),
f"{tenant_id}:{harness.target.id}",
)
if mismatch == "app":
requested_app = harness.other.id
response = harness.request(action, app_id=requested_app, job_id=job_id)
assert response.status_code == 404
assert response.get_json()["code"] == "not_found"
assert response.get_json()["message"] == "The job does not exist."
assert harness.publications == []
@pytest.mark.parametrize("action", ["enable", "disable"])
@pytest.mark.parametrize(
("status", "error", "expected"),
[("error", "Provider unavailable", "Provider unavailable"), ("error", None, ""), ("completed", "Old error", "")],
)
def test_status_preserves_worker_error_and_handles_expired_error_key(
harness: _Harness, action: AnnotationReplyAction, status: str, error: str | None, expected: str
) -> None:
body = harness.request(action).get_json()
job_id = body["job_id"]
harness.redis.set(f"{action}_app_annotation_job_{job_id}", status)
if error is not None:
harness.redis.set(f"{action}_app_annotation_error_{job_id}", error)
response = harness.request(action, job_id=job_id)
assert response.status_code == 200
assert response.get_json() == {"job_id": job_id, "job_status": status, "error_msg": expected}
@pytest.mark.parametrize("action", ["enable", "disable"])
def test_concurrent_caller_can_poll_publication_failure_and_retry(
harness: _Harness, action: AnnotationReplyAction
) -> None:
task = harness.tasks[0 if action == "enable" else 1]
task.serializer = "not-installed"
vars(task).pop("_exec_options", None)
publishing = Event()
resume_publication = Event()
def pause_publication(**_kwargs: object) -> None:
publishing.set()
assert resume_publication.wait(timeout=10)
def start_job() -> None:
if action == "enable":
harness.service.enable(
tenant_id=harness.target.tenant_id,
app_id=harness.target.id,
account_id=harness.account.id,
score_threshold=0.75,
embedding_provider_name="openai",
embedding_model_name="text-embedding-3-small",
)
else:
harness.service.disable(tenant_id=harness.target.tenant_id, app_id=harness.target.id)
# Pause the real publisher after reservation, then let its serializer fail.
before_task_publish.connect(pause_publication, sender=task.name, weak=True)
try:
with ThreadPoolExecutor(max_workers=1) as executor:
first = executor.submit(start_job)
try:
assert publishing.wait(timeout=10)
response = harness.request(action)
assert response.status_code == 200
job_id = response.get_json()["job_id"]
assert response.get_json() == {"job_id": job_id, "job_status": "processing"}
pending = harness.request(action, job_id=job_id)
assert pending.status_code == 200
assert pending.get_json()["job_status"] == "waiting"
assert not first.done()
finally:
resume_publication.set()
with pytest.raises(SerializerNotInstalled) as error:
first.result(timeout=10)
finally:
del pause_publication
task.serializer = "json"
# Celery caches publication options on the first delay(), including a failed attempt.
vars(task).pop("_exec_options", None)
status = harness.request(action, job_id=job_id)
assert status.status_code == 200
assert status.get_json() == {"job_id": job_id, "job_status": "error", "error_msg": str(error.value)}
for key in (
annotation_reply_job_owner_key(action=action, job_id=job_id),
f"{action}_app_annotation_job_{job_id}",
f"{action}_app_annotation_error_{job_id}",
):
assert 0 < harness.redis.ttl(key) <= 600
assert harness.redis.get(f"{action}_app_annotation_{harness.target.id}") is None
assert harness.publications == [True]
with harness.celery.connection_for_read() as connection, SimpleQueue(connection, harness.queue) as messages:
with pytest.raises(Empty):
messages.get(block=False)
response = harness.request(action)
assert response.status_code == 200
assert response.get_json()["job_status"] == "waiting"
assert response.get_json()["job_id"] != job_id
_consume_task(harness, action, response.get_json()["job_id"])
@pytest.mark.parametrize("action", ["enable", "disable"])
def test_concurrent_requests_publish_only_one_reply_task(harness: _Harness, action: AnnotationReplyAction) -> None:
barrier = Barrier(8)
def request() -> str:
barrier.wait(timeout=10)
if action == "enable":
result = harness.service.enable(
tenant_id=harness.target.tenant_id,
app_id=harness.target.id,
account_id=harness.account.id,
score_threshold=0.75,
embedding_provider_name="openai",
embedding_model_name="text-embedding-3-small",
)
else:
result = harness.service.disable(tenant_id=harness.target.tenant_id, app_id=harness.target.id)
return result.job_id
with ThreadPoolExecutor(max_workers=8) as executor:
futures = [executor.submit(request) for _ in range(8)]
job_ids = [future.result() for future in futures]
assert len(set(job_ids)) == 1
_consume_task(harness, action, job_ids[0])
def _run_worker(harness: _Harness, action: AnnotationReplyAction, job_id: str) -> None:
with harness.app.app_context():
if action == "enable":
enable_annotation_reply_task.run(
job_id,
harness.target.id,
harness.account.id,
harness.target.tenant_id,
0.75,
"openai",
"text-embedding-3-small",
)
else:
disable_annotation_reply_task.run(job_id, harness.target.id, harness.target.tenant_id)
@pytest.mark.parametrize("action", ["enable", "disable"])
def test_finished_worker_releases_its_reservation(harness: _Harness, action: AnnotationReplyAction) -> None:
if action == "disable":
with harness.factory.begin() as session:
session.add(
AppAnnotationSetting(
app_id=harness.target.id,
score_threshold=0.75,
collection_binding_id=str(uuid4()),
created_user_id=harness.account.id,
updated_user_id=harness.account.id,
)
)
started = harness.request(action).get_json()
job_id = started["job_id"]
_consume_task(harness, action, job_id)
_run_worker(harness, action, job_id)
assert harness.redis.get(f"{action}_app_annotation_{harness.target.id}") is None
response = harness.request(action, job_id=job_id)
assert response.get_json() == {"job_id": job_id, "job_status": "completed", "error_msg": ""}
assert 0 < harness.redis.ttl(annotation_reply_job_owner_key(action=action, job_id=job_id)) <= 600
with harness.factory() as session:
setting = session.scalar(select(AppAnnotationSetting).where(AppAnnotationSetting.app_id == harness.target.id))
assert (setting is not None) == (action == "enable")
@pytest.mark.parametrize("action", ["enable", "disable"])
def test_early_returning_old_worker_does_not_release_new_reservation(
harness: _Harness, action: AnnotationReplyAction
) -> None:
started = harness.request(action).get_json()
old_job_id = started["job_id"]
_consume_task(harness, action, old_job_id)
harness.redis.expire(f"{action}_app_annotation_{harness.target.id}", 0)
current = harness.request(action).get_json()
_consume_task(harness, action, current["job_id"])
if action == "enable":
with harness.factory.begin() as session:
session.execute(delete(App).where(App.id == harness.target.id))
_run_worker(harness, action, old_job_id)
assert harness.redis.get(f"{action}_app_annotation_{harness.target.id}") == current["job_id"].encode()
@@ -0,0 +1,41 @@
"""Integration coverage for console app endpoints that require real persistence boundaries."""
import pytest
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from models.model import AppMode
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
create_console_app,
)
@pytest.mark.parametrize(
"path_template",
[
"/console/api/apps/{app_id}/trace-config?tracing_provider=langfuse",
"/console/api/apps/{app_id}/trace",
],
)
def test_trace_endpoints_hide_apps_from_other_tenants(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
path_template: str,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_app = create_console_app(
db_session_with_containers,
tenant_id=foreign_tenant.id,
account_id=foreign_account.id,
mode=AppMode.CHAT,
)
response = test_client_with_containers.get(
path_template.format(app_id=foreign_app.id),
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 404
@@ -0,0 +1,86 @@
"""App detail responses must not write masked configuration back to storage."""
import json
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from models.model import AppMode, AppModelConfig
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
create_console_app,
)
def test_put_app_detail_preserves_agent_tool_secret_after_commit(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.AGENT_CHAT)
agent_mode = {
"enabled": True,
"strategy": "react",
"tools": [
{
"provider_type": "api",
"provider_id": "00000000-0000-0000-0000-000000000001",
"tool_name": "private_tool",
"tool_parameters": {"api_key": "encrypted-secret"},
}
],
}
config = AppModelConfig(app_id=app.id, agent_mode=json.dumps(agent_mode))
db_session_with_containers.add(config)
db_session_with_containers.flush()
app.app_model_config_id = config.id
db_session_with_containers.commit()
headers = authenticate_console_client(test_client_with_containers, account)
response = test_client_with_containers.put(
f"/console/api/apps/{app.id}",
headers=headers,
json={"name": "Updated App"},
)
assert response.status_code == 200
assert response.json is not None
assert response.json["model_config"]["agent_mode"]["tools"][0]["tool_parameters"] != {"api_key": "encrypted-secret"}
with Session(db_session_with_containers.get_bind()) as reread_session:
persisted = reread_session.get(AppModelConfig, config.id)
assert persisted is not None
assert persisted.agent_mode is not None
assert json.loads(persisted.agent_mode) == agent_mode
def test_get_and_put_app_detail_preserve_historical_agent_mode_without_tools(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.AGENT_CHAT)
agent_mode = {"enabled": True, "max_iteration": 5, "strategy": "function_call"}
config = AppModelConfig(app_id=app.id, agent_mode=json.dumps(agent_mode))
db_session_with_containers.add(config)
db_session_with_containers.flush()
app.app_model_config_id = config.id
db_session_with_containers.commit()
headers = authenticate_console_client(test_client_with_containers, account)
get_response = test_client_with_containers.get(f"/console/api/apps/{app.id}", headers=headers)
assert get_response.status_code == 200
assert get_response.json is not None
assert get_response.json["model_config"]["agent_mode"] == agent_mode
put_response = test_client_with_containers.put(
f"/console/api/apps/{app.id}", headers=headers, json={"name": "Updated App"}
)
assert put_response.status_code == 200
assert put_response.json is not None
assert put_response.json["model_config"]["agent_mode"] == agent_mode
with Session(db_session_with_containers.get_bind()) as reread_session:
persisted = reread_session.get(AppModelConfig, config.id)
assert persisted is not None
assert persisted.agent_mode == json.dumps(agent_mode)
@@ -0,0 +1,165 @@
"""TestContainers integration tests for ChatConversationApi status_count behavior."""
import json
import uuid
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from constants import HEADER_NAME_CSRF_TOKEN
from extensions.ext_application_services import application_services
from graphon.enums import WorkflowExecutionStatus
from libs.datetime_utils import naive_utc_now
from libs.token import _real_cookie_name, generate_csrf_token
from models import Account, Tenant, TenantAccountJoin
from models.account import AccountStatus, TenantAccountRole, TenantStatus
from models.enums import ConversationFromSource, CreatorUserRole
from models.model import App, AppMode, Conversation, Message
from models.workflow import WorkflowRun
from models.workflow import WorkflowType as ModelWorkflowType
from tests.e2e_tests.containers.controllers.console.helpers import ensure_dify_setup
def _create_account_and_tenant(db_session: Session) -> tuple[Account, Tenant]:
account = Account(
email=f"test-{uuid.uuid4()}@example.com",
name="Test User",
interface_language="en-US",
status=AccountStatus.ACTIVE,
)
account.initialized_at = naive_utc_now()
db_session.add(account)
db_session.commit()
tenant = Tenant(name="Test Tenant", status=TenantStatus.NORMAL)
db_session.add(tenant)
db_session.commit()
join = TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role=TenantAccountRole.OWNER,
current=True,
)
db_session.add(join)
db_session.commit()
account.set_tenant_id_with_session(tenant.id, session=db_session)
account.timezone = "UTC"
db_session.commit()
ensure_dify_setup(db_session)
return account, tenant
def _create_app(db_session: Session, tenant_id: str, account_id: str) -> App:
app = App(
tenant_id=tenant_id,
name="Test Chat App",
mode=AppMode.CHAT,
enable_site=True,
enable_api=True,
created_by=account_id,
)
db_session.add(app)
db_session.commit()
return app
def _create_conversation(db_session: Session, app_id: str, account_id: str) -> Conversation:
conversation = Conversation(
app_id=app_id,
name="Test Conversation",
_inputs={},
status="normal",
mode=AppMode.CHAT,
from_source=ConversationFromSource.CONSOLE,
from_account_id=account_id,
)
db_session.add(conversation)
db_session.commit()
return conversation
def _create_workflow_run(db_session: Session, app_id: str, tenant_id: str, account_id: str) -> WorkflowRun:
workflow_run = WorkflowRun(
tenant_id=tenant_id,
app_id=app_id,
workflow_id=str(uuid.uuid4()),
type=ModelWorkflowType("chat"),
triggered_from="app-run",
version="1.0.0",
graph=json.dumps({"nodes": [], "edges": []}),
inputs=json.dumps({"query": "test"}),
status=WorkflowExecutionStatus.PAUSED,
outputs=json.dumps({}),
elapsed_time=0.0,
total_tokens=0,
total_steps=0,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=account_id,
)
workflow_run.created_at = naive_utc_now()
db_session.add(workflow_run)
db_session.commit()
return workflow_run
def _create_message(
db_session: Session, app_id: str, conversation_id: str, workflow_run_id: str, account_id: str
) -> Message:
message = Message(
app_id=app_id,
conversation_id=conversation_id,
query="Hello",
message={"type": "text", "content": "Hello"},
answer="Hi there",
message_tokens=1,
answer_tokens=1,
message_unit_price=0.001,
answer_unit_price=0.001,
message_price_unit=0.001,
answer_price_unit=0.001,
currency="USD",
status="normal",
from_source=ConversationFromSource.CONSOLE,
from_account_id=account_id,
workflow_run_id=workflow_run_id,
_inputs={"query": "Hello"},
)
db_session.add(message)
db_session.commit()
return message
def test_chat_conversation_status_count_includes_paused(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
):
account, tenant = _create_account_and_tenant(db_session_with_containers)
app = _create_app(db_session_with_containers, tenant.id, account.id)
conversation = _create_conversation(db_session_with_containers, app.id, account.id)
conversation_id = conversation.id
workflow_run = _create_workflow_run(db_session_with_containers, app.id, tenant.id, account.id)
_create_message(db_session_with_containers, app.id, conversation.id, workflow_run.id, account.id)
access_token = application_services().accounts.lifecycle.login(account.id, ip_address="127.0.0.1").access_token
csrf_token = generate_csrf_token(account.id)
cookie_name = _real_cookie_name("csrf_token")
test_client_with_containers.set_cookie(cookie_name, csrf_token, domain="localhost")
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/chat-conversations",
headers={
"Authorization": f"Bearer {access_token}",
HEADER_NAME_CSRF_TOKEN: csrf_token,
},
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert payload["total"] == 1
assert payload["data"][0]["id"] == conversation_id
assert payload["data"][0]["status_count"]["paused"] == 1
@@ -0,0 +1,105 @@
"""Execute Console read-marker writes against PostgreSQL without replacing the clock."""
from datetime import datetime
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session, sessionmaker
from libs.datetime_utils import naive_utc_now
from machinery.context import RequestContext
from models.enums import ConversationFromSource, ConversationStatus
from models.model import AppMode, Conversation
from repositories.conversation_repository import ConversationRepository
from services.errors.conversation import ConversationNotExistsError
from tests.e2e_tests.containers.controllers.console.helpers import (
create_console_account_and_tenant,
create_console_app,
)
def test_console_detail_then_mark_preserves_updated_at_and_the_first_reader(
db_session_with_containers: Session,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
original_updated_at = datetime(2020, 2, 8)
conversation = Conversation(
app_id=app.id,
name="read timestamp test",
_inputs={},
status=ConversationStatus.NORMAL,
mode=AppMode.CHAT,
from_source=ConversationFromSource.CONSOLE,
from_account_id=account.id,
)
conversation.updated_at = original_updated_at
db_session_with_containers.add(conversation)
db_session_with_containers.commit()
context = RequestContext(
request_id="postgres-read", trace_id=None, account_id=account.id, active_workspace_id=tenant.id
)
app_id, conversation_id = app.id, conversation.id
sessions = sessionmaker(bind=db_session_with_containers.get_bind(), expire_on_commit=False)
db_session_with_containers.rollback()
repository = ConversationRepository(session_factory=sessions)
loaded = repository.get_console_detail(context, app_id, conversation_id, kind="chat")
assert loaded.record.id == conversation_id
with sessions() as session:
stored = session.get_one(Conversation, conversation_id)
assert stored.read_at is None
assert stored.read_account_id is None
assert stored.updated_at == original_updated_at
before = naive_utc_now()
repository.mark_console_read(context, app_id, conversation_id, kind="chat")
after = naive_utc_now()
with sessions() as session:
stored = session.get_one(Conversation, conversation_id)
first_read_at = stored.read_at
assert first_read_at is not None
assert before <= first_read_at <= after
assert stored.read_account_id == context.account_id
assert stored.updated_at == original_updated_at
second_reader = context._replace(account_id=str(uuid4()))
repository.mark_console_read(second_reader, app_id, conversation_id, kind="chat")
with sessions() as session:
stored = session.get_one(Conversation, conversation_id)
assert stored.read_at == first_read_at
assert stored.read_account_id == context.account_id
assert stored.updated_at == original_updated_at
def test_console_missing_detail_or_mark_does_not_mark_another_conversation(
db_session_with_containers: Session,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = Conversation(
app_id=app.id,
name="Untouched conversation",
_inputs={},
mode=AppMode.CHAT,
from_source=ConversationFromSource.CONSOLE,
from_account_id=account.id,
)
db_session_with_containers.add(conversation)
db_session_with_containers.commit()
context = RequestContext(
request_id="postgres-read", trace_id=None, account_id=account.id, active_workspace_id=tenant.id
)
app_id, conversation_id = app.id, conversation.id
sessions = sessionmaker(bind=db_session_with_containers.get_bind(), expire_on_commit=False)
db_session_with_containers.rollback()
repository = ConversationRepository(session_factory=sessions)
missing_id = str(uuid4())
with pytest.raises(ConversationNotExistsError):
repository.get_console_detail(context, app_id, missing_id, kind="chat")
with pytest.raises(ConversationNotExistsError):
repository.mark_console_read(context, app_id, missing_id, kind="chat")
with sessions() as session:
stored = session.get_one(Conversation, conversation_id)
assert stored.read_at is None
assert stored.read_account_id is None
@@ -0,0 +1,309 @@
"""Authenticated controller integration tests for console message APIs."""
from datetime import timedelta
from decimal import Decimal
from uuid import uuid4
import pytest
from flask.testing import FlaskClient
from sqlalchemy import select
from sqlalchemy.orm import Session
from controllers.console.app.message import AppMessageFeedbackPayload, ChatMessagesQuery
from libs.datetime_utils import naive_utc_now
from models.enums import ConversationFromSource, ConversationStatus, FeedbackRating
from models.model import AppMode, AppModelConfig, Conversation, Message, MessageAnnotation, MessageFeedback
from models.provider import Provider
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
create_console_app,
)
def _create_conversation(db_session: Session, app_id: str, account_id: str, mode: AppMode) -> Conversation:
conversation = Conversation(
app_id=app_id,
app_model_config_id=None,
model_provider=None,
model_id="",
override_model_configs=None,
mode=mode,
name="Test Conversation",
_inputs={},
introduction="",
system_instruction="",
system_instruction_tokens=0,
status=ConversationStatus.NORMAL,
from_source=ConversationFromSource.CONSOLE,
from_account_id=account_id,
)
db_session.add(conversation)
db_session.commit()
return conversation
def _create_message(
db_session: Session,
app_id: str,
conversation_id: str,
account_id: str,
*,
created_at_offset_seconds: int = 0,
) -> Message:
created_at = naive_utc_now() + timedelta(seconds=created_at_offset_seconds)
message = Message(
app_id=app_id,
model_provider=None,
model_id="",
override_model_configs=None,
conversation_id=conversation_id,
_inputs={},
query="Hello",
message={"type": "text", "content": "Hello"},
message_tokens=1,
message_unit_price=Decimal("0.0001"),
message_price_unit=Decimal("0.001"),
answer="Hi there",
answer_tokens=1,
answer_unit_price=Decimal("0.0001"),
answer_price_unit=Decimal("0.001"),
parent_message_id=None,
provider_response_latency=0,
total_price=Decimal("0.0002"),
currency="USD",
from_source=ConversationFromSource.CONSOLE,
from_account_id=account_id,
app_mode=AppMode.CHAT,
)
message.created_at = created_at
message.updated_at = created_at
db_session.add(message)
db_session.commit()
return message
class TestMessageValidators:
def test_chat_messages_query_validators(self) -> None:
assert ChatMessagesQuery.empty_to_none("") is None
assert ChatMessagesQuery.empty_to_none("val") == "val"
assert ChatMessagesQuery.validate_uuid(None) is None
assert (
ChatMessagesQuery.validate_uuid("123e4567-e89b-12d3-a456-426614174000")
== "123e4567-e89b-12d3-a456-426614174000"
)
def test_message_feedback_validators(self) -> None:
assert (
AppMessageFeedbackPayload.validate_message_id("123e4567-e89b-12d3-a456-426614174000")
== "123e4567-e89b-12d3-a456-426614174000"
)
def test_chat_message_list_not_found(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/chat-messages",
query_string={"conversation_id": str(uuid4())},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 404
payload = response.get_json()
assert payload is not None
assert payload["code"] == "not_found"
def test_chat_message_list_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
_create_message(db_session_with_containers, app.id, conversation.id, account.id, created_at_offset_seconds=0)
second = _create_message(
db_session_with_containers,
app.id,
conversation.id,
account.id,
created_at_offset_seconds=1,
)
# Capture IDs before the HTTP request detaches ORM instances from the session
app_id = app.id
conversation_id = conversation.id
second_id = second.id
response = test_client_with_containers.get(
f"/console/api/apps/{app_id}/chat-messages",
query_string={"conversation_id": conversation_id, "limit": 1},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert payload["limit"] == 1
assert payload["has_more"] is True
assert len(payload["data"]) == 1
assert payload["data"][0]["id"] == second_id
def test_message_feedback_not_found(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
response = test_client_with_containers.post(
f"/console/api/apps/{app.id}/feedbacks",
json={"message_id": str(uuid4()), "rating": "like"},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 404
payload = response.get_json()
assert payload is not None
assert payload["code"] == "not_found"
def test_message_feedback_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
message = _create_message(db_session_with_containers, app.id, conversation.id, account.id)
response = test_client_with_containers.post(
f"/console/api/apps/{app.id}/feedbacks",
json={"message_id": message.id, "rating": "like"},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"result": "success"}
feedback = db_session_with_containers.scalar(
select(MessageFeedback).where(MessageFeedback.message_id == message.id)
)
assert feedback is not None
assert feedback.rating == FeedbackRating.LIKE
assert feedback.from_account_id == account.id
def test_message_annotation_count(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
message = _create_message(db_session_with_containers, app.id, conversation.id, account.id)
db_session_with_containers.add(
MessageAnnotation(
app_id=app.id,
conversation_id=conversation.id,
message_id=message.id,
question="Q",
content="A",
account_id=account.id,
)
)
db_session_with_containers.commit()
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/annotations/count",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"count": 1}
@pytest.mark.parametrize(
("scenario", "expected_status", "expected_code"),
[
("invalid-provider", 200, None),
("missing-message", 404, "not_found"),
("other-account", 404, "not_found"),
("deleted-conversation", 404, "not_found"),
("disabled", 403, "app_suggested_questions_after_answer_disabled"),
("broken-config", 500, "internal_server_error"),
],
)
def test_message_suggested_questions_with_persisted_configuration(
scenario: str,
expected_status: int,
expected_code: str | None,
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
session = db_session_with_containers
account, tenant = create_console_account_and_tenant(session)
app = create_console_app(session, tenant.id, account.id, AppMode.CHAT)
config = AppModelConfig(
app_id=app.id,
suggested_questions_after_answer=(
"not json"
if scenario == "broken-config"
else '{"enabled":false}'
if scenario == "disabled"
else '{"enabled":true}'
),
)
session.add(config)
session.flush()
app.app_model_config_id = config.id
conversation = _create_conversation(session, app.id, account.id, AppMode.CHAT)
conversation.app_model_config_id = config.id
message = _create_message(session, app.id, conversation.id, account.id)
if scenario == "other-account":
message.from_account_id = str(uuid4())
elif scenario == "deleted-conversation":
conversation.is_deleted = True
elif scenario == "invalid-provider":
# Real model resolution rejects the stored ID before contacting the daemon.
session.add(Provider(tenant_id=tenant.id, provider_name="invalid/provider", is_valid=True))
session.commit()
message_id = str(uuid4()) if scenario == "missing-message" else message.id
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/chat-messages/{message_id}/suggested-questions",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == expected_status
payload = response.get_json()
assert payload is not None
if expected_code is None:
assert payload == {"data": []}
else:
assert payload["code"] == expected_code
def test_message_api_get_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, app.mode)
message = _create_message(db_session_with_containers, app.id, conversation.id, account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/messages/{message.id}",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert payload["id"] == message.id
@@ -0,0 +1,349 @@
"""Controller integration tests for console statistic routes."""
from datetime import datetime, timedelta
from decimal import Decimal
from uuid import uuid4
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from libs.datetime_utils import naive_utc_now
from models.enums import ConversationFromSource, ConversationStatus, FeedbackFromSource, FeedbackRating, InvokeFrom
from models.model import AppMode, Conversation, Message, MessageFeedback
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
create_console_app,
)
def _create_conversation(
db_session: Session,
app_id: str,
account_id: str,
*,
mode: AppMode,
created_at_offset_days: int = 0,
) -> Conversation:
created_at = naive_utc_now() + timedelta(days=created_at_offset_days)
conversation = Conversation(
app_id=app_id,
app_model_config_id=None,
model_provider=None,
model_id="",
override_model_configs=None,
mode=mode,
name="Stats Conversation",
_inputs={},
introduction="",
system_instruction="",
system_instruction_tokens=0,
status=ConversationStatus.NORMAL,
from_source=ConversationFromSource.CONSOLE,
from_account_id=account_id,
)
conversation.created_at = created_at
conversation.updated_at = created_at
db_session.add(conversation)
db_session.commit()
return conversation
def _create_message(
db_session: Session,
app_id: str,
conversation_id: str,
*,
from_account_id: str | None,
from_end_user_id: str | None = None,
message_tokens: int = 1,
answer_tokens: int = 1,
total_price: Decimal = Decimal("0.01"),
provider_response_latency: float = 1.0,
created_at_offset_days: int = 0,
) -> Message:
created_at = naive_utc_now() + timedelta(days=created_at_offset_days)
message = Message(
app_id=app_id,
model_provider=None,
model_id="",
override_model_configs=None,
conversation_id=conversation_id,
_inputs={},
query="Hello",
message={"type": "text", "content": "Hello"},
message_tokens=message_tokens,
message_unit_price=Decimal("0.001"),
message_price_unit=Decimal("0.001"),
answer="Hi there",
answer_tokens=answer_tokens,
answer_unit_price=Decimal("0.001"),
answer_price_unit=Decimal("0.001"),
parent_message_id=None,
provider_response_latency=provider_response_latency,
total_price=total_price,
currency="USD",
invoke_from=InvokeFrom.EXPLORE,
from_source=ConversationFromSource.CONSOLE,
from_end_user_id=from_end_user_id,
from_account_id=from_account_id,
app_mode=AppMode.CHAT,
)
message.created_at = created_at
message.updated_at = created_at
db_session.add(message)
db_session.commit()
return message
def _create_like_feedback(
db_session: Session,
app_id: str,
conversation_id: str,
message_id: str,
account_id: str,
) -> None:
db_session.add(
MessageFeedback(
app_id=app_id,
conversation_id=conversation_id,
message_id=message_id,
rating=FeedbackRating.LIKE,
from_source=FeedbackFromSource.ADMIN,
from_account_id=account_id,
)
)
db_session.commit()
def test_daily_message_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/daily-messages",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json()["data"][0]["message_count"] == 1
def test_daily_conversation_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/daily-conversations",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json()["data"][0]["conversation_count"] == 1
def test_daily_terminals_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
_create_message(
db_session_with_containers,
app.id,
conversation.id,
from_account_id=None,
from_end_user_id=str(uuid4()),
)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/daily-end-users",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json()["data"][0]["terminal_count"] == 1
def test_daily_token_cost_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
_create_message(
db_session_with_containers,
app.id,
conversation.id,
from_account_id=account.id,
message_tokens=40,
answer_tokens=60,
total_price=Decimal("0.02"),
)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/token-costs",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload["data"][0]["token_count"] == 100
assert Decimal(payload["data"][0]["total_price"]) == Decimal("0.02")
def test_average_session_interaction_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/average-session-interactions",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json()["data"][0]["interactions"] == 2.0
def test_user_satisfaction_rate_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
first = _create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
for _ in range(9):
_create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
_create_like_feedback(db_session_with_containers, app.id, conversation.id, first.id, account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/user-satisfaction-rate",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json()["data"][0]["rate"] == 100.0
def test_average_response_time_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.COMPLETION)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
_create_message(
db_session_with_containers,
app.id,
conversation.id,
from_account_id=account.id,
provider_response_latency=1.234,
)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/average-response-time",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json()["data"][0]["latency"] == 1234.0
def test_tokens_per_second_statistic(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
_create_message(
db_session_with_containers,
app.id,
conversation.id,
from_account_id=account.id,
answer_tokens=31,
provider_response_latency=2.0,
)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/tokens-per-second",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json()["data"][0]["tps"] == 15.5
def test_invalid_time_range(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/daily-messages",
query_string={"start": "invalid", "end": "invalid"},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 400
assert response.get_json()["code"] == "invalid_param"
assert response.get_json()["message"].startswith("Invalid start time format:")
def test_daily_messages_use_account_timezone_and_exclude_other_apps(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
account.timezone = "Asia/Shanghai"
db_session_with_containers.commit()
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
conversation = _create_conversation(db_session_with_containers, app.id, account.id, mode=app.mode)
for created_at in (
datetime(2026, 9, 30, 15, 59), # Before the local start date.
datetime(2026, 9, 30, 16), # Local midnight: included.
datetime(2026, 10, 1, 15, 59),
datetime(2026, 10, 1, 16), # Local end date: excluded.
):
message = _create_message(db_session_with_containers, app.id, conversation.id, from_account_id=account.id)
message.created_at = created_at
db_session_with_containers.commit()
other_app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
other_conversation = _create_conversation(db_session_with_containers, other_app.id, account.id, mode=other_app.mode)
other_message = _create_message(
db_session_with_containers, other_app.id, other_conversation.id, from_account_id=account.id
)
other_message.created_at = datetime(2026, 10, 1, 8)
db_session_with_containers.commit()
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/statistics/daily-messages",
query_string={"start": "2026-10-01 00:00", "end": "2026-10-02 00:00"},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"data": [{"date": "2026-10-01", "message_count": 2}]}
@@ -0,0 +1,417 @@
"""Authenticated controller integration tests for workflow draft variable APIs."""
import uuid
from flask.testing import FlaskClient
from sqlalchemy import select
from sqlalchemy.orm import Session
from core.workflow.variable_prefixes import CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID
from factories.variable_factory import segment_to_variable
from graphon.variables.segments import StringSegment
from models import Workflow
from models.model import AppMode
from models.workflow import WorkflowDraftVariable
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
create_console_app,
)
def _create_draft_workflow(
db_session: Session,
app_id: str,
tenant_id: str,
account_id: str,
*,
environment_variables: list | None = None,
conversation_variables: list | None = None,
) -> Workflow:
workflow = Workflow.new(
tenant_id=tenant_id,
app_id=app_id,
type="workflow",
version=Workflow.VERSION_DRAFT,
graph='{"nodes": [], "edges": []}',
features="{}",
created_by=account_id,
environment_variables=environment_variables or [],
conversation_variables=conversation_variables or [],
rag_pipeline_variables=[],
)
db_session.add(workflow)
db_session.commit()
return workflow
def _create_node_variable(
db_session: Session,
app_id: str,
user_id: str,
*,
node_id: str = "node_1",
name: str = "test_var",
) -> WorkflowDraftVariable:
variable = WorkflowDraftVariable.new_node_variable(
app_id=app_id,
user_id=user_id,
node_id=node_id,
name=name,
value=StringSegment(value="test_value"),
node_execution_id=str(uuid.uuid4()),
visible=True,
editable=True,
)
db_session.add(variable)
db_session.commit()
return variable
def _create_system_variable(
db_session: Session, app_id: str, user_id: str, name: str = "query"
) -> WorkflowDraftVariable:
variable = WorkflowDraftVariable.new_sys_variable(
app_id=app_id,
user_id=user_id,
name=name,
value=StringSegment(value="system-value"),
node_execution_id=str(uuid.uuid4()),
editable=True,
)
db_session.add(variable)
db_session.commit()
return variable
def _build_environment_variable(name: str, value: str):
return segment_to_variable(
segment=StringSegment(value=value),
selector=[ENVIRONMENT_VARIABLE_NODE_ID, name],
name=name,
description=f"Environment variable {name}",
)
def _build_conversation_variable(name: str, value: str):
return segment_to_variable(
segment=StringSegment(value=value),
selector=[CONVERSATION_VARIABLE_NODE_ID, name],
name=name,
description=f"Conversation variable {name}",
)
def test_workflow_variable_collection_get_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/variables?page=1&limit=20",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"items": [], "total": 0}
def test_workflow_variable_collection_get_not_exist(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 404
payload = response.get_json()
assert payload is not None
assert payload["code"] == "draft_workflow_not_exist"
def test_workflow_variable_collection_delete(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_node_variable(db_session_with_containers, app.id, account.id)
_create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_2", name="other_var")
response = test_client_with_containers.delete(
f"/console/api/apps/{app.id}/workflows/draft/variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 204
remaining = db_session_with_containers.scalars(
select(WorkflowDraftVariable).where(
WorkflowDraftVariable.app_id == app.id,
WorkflowDraftVariable.user_id == account.id,
)
).all()
assert remaining == []
def test_node_variable_collection_get_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
node_variable = _create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_123")
node_variable_id = node_variable.id
_create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_456", name="other")
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/nodes/node_123/variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert [item["id"] for item in payload["items"]] == [node_variable_id]
def test_node_variable_collection_get_invalid_node_id(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/nodes/sys/variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 400
payload = response.get_json()
assert payload is not None
assert payload["code"] == "invalid_param"
def test_node_variable_collection_delete(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
target = _create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_123")
untouched = _create_node_variable(db_session_with_containers, app.id, account.id, node_id="node_456")
target_id = target.id
untouched_id = untouched.id
response = test_client_with_containers.delete(
f"/console/api/apps/{app.id}/workflows/draft/nodes/node_123/variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 204
assert (
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == target_id))
is None
)
assert (
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == untouched_id))
is not None
)
def test_variable_api_get_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert payload["id"] == variable.id
assert payload["name"] == "test_var"
def test_variable_api_get_not_found(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/variables/{uuid.uuid4()}",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 404
payload = response.get_json()
assert payload is not None
assert payload["code"] == "not_found"
def test_variable_api_patch_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
response = test_client_with_containers.patch(
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}",
headers=authenticate_console_client(test_client_with_containers, account),
json={"name": "renamed_var"},
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert payload["id"] == variable.id
assert payload["name"] == "renamed_var"
refreshed = db_session_with_containers.scalar(
select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == variable.id)
)
assert refreshed is not None
assert refreshed.name == "renamed_var"
def test_variable_api_delete_success(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
response = test_client_with_containers.delete(
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 204
assert (
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == variable.id))
is None
)
def test_variable_reset_api_put_success_returns_no_content_without_execution(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(db_session_with_containers, app.id, tenant.id, account.id)
variable = _create_node_variable(db_session_with_containers, app.id, account.id)
response = test_client_with_containers.put(
f"/console/api/apps/{app.id}/workflows/draft/variables/{variable.id}/reset",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 204
assert (
db_session_with_containers.scalar(select(WorkflowDraftVariable).where(WorkflowDraftVariable.id == variable.id))
is None
)
def test_conversation_variable_collection_get(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(
db_session_with_containers,
app.id,
tenant.id,
account.id,
conversation_variables=[_build_conversation_variable("session_name", "Alice")],
)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/conversation-variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert [item["name"] for item in payload["items"]] == ["session_name"]
created = db_session_with_containers.scalars(
select(WorkflowDraftVariable).where(
WorkflowDraftVariable.app_id == app.id,
WorkflowDraftVariable.user_id == account.id,
WorkflowDraftVariable.node_id == CONVERSATION_VARIABLE_NODE_ID,
)
).all()
assert len(created) == 1
def test_system_variable_collection_get(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
variable = _create_system_variable(db_session_with_containers, app.id, account.id)
variable_id = variable.id
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/system-variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert [item["id"] for item in payload["items"]] == [variable_id]
def test_environment_variable_collection_get(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
_create_draft_workflow(
db_session_with_containers,
app.id,
tenant.id,
account.id,
environment_variables=[_build_environment_variable("api_key", "secret-value")],
)
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflows/draft/environment-variables",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert payload["items"][0]["name"] == "api_key"
assert payload["items"][0]["value"] == "secret-value"
@@ -0,0 +1,112 @@
"""Exercise workflow statistics through console admission and PostgreSQL."""
from datetime import datetime
from uuid import uuid4
import pytest
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from graphon.enums import WorkflowExecutionStatus
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.model import AppMode
from models.workflow import WorkflowRun, WorkflowType
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
create_console_app,
)
def _create_workflow_run(
session: Session,
*,
tenant_id: str,
app_id: str,
created_by: str,
created_at: datetime,
total_tokens: int,
triggered_from: WorkflowRunTriggeredFrom = WorkflowRunTriggeredFrom.APP_RUN,
) -> None:
run = WorkflowRun(
tenant_id=tenant_id,
app_id=app_id,
workflow_id=str(uuid4()),
type=WorkflowType.WORKFLOW,
triggered_from=triggered_from,
version="1",
graph="{}",
inputs="{}",
status=WorkflowExecutionStatus.SUCCEEDED,
total_tokens=total_tokens,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=created_by,
)
run.created_at = created_at
session.add(run)
@pytest.mark.parametrize(
("endpoint", "metric", "expected"),
[
("daily-conversations", "runs", 3),
("daily-terminals", "terminal_count", 2),
("token-costs", "token_count", 60),
("average-app-interactions", "interactions", 1.5),
],
)
def test_workflow_statistics_scope_and_local_date_range(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
endpoint: str,
metric: str,
expected: int | float,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
account.timezone = "Asia/Shanghai"
db_session_with_containers.commit()
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
other_app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.WORKFLOW)
other_account, other_tenant = create_console_account_and_tenant(db_session_with_containers)
for created_by, created_at, tokens in (
(account.id, datetime(2026, 9, 30, 16), 10),
(account.id, datetime(2026, 10, 1, 8), 20),
(other_account.id, datetime(2026, 10, 1, 15, 59), 30),
):
_create_workflow_run(
db_session_with_containers,
tenant_id=tenant.id,
app_id=app.id,
created_by=created_by,
created_at=created_at,
total_tokens=tokens,
)
# Each decoy is independently excluded by the repository's scope or range.
for tenant_id, app_id, triggered_from, created_at in (
(tenant.id, other_app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 10, 1, 8)),
(other_tenant.id, app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 10, 1, 8)),
(tenant.id, app.id, WorkflowRunTriggeredFrom.DEBUGGING, datetime(2026, 10, 1, 8)),
(tenant.id, app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 9, 30, 15, 59)),
(tenant.id, app.id, WorkflowRunTriggeredFrom.APP_RUN, datetime(2026, 10, 1, 16)),
):
_create_workflow_run(
db_session_with_containers,
tenant_id=tenant_id,
app_id=app_id,
created_by=account.id,
created_at=created_at,
total_tokens=100,
triggered_from=triggered_from,
)
db_session_with_containers.commit()
response = test_client_with_containers.get(
f"/console/api/apps/{app.id}/workflow/statistics/{endpoint}",
query_string={"start": "2026-10-01 00:00", "end": "2026-10-02 00:00"},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"data": [{"date": "2026-10-01", metric: expected}]}
@@ -0,0 +1,190 @@
"""Controller integration tests for API key data source auth routes."""
import json
from unittest.mock import ANY, patch
from flask.testing import FlaskClient
from sqlalchemy import select
from sqlalchemy.orm import Session
from models.source import DataSourceApiKeyAuthBinding
from services.auth.errors import DataSourceApiKeyAuthCredentialValidationError
from services.data_source.entities.api_key_auth import (
DataSourceApiKeyAuthBindingCreate,
DataSourceApiKeyAuthCredentials,
)
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def test_get_api_key_auth_data_source(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
binding = DataSourceApiKeyAuthBinding(
tenant_id=tenant.id,
category="api_key",
provider="custom_provider",
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
disabled=False,
)
foreign_binding = DataSourceApiKeyAuthBinding(
tenant_id=foreign_tenant.id,
category="api_key",
provider="foreign_provider",
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
disabled=False,
)
db_session_with_containers.add_all([binding, foreign_binding])
db_session_with_containers.commit()
authenticate_console_client(test_client_with_containers, foreign_account)
response = test_client_with_containers.get(
"/console/api/api-key-auth/data-source",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert len(payload["sources"]) == 1
assert payload["sources"][0]["provider"] == "custom_provider"
def test_get_api_key_auth_data_source_empty(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
response = test_client_with_containers.get(
"/console/api/api-key-auth/data-source",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"sources": []}
def test_create_binding_successful(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
tenant_id = tenant.id
payload = {
"category": "api_key",
"provider": "custom",
"credentials": {"auth_type": "bearer", "config": {"api_key": "secret"}},
}
with patch("services.data_source.auth.api_key_service.DataSourceApiKeyAuthService.create_binding") as create_auth:
response = test_client_with_containers.post(
"/console/api/api-key-auth/data-source/binding",
json=payload,
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"result": "success"}
create_auth.assert_called_once_with(
ANY,
DataSourceApiKeyAuthBindingCreate(
category=payload["category"],
provider=payload["provider"],
credentials=DataSourceApiKeyAuthCredentials("bearer", "secret", {}),
),
)
assert create_auth.call_args.args[0].active_workspace_id == tenant_id
def test_create_binding_failure(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
with patch(
"services.data_source.auth.api_key_service.DataSourceApiKeyAuthService.create_binding",
side_effect=DataSourceApiKeyAuthCredentialValidationError("Credentials rejected"),
):
response = test_client_with_containers.post(
"/console/api/api-key-auth/data-source/binding",
json={
"category": "api_key",
"provider": "custom",
"credentials": {"auth_type": "bearer", "config": {"api_key": "secret"}},
},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 400
payload = response.get_json()
assert payload is not None
assert payload["code"] == "data_source_api_key_auth_credentials_rejected"
assert payload["message"] == "Credentials rejected"
def test_delete_binding_successful(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
binding = DataSourceApiKeyAuthBinding(
tenant_id=tenant.id,
category="api_key",
provider="custom_provider",
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
disabled=False,
)
db_session_with_containers.add(binding)
db_session_with_containers.commit()
response = test_client_with_containers.delete(
f"/console/api/api-key-auth/data-source/{binding.id}",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 204
assert (
db_session_with_containers.scalar(
select(DataSourceApiKeyAuthBinding).where(DataSourceApiKeyAuthBinding.id == binding.id)
)
is None
)
def test_delete_binding_scopes_to_authenticated_tenant(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_binding = DataSourceApiKeyAuthBinding(
tenant_id=foreign_tenant.id,
category="api_key",
provider="custom_provider",
credentials=json.dumps({"auth_type": "api_key", "config": {"api_key": "encrypted"}}),
disabled=False,
)
db_session_with_containers.add(foreign_binding)
db_session_with_containers.commit()
foreign_binding_id = foreign_binding.id
authenticate_console_client(test_client_with_containers, foreign_account)
response = test_client_with_containers.delete(
f"/console/api/api-key-auth/data-source/{foreign_binding_id}",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 204
assert (
db_session_with_containers.scalar(
select(DataSourceApiKeyAuthBinding).where(DataSourceApiKeyAuthBinding.id == foreign_binding_id)
)
is not None
)
@@ -0,0 +1,179 @@
"""Controller integration tests for console OAuth data source routes."""
from unittest.mock import MagicMock, create_autospec, patch
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from extensions.ext_application_services import ApplicationServices
from models.source import DataSourceOauthBinding
from services.data_source.entities.oauth import DataSourceOAuthCallback
from services.data_source.oauth_service import InvalidDataSourceOAuthProviderError
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def _services(service: MagicMock) -> MagicMock:
services = create_autospec(ApplicationServices, instance=True, spec_set=True)
services.data_sources.resolve_oauth.return_value = service
return services
def test_get_oauth_url_successful(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
tenant_id = tenant.id
current_tenant_id = account.current_tenant_id
service = MagicMock()
service.start_authorization.return_value = "http://oauth.provider/auth"
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=_services(service),
):
response = test_client_with_containers.get(
"/console/api/oauth/data-source/notion",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert tenant_id == current_tenant_id
assert response.status_code == 200
assert response.get_json() == {"data": "http://oauth.provider/auth"}
service.start_authorization.assert_called_once()
def test_get_oauth_url_invalid_provider(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
service = MagicMock()
services = _services(service)
services.data_sources.resolve_oauth.side_effect = InvalidDataSourceOAuthProviderError
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=services,
):
response = test_client_with_containers.get(
"/console/api/oauth/data-source/unknown_provider",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 400
assert response.get_json() == {"error": "Invalid provider"}
def test_oauth_callback_successful(test_client_with_containers: FlaskClient) -> None:
service = MagicMock()
service.complete_callback.return_value = DataSourceOAuthCallback(provider="notion", code="mock_code", error=None)
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=_services(service),
):
response = test_client_with_containers.get("/console/api/oauth/data-source/callback/notion?code=mock_code")
assert response.status_code == 302
assert "code=mock_code" in response.location
def test_oauth_callback_missing_code(test_client_with_containers: FlaskClient) -> None:
service = MagicMock()
service.complete_callback.return_value = DataSourceOAuthCallback(
provider="notion", code=None, error="Access denied"
)
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=_services(service),
):
response = test_client_with_containers.get("/console/api/oauth/data-source/callback/notion")
assert response.status_code == 302
assert "error=Access%20denied" in response.location
def test_oauth_callback_invalid_provider(test_client_with_containers: FlaskClient) -> None:
service = MagicMock()
services = _services(service)
services.data_sources.resolve_oauth.side_effect = InvalidDataSourceOAuthProviderError
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=services,
):
response = test_client_with_containers.get("/console/api/oauth/data-source/callback/invalid?code=mock_code")
assert response.status_code == 400
assert response.get_json() == {"error": "Invalid provider"}
def test_get_binding_successful(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
service = MagicMock()
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=_services(service),
):
response = test_client_with_containers.get(
"/console/api/oauth/data-source/binding/notion?code=auth_code_123",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"result": "success"}
service.bind.assert_called_once()
def test_get_binding_missing_code(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
service = MagicMock()
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=_services(service),
):
response = test_client_with_containers.get(
"/console/api/oauth/data-source/binding/notion?code=",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 400
assert response.get_json() == {"error": "Invalid code"}
def test_sync_successful(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
binding = DataSourceOauthBinding(
tenant_id=tenant.id,
access_token="test-access-token",
provider="notion",
source_info={"workspace_name": "Workspace", "workspace_icon": None, "workspace_id": tenant.id, "pages": []},
disabled=False,
)
db_session_with_containers.add(binding)
db_session_with_containers.commit()
service = MagicMock()
with patch(
"controllers.console.auth.data_source_oauth.application_services",
return_value=_services(service),
):
response = test_client_with_containers.get(
f"/console/api/oauth/data-source/notion/{binding.id}/sync",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"result": "success"}
service.sync.assert_called_once()
@@ -0,0 +1,338 @@
"""Controller integration tests for console OAuth server routes."""
from datetime import UTC, datetime
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from services.entities.oauth_server_entities import (
OAuthAuthorizationCode,
OAuthProviderAccount,
OAuthProviderAppPresentation,
OAuthTokenSet,
)
from services.oauth_server_service import (
OAUTH_ACCESS_TOKEN_EXPIRES_IN,
OAuthServerClientNotFoundError,
OAuthServerRequestError,
OAuthServerUnauthorizedError,
)
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
ensure_dify_setup,
)
def _application_services(service: MagicMock) -> SimpleNamespace:
return SimpleNamespace(oauth_server=service)
def test_oauth_provider_successful_post(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.get_provider.return_value = OAuthProviderAppPresentation(
app_icon="icon_url",
app_label={"en-US": "Test App"},
scope="read,write",
auto_authorize=True,
)
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider",
json={"client_id": "test_client_id", "redirect_uri": "http://localhost/callback"},
)
assert response.status_code == 200
assert response.get_json() == {
"app_icon": "icon_url",
"app_label": {"en-US": "Test App"},
"scope": "read,write",
"auto_authorize": True,
}
@pytest.mark.parametrize(
("error", "status", "message"),
[
(OAuthServerRequestError("redirect_uri is invalid"), 400, "redirect_uri is invalid"),
(OAuthServerClientNotFoundError("client_id is invalid"), 404, "client_id is invalid"),
],
)
def test_oauth_provider_maps_application_errors(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
error: Exception,
status: int,
message: str,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.get_provider.side_effect = error
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider",
json={"client_id": "test_client_id", "redirect_uri": "http://invalid/callback"},
)
assert response.status_code == status
assert message in response.get_json()["message"]
def test_oauth_authorize_successful(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
service = MagicMock()
service.authorize.return_value = OAuthAuthorizationCode(code="auth_code_123")
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider/authorize",
json={"client_id": "test_client_id"},
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
assert response.get_json() == {"code": "auth_code_123"}
context = service.authorize.call_args.args[0]
assert context.account_id == account.id
def test_oauth_token_authorization_code_grant(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.exchange_token.return_value = OAuthTokenSet(
access_token="access_123",
token_type="Bearer",
expires_in=OAUTH_ACCESS_TOKEN_EXPIRES_IN,
refresh_token="refresh_123",
)
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider/token",
json={
"client_id": "test_client_id",
"grant_type": "authorization_code",
"code": "auth_code",
"client_secret": "test_secret",
"redirect_uri": "http://localhost/callback",
},
)
assert response.status_code == 200
assert response.get_json() == {
"access_token": "access_123",
"token_type": "Bearer",
"expires_in": OAUTH_ACCESS_TOKEN_EXPIRES_IN,
"refresh_token": "refresh_123",
}
@pytest.mark.parametrize(
("payload", "message"),
[
(
{
"client_id": "test_client_id",
"grant_type": "authorization_code",
"client_secret": "test_secret",
"redirect_uri": "http://localhost/callback",
},
"code is required",
),
(
{
"client_id": "test_client_id",
"grant_type": "authorization_code",
"code": "auth_code",
"client_secret": "invalid_secret",
"redirect_uri": "http://localhost/callback",
},
"client_secret is invalid",
),
(
{
"client_id": "test_client_id",
"grant_type": "authorization_code",
"code": "auth_code",
"client_secret": "test_secret",
"redirect_uri": "http://invalid/callback",
},
"redirect_uri is invalid",
),
(
{"client_id": "test_client_id", "grant_type": "refresh_token"},
"refresh_token is required",
),
(
{"client_id": "test_client_id", "grant_type": "invalid_grant"},
"invalid grant_type",
),
],
)
def test_oauth_token_maps_invalid_grant_requests(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
payload: dict[str, str],
message: str,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.exchange_token.side_effect = OAuthServerRequestError(message)
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post("/console/api/oauth/provider/token", json=payload)
assert response.status_code == 400
assert response.get_json()["message"] == message
def test_oauth_token_refresh_token_grant(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.exchange_token.return_value = OAuthTokenSet(
access_token="new_access",
token_type="Bearer",
expires_in=OAUTH_ACCESS_TOKEN_EXPIRES_IN,
refresh_token="new_refresh",
)
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider/token",
json={"client_id": "test_client_id", "grant_type": "refresh_token", "refresh_token": "refresh_123"},
)
assert response.status_code == 200
assert response.get_json() == {
"access_token": "new_access",
"token_type": "Bearer",
"expires_in": OAUTH_ACCESS_TOKEN_EXPIRES_IN,
"refresh_token": "new_refresh",
}
def test_oauth_account_successful_retrieval(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.get_account.return_value = OAuthProviderAccount(
id="account-1",
name="Test User",
email="test@example.com",
avatar=None,
interface_language=None,
timezone=None,
created_at=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),
)
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider/account",
json={"client_id": "test_client_id"},
headers={"Authorization": "Bearer valid_access_token"},
)
assert response.status_code == 200
assert response.get_json() == {
"id": "account-1",
"name": "Test User",
"email": "test@example.com",
"avatar": None,
"interface_language": None,
"timezone": None,
"created_at": 1704164645,
}
@pytest.mark.parametrize(
("headers", "message"),
[
({}, "Authorization header is required"),
({"Authorization": "InvalidFormat"}, "Invalid Authorization header format"),
({"Authorization": "Basic token"}, "token_type is invalid"),
({"Authorization": "Bearer "}, "Invalid Authorization header format"),
],
)
def test_oauth_account_rejects_invalid_authorization_header(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
headers: dict[str, str],
message: str,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.get_account.side_effect = OAuthServerUnauthorizedError("access_token is required")
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider/account",
json={"client_id": "test_client_id"},
headers=headers,
)
assert response.status_code == 401
assert response.get_json() == {"error": message}
assert response.headers["WWW-Authenticate"] == "Bearer"
def test_oauth_account_validates_client_before_authorization_header(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
ensure_dify_setup(db_session_with_containers)
service = MagicMock()
service.get_account.side_effect = OAuthServerClientNotFoundError("client_id is invalid")
with patch(
"controllers.console.auth.oauth_server.application_services",
return_value=_application_services(service),
):
response = test_client_with_containers.post(
"/console/api/oauth/provider/account",
json={"client_id": "invalid"},
)
assert response.status_code == 404
assert "client_id is invalid" in response.get_json()["message"]
@@ -0,0 +1,42 @@
"""Integration coverage for customized pipeline template persistence."""
from collections.abc import Callable
from inspect import unwrap
from typing import cast
from uuid import uuid4
from flask import Flask
from sqlalchemy.orm import Session
from controllers.common.schema import JsonResponseWithStatus
from controllers.console.datasets.rag_pipeline.rag_pipeline import CustomizedPipelineTemplateApi
from models.dataset import PipelineCustomizedTemplate
def test_export_customized_pipeline_template_from_database(
flask_app_with_containers: Flask,
db_session_with_containers: Session,
) -> None:
api = CustomizedPipelineTemplateApi()
method = unwrap(cast(Callable[..., JsonResponseWithStatus], api.post))
template = PipelineCustomizedTemplate(
tenant_id=str(uuid4()),
name="Test Template",
description="Test",
chunk_structure="hierarchical",
icon={"icon": "📘"},
position=0,
yaml_content="yaml-data",
install_count=0,
language="en-US",
created_by=str(uuid4()),
)
db_session_with_containers.add(template)
db_session_with_containers.commit()
db_session_with_containers.expire_all()
with flask_app_with_containers.test_request_context("/"):
response, status = method(api, db_session_with_containers, template.tenant_id, template.id)
assert status == 200
assert response == {"data": "yaml-data"}
@@ -0,0 +1,57 @@
"""Integration coverage for persisted empty RAG pipeline dataset responses."""
from inspect import unwrap
from unittest.mock import MagicMock, patch
from uuid import uuid4
from flask import Flask
from sqlalchemy.orm import Session
from controllers.console.datasets.rag_pipeline.rag_pipeline_datasets import CreateEmptyRagPipelineDatasetApi
from models.dataset import Dataset, DatasetPermissionEnum, DatasetRuntimeMode, Pipeline
def test_create_empty_rag_pipeline_dataset_serializes_persisted_models(
flask_app_with_containers: Flask,
db_session_with_containers: Session,
) -> None:
tenant_id = str(uuid4())
account_id = str(uuid4())
pipeline = Pipeline(
tenant_id=tenant_id,
name="Pipeline dataset",
description="",
created_by=account_id,
)
db_session_with_containers.add(pipeline)
db_session_with_containers.flush()
dataset = Dataset(
tenant_id=tenant_id,
name="Pipeline dataset",
description="",
permission=DatasetPermissionEnum.ONLY_ME,
provider="vendor",
runtime_mode=DatasetRuntimeMode.RAG_PIPELINE,
icon_info={"icon": "📙", "icon_background": "#FFF4ED", "icon_type": "emoji"},
created_by=account_id,
pipeline_id=pipeline.id,
)
db_session_with_containers.add(dataset)
db_session_with_containers.commit()
db_session_with_containers.expire_all()
with (
flask_app_with_containers.test_request_context("/"),
patch(
"controllers.console.datasets.rag_pipeline.rag_pipeline_datasets.DatasetService.create_empty_rag_pipeline_dataset",
return_value=dataset,
),
):
response, status = unwrap(CreateEmptyRagPipelineDatasetApi().post)(
CreateEmptyRagPipelineDatasetApi(), tenant_id, MagicMock(is_dataset_editor=True)
)
assert status == 201
assert response["id"] == dataset.id
assert response["pipeline_id"] == pipeline.id
assert response["runtime_mode"] == "rag_pipeline"
@@ -0,0 +1,129 @@
"""Integration coverage for Notion page bindings backed by persisted documents."""
from inspect import unwrap
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from uuid import uuid4
from flask import Flask
from sqlalchemy.orm import Session, sessionmaker
from controllers.console.datasets.data_source import DataSourceNotionListApi, DataSourceNotionListQuery
from extensions.application_services.data_sources import build_data_source_credentials
from machinery.context import RequestContext
from models import Account, Tenant, TenantAccountJoin, TenantAccountRole
from models.dataset import Dataset, Document
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus
from repositories.knowledge.dataset_repository import SQLAlchemyDatasetRepository
from repositories.knowledge.document_repository import SQLAlchemyDocumentRepository
from repositories.workspace.workspace_repository import WorkspaceRepository
from services.data_source.notion_import_adapters import PluginNotionSourceGateway
from services.data_source.notion_import_application_service import NotionImportApplicationService
from services.knowledge.dataset_access import DatasetAccessService
def test_notion_page_is_marked_bound_from_persisted_document(
flask_app_with_containers: Flask,
db_session_with_containers: Session,
) -> None:
tenant = Tenant(name="Workspace")
tenant_id = tenant.id
dataset_id = str(uuid4())
account = Account(name="Test User", email="user@example.com")
account.id = str(uuid4())
dataset = Dataset(
id=dataset_id,
tenant_id=tenant_id,
name="Notion dataset",
created_by=account.id,
data_source_type=DataSourceType.NOTION_IMPORT,
)
db_session_with_containers.add_all(
[
account,
tenant,
TenantAccountJoin(tenant_id=tenant_id, account_id=account.id, role=TenantAccountRole.OWNER, current=True),
dataset,
]
)
document = Document(
tenant_id=tenant_id,
dataset_id=dataset_id,
position=1,
data_source_type=DataSourceType.NOTION_IMPORT,
data_source_info='{"notion_page_id": "page-1"}',
batch=f"batch-{uuid4()}",
name="Notion Page",
created_from=DocumentCreatedFrom.WEB,
created_by=account.id,
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
runtime = MagicMock(
get_online_document_pages=lambda **_kwargs: iter(
[
MagicMock(
result=[
MagicMock(
workspace_id="workspace-1",
workspace_name="Workspace",
workspace_icon=None,
pages=[
MagicMock(
page_id="page-1",
page_name="Page",
type="page",
parent_id="parent",
page_icon=None,
)
],
)
]
)
]
),
datasource_provider_type=lambda: None,
)
sessions = sessionmaker(bind=db_session_with_containers.get_bind(), expire_on_commit=False)
datasets = SQLAlchemyDatasetRepository(session_factory=sessions)
credentials = build_data_source_credentials(database_client=sessions).actor
notion_imports = NotionImportApplicationService(
dataset_access=DatasetAccessService(
datasets=datasets,
workspace_roles=WorkspaceRepository(session_factory=sessions),
legacy_permissions_enabled=True,
),
datasets=datasets,
documents=SQLAlchemyDocumentRepository(session_factory=sessions),
source=PluginNotionSourceGateway(credentials=credentials, runtime_loader=MagicMock(return_value=runtime)),
)
context = RequestContext(
request_id="notion-binding-test", trace_id=None, account_id=account.id, active_workspace_id=tenant_id
)
with (
patch.object(credentials, "resolve", return_value={"token": "token"}) as resolve_credentials,
flask_app_with_containers.test_request_context(f"/?credential_id=c1&dataset_id={dataset_id}"),
patch(
"controllers.console.datasets.data_source.application_services",
return_value=SimpleNamespace(data_sources=SimpleNamespace(notion_imports=notion_imports)),
),
):
response, status = unwrap(DataSourceNotionListApi.get)(
DataSourceNotionListApi(),
DataSourceNotionListQuery(credential_id="c1", dataset_id=dataset_id),
context,
)
assert status == 200
assert response["notion_info"][0]["pages"][0]["is_bound"] is True
resolve_credentials.assert_called_once_with(
workspace_id=tenant_id,
actor_id=account.id,
credential_id="c1",
provider="notion_datasource",
plugin_id="langgenius/notion_datasource",
)
@@ -0,0 +1,116 @@
"""Integration tests for console external knowledge API endpoints."""
from __future__ import annotations
import json
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from models.dataset import ExternalKnowledgeApis
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def _create_external_api(
db_session: Session,
*,
tenant_id: str,
account_id: str,
name: str,
) -> ExternalKnowledgeApis:
external_api = ExternalKnowledgeApis(
tenant_id=tenant_id,
created_by=account_id,
updated_by=account_id,
name=name,
description=f"{name} description",
settings=json.dumps(
{
"endpoint": "https://example.com",
"api_key": "test-api-key",
}
),
)
db_session.add(external_api)
db_session.commit()
return external_api
def test_external_api_template_list_filters_paginates_and_scopes_to_authenticated_tenant(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
"""Exercise the real list route, including query parsing, DB lookup, and tenant isolation."""
account, tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
account_id = account.id
tenant_id = tenant.id
foreign_account_id = foreign_account.id
foreign_tenant_id = foreign_tenant.id
headers = authenticate_console_client(test_client_with_containers, account)
_create_external_api(
db_session_with_containers,
tenant_id=tenant_id,
account_id=account_id,
name="Alpha Primary",
)
_create_external_api(
db_session_with_containers,
tenant_id=tenant_id,
account_id=account_id,
name="Alpha Secondary",
)
_create_external_api(
db_session_with_containers,
tenant_id=tenant_id,
account_id=account_id,
name="Beta Unmatched",
)
_create_external_api(
db_session_with_containers,
tenant_id=foreign_tenant_id,
account_id=foreign_account_id,
name="Alpha Foreign",
)
response = test_client_with_containers.get(
"/console/api/datasets/external-knowledge-api?page=1&limit=1&keyword=Alpha",
headers=headers,
)
assert response.status_code == 200
assert response.json is not None
assert response.json["page"] == 1
assert response.json["limit"] == 1
assert response.json["total"] == 2
assert response.json["has_more"] is True
assert len(response.json["data"]) == 1
first_page_item = response.json["data"][0]
assert first_page_item["tenant_id"] == tenant_id
assert first_page_item["name"] in {"Alpha Primary", "Alpha Secondary"}
assert first_page_item["settings"] == {
"endpoint": "https://example.com",
"api_key": "test-api-key",
}
assert first_page_item["dataset_bindings"] == []
second_response = test_client_with_containers.get(
"/console/api/datasets/external-knowledge-api?page=2&limit=1&keyword=Alpha",
headers=headers,
)
assert second_response.status_code == 200
assert second_response.json is not None
assert second_response.json["page"] == 2
assert second_response.json["limit"] == 1
assert second_response.json["total"] == 2
assert len(second_response.json["data"]) == 1
second_page_item = second_response.json["data"][0]
assert second_page_item["name"] in {"Alpha Primary", "Alpha Secondary"}
assert second_response.json["data"][0]["tenant_id"] == tenant_id
@@ -0,0 +1,97 @@
"""DB-backed integration tests for console dataset segment endpoints."""
from __future__ import annotations
from uuid import uuid4
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
from models.dataset import Dataset, Document, DocumentSegment, DocumentSegmentSummary
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus, SegmentStatus, SummaryStatus
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def test_list_segments_uses_real_db_query_and_console_response_shape(
test_client_with_containers: FlaskClient,
db_session_with_containers: Session,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
dataset = Dataset(
tenant_id=tenant.id,
name=f"Console Segment Dataset {uuid4()}",
description="Console segment integration dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
indexing_technique=IndexTechniqueType.ECONOMY,
created_by=account.id,
permission="only_me",
provider="vendor",
)
db_session_with_containers.add(dataset)
db_session_with_containers.commit()
document = Document(
tenant_id=tenant.id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=f"batch-{uuid4()}",
name="console-segment-doc.txt",
created_from=DocumentCreatedFrom.WEB,
created_by=account.id,
enabled=True,
archived=False,
indexing_status=IndexingStatus.COMPLETED,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
word_count=3,
tokens=4,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
segment = DocumentSegment(
tenant_id=tenant.id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Console integration segment",
word_count=3,
tokens=4,
keywords=["console", "integration"],
status=SegmentStatus.COMPLETED,
created_by=account.id,
)
db_session_with_containers.add(segment)
db_session_with_containers.commit()
segment_id = segment.id
db_session_with_containers.add(
DocumentSegmentSummary(
dataset_id=dataset.id,
document_id=document.id,
chunk_id=segment.id,
summary_content="Console DB summary",
status=SummaryStatus.COMPLETED,
)
)
db_session_with_containers.commit()
response = test_client_with_containers.get(
f"/console/api/datasets/{dataset.id}/documents/{document.id}/segments"
"?page=1&limit=10&status=completed&keyword=integration&enabled=all",
headers=authenticate_console_client(test_client_with_containers, account),
)
assert response.status_code == 200
body = response.get_json()
assert set(body) == {"data", "limit", "total", "total_pages", "page"}
assert body["limit"] == 10
assert body["total"] == 1
assert body["total_pages"] == 1
assert "has_more" not in body
assert body["data"][0]["id"] == segment_id
assert body["data"][0]["summary"] == "Console DB summary"
@@ -0,0 +1,94 @@
"""Shared helpers for console controller integration tests."""
import uuid
from collections.abc import Callable
from typing import cast
from flask.testing import FlaskClient
from sqlalchemy import select
from sqlalchemy.orm import Session
from configs import dify_config
from constants import HEADER_NAME_CSRF_TOKEN
from extensions.ext_application_services import application_services
from libs.datetime_utils import naive_utc_now
from libs.token import _real_cookie_name, generate_csrf_token
from models import Account, DifySetup, Tenant, TenantAccountJoin
from models.account import AccountStatus, TenantAccountRole, TenantStatus
from models.model import App, AppMode
def ensure_dify_setup(db_session: Session) -> None:
"""Create a setup marker once so setup-protected console routes can be exercised."""
if db_session.scalar(select(DifySetup).limit(1)) is not None:
return
db_session.add(DifySetup(version=dify_config.project.version))
db_session.commit()
def create_console_account_and_tenant(db_session: Session) -> tuple[Account, Tenant]:
"""Create an initialized owner account with a current tenant."""
account = Account(
email=f"test-{uuid.uuid4()}@example.com",
name="Test User",
interface_language="en-US",
status=AccountStatus.ACTIVE,
)
account.initialized_at = naive_utc_now()
db_session.add(account)
db_session.commit()
tenant = Tenant(name="Test Tenant", status=TenantStatus.NORMAL)
db_session.add(tenant)
db_session.commit()
db_session.add(
TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role=TenantAccountRole.OWNER,
current=True,
)
)
db_session.commit()
account.set_tenant_id_with_session(tenant.id, session=db_session)
account.timezone = "UTC"
db_session.commit()
ensure_dify_setup(db_session)
return account, tenant
def create_console_app(db_session: Session, tenant_id: str, account_id: str, mode: AppMode) -> App:
"""Create a minimal app row that can be loaded by get_app_model."""
app = App(
tenant_id=tenant_id,
name="Test App",
mode=mode,
enable_site=True,
enable_api=True,
created_by=account_id,
)
db_session.add(app)
db_session.commit()
return app
def authenticate_console_client(test_client: FlaskClient, account: Account) -> dict[str, str]:
"""Attach console auth cookies/headers for endpoints guarded by login_required."""
access_token = application_services().accounts.lifecycle.login(account.id, ip_address="127.0.0.1").access_token
csrf_token = generate_csrf_token(account.id)
test_client.set_cookie(_real_cookie_name("csrf_token"), csrf_token, domain="localhost")
return {
"Authorization": f"Bearer {access_token}",
HEADER_NAME_CSRF_TOKEN: csrf_token,
}
def unwrap[R](func: Callable[..., R]) -> Callable[..., R]:
"""Return the undecorated callable for controller methods wrapped by Flask/RESTX."""
while hasattr(func, "__wrapped__"):
func = cast(Callable[..., R], func.__wrapped__)
return func
@@ -0,0 +1,180 @@
"""Integration tests for console API-based extension endpoints using testcontainers."""
from __future__ import annotations
from collections.abc import Iterator
from unittest.mock import MagicMock, patch
import pytest
from flask.testing import FlaskClient
from sqlalchemy import select
from sqlalchemy.orm import Session
from constants import HIDDEN_VALUE
from core.helper.encrypter import encrypt_token
from libs.rsa import generate_key_pair
from models.api_based_extension import APIBasedExtension
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def _masked_api_key(api_key: str) -> str:
if len(api_key) <= 8:
return api_key[0] + "******" + api_key[-1]
return api_key[:3] + "******" + api_key[-3:]
@pytest.fixture
def api_extension_client(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> tuple[FlaskClient, dict[str, str], str]:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
tenant_id = tenant.id
tenant.encrypt_public_key = generate_key_pair(tenant.id)
db_session_with_containers.commit()
headers = authenticate_console_client(test_client_with_containers, account)
return test_client_with_containers, headers, tenant_id
@pytest.fixture(autouse=True)
def mock_api_based_extension_ping() -> Iterator[MagicMock]:
with patch("services.api_based_extension_adapters.APIBasedExtensionRequestor") as requestor:
requestor.return_value.request.return_value = {"result": "pong"}
yield requestor
def test_create_response_masks_plaintext_api_key(
api_extension_client: tuple[FlaskClient, dict[str, str], str],
db_session_with_containers: Session,
) -> None:
client, headers, tenant_id = api_extension_client
api_key = "plain-secret-12345"
response = client.post(
"/console/api/api-based-extension",
headers=headers,
json={
"name": "Docs API",
"api_endpoint": "https://docs.example.com/hook",
"api_key": api_key,
},
)
assert response.status_code == 201
assert response.json is not None
assert response.json["api_key"] == _masked_api_key(api_key)
extension = db_session_with_containers.scalar(
select(APIBasedExtension).where(APIBasedExtension.id == response.json["id"]).limit(1)
)
assert extension is not None
assert extension.tenant_id == tenant_id
def test_list_scopes_api_based_extensions_to_authenticated_tenant(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
account_headers = authenticate_console_client(test_client_with_containers, account)
tenant.encrypt_public_key = generate_key_pair(tenant.id)
_foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_tenant_id = foreign_tenant.id
foreign_tenant.encrypt_public_key = generate_key_pair(foreign_tenant.id)
db_session_with_containers.commit()
account_create_response = test_client_with_containers.post(
"/console/api/api-based-extension",
headers=account_headers,
json={
"name": "Tenant API",
"api_endpoint": "https://tenant.example.com/hook",
"api_key": "tenant-secret-12345",
},
)
assert account_create_response.status_code == 201
# Seed another workspace's extension directly; the list endpoint must not expose it.
db_session_with_containers.add(
APIBasedExtension(
tenant_id=foreign_tenant_id,
name="Foreign API",
api_endpoint="https://foreign.example.com/hook",
api_key=encrypt_token(foreign_tenant_id, "foreign-secret-12345"),
)
)
db_session_with_containers.commit()
response = test_client_with_containers.get(
"/console/api/api-based-extension",
headers=account_headers,
)
assert response.status_code == 200
assert response.json is not None
assert [item["name"] for item in response.json] == ["Tenant API"]
def test_update_response_masks_new_plaintext_api_key(
api_extension_client: tuple[FlaskClient, dict[str, str], str],
) -> None:
client, headers, _ = api_extension_client
new_api_key = "new-secret-67890"
create_response = client.post(
"/console/api/api-based-extension",
headers=headers,
json={
"name": "Docs API",
"api_endpoint": "https://docs.example.com/hook",
"api_key": "old-secret-12345",
},
)
assert create_response.json is not None
update_response = client.post(
f"/console/api/api-based-extension/{create_response.json['id']}",
headers=headers,
json={
"name": "Docs API Updated",
"api_endpoint": "https://docs.example.com/v2",
"api_key": new_api_key,
},
)
assert update_response.status_code == 200
assert update_response.json is not None
assert update_response.json["api_key"] == _masked_api_key(new_api_key)
def test_update_response_masks_existing_plaintext_api_key_when_hidden_value_is_submitted(
api_extension_client: tuple[FlaskClient, dict[str, str], str],
) -> None:
client, headers, _ = api_extension_client
existing_api_key = "old-secret-12345"
create_response = client.post(
"/console/api/api-based-extension",
headers=headers,
json={
"name": "Docs API",
"api_endpoint": "https://docs.example.com/hook",
"api_key": existing_api_key,
},
)
assert create_response.json is not None
update_response = client.post(
f"/console/api/api-based-extension/{create_response.json['id']}",
headers=headers,
json={
"name": "Docs API Updated",
"api_endpoint": "https://docs.example.com/v2",
"api_key": HIDDEN_VALUE,
},
)
assert update_response.status_code == 200
assert update_response.json is not None
assert update_response.json["api_key"] == _masked_api_key(existing_api_key)
@@ -0,0 +1,453 @@
"""Integration tests for console API key endpoints using testcontainers."""
from __future__ import annotations
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from threading import Event
from uuid import uuid4
import pytest
from flask.testing import FlaskClient
from sqlalchemy import delete, select
from sqlalchemy.orm import Session, sessionmaker
from models.account import TenantAccountJoin, TenantAccountRole
from models.dataset import Dataset
from models.enums import ApiTokenType, DataSourceType
from models.model import ApiToken, App, AppMode, DatasetApiTokenBinding
from repositories.knowledge.dataset_api_key_repository import DatasetApiKeyRepository
from services.auth.api_key_contracts import ApiKeyLimitExceededError
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
create_console_app,
)
@pytest.fixture
def setup_app(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> tuple[FlaskClient, dict[str, str], App]:
"""Create an authenticated client with an app for API key tests."""
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
headers = authenticate_console_client(test_client_with_containers, account)
return test_client_with_containers, headers, app
@pytest.fixture
def setup_dataset(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> tuple[FlaskClient, dict[str, str], Dataset]:
"""Create an authenticated client with a dataset for per-dataset API key tests."""
account, tenant = create_console_account_and_tenant(db_session_with_containers)
dataset = Dataset(
tenant_id=tenant.id,
name=f"API Key Dataset {uuid4()}",
description="Dataset for API key scoping tests",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
permission="only_me",
provider="vendor",
)
db_session_with_containers.add(dataset)
db_session_with_containers.commit()
headers = authenticate_console_client(test_client_with_containers, account)
return test_client_with_containers, headers, dataset
@pytest.fixture(autouse=True)
def cleanup_api_tokens(db_session_with_containers: Session) -> Iterator[None]:
"""Remove API tokens created during each test."""
yield
db_session_with_containers.execute(delete(ApiToken))
db_session_with_containers.commit()
class TestAppApiKeyListResource:
"""Tests for GET/POST /apps/<resource_id>/api-keys."""
def test_get_empty_keys(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
client, headers, app = setup_app
resp = client.get(f"/console/api/apps/{app.id}/api-keys", headers=headers)
assert resp.status_code == 200
assert resp.json is not None
assert resp.json["data"] == []
def test_create_api_key(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
client, headers, app = setup_app
resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
assert resp.status_code == 201
data = resp.json
assert data is not None
assert data["token"].startswith("app-")
assert data["id"] is not None
def test_create_api_key_persists_authenticated_tenant(
self,
setup_app: tuple[FlaskClient, dict[str, str], App],
db_session_with_containers: Session,
) -> None:
client, headers, app = setup_app
tenant_id = app.tenant_id
resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
assert resp.status_code == 201
assert resp.json is not None
api_token = db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == resp.json["id"]))
assert api_token is not None
assert api_token.tenant_id == tenant_id
assert api_token.app_id == app.id
assert api_token.type == ApiTokenType.APP
def test_get_keys_after_create(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
client, headers, app = setup_app
client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
resp = client.get(f"/console/api/apps/{app.id}/api-keys", headers=headers)
assert resp.status_code == 200
assert resp.json is not None
assert len(resp.json["data"]) == 2
def test_create_key_max_limit(
self,
setup_app: tuple[FlaskClient, dict[str, str], App],
db_session_with_containers: Session,
) -> None:
client, headers, app = setup_app
# Create 10 keys (the max)
for _ in range(10):
client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
# 11th should fail
resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
assert resp.status_code == 400
def test_get_keys_for_nonexistent_app(
self,
setup_app: tuple[FlaskClient, dict[str, str], App],
) -> None:
client, headers, _ = setup_app
resp = client.get(
"/console/api/apps/00000000-0000-0000-0000-000000000000/api-keys",
headers=headers,
)
assert resp.status_code == 404
def test_get_foreign_app_keys_not_found(
self,
setup_app: tuple[FlaskClient, dict[str, str], App],
db_session_with_containers: Session,
) -> None:
client, headers, _ = setup_app
foreign_account, foreign_tenant = create_console_account_and_tenant(db_session_with_containers)
foreign_app = create_console_app(
db_session_with_containers, foreign_tenant.id, foreign_account.id, AppMode.CHAT
)
resp = client.get(f"/console/api/apps/{foreign_app.id}/api-keys", headers=headers)
assert resp.status_code == 404
class TestAppApiKeyResource:
"""Tests for DELETE /apps/<resource_id>/api-keys/<api_key_id>."""
def test_delete_key_success(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
client, headers, app = setup_app
create_resp = client.post(f"/console/api/apps/{app.id}/api-keys", headers=headers)
assert create_resp.json is not None
key_id = create_resp.json["id"]
resp = client.delete(f"/console/api/apps/{app.id}/api-keys/{key_id}", headers=headers)
assert resp.status_code == 204
def test_delete_nonexistent_key(self, setup_app: tuple[FlaskClient, dict[str, str], App]) -> None:
client, headers, app = setup_app
resp = client.delete(
f"/console/api/apps/{app.id}/api-keys/00000000-0000-0000-0000-000000000000",
headers=headers,
)
assert resp.status_code == 404
def test_delete_key_nonexistent_app(
self,
setup_app: tuple[FlaskClient, dict[str, str], App],
) -> None:
client, headers, _ = setup_app
resp = client.delete(
"/console/api/apps/00000000-0000-0000-0000-000000000000/api-keys/00000000-0000-0000-0000-000000000000",
headers=headers,
)
assert resp.status_code == 404
def test_delete_forbidden_for_non_admin(
self,
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
"""A non-admin member cannot delete API keys through Console admission."""
account, tenant = create_console_account_and_tenant(db_session_with_containers)
app = create_console_app(db_session_with_containers, tenant.id, account.id, AppMode.CHAT)
membership = db_session_with_containers.scalar(
select(TenantAccountJoin).where(
TenantAccountJoin.tenant_id == tenant.id, TenantAccountJoin.account_id == account.id
)
)
assert membership is not None
membership.role = TenantAccountRole.NORMAL
db_session_with_containers.commit()
headers = authenticate_console_client(test_client_with_containers, account)
response = test_client_with_containers.delete(f"/console/api/apps/{app.id}/api-keys/{uuid4()}", headers=headers)
assert response.status_code == 403
class TestDatasetApiKeyListResource:
"""Tests for GET/POST /datasets/api-keys with per-knowledge-base scope.
Scope is expressed by DatasetApiTokenBinding rows: absent/empty ``dataset_ids``
on create makes an unrestricted key; a non-empty list binds the key to exactly
those knowledge bases.
"""
def _bound_dataset_ids(self, session: Session, api_token_id: str) -> set[str]:
return {
dataset_id
for dataset_id in session.scalars(
select(DatasetApiTokenBinding.dataset_id).where(DatasetApiTokenBinding.api_token_id == api_token_id)
).all()
if dataset_id is not None
}
def test_create_unbound_key(
self,
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
db_session_with_containers: Session,
) -> None:
client, headers, dataset = setup_dataset
tenant_id = dataset.tenant_id
resp = client.post("/console/api/datasets/api-keys", headers=headers)
assert resp.status_code == 200
assert resp.json is not None
assert resp.json["token"].startswith("dataset-")
assert resp.json["dataset_ids"] == []
api_token = db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == resp.json["id"]))
assert api_token is not None
assert api_token.tenant_id == tenant_id
assert api_token.type == ApiTokenType.DATASET
# No bindings -> unrestricted key.
assert self._bound_dataset_ids(db_session_with_containers, resp.json["id"]) == set()
def test_create_scoped_key_persists_bindings(
self,
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
db_session_with_containers: Session,
) -> None:
client, headers, dataset = setup_dataset
dataset_id = dataset.id
resp = client.post(
"/console/api/datasets/api-keys",
headers=headers,
json={"dataset_ids": [dataset_id]},
)
assert resp.status_code == 200
assert resp.json is not None
assert resp.json["dataset_ids"] == [dataset_id]
assert self._bound_dataset_ids(db_session_with_containers, resp.json["id"]) == {dataset_id}
def test_create_rejects_dataset_outside_tenant(
self,
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
) -> None:
"""A dataset id that does not belong to the tenant is rejected with 400."""
client, headers, _ = setup_dataset
resp = client.post(
"/console/api/datasets/api-keys",
headers=headers,
json={"dataset_ids": [str(uuid4())]},
)
assert resp.status_code == 400
def test_list_reports_scope_for_each_key(
self,
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
db_session_with_containers: Session,
) -> None:
client, headers, dataset = setup_dataset
dataset_id = dataset.id
scoped_resp = client.post(
"/console/api/datasets/api-keys",
headers=headers,
json={"dataset_ids": [dataset_id]},
)
assert scoped_resp.status_code == 200
unbound_resp = client.post("/console/api/datasets/api-keys", headers=headers)
assert unbound_resp.status_code == 200
resp = client.get("/console/api/datasets/api-keys", headers=headers)
assert resp.status_code == 200
assert resp.json is not None
assert scoped_resp.json is not None
assert unbound_resp.json is not None
scopes = {item["id"]: item["dataset_ids"] for item in resp.json["data"]}
assert scopes[scoped_resp.json["id"]] == [dataset_id]
assert scopes[unbound_resp.json["id"]] == []
# reveal-once: the list returns masked tokens, never the full secret.
listed = {item["id"]: item["token"] for item in resp.json["data"]}
assert listed[scoped_resp.json["id"]] != scoped_resp.json["token"]
def test_dataset_creation_routes_serialize_on_the_same_workspace(
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
db_session_with_containers: Session,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The workspace request must wait until the per-dataset count/insert commits."""
_, _, dataset = setup_dataset
workspace_id, dataset_id = dataset.tenant_id, dataset.id
db_session_with_containers.add_all(
ApiToken(tenant_id=workspace_id, type=ApiTokenType.DATASET, token=f"dataset-{uuid4()}") for _ in range(9)
)
db_session_with_containers.commit()
repository = DatasetApiKeyRepository(session_factory=sessionmaker(bind=db_session_with_containers.get_bind()))
first_counted, release_first, second_started = Event(), Event(), Event()
generate_key = ApiToken.generate_api_key
def pause_first_insert(prefix: str, n: int, *, session: Session) -> str:
if prefix == "ds-":
first_counted.set()
assert release_first.wait(timeout=10), "Timed out waiting to release the first insertion"
return generate_key(prefix, n, session=session)
def create_workspace_key() -> None:
second_started.set()
repository.create_workspace_key(workspace_id, (), max_keys=10, prefix="dataset-")
monkeypatch.setattr(ApiToken, "generate_api_key", pause_first_insert)
with ThreadPoolExecutor(max_workers=2) as pool:
first = pool.submit(repository.create_key, workspace_id, dataset_id, max_keys=10, prefix="ds-")
try:
assert first_counted.wait(timeout=5)
second = pool.submit(create_workspace_key)
assert second_started.wait(timeout=5)
with pytest.raises(TimeoutError):
second.result(timeout=0.5)
finally:
release_first.set()
first.result(timeout=5)
with pytest.raises(ApiKeyLimitExceededError):
second.result(timeout=5)
assert len(repository.list_workspace_keys(workspace_id)) == 10
class TestDatasetApiKeyResource:
"""Tests for DELETE /datasets/api-keys/<api_key_id>."""
def test_delete_key_removes_bindings(
self,
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
db_session_with_containers: Session,
) -> None:
client, headers, dataset = setup_dataset
dataset_id = dataset.id
create_resp = client.post(
"/console/api/datasets/api-keys",
headers=headers,
json={"dataset_ids": [dataset_id]},
)
assert create_resp.json is not None
api_key_id = create_resp.json["id"]
resp = client.delete(f"/console/api/datasets/api-keys/{api_key_id}", headers=headers)
assert resp.status_code == 204
assert db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == api_key_id)) is None
# The binding rows cascade away with the deleted key.
remaining = db_session_with_containers.scalars(
select(DatasetApiTokenBinding).where(DatasetApiTokenBinding.api_token_id == api_key_id)
).all()
assert remaining == []
class TestDatasetDeleteCascadesToScopedKeys:
"""Deleting a knowledge base must not let a scoped key degrade to access-all."""
def _create_other_dataset(self, session: Session, tenant_id: str, created_by: str) -> Dataset:
other = Dataset(
tenant_id=tenant_id,
name=f"Other Dataset {uuid4()}",
description="Second dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
permission="only_me",
provider="vendor",
)
session.add(other)
session.commit()
return other
def test_deleting_last_bound_dataset_deletes_the_scoped_key(
self,
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
db_session_with_containers: Session,
) -> None:
"""A key bound only to the deleted dataset is removed, never left unrestricted."""
client, headers, dataset = setup_dataset
dataset_id = dataset.id
create_resp = client.post(
"/console/api/datasets/api-keys",
headers=headers,
json={"dataset_ids": [dataset_id]},
)
assert create_resp.json is not None
api_key_id = create_resp.json["id"]
resp = client.delete(f"/console/api/datasets/{dataset_id}", headers=headers)
assert resp.status_code == 204
assert db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == api_key_id)) is None
def test_deleting_one_bound_dataset_keeps_a_multi_scoped_key(
self,
setup_dataset: tuple[FlaskClient, dict[str, str], Dataset],
db_session_with_containers: Session,
) -> None:
"""A key bound to several datasets survives and just drops the deleted one."""
client, headers, dataset = setup_dataset
dataset_id = dataset.id
other = self._create_other_dataset(db_session_with_containers, dataset.tenant_id, dataset.created_by)
other_id = other.id
create_resp = client.post(
"/console/api/datasets/api-keys",
headers=headers,
json={"dataset_ids": [dataset_id, other_id]},
)
assert create_resp.json is not None
api_key_id = create_resp.json["id"]
resp = client.delete(f"/console/api/datasets/{dataset_id}", headers=headers)
assert resp.status_code == 204
# The key survives, still scoped to the remaining dataset only.
assert db_session_with_containers.scalar(select(ApiToken).where(ApiToken.id == api_key_id)) is not None
remaining = set(
db_session_with_containers.scalars(
select(DatasetApiTokenBinding.dataset_id).where(DatasetApiTokenBinding.api_token_id == api_key_id)
).all()
)
assert remaining == {other_id}
@@ -0,0 +1,66 @@
"""Integration tests for console feature endpoints."""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from services.entities.feature_entities import FeatureModel, LimitationModel
from services.feature_service import FeatureService
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def test_feature_list_returns_current_tenant_configuration_without_vector_space(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
"""Exercise auth, tenant injection, and the feature response shaping contract."""
account, tenant = create_console_account_and_tenant(db_session_with_containers)
tenant_id = tenant.id
headers = authenticate_console_client(test_client_with_containers, account)
feature_model = FeatureModel(
members=LimitationModel(size=1, limit=2),
apps=LimitationModel(size=3, limit=4),
vector_space=LimitationModel(size=5, limit=6),
)
with patch.object(FeatureService, "get_features", return_value=feature_model) as get_features:
response = test_client_with_containers.get(
"/console/api/features",
headers=headers,
)
assert response.status_code == 200
assert response.json is not None
assert response.json["members"] == {"size": 1, "limit": 2}
assert response.json["apps"] == {"size": 3, "limit": 4}
assert "vector_space" not in response.json
get_features.assert_called_once_with(tenant_id, exclude_vector_space=True)
def test_feature_vector_space_returns_current_tenant_usage(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
"""Exercise tenant injection and vector-space response serialization through the registered route."""
account, tenant = create_console_account_and_tenant(db_session_with_containers)
tenant_id = tenant.id
headers = authenticate_console_client(test_client_with_containers, account)
vector_space = SimpleNamespace(model_dump=lambda: {"size": 0, "limit": 100})
with patch.object(FeatureService, "get_vector_space", return_value=vector_space) as get_vector_space:
response = test_client_with_containers.get(
"/console/api/features/vector-space",
headers=headers,
)
assert response.status_code == 200
assert response.json == {"size": 0, "limit": 100}
get_vector_space.assert_called_once_with(tenant_id)
@@ -0,0 +1,103 @@
"""Integration tests for console file endpoints."""
from __future__ import annotations
from io import BytesIO
from flask.testing import FlaskClient
from sqlalchemy import select
from sqlalchemy.orm import Session
from configs import dify_config
from models.model import UploadFile
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def test_file_upload_config_returns_console_limits(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
"""Exercise the authenticated upload-config route and response contract."""
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
response = test_client_with_containers.get(
"/console/api/files/upload",
headers=headers,
)
assert response.status_code == 200
assert response.json == {
"file_size_limit": dify_config.UPLOAD_FILE_SIZE_LIMIT,
"knowledge_file_size_limit": dify_config.UPLOAD_FILE_SIZE_LIMIT,
"batch_count_limit": dify_config.UPLOAD_FILE_BATCH_LIMIT,
"file_upload_limit": dify_config.BATCH_UPLOAD_LIMIT,
"image_file_size_limit": dify_config.UPLOAD_IMAGE_FILE_SIZE_LIMIT,
"video_file_size_limit": dify_config.UPLOAD_VIDEO_FILE_SIZE_LIMIT,
"audio_file_size_limit": dify_config.UPLOAD_AUDIO_FILE_SIZE_LIMIT,
"skill_file_size_limit": dify_config.UPLOAD_SKILL_FILE_SIZE_LIMIT,
"workflow_file_upload_limit": dify_config.WORKFLOW_FILE_UPLOAD_LIMIT,
"image_file_batch_limit": dify_config.IMAGE_FILE_BATCH_LIMIT,
"single_chunk_attachment_limit": dify_config.SINGLE_CHUNK_ATTACHMENT_LIMIT,
"attachment_image_file_size_limit": dify_config.ATTACHMENT_IMAGE_FILE_SIZE_LIMIT,
}
def test_file_upload_persists_file_for_authenticated_current_user(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
"""Exercise real upload behavior plus current-user and tenant propagation."""
account, tenant = create_console_account_and_tenant(db_session_with_containers)
account_id = account.id
tenant_id = tenant.id
headers = authenticate_console_client(test_client_with_containers, account)
content = b"hello from console integration"
response = test_client_with_containers.post(
"/console/api/files/upload",
headers=headers,
data={"file": (BytesIO(content), "tenant-owned.txt")},
content_type="multipart/form-data",
)
assert response.status_code == 201
assert response.json is not None
assert response.json["name"] == "tenant-owned.txt"
assert response.json["size"] == len(content)
assert response.json["extension"] == "txt"
assert response.json["mime_type"] == "text/plain"
assert response.json["created_by"] == account_id
upload_file = db_session_with_containers.scalar(
select(UploadFile).where(UploadFile.id == response.json["id"]).limit(1)
)
assert upload_file is not None
assert upload_file.tenant_id == tenant_id
assert upload_file.created_by == account_id
assert upload_file.name == "tenant-owned.txt"
assert upload_file.size == len(content)
assert f"/{tenant_id}/" in upload_file.key
def test_file_upload_rejects_missing_file_after_authentication(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
"""Exercise the route's validation path with a real authenticated account."""
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
response = test_client_with_containers.post(
"/console/api/files/upload",
headers=headers,
data={},
content_type="multipart/form-data",
)
assert response.status_code == 400
assert response.json is not None
assert response.json["code"] == "no_file_uploaded"
@@ -0,0 +1,222 @@
"""Console Channel API through the real service and PostgreSQL transaction boundary."""
from __future__ import annotations
import json
from base64 import b64decode
from typing import Never
import pytest
import sqlalchemy as sa
from cryptography.fernet import Fernet
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from configs import dify_config
from configs.deploy import IMEventTransportMode
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters.credentials import IMProviderCredentials
from core.human_input_v2.im_integration.adapters.entities import CredentialTestSuccess
from core.human_input_v2.shared import AccountId, TenantId
from models.human_input_v2 import HumanInputIMChannel
from repositories.human_input_v2.im_channel_repository import IMChannel, IMChannelId
from repositories.human_input_v2.sqlalchemy_im_channel_repository import WorkspaceIMChannelWriter
from services.human_input_v2 import im_channel_service as service_module
from services.human_input_v2.im_channel_service_composition import build_workspace_im_channel_service
from services.human_input_v2.im_tenant_credential_cipher import TenantBoundCredentialCipher
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
_BASE_PATH = "/console/api/workspaces/current/human-input/v2/channels/im"
_SLACK_CREDENTIALS = {
"provider": "slack",
"client_id": "slack-client-1",
"client_secret": "client-secret",
"signing_secret": "signing-secret",
"bot_token": "xoxb-bot-token",
"app_token": None,
}
class _StaticAdapter:
def __init__(self, credentials: IMProviderCredentials) -> None:
assert credentials.provider is IMProvider.SLACK
def test_credentials(self) -> CredentialTestSuccess:
return CredentialTestSuccess(IMProvider.SLACK, "slack-tenant-1")
def close(self) -> None:
return None
@pytest.fixture(autouse=True)
def static_provider_and_cipher(monkeypatch: pytest.MonkeyPatch) -> Fernet:
cipher = Fernet(Fernet.generate_key())
monkeypatch.setattr(service_module, "build_im_provider_adapter", _StaticAdapter)
monkeypatch.setattr(
TenantBoundCredentialCipher,
"encrypt",
lambda _self, plaintext: cipher.encrypt(plaintext.encode()),
)
monkeypatch.setattr(
TenantBoundCredentialCipher,
"decrypt",
lambda _self, ciphertext: cipher.decrypt(ciphertext).decode(),
)
monkeypatch.setattr(
dify_config,
"HUMAN_INPUT_IM_EVENT_TRANSPORT_MODE",
IMEventTransportMode.STREAM,
)
return cipher
def test_im_update_wires_opaque_version_through_real_service_and_postgresql_cas(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
created_response = test_client_with_containers.post(
_BASE_PATH,
json={"credentials": _SLACK_CREDENTIALS},
headers=headers,
)
assert created_response.status_code == 200
created_summary = created_response.get_json()["summary"]
channel_id = IMChannelId(created_summary["id"])
original_config_version = created_summary["config_version"]
original_record = db_session_with_containers.scalar(
sa.select(HumanInputIMChannel).where(HumanInputIMChannel.id == str(channel_id))
)
assert original_record is not None
original_webhook_id = original_record.webhook_id
rotated_response = test_client_with_containers.put(
f"{_BASE_PATH}/{channel_id}",
json={
"credentials": _SLACK_CREDENTIALS,
"expected_config_version": original_config_version,
},
headers=headers,
)
assert rotated_response.status_code == 200
rotated_summary = rotated_response.get_json()["summary"]
assert rotated_summary["id"] == str(channel_id)
assert rotated_summary["config_version"] != original_config_version
assert rotated_summary["webhook_url"] is None
stale_response = test_client_with_containers.put(
f"{_BASE_PATH}/{channel_id}",
json={
"credentials": _SLACK_CREDENTIALS,
"expected_config_version": original_config_version,
},
headers=headers,
)
assert stale_response.status_code == 409
assert stale_response.get_json()["code"] == "provider_configuration_updated"
service = build_workspace_im_channel_service(TenantId(tenant.id), AccountId(account.id))
persisted = service.get(channel_id)
assert persisted.id == channel_id
assert persisted.config_version == 2
db_session_with_containers.expire_all()
rotated_record = db_session_with_containers.scalar(
sa.select(HumanInputIMChannel).where(HumanInputIMChannel.id == str(channel_id))
)
assert rotated_record is not None
assert rotated_record.webhook_id == original_webhook_id
def test_service_transaction_rolls_back_a_flushed_create_on_unclassified_failure(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
monkeypatch: pytest.MonkeyPatch,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
original_create = WorkspaceIMChannelWriter.create
def create_then_fail(self: WorkspaceIMChannelWriter, channel: IMChannel) -> Never:
original_create(self, channel)
raise RuntimeError("sql-owner-key-secret-detail")
monkeypatch.setattr(WorkspaceIMChannelWriter, "create", create_then_fail)
response = test_client_with_containers.post(
_BASE_PATH,
json={"credentials": _SLACK_CREDENTIALS},
headers=headers,
)
assert response.status_code == 500
assert "sql-owner-key-secret-detail" not in response.get_data(as_text=True)
db_session_with_containers.expire_all()
persisted_count = db_session_with_containers.scalar(
sa.select(sa.func.count(HumanInputIMChannel.id)).where(
HumanInputIMChannel.owner_key == f"workspace:{tenant.id}"
)
)
assert persisted_count == 0
def test_partial_edit_and_saved_test_preserve_one_encrypted_document(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
static_provider_and_cipher: Fernet,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
client = test_client_with_containers
created = client.post(_BASE_PATH, json={"credentials": _SLACK_CREDENTIALS}, headers=headers)
assert created.status_code == 200
summary = created.get_json()["summary"]
channel_id = summary["id"]
record = db_session_with_containers.get(HumanInputIMChannel, channel_id)
assert record is not None
original_envelope = record.encrypted_credentials
edit = {
"provider": "slack",
"client_id": {"type": "unchanged"},
"client_secret": "rotated-client-secret",
"signing_secret": {"type": "unchanged"},
"bot_token": {"type": "unchanged"},
"app_token": None,
}
payload = {"credentials": edit, "expected_config_version": summary["config_version"]}
tested = client.post(f"{_BASE_PATH}/{channel_id}/test", json=payload, headers=headers)
assert tested.status_code == 200
db_session_with_containers.refresh(record)
assert record.config_version == 1
assert record.encrypted_credentials == original_envelope
updated = client.put(f"{_BASE_PATH}/{channel_id}", json=payload, headers=headers)
assert updated.status_code == 200
db_session_with_containers.refresh(record)
assert record.config_version == 2
assert record.encrypted_credentials != original_envelope
decrypted = json.loads(static_provider_and_cipher.decrypt(b64decode(record.encrypted_credentials.ciphertext)))
assert decrypted == {
"provider": "slack",
"client_id": "slack-client-1",
"client_secret": "rotated-client-secret",
"signing_secret": "signing-secret",
"bot_token": "xoxb-bot-token",
"app_token": None,
}
assert "rotated-client-secret" not in record.encrypted_credentials.ciphertext
detail = client.get(f"{_BASE_PATH}/{channel_id}", headers=headers)
assert detail.status_code == 200
assert detail.get_json()["credentials"] == {
"provider": "slack",
"client_id": "slack-client-1",
"client_secret": {"type": "redacted"},
"signing_secret": {"type": "redacted"},
"bot_token": {"type": "redacted"},
"app_token": None,
}
@@ -0,0 +1,146 @@
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
from contextlib import AbstractContextManager
from threading import Event, Lock
from unittest.mock import MagicMock, patch
import pytest
from faker import Faker
from flask import Flask
from flask.testing import FlaskClient
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from models.account import Account, Tenant, TenantAccountJoin
from models.model import DifySetup
from services.account.contracts import SetupInput
from services.account.service import AccountSetupProvisioner
from services.setup_adapters import RedisSetupLock
from tests.e2e_tests.containers.helpers import generate_valid_password
@pytest.fixture
def setup_dependencies() -> Iterator[MagicMock]:
with (
patch("services.account.login_adapters.SystemFeatureService") as feature_service,
patch("services.account.login_adapters.BillingService") as billing_service,
patch("services.account.adapters.CommunityTelemetryService.report_install") as report_install,
):
feature_service.is_registration_allowed.return_value = True
feature_service.get_license.return_value.seats.is_available.return_value = True
feature_service.get_license.return_value.workspaces.is_available.return_value = True
feature_service.is_workspace_creation_allowed.return_value = True
billing_service.is_email_in_freeze.return_value = False
yield report_install
def _setup_payload(*, email: str, password: str) -> dict[str, str]:
return {
"email": email,
"name": "Admin",
"password": password,
"language": "en-US",
}
def test_setup_endpoint_persists_bootstrap_state_and_rejects_repeat(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
monkeypatch: pytest.MonkeyPatch,
setup_dependencies: MagicMock,
) -> None:
monkeypatch.delenv("INIT_PASSWORD", raising=False)
password = generate_valid_password(Faker())
response = test_client_with_containers.post(
"/console/api/setup",
json=_setup_payload(email="admin@example.com", password=password),
headers={"CF-Connecting-IP": "198.51.100.7"},
environ_overrides={"REMOTE_ADDR": "203.0.113.7"},
)
assert response.status_code == 201
assert response.get_json() == {"result": "success"}
setup_dependencies.assert_called_once()
repeated_response = test_client_with_containers.post(
"/console/api/setup",
json=_setup_payload(email="other@example.com", password=password),
)
assert repeated_response.status_code == 403
db_session_with_containers.expire_all()
assert db_session_with_containers.scalar(select(func.count()).select_from(DifySetup)) == 1
assert db_session_with_containers.scalar(select(func.count()).select_from(Account)) == 1
assert db_session_with_containers.scalar(select(func.count()).select_from(Tenant)) == 1
assert db_session_with_containers.scalar(select(func.count()).select_from(TenantAccountJoin)) == 1
account = db_session_with_containers.scalar(select(Account))
assert account is not None
assert account.email == "admin@example.com"
assert account.last_login_ip == "203.0.113.7"
def test_concurrent_setup_requests_create_only_one_bootstrap_identity(
flask_app_with_containers: Flask,
db_session_with_containers: Session,
monkeypatch: pytest.MonkeyPatch,
setup_dependencies: MagicMock,
) -> None:
monkeypatch.delenv("INIT_PASSWORD", raising=False)
password = generate_valid_password(Faker())
provision_started = Event()
allow_provision_to_finish = Event()
second_lock_attempted = Event()
attempt_guard = Lock()
lock_attempts = 0
original_setup = AccountSetupProvisioner.provision
original_acquire = RedisSetupLock.acquire
def blocking_setup(self: AccountSetupProvisioner, setup: SetupInput) -> None:
if not provision_started.is_set():
provision_started.set()
assert allow_provision_to_finish.wait(timeout=10)
original_setup(self, setup)
def tracked_acquire(self: RedisSetupLock) -> AbstractContextManager[None]:
nonlocal lock_attempts
with attempt_guard:
lock_attempts += 1
if lock_attempts == 2:
second_lock_attempted.set()
return original_acquire(self)
def post_setup(email: str) -> int:
with flask_app_with_containers.test_client() as client:
response = client.post(
"/console/api/setup",
json=_setup_payload(email=email, password=password),
)
return response.status_code
with (
patch.object(AccountSetupProvisioner, "provision", blocking_setup),
patch.object(RedisSetupLock, "acquire", tracked_acquire),
ThreadPoolExecutor(max_workers=2) as executor,
):
first_request = executor.submit(post_setup, "admin-1@example.com")
try:
assert provision_started.wait(timeout=10)
second_request = executor.submit(post_setup, "admin-2@example.com")
assert second_lock_attempted.wait(timeout=10)
assert not second_request.done()
finally:
allow_provision_to_finish.set()
results = [first_request.result(timeout=30), second_request.result(timeout=30)]
assert sorted(results) == [201, 403]
setup_dependencies.assert_called_once()
db_session_with_containers.expire_all()
assert db_session_with_containers.scalar(select(func.count()).select_from(DifySetup)) == 1
assert db_session_with_containers.scalar(select(func.count()).select_from(Account)) == 1
assert db_session_with_containers.scalar(select(func.count()).select_from(Tenant)) == 1
assert db_session_with_containers.scalar(select(func.count()).select_from(TenantAccountJoin)) == 1
@@ -0,0 +1,37 @@
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def test_schema_definitions_endpoint_uses_admission_and_builtin_registry(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _ = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
response = test_client_with_containers.get(
"/console/api/spec/schema-definitions",
headers=headers,
)
assert response.status_code == 200
definitions = response.get_json()
assert isinstance(definitions, list)
assert definitions
assert all({"name", "label", "schema"} <= definition.keys() for definition in definitions)
def test_schema_definitions_endpoint_rejects_unauthenticated_request(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
create_console_account_and_tenant(db_session_with_containers)
response = test_client_with_containers.get("/console/api/spec/schema-definitions")
assert response.status_code == 401
@@ -0,0 +1,430 @@
"""PostgreSQL and Redis HTTP contracts for the IM Contact Sync control plane."""
from __future__ import annotations
from dataclasses import replace
from datetime import datetime
import pytest
from flask.testing import FlaskClient
from sqlalchemy import select
from sqlalchemy.orm import Session
from core.human_input_v2.entities import (
IMProvider,
IMSyncRemovalReason,
IMSyncResultType,
IMSyncRunStatus,
)
from core.human_input_v2.im_integration import (
IMChannelRevision,
IMSyncRun,
SyncContactSnapshot,
SyncIdentitySnapshot,
SyncResultFact,
)
from core.human_input_v2.shared import (
AccountId,
ContactId,
IMIdentityId,
IMSyncResultId,
IMSyncRunId,
NormalizedEmail,
TenantId,
)
from models.account import Account, Tenant
from models.human_input_v2 import (
ContactSubjectType,
HumanInputContactIdentity,
HumanInputIMBinding,
HumanInputIMSyncRun,
)
from repositories.human_input_v2.channel_credentials import ChannelEncryptedCredentials
from repositories.human_input_v2.contact import Contact, ContactType
from repositories.human_input_v2.im_channel_repository import (
IMChannel,
IMChannelId,
IMChannelStatus,
WebhookId,
)
from repositories.human_input_v2.im_identity_repository import IMIdentity, IMIdentityObservation, OpaqueProviderPayload
from repositories.human_input_v2.im_integration.mappers import (
sync_result_to_record,
sync_run_to_record,
)
from repositories.human_input_v2.sqlalchemy_im_channel_repository import WorkspaceIMChannelWriter
from repositories.human_input_v2.sqlalchemy_im_identity_repository import SQLAlchemyIMIdentityRepository
from tasks.im_contact_sync_tasks import reconcile_im_contacts_task
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
_NOW = datetime(2026, 8, 11, 8)
_LATER = datetime(2026, 8, 11, 9)
_CONTACT_ID = ContactId("00000000-0000-0000-0000-000000000101")
_CHANNEL_ID = IMChannelId("00000000-0000-0000-0000-000000000201")
_PRIMARY_IDENTITY_ID = IMIdentityId("00000000-0000-0000-0000-000000000301")
_SECONDARY_IDENTITY_ID = IMIdentityId("00000000-0000-0000-0000-000000000302")
_SYNC_RUNS_PATH = "/console/api/workspaces/current/human-input/v2/im-sync-runs"
def _seed_control_plane(
session: Session,
) -> tuple[Account, Tenant, Contact, IMChannel, IMIdentity, IMIdentity]:
account, tenant = create_console_account_and_tenant(session)
tenant_id = TenantId(tenant.id)
account.name = "Reviewer"
account.email = "reviewer@example.com"
contact_identity = HumanInputContactIdentity(
subject_type=ContactSubjectType.ACCOUNT,
account_id=account.id,
)
contact_identity.id = str(_CONTACT_ID)
contact_identity.created_at = _NOW
contact_identity.updated_at = _NOW
contact = Contact(
id=_CONTACT_ID,
type=ContactType.WORKSPACE,
name="Reviewer",
email="reviewer@example.com",
avatar_file_id=None,
created_at=_NOW,
)
channel = IMChannel(
id=_CHANNEL_ID,
created_at=_NOW,
updated_at=_NOW,
provider=IMProvider.FEISHU,
provider_tenant_id="provider-tenant-1",
encrypted_credentials=ChannelEncryptedCredentials(ciphertext="opaque-feishu-ciphertext"),
app_identifier="app-1",
webhook_id=WebhookId("00000000000000000000000000000001"),
config_version=1,
status=IMChannelStatus.CONNECTED,
)
session.add(contact_identity)
WorkspaceIMChannelWriter(session, tenant_id, AccountId(account.id)).create(channel)
identity_repository = SQLAlchemyIMIdentityRepository(session, channel.id)
primary_identity = _create_identity(
identity_repository,
_PRIMARY_IDENTITY_ID,
"provider-user-primary",
"Primary Reviewer",
"reviewer@example.com",
)
secondary_identity = _create_identity(
identity_repository,
_SECONDARY_IDENTITY_ID,
"provider-user-secondary",
"Secondary Reviewer",
"secondary@example.com",
)
session.commit()
return account, tenant, contact, channel, primary_identity, secondary_identity
def _create_identity(
repository: SQLAlchemyIMIdentityRepository,
identity_id: IMIdentityId,
provider_user_id: str,
display_name: str,
email: str,
) -> IMIdentity:
return repository.create(
identity_id,
IMIdentityObservation(
provider_user_id=provider_user_id,
display_name=display_name,
email=email,
raw_payload=OpaqueProviderPayload({}),
sync_run_id=IMSyncRunId("00000000-0000-0000-0000-000000000901"),
observed_at=_NOW,
),
)
def test_manual_binding_http_commands_use_real_guarded_postgresql_writes(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant, contact, _channel, _primary, _secondary = _seed_control_plane(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
binding_path = f"/console/api/workspaces/current/human-input/v2/contacts/{contact.id}/im-bindings"
override_path = f"/console/api/workspaces/current/human-input/v2/contacts/{contact.id}/im-override"
created = test_client_with_containers.put(
binding_path,
json={"identity_id": str(_PRIMARY_IDENTITY_ID)},
headers=headers,
)
assert created.status_code == 200
created_payload = created.get_json()
assert created_payload is not None
organization_binding = created_payload["contact"]["im_bindings"][0]
assert organization_binding["scope"] == "organization"
idempotent = test_client_with_containers.put(
binding_path,
json={"identity_id": str(_PRIMARY_IDENTITY_ID)},
headers=headers,
)
assert idempotent.status_code == 200
assert idempotent.get_json()["contact"]["im_bindings"] == [organization_binding]
replacement = test_client_with_containers.put(
binding_path,
json={"identity_id": str(_SECONDARY_IDENTITY_ID)},
headers=headers,
)
assert replacement.status_code == 200
replacement_bindings = replacement.get_json()["contact"]["im_bindings"]
assert len(replacement_bindings) == 1
replacement_binding = replacement_bindings[0]
assert replacement_binding["scope"] == "organization"
assert replacement_binding["id"] != organization_binding["id"]
missing_identity = test_client_with_containers.put(
binding_path,
json={"identity_id": "00000000-0000-0000-0000-000000000399"},
headers=headers,
)
assert missing_identity.status_code == 404
assert missing_identity.get_json()["code"] == "im_identity_not_found"
override = test_client_with_containers.put(
override_path,
json={"identity_id": str(_SECONDARY_IDENTITY_ID)},
headers=headers,
)
assert override.status_code == 403
assert override.get_json() == {
"code": "workspace_im_override_not_allowed",
"message": "Workspace IM overrides require centrally managed bindings.",
"status": 403,
}
reset = test_client_with_containers.delete(override_path, headers=headers)
assert reset.status_code == 403
assert reset.get_json() == override.get_json()
db_session_with_containers.expire_all()
stored_binding = db_session_with_containers.scalar(select(HumanInputIMBinding))
assert stored_binding is not None
assert stored_binding.id == replacement_binding["id"]
assert stored_binding.im_identity_id == str(_SECONDARY_IDENTITY_ID)
assert db_session_with_containers.get(HumanInputIMBinding, organization_binding["id"]) is None
deleted = test_client_with_containers.delete(binding_path, headers=headers)
assert deleted.status_code == 200
assert deleted.get_json() == {}
db_session_with_containers.expire_all()
assert db_session_with_containers.scalar(select(HumanInputIMBinding)) is None
missing_binding = test_client_with_containers.delete(binding_path, headers=headers)
assert missing_binding.status_code == 404
assert missing_binding.get_json()["code"] == "im_binding_not_found"
def test_sync_command_and_identity_queries_use_real_postgresql(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
monkeypatch: pytest.MonkeyPatch,
) -> None:
account, tenant, _contact, channel, _primary, _secondary = _seed_control_plane(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
dispatched: list[tuple[tuple[str, str, str | None], str]] = []
def capture_dispatch(*, args: tuple[str, str, str | None], queue: str) -> None:
dispatched.append((args, queue))
monkeypatch.setattr(reconcile_im_contacts_task, "apply_async", capture_dispatch)
created = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
replayed = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
latest = test_client_with_containers.get(f"{_SYNC_RUNS_PATH}/latest", headers=headers)
identities = test_client_with_containers.get(
"/console/api/workspaces/current/human-input/v2/im-identities",
query_string={"keyword": "provider-user", "page": 1, "limit": 1},
headers=headers,
)
assert created.status_code == replayed.status_code == latest.status_code == identities.status_code == 200
created_run = created.get_json()["run"]
assert replayed.get_json()["run"]["id"] == created_run["id"]
assert latest.get_json()["run"]["id"] == created_run["id"]
expected_dispatch = (
(created_run["id"], "workspace", tenant.id),
"human_input_contact_sync",
)
assert dispatched == [expected_dispatch, expected_dispatch]
identity_page = identities.get_json()
assert identity_page["total"] == 2
assert len(identity_page["data"]) == 1
assert identity_page["data"][0]["provider"] == IMProvider.FEISHU.value
assert identity_page["data"][0]["binding_status"] == "unbound"
assert created_run["channel_id"] == str(channel.id)
def test_latest_result_http_projection_reads_every_persisted_bucket(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, _tenant, contact, channel, primary_identity, _secondary = _seed_control_plane(db_session_with_containers)
run = replace(
IMSyncRun.create(
sync_run_id=IMSyncRunId("00000000-0000-0000-0000-000000000501"),
channel_revision=IMChannelRevision(str(channel.id), channel.config_version),
provider=channel.provider,
started_by_account_id=AccountId(account.id),
now=_NOW,
),
status=IMSyncRunStatus.SUCCEEDED,
added_count=1,
not_matched_count=1,
failed_count=1,
removed_count=1,
skipped_count=1,
started_at=_NOW,
finished_at=_LATER,
)
results = _result_facts(run, contact, primary_identity, channel.provider)
db_session_with_containers.add(sync_run_to_record(run))
db_session_with_containers.add_all(sync_result_to_record(result) for result in results)
db_session_with_containers.commit()
headers = authenticate_console_client(test_client_with_containers, account)
for result in results:
response = test_client_with_containers.get(
f"{_SYNC_RUNS_PATH}/latest/results",
query_string={"result": result.result_type.value, "page": 1, "limit": 20},
headers=headers,
)
assert response.status_code == 200
payload = response.get_json()
assert payload is not None
assert (payload["page"], payload["limit"], payload["total"]) == (1, 20, 1)
assert payload["data"][0]["result"]["type"] == result.result_type.value
added = test_client_with_containers.get(
f"{_SYNC_RUNS_PATH}/latest/results",
query_string={"result": IMSyncResultType.ADDED.value, "page": 1, "limit": 20},
headers=headers,
).get_json()["data"][0]["result"]
failed = test_client_with_containers.get(
f"{_SYNC_RUNS_PATH}/latest/results",
query_string={"result": IMSyncResultType.FAILED.value, "page": 1, "limit": 20},
headers=headers,
).get_json()["data"][0]["result"]
removed = test_client_with_containers.get(
f"{_SYNC_RUNS_PATH}/latest/results",
query_string={"result": IMSyncResultType.REMOVED.value, "page": 1, "limit": 20},
headers=headers,
).get_json()["data"][0]["result"]
assert added["contact"]["id"] == str(contact.id)
assert failed["reason"] == "Directory read failed"
assert removed["last_known_identity"]["identity_id"] == str(primary_identity.id)
assert removed["reason"] == IMSyncRemovalReason.NOT_PRESENT_IN_DIRECTORY.value
def _result_facts(
run: IMSyncRun,
contact: Contact,
identity: IMIdentity,
provider: IMProvider,
) -> tuple[SyncResultFact, ...]:
contact_snapshot = SyncContactSnapshot(contact.id, contact.name, contact.email, contact.avatar_file_id)
identity_snapshot = SyncIdentitySnapshot(
identity.id,
provider,
identity.provider_user_id,
identity.display_name,
identity.email,
)
def result(
result_id: int,
result_type: IMSyncResultType,
*,
include_entry: bool = True,
include_contact: bool = False,
removal_reason: IMSyncRemovalReason | None = None,
reason_message: str | None = None,
) -> SyncResultFact:
suffix = str(result_id).zfill(12)
return SyncResultFact(
id=IMSyncResultId(f"00000000-0000-0000-0000-{suffix}"),
channel_id=IMChannelId(run.channel_revision.channel_id),
sync_run_id=run.id,
operation_key=f"result:{result_type.value}:{result_id}",
result_type=result_type,
provider_user_id=identity.provider_user_id if include_entry else None,
display_name=identity.display_name if include_entry else None,
email=identity.email if include_entry else None,
normalized_email=NormalizedEmail(identity.email) if include_entry and identity.email is not None else None,
contact_id=contact.id if include_contact else None,
identity_id=identity.id,
binding_id=None,
removal_reason=removal_reason,
reason_code=None,
reason_message=reason_message,
directory_entry_payload=None,
contact_snapshot=contact_snapshot if include_contact else None,
identity_snapshot=identity_snapshot if removal_reason is not None else None,
created_at=_NOW,
updated_at=_NOW,
)
return (
result(1, IMSyncResultType.ADDED, include_contact=True),
result(2, IMSyncResultType.NOT_MATCHED),
result(3, IMSyncResultType.FAILED, reason_message="Directory read failed"),
result(
4,
IMSyncResultType.REMOVED,
include_entry=False,
include_contact=True,
removal_reason=IMSyncRemovalReason.NOT_PRESENT_IN_DIRECTORY,
),
result(5, IMSyncResultType.SKIPPED, include_contact=True),
)
def test_missing_control_plane_state_returns_stable_http_errors(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(test_client_with_containers, account)
missing_integration = test_client_with_containers.get(
"/console/api/workspaces/current/human-input/v2/im-identities",
headers=headers,
)
missing_sync_integration = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
assert missing_integration.status_code == missing_sync_integration.status_code == 404
assert missing_integration.get_json()["code"] == "im_integration_not_configured"
channel = IMChannel(
id=_CHANNEL_ID,
created_at=_NOW,
updated_at=_NOW,
provider=IMProvider.FEISHU,
provider_tenant_id="provider-tenant-1",
encrypted_credentials=ChannelEncryptedCredentials(ciphertext="opaque-feishu-ciphertext"),
app_identifier="app-1",
webhook_id=WebhookId("00000000000000000000000000000001"),
config_version=1,
status=IMChannelStatus.CONNECTED,
)
WorkspaceIMChannelWriter(db_session_with_containers, TenantId(tenant.id), AccountId(account.id)).create(channel)
db_session_with_containers.commit()
missing_run = test_client_with_containers.get(f"{_SYNC_RUNS_PATH}/latest", headers=headers)
missing_results = test_client_with_containers.get(
f"{_SYNC_RUNS_PATH}/latest/results",
query_string={"result": IMSyncResultType.ADDED.value},
headers=headers,
)
assert missing_run.status_code == missing_results.status_code == 404
assert missing_run.get_json()["code"] == "im_sync_run_not_found"
assert db_session_with_containers.scalar(select(HumanInputIMSyncRun)) is None
@@ -0,0 +1,176 @@
"""Authenticated HTTP-to-worker live Slack reconciliation verification."""
from __future__ import annotations
import os
from datetime import datetime
import pytest
from flask.testing import FlaskClient
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from core.human_input_v2.entities import IMProvider, IMSyncRunStatus
from core.human_input_v2.im_integration.adapters import SlackCredentials
from core.human_input_v2.shared import AccountId, IMSyncRunId, TenantId, WorkspaceScope
from extensions.ext_key_provider import key_provider_manager
from libs.datetime_utils import naive_utc_now
from libs.rsa import generate_key_pair
from libs.uuid_utils import uuidv7
from models.human_input_v2 import HumanInputIMIdentity, HumanInputIMSyncResult
from repositories.human_input_v2.im_channel_repository import (
IMChannel,
IMChannelId,
IMChannelStatus,
WebhookId,
)
from repositories.human_input_v2.sqlalchemy_im_channel_repository import WorkspaceIMChannelWriter
from services.human_input_v2.im_contact_sync.composition import build_im_contact_sync_worker
from services.human_input_v2.im_credential_codec import IMCredentialCodec
from services.human_input_v2.im_tenant_credential_cipher import TenantBoundCredentialCipher
from tasks.im_contact_sync_tasks import reconcile_im_contacts_task
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
_SYNC_RUNS_PATH = "/console/api/workspaces/current/human-input/v2/im-sync-runs"
_REQUIRED_SLACK_ENVIRONMENT = (
"SLACK_CLIENT_ID",
"SLACK_CLIENT_SECRET",
"SLACK_SIGNING_SECRET",
"SLACK_BOT_TOKEN",
"SLACK_APP_SOCKET_TOKEN",
)
def test_authenticated_http_sync_reaches_live_provider_worker_and_persisted_queries(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
monkeypatch: pytest.MonkeyPatch,
) -> None:
credentials = _live_slack_credentials()
account, tenant = create_console_account_and_tenant(db_session_with_containers)
tenant.encrypt_public_key = generate_key_pair(tenant.id)
db_session_with_containers.commit()
channel = _persist_live_slack_channel(
db_session_with_containers,
tenant_id=TenantId(tenant.id),
actor_id=AccountId(account.id),
credentials=credentials,
now=naive_utc_now(),
)
headers = authenticate_console_client(test_client_with_containers, account)
dispatched: list[tuple[tuple[str, str, str | None], str]] = []
def capture_dispatch(*, args: tuple[str, str, str | None], queue: str) -> None:
dispatched.append((args, queue))
monkeypatch.setattr(reconcile_im_contacts_task, "apply_async", capture_dispatch)
create_response = test_client_with_containers.post(_SYNC_RUNS_PATH, headers=headers)
assert create_response.status_code == 200
create_payload = create_response.get_json()
assert create_payload is not None
run_payload = create_payload["run"]
assert run_payload["status"] == IMSyncRunStatus.QUEUED.value
sync_run_id = IMSyncRunId(run_payload["id"])
assert dispatched == [
(
(str(sync_run_id), "workspace", tenant.id),
"human_input_contact_sync",
)
]
terminal_run = build_im_contact_sync_worker().execute(
sync_run_id,
WorkspaceScope(id=TenantId(tenant.id)),
)
assert terminal_run.status is IMSyncRunStatus.SUCCEEDED
latest_response = test_client_with_containers.get(f"{_SYNC_RUNS_PATH}/latest", headers=headers)
assert latest_response.status_code == 200
latest_payload = latest_response.get_json()
assert latest_payload is not None
assert latest_payload["run"]["id"] == str(sync_run_id)
assert latest_payload["run"]["status"] == IMSyncRunStatus.SUCCEEDED.value
result_counts: dict[str, int] = latest_payload["run"]["result_counts"]
assert sum(result_counts.values()) > 0
result_bucket, expected_total = next((bucket, count) for bucket, count in result_counts.items() if count > 0)
first_page_response = test_client_with_containers.get(
f"{_SYNC_RUNS_PATH}/latest/results",
query_string={"result": result_bucket, "page": 1, "limit": 1},
headers=headers,
)
assert first_page_response.status_code == 200
first_page = first_page_response.get_json()
assert first_page is not None
assert (first_page["page"], first_page["limit"], first_page["total"]) == (1, 1, expected_total)
assert len(first_page["data"]) == 1
if expected_total > 1:
second_page_response = test_client_with_containers.get(
f"{_SYNC_RUNS_PATH}/latest/results",
query_string={"result": result_bucket, "page": 2, "limit": 1},
headers=headers,
)
assert second_page_response.status_code == 200
second_page = second_page_response.get_json()
assert second_page is not None
assert (second_page["page"], second_page["limit"], second_page["total"]) == (2, 1, expected_total)
assert len(second_page["data"]) == 1
db_session_with_containers.expire_all()
persisted_result_count = db_session_with_containers.scalar(
select(func.count(HumanInputIMSyncResult.id)).where(HumanInputIMSyncResult.sync_run_id == str(sync_run_id))
)
persisted_identity_count = db_session_with_containers.scalar(
select(func.count(HumanInputIMIdentity.id)).where(HumanInputIMIdentity.channel_id == str(channel.id))
)
assert persisted_result_count == sum(result_counts.values())
assert persisted_identity_count == persisted_result_count
def _live_slack_credentials() -> dict[str, str]:
missing_names = tuple(name for name in _REQUIRED_SLACK_ENVIRONMENT if not os.getenv(name))
if missing_names:
pytest.skip("live Slack credentials are not configured")
return {name: os.environ[name] for name in _REQUIRED_SLACK_ENVIRONMENT}
def _persist_live_slack_channel(
session: Session,
*,
tenant_id: TenantId,
actor_id: AccountId,
credentials: dict[str, str],
now: datetime,
) -> IMChannel:
plaintext_credentials = SlackCredentials(
provider=IMProvider.SLACK,
client_id=credentials["SLACK_CLIENT_ID"],
client_secret=credentials["SLACK_CLIENT_SECRET"],
signing_secret=credentials["SLACK_SIGNING_SECRET"],
bot_token=credentials["SLACK_BOT_TOKEN"],
app_token=credentials["SLACK_APP_SOCKET_TOKEN"],
)
protected = IMCredentialCodec(TenantBoundCredentialCipher(key_provider_manager.provider, str(tenant_id))).seal(
plaintext_credentials
)
channel = IMChannel(
id=IMChannelId(str(uuidv7())),
created_at=now,
updated_at=now,
provider=IMProvider.SLACK,
provider_tenant_id="live-slack-workspace",
encrypted_credentials=protected,
app_identifier=plaintext_credentials.client_id,
webhook_id=WebhookId(uuidv7().hex),
config_version=1,
status=IMChannelStatus.CONNECTED,
)
WorkspaceIMChannelWriter(session, tenant_id, actor_id).create(channel)
session.commit()
return channel
@@ -0,0 +1,317 @@
from __future__ import annotations
import inspect
from collections.abc import Callable
from typing import cast
from unittest.mock import patch
from uuid import uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import HTTPException
import services.errors.base
import services.errors.workspace
from controllers.console.auth.error import MemberNotInTenantError
from controllers.console.workspace.members import MemberCancelInviteApi, MemberUpdateRoleApi, OwnerTransfer
from extensions.ext_application_services import application_services
from libs.exception import BaseHTTPException
from libs.helper import TokenManager
from machinery.context import RequestContext
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus
from services.workspace import gateways
JsonResponse = dict[str, object]
StatusResponse = tuple[JsonResponse, int]
def unwrap(func: Callable[..., object]) -> Callable[..., object]:
return inspect.unwrap(func)
def unwrap_status_response(func: Callable[..., object]) -> Callable[..., StatusResponse]:
return cast(Callable[..., StatusResponse], inspect.unwrap(func))
def unwrap_json_response(func: Callable[..., object]) -> Callable[..., JsonResponse]:
return cast(Callable[..., JsonResponse], inspect.unwrap(func))
def unwrap_json_or_status_response(func: Callable[..., object]) -> Callable[..., JsonResponse | StatusResponse]:
return cast(Callable[..., JsonResponse | StatusResponse], inspect.unwrap(func))
def unwrap_raises(func: Callable[..., object]) -> Callable[..., object]:
return unwrap(func)
class WorkspaceMembersIntegrationFactory:
@staticmethod
def create_tenant(db_session_with_containers: Session) -> Tenant:
tenant = Tenant(name=f"Tenant {uuid4()}", plan="basic", status=TenantStatus.NORMAL)
db_session_with_containers.add(tenant)
db_session_with_containers.commit()
return tenant
@staticmethod
def create_account(
db_session_with_containers: Session,
*,
email_prefix: str,
tenant: Tenant | None = None,
role: TenantAccountRole = TenantAccountRole.NORMAL,
current: bool = False,
) -> Account:
account = Account(
name=f"Account {uuid4()}",
email=f"{email_prefix}-{uuid4()}@example.com",
password="hashed-password",
password_salt="salt",
interface_language="en-US",
timezone="UTC",
)
db_session_with_containers.add(account)
db_session_with_containers.commit()
if tenant is not None:
join = TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role=role,
current=current,
)
db_session_with_containers.add(join)
db_session_with_containers.commit()
account.set_current_tenant_with_session(tenant, session=db_session_with_containers)
return account
@staticmethod
def create_owner_workspace(db_session_with_containers: Session) -> tuple[Tenant, Account]:
tenant = WorkspaceMembersIntegrationFactory.create_tenant(db_session_with_containers)
owner = WorkspaceMembersIntegrationFactory.create_account(
db_session_with_containers,
email_prefix="owner",
tenant=tenant,
role=TenantAccountRole.OWNER,
current=True,
)
return tenant, owner
@staticmethod
def create_owner_transfer_token(account: Account) -> str:
token = TokenManager.generate_token(
account_id=account.id, email=account.email, token_type="owner_transfer", additional_data={"code": "123456"}
)
return token
@staticmethod
def get_join(db_session_with_containers: Session, *, tenant: Tenant, account: Account) -> TenantAccountJoin:
tenant_id = tenant.id
account_id = account.id
db_session_with_containers.expire_all()
join = (
db_session_with_containers.query(TenantAccountJoin)
.filter_by(tenant_id=tenant_id, account_id=account_id)
.one()
)
return join
class TestMemberCancelInviteApiWithContainers:
def test_cancel_success(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
api = MemberCancelInviteApi()
method = unwrap_status_response(api.delete)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
member = factory.create_account(db_session_with_containers, email_prefix="member")
with (
flask_app_with_containers.test_request_context("/"),
patch.object(application_services().workspaces.members, "remove") as mock_remove_member,
):
result, status = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
assert status == 200
assert result["result"] == "success"
mock_remove_member.assert_called_once()
called_tenant, called_member, called_current_user = mock_remove_member.call_args.args
assert called_tenant == tenant.id
assert called_member == member.id
assert called_current_user == current_user.id
def test_cancel_not_found(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
api = MemberCancelInviteApi()
method = unwrap_raises(api.delete)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
with flask_app_with_containers.test_request_context("/"):
with pytest.raises(HTTPException):
method(api, RequestContext("request", None, current_user.id, tenant.id), str(uuid4()))
def test_cancel_cannot_operate_self(
self, flask_app_with_containers: Flask, db_session_with_containers: Session
) -> None:
api = MemberCancelInviteApi()
method = unwrap_status_response(api.delete)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
member = factory.create_account(db_session_with_containers, email_prefix="member")
with (
flask_app_with_containers.test_request_context("/"),
patch.object(
application_services().workspaces.members,
"remove",
side_effect=services.errors.workspace.CannotOperateSelfError("x"),
),
):
with pytest.raises(BaseHTTPException) as exc_info:
method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
assert exc_info.value.code == 400
assert exc_info.value.data == {
"code": "cannot_operate_self",
"message": exc_info.value.description,
"status": 400,
}
def test_cancel_no_permission(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
api = MemberCancelInviteApi()
method = unwrap_status_response(api.delete)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
member = factory.create_account(db_session_with_containers, email_prefix="member")
with (
flask_app_with_containers.test_request_context("/"),
patch.object(
application_services().workspaces.members,
"remove",
side_effect=services.errors.base.NoPermissionError("x"),
),
):
with pytest.raises(BaseHTTPException) as exc_info:
method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
assert exc_info.value.code == 403
assert exc_info.value.data == {"code": "forbidden", "message": exc_info.value.description, "status": 403}
def test_cancel_member_not_in_tenant(
self, flask_app_with_containers: Flask, db_session_with_containers: Session
) -> None:
api = MemberCancelInviteApi()
method = unwrap_status_response(api.delete)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
member = factory.create_account(db_session_with_containers, email_prefix="member")
with (
flask_app_with_containers.test_request_context("/"),
patch.object(
application_services().workspaces.members,
"remove",
side_effect=services.errors.workspace.MemberNotInTenantError(),
),
):
with pytest.raises(BaseHTTPException) as exc_info:
method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
assert exc_info.value.code == 404
assert exc_info.value.data == {"code": "member_not_found", "message": exc_info.value.description, "status": 404}
class TestMemberUpdateRoleApiWithContainers:
def test_update_success(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
api = MemberUpdateRoleApi()
method = unwrap_json_or_status_response(api.put)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
member = factory.create_account(
db_session_with_containers,
email_prefix="member",
tenant=tenant,
role=TenantAccountRole.EDITOR,
)
with flask_app_with_containers.test_request_context("/", json={"role": "normal"}):
result = method(api, RequestContext("request", None, current_user.id, tenant.id), member.id)
if isinstance(result, tuple):
result = result[0]
assert result["result"] == "success"
assert (
factory.get_join(db_session_with_containers, tenant=tenant, account=member).role == TenantAccountRole.NORMAL
)
def test_update_member_not_found(
self, flask_app_with_containers: Flask, db_session_with_containers: Session
) -> None:
api = MemberUpdateRoleApi()
method = unwrap_raises(api.put)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
with flask_app_with_containers.test_request_context("/", json={"role": "normal"}):
with pytest.raises(HTTPException):
method(api, RequestContext("request", None, current_user.id, tenant.id), str(uuid4()))
class TestOwnerTransferApiWithContainers:
def test_member_not_in_tenant(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
api = OwnerTransfer()
method = unwrap_raises(api.post)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
member = factory.create_account(db_session_with_containers, email_prefix="member")
token = factory.create_owner_transfer_token(current_user)
with flask_app_with_containers.test_request_context("/", json={"token": token}):
with pytest.raises(MemberNotInTenantError):
method(api, RequestContext("test", None, current_user.id, tenant.id), member.id)
def test_member_not_found(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
api = OwnerTransfer()
method = unwrap_raises(api.post)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
token = factory.create_owner_transfer_token(current_user)
with flask_app_with_containers.test_request_context("/", json={"token": token}):
with pytest.raises(HTTPException):
method(api, RequestContext("test", None, current_user.id, tenant.id), str(uuid4()))
def test_transfer_success(self, flask_app_with_containers: Flask, db_session_with_containers: Session) -> None:
api = OwnerTransfer()
method = unwrap_json_response(api.post)
factory = WorkspaceMembersIntegrationFactory
tenant, current_user = factory.create_owner_workspace(db_session_with_containers)
member = factory.create_account(
db_session_with_containers,
email_prefix="member",
tenant=tenant,
role=TenantAccountRole.NORMAL,
)
token = factory.create_owner_transfer_token(current_user)
with (
flask_app_with_containers.test_request_context("/", json={"token": token}),
patch.object(gateways.send_new_owner_transfer_notify_email_task, "delay") as notify_new,
patch.object(gateways.send_old_owner_transfer_notify_email_task, "delay") as notify_old,
):
result = method(api, RequestContext("test", None, current_user.id, tenant.id), member.id)
assert result["result"] == "success"
assert (
factory.get_join(db_session_with_containers, tenant=tenant, account=member).role == TenantAccountRole.OWNER
)
assert (
factory.get_join(db_session_with_containers, tenant=tenant, account=current_user).role
== TenantAccountRole.NORMAL
)
notify_new.assert_called_once_with(language="en-US", to=member.email, workspace=tenant.name)
notify_old.assert_called_once_with(
language="en-US", to=current_user.email, workspace=tenant.name, new_owner_email=member.email
)
@@ -0,0 +1,115 @@
"""Integration coverage for the console MCP provider HTTP endpoint."""
import json
from unittest.mock import MagicMock, patch
import pytest
from flask import Flask
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from core.tools.entities.api_entities import ToolProviderApiEntity
from tests.e2e_tests.containers.controllers.console.helpers import (
authenticate_console_client,
create_console_account_and_tenant,
)
def _i18n(text: str) -> dict[str, str]:
return {"en_US": text}
def _tool_payload() -> dict[str, object]:
return {
"author": "langgenius",
"name": "ping",
"label": _i18n("Ping"),
"description": _i18n("Ping description"),
"parameters": [],
"labels": ["utilities"],
"output_schema": {},
}
def _provider_entity() -> ToolProviderApiEntity:
return ToolProviderApiEntity.model_validate(
{
"id": "provider-1",
"author": "langgenius",
"name": "provider",
"description": _i18n("Provider description"),
"icon": {"content": "tool", "background": "#252525"},
"icon_dark": {"content": "tool", "background": "#252525"},
"label": _i18n("Provider"),
"type": "mcp",
"masked_credentials": {"api_key": "[__HIDDEN__]"},
"original_credentials": {"api_key": "sk-secret"},
"is_team_authorization": False,
"allow_delete": True,
"plugin_id": "langgenius/provider",
"plugin_unique_identifier": "langgenius/provider:1.0.0",
"tools": [_tool_payload()],
"labels": ["utilities"],
"server_url": "",
"updated_at": 1710000000,
"server_identifier": "",
"masked_headers": None,
"original_headers": None,
"authentication": None,
"is_dynamic_registration": True,
"configuration": None,
"identity_mode": "off",
"workflow_app_id": None,
}
)
@pytest.fixture
def client(flask_app_with_containers: Flask) -> FlaskClient:
return flask_app_with_containers.test_client()
def test_create_mcp_provider_populates_tools(
client: FlaskClient,
db_session_with_containers: Session,
) -> None:
account, _tenant = create_console_account_and_tenant(db_session_with_containers)
headers = authenticate_console_client(client, account)
service = MagicMock()
service.create_provider.return_value = MagicMock(id="provider-1")
service.get_provider.return_value = MagicMock(id="provider-1", tenant_id="t1")
with (
patch("controllers.console.workspace.tool_providers.MCPToolManageService", return_value=service, autospec=True),
patch(
"services.tools.tools_transform_service.ToolTransformService.mcp_provider_to_user_provider",
return_value=_provider_entity(),
autospec=True,
),
):
response = client.post(
"/console/api/workspaces/current/tool-provider/mcp",
data=json.dumps(
{
"server_url": "http://example.com/mcp",
"name": "demo",
"icon": "😀",
"icon_type": "emoji",
"icon_background": "#000",
"server_identifier": "demo-sid",
"configuration": {"timeout": 5, "sse_read_timeout": 30},
"headers": {},
"authentication": {},
}
),
headers=headers,
content_type="application/json",
)
assert response.status_code == 200
body = response.get_json()
assert body["id"] == "provider-1"
assert body["team_credentials"] == {"api_key": "[__HIDDEN__]"}
assert "masked_credentials" not in body
assert "original_credentials" not in body
assert body["tools"]
@@ -0,0 +1,237 @@
"""Testcontainers integration tests for plugin_permission_required decorator."""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from sqlalchemy.orm import Session
from werkzeug.exceptions import Forbidden
from controllers.console.workspace import plugin_permission_required
from models.account import (
Tenant,
TenantPluginDebugPermission,
TenantPluginInstallPermission,
TenantPluginPermission,
TenantStatus,
)
def _create_tenant(db_session: Session) -> Tenant:
tenant = Tenant(name="test-tenant", status=TenantStatus.NORMAL, plan="basic")
db_session.add(tenant)
db_session.commit()
db_session.expire_all()
return tenant
def _create_permission(
db_session: Session,
tenant_id: str,
install: TenantPluginInstallPermission = TenantPluginInstallPermission.EVERYONE,
debug: TenantPluginDebugPermission = TenantPluginDebugPermission.EVERYONE,
) -> TenantPluginPermission:
perm = TenantPluginPermission(
tenant_id=tenant_id,
install_permission=install,
debug_permission=debug,
)
db_session.add(perm)
db_session.commit()
db_session.expire_all()
return perm
class TestPluginPermissionRequired:
def test_allows_without_permission(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
user = SimpleNamespace(is_admin_or_owner=False)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required()
def handler():
return "ok"
assert handler() == "ok"
def test_install_without_permission_forbids_non_admin(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
user = SimpleNamespace(is_admin_or_owner=False)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(install_required=True)
def handler():
return "ok"
with pytest.raises(Forbidden):
handler()
def test_install_without_permission_allows_admin(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
user = SimpleNamespace(is_admin_or_owner=True)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(install_required=True)
def handler():
return "ok"
assert handler() == "ok"
def test_debug_without_permission_allows_non_admin(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
user = SimpleNamespace(is_admin_or_owner=False)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(debug_required=True)
def handler():
return "ok"
assert handler() == "ok"
def test_install_nobody_forbidden(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
_create_permission(
db_session_with_containers,
tenant.id,
install=TenantPluginInstallPermission.NOBODY,
debug=TenantPluginDebugPermission.EVERYONE,
)
user = SimpleNamespace(is_admin_or_owner=True)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(install_required=True)
def handler():
return "ok"
with pytest.raises(Forbidden):
handler()
def test_install_admin_requires_admin(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
_create_permission(
db_session_with_containers,
tenant.id,
install=TenantPluginInstallPermission.ADMINS,
debug=TenantPluginDebugPermission.EVERYONE,
)
user = SimpleNamespace(is_admin_or_owner=False)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(install_required=True)
def handler():
return "ok"
with pytest.raises(Forbidden):
handler()
def test_install_admin_allows_admin(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
_create_permission(
db_session_with_containers,
tenant.id,
install=TenantPluginInstallPermission.ADMINS,
debug=TenantPluginDebugPermission.EVERYONE,
)
user = SimpleNamespace(is_admin_or_owner=True)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(install_required=True)
def handler():
return "ok"
assert handler() == "ok"
def test_debug_nobody_forbidden(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
_create_permission(
db_session_with_containers,
tenant.id,
install=TenantPluginInstallPermission.EVERYONE,
debug=TenantPluginDebugPermission.NOBODY,
)
user = SimpleNamespace(is_admin_or_owner=True)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(debug_required=True)
def handler():
return "ok"
with pytest.raises(Forbidden):
handler()
def test_debug_admin_requires_admin(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
_create_permission(
db_session_with_containers,
tenant.id,
install=TenantPluginInstallPermission.EVERYONE,
debug=TenantPluginDebugPermission.ADMINS,
)
user = SimpleNamespace(is_admin_or_owner=False)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(debug_required=True)
def handler():
return "ok"
with pytest.raises(Forbidden):
handler()
def test_debug_admin_allows_admin(self, db_session_with_containers: Session):
tenant = _create_tenant(db_session_with_containers)
_create_permission(
db_session_with_containers,
tenant.id,
install=TenantPluginInstallPermission.EVERYONE,
debug=TenantPluginDebugPermission.ADMINS,
)
user = SimpleNamespace(is_admin_or_owner=True)
with patch(
"controllers.console.workspace.current_account_with_tenant",
return_value=(user, tenant.id),
):
@plugin_permission_required(debug_required=True)
def handler():
return "ok"
assert handler() == "ok"
@@ -0,0 +1,121 @@
from __future__ import annotations
import uuid
from collections.abc import Callable, Sequence
from unittest.mock import patch
import pytest
from faker import Faker
from flask import Flask
from sqlalchemy.orm import Session
from constants.oauth_bearer import TokenType
from controllers.openapi.auth.context import Context
from controllers.openapi.auth.loaders import PathParam, load_app
from controllers.openapi.auth.requirements import Requirement, ResolveCaller
from controllers.openapi.auth.subjects import subject_from_auth
from libs.oauth_bearer import AuthContext
from models import Account, Tenant
from tests.e2e_tests.containers.helpers import accounts as account_fixtures
from tests.e2e_tests.containers.helpers import generate_valid_password
_CLIENT_ID = "integration-cli"
@pytest.fixture
def app(flask_app_with_containers: Flask) -> Flask:
return flask_app_with_containers
@pytest.fixture
def make_account(db_session_with_containers: Session) -> Callable[..., Account]:
"""Factory that registers a real Account and gives it an owner workspace.
System feature gates are stubbed (registration / workspace creation
allowed) exactly like the AppDslService integration tests, so this stays a
pure account+tenant setup helper.
"""
# Depend on db_session_with_containers so the app context / DB session is
# active for the composed account and workspace services below.
assert db_session_with_containers is not None
def _make(*, with_owner_tenant: bool = True) -> Account:
fake = Faker()
with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:
mock_feature_service.is_registration_allowed.return_value = True
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
if with_owner_tenant:
account_fixtures.create_owner_workspace(
account, name=fake.company(), session=db_session_with_containers
)
return account
return _make
def add_tenant_for_account(
account: Account, *, session: Session, role: str = "normal", name: str = "Second WS"
) -> Tenant:
"""Create an additional tenant and join ``account`` to it (real service calls)."""
with patch("services.account.login_adapters.SystemFeatureService") as mock_feature_service:
mock_feature_service.is_workspace_creation_allowed.return_value = True
tenant = account_fixtures.create_workspace(name=name, session=session)
account_fixtures.join_workspace(tenant, account, session, role=role)
return tenant
def _account_auth(
account: Account,
*,
token_id: uuid.UUID | None = None,
client_id: str = _CLIENT_ID,
) -> AuthContext:
"""The ``AuthContext`` a live ``dfoa_`` token for ``account`` would carry."""
return AuthContext(
subject_email=account.email,
subject_issuer=None,
account_id=uuid.UUID(str(account.id)),
client_id=client_id,
token_id=token_id or uuid.uuid4(),
token_type=TokenType.OAUTH_ACCOUNT,
expires_at=None,
)
def context_for(
account: Account,
*,
session: Session,
view_args: dict[str, str] | None = None,
token_id: uuid.UUID | None = None,
requirements: Sequence[Requirement] = (),
) -> Context:
"""Build the ``Context`` a handler is given after the pipeline ran.
The subject comes from a real ``AuthContext`` through ``subject_from_auth``,
so the helper walks the same resolution path the router does. ``view_args``
is the route's path params — the app and the workspace are loaded from it,
so a route carrying ``<app_id>`` needs ``{"app_id": ...}`` here.
``token_id`` only matters to the ``/account/sessions*`` family, which reads
it back off the subject.
Pass the route's context-loading requirements, such as
``CheckWorkspaceMember``, to bind the caller to its requested workspace.
They run alongside the pipeline's fixed ``ResolveCaller`` in rank order;
the caller is freshly loaded and does not inherit ``account.current_tenant``.
App routes also load their app, as ``CheckAppApiEnabled`` does before the
handler runs. Authorization itself is covered by the auth-layer tests.
"""
ctx = Context(subject_from_auth(_account_auth(account, token_id=token_id)), session, view_args or {})
if PathParam.APP_ID in ctx.view_args:
load_app(ctx)
for requirement in sorted((*requirements, ResolveCaller()), key=lambda item: item.rank):
requirement.run(ctx.subject, ctx, session)
return ctx
@@ -0,0 +1,54 @@
from __future__ import annotations
from collections.abc import Callable
from flask import Flask
from sqlalchemy.orm import Session
from controllers.openapi.account import AccountApi
from models import Account
from models.account import TenantAccountRole
from tests.e2e_tests.containers.controllers.openapi.conftest import add_tenant_for_account, context_for
class TestAccountInfo:
def test_returns_account_and_owner_workspace(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
api = AccountApi()
with app.test_request_context("/openapi/v1/account"):
result = api.get.__handler__(api, context_for(account, session=db_session_with_containers)) # pyrefly: ignore[missing-attribute]
assert result.subject_type == "account"
assert result.subject_email == account.email
assert result.account is not None
assert result.account.id == account.id
assert result.account.email == account.email
workspaces = {w.id: w for w in result.workspaces}
assert set(workspaces) == {owner_tenant.id}
assert workspaces[owner_tenant.id].role == TenantAccountRole.OWNER.value
# No membership is flagged `current` yet, so the default falls back to
# the only workspace the account belongs to.
assert result.default_workspace_id == owner_tenant.id
def test_lists_all_joined_workspaces(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
second = add_tenant_for_account(account, session=db_session_with_containers, role="normal", name="Second WS")
api = AccountApi()
with app.test_request_context("/openapi/v1/account"):
result = api.get.__handler__(api, context_for(account, session=db_session_with_containers)) # pyrefly: ignore[missing-attribute]
assert {w.id for w in result.workspaces} == {owner_tenant.id, second.id}
roles = {w.id: w.role for w in result.workspaces}
assert roles[owner_tenant.id] == TenantAccountRole.OWNER.value
assert roles[second.id] == "normal"
@@ -0,0 +1,153 @@
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound
from constants.oauth_bearer import TokenType
from controllers.openapi._models import SessionListQuery
from controllers.openapi.account import (
AccountSessionByIdApi,
AccountSessionsApi,
AccountSessionsSelfApi,
)
from models import Account
from models.oauth import OAuthAccessToken
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
@dataclass(frozen=True, slots=True)
class _MintResult:
token_id: UUID
def _mint_account_token(
db_session: Session,
account: Account,
*,
client_id: str = "integration-cli",
device_label: str = "Test Device",
) -> _MintResult:
"""Mint a real, persisted ``dfoa_`` access token for ``account``."""
record = OAuthAccessToken(
subject_email=account.email,
subject_issuer="dify:account",
account_id=str(account.id),
client_id=client_id,
device_label=device_label,
prefix=TokenType.OAUTH_ACCOUNT.prefix,
token_hash=f"integration-{uuid4().hex}",
expires_at=datetime.now(UTC) + timedelta(days=14),
)
db_session.add(record)
db_session.commit()
return _MintResult(token_id=UUID(str(record.id)))
class TestSessionList:
def test_lists_active_session(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
mint = _mint_account_token(db_session_with_containers, account, device_label="Laptop")
api = AccountSessionsApi()
with app.test_request_context("/openapi/v1/account/sessions"):
result = api.get.__handler__(
api,
context_for(account, session=db_session_with_containers, token_id=mint.token_id),
query=SessionListQuery(),
)
assert result.total == 1
row = result.data[0]
assert row.id == str(mint.token_id)
assert row.prefix == TokenType.OAUTH_ACCOUNT.prefix
assert row.device_label == "Laptop"
def test_excludes_other_accounts_sessions(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""Sessions are subject-scoped: another account's token must not appear."""
account = make_account()
other = make_account()
mine = _mint_account_token(db_session_with_containers, account)
_mint_account_token(db_session_with_containers, other)
api = AccountSessionsApi()
with app.test_request_context("/openapi/v1/account/sessions"):
result = api.get.__handler__(
api,
context_for(account, session=db_session_with_containers, token_id=mine.token_id),
query=SessionListQuery(),
)
assert {row.id for row in result.data} == {str(mine.token_id)}
class TestSessionRevoke:
def test_revoke_self_removes_from_active_list(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
mint = _mint_account_token(db_session_with_containers, account)
revoke_api = AccountSessionsSelfApi()
with app.test_request_context("/openapi/v1/account/sessions/self", method="DELETE"):
result = revoke_api.delete.__handler__(
revoke_api, context_for(account, session=db_session_with_containers, token_id=mint.token_id)
)
assert result.status == "revoked"
# Revocation persisted: the real list path no longer returns it.
list_api = AccountSessionsApi()
with app.test_request_context("/openapi/v1/account/sessions"):
listing = list_api.get.__handler__(
list_api,
context_for(account, session=db_session_with_containers, token_id=mint.token_id),
query=SessionListQuery(),
)
assert listing.total == 0
def test_revoke_by_id_for_own_session(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
mint = _mint_account_token(db_session_with_containers, account)
session_id = str(mint.token_id)
api = AccountSessionByIdApi()
ctx = context_for(
account,
session=db_session_with_containers,
view_args={"session_id": session_id},
token_id=mint.token_id,
)
with app.test_request_context(f"/openapi/v1/account/sessions/{session_id}", method="DELETE"):
result = api.delete.__handler__(api, ctx, session_id)
assert result.status == "revoked"
def test_revoke_foreign_session_is_404(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""A token id owned by another subject must be indistinguishable from a
missing one (404), so token ids can't be probed across subjects. The
access service makes that call; the handler only maps it to 404."""
owner = make_account()
outsider = make_account()
foreign = _mint_account_token(db_session_with_containers, owner)
session_id = str(foreign.token_id)
ctx = context_for(outsider, session=db_session_with_containers, view_args={"session_id": session_id})
with app.test_request_context(f"/openapi/v1/account/sessions/{session_id}", method="DELETE"):
api = AccountSessionByIdApi()
with pytest.raises(NotFound):
api.delete.__handler__(api, ctx, session_id)
@@ -0,0 +1,287 @@
from __future__ import annotations
import json
from collections.abc import Callable, Generator
from typing import Protocol, cast
from unittest.mock import patch
from uuid import uuid4
import pytest
import yaml
from faker import Faker
from flask import Flask
from sqlalchemy.orm import Session
from controllers.openapi._errors import DraftNotFound
from controllers.openapi._models import AppDslExportQuery, AppDslExportResponse, AppDslImportPayload
from controllers.openapi.app_dsl import (
AppDslCheckDependenciesApi,
AppDslExportApi,
AppDslImportApi,
AppDslImportConfirmApi,
)
from machinery.context import AppRequestContext, RequestContext
from models import Account, App
from models.model import AppMode, AppModelConfig
from services.app_dsl_service import CURRENT_DSL_VERSION
from services.app_service import AppService, CreateAppParams
from services.entities.dsl_entities import CheckDependenciesResult, Import, ImportStatus
from services.errors.app import WorkflowNotFoundError
from tests.e2e_tests.containers.helpers import accounts as account_fixtures
from tests.e2e_tests.containers.helpers import generate_valid_password
class _Endpoint[T](Protocol):
__handler__: Callable[..., T]
def _workflow_yaml(*, version: str = CURRENT_DSL_VERSION, name: str = "My App") -> str:
return yaml.safe_dump(
{
"version": version,
"kind": "app",
"app": {"name": name, "mode": "workflow"},
"workflow": {"graph": {"nodes": []}, "features": {}},
},
allow_unicode=True,
)
@pytest.fixture
def external_deps() -> Generator[dict[str, object]]:
"""Stub the heavy collaborators an import/export touches (model runtime,
workflow sync, dependency analysis, enterprise hooks) while leaving the DSL
service and DB writes real."""
with (
patch("services.app_dsl_service.WorkflowService") as mock_workflow_service,
patch("services.app_dsl_service.DependenciesAnalysisService") as mock_dependencies_service,
patch("services.app_dsl_service.app_was_created") as mock_app_was_created,
patch("services.app_service.ModelManager.for_tenant") as mock_model_manager,
patch("services.app_service.SystemFeatureService") as mock_feature_service,
patch("services.app_service.EnterpriseService") as mock_enterprise_service,
):
mock_workflow_service.get_draft_workflow.return_value = None
mock_workflow_service.get_published_workflow_by_id.return_value = None
mock_workflow_service.return_value.get_draft_workflow.return_value = None
mock_workflow_service.return_value.sync_draft_workflow.return_value = None
mock_dependencies_service.generate_latest_dependencies.return_value = [] # type: ignore[assignment]
mock_dependencies_service.get_leaked_dependencies.return_value = [] # type: ignore[assignment]
mock_dependencies_service.generate_dependencies.return_value = [] # type: ignore[assignment]
mock_app_was_created.send.return_value = None
mock_model_instance = mock_model_manager.return_value
mock_model_instance.get_default_model_instance.return_value = None
mock_model_instance.get_default_provider_model_name.return_value = ("openai", "gpt-3.5-turbo")
mock_feature_service.is_webapp_auth_enabled.return_value = False
mock_enterprise_service.WebAppAuth.update_app_access_mode.return_value = None
mock_enterprise_service.WebAppAuth.cleanup_webapp.return_value = None
yield {"workflow_service": mock_workflow_service}
def _app_and_account(db_session: Session, *, mode: str = "chat") -> tuple[App, Account]:
fake = Faker()
with patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service:
mock_account_feature_service.is_registration_allowed.return_value = True
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session)
tenant = account.current_tenant
assert tenant is not None
app_args = CreateAppParams(
name=fake.company(),
description=fake.text(max_nb_chars=100),
mode=mode, # type: ignore[arg-type]
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
api_rph=100,
api_rpm=10,
)
app_model = AppService().create_app(tenant.id, app_args, account, session=db_session)
return app_model, account
class TestDslImport:
def test_invalid_dsl_maps_to_400_and_persists_nothing(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = AppDslImportApi()
body = AppDslImportPayload(mode="yaml-content", yaml_content="[]") # not a mapping
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
body=body,
)
assert code == 400
assert result.status == ImportStatus.FAILED
# A failed import must not leave an app behind.
assert db_session_with_containers.query(App).filter(App.tenant_id == tenant.id).count() == 0
def test_major_version_mismatch_maps_to_202_pending(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = AppDslImportApi()
body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(version="99.0.0"))
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
body=body,
)
assert code == 202
assert result.status == ImportStatus.PENDING
assert result.id # a pending import id the caller can confirm with
def test_valid_dsl_maps_to_200_completed(
self,
app: Flask,
db_session_with_containers: Session,
make_account: Callable[..., Account],
external_deps: dict[str, object],
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = AppDslImportApi()
body = AppDslImportPayload(mode="yaml-content", yaml_content=_workflow_yaml(name="Imported"))
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}/apps/imports", method="POST"):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
body=body,
)
assert code == 200
assert result.status in (ImportStatus.COMPLETED, ImportStatus.COMPLETED_WITH_WARNINGS)
assert result.app_id is not None
class TestDslImportConfirm:
def test_unknown_pending_import_maps_to_400(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""An expired/unknown import id has no Redis pending data → FAILED → 400."""
account = make_account()
tenant = account.current_tenant
assert tenant is not None
import_id = str(uuid4())
api = AppDslImportConfirmApi()
with app.test_request_context(
f"/openapi/v1/workspaces/{tenant.id}/apps/imports/{import_id}:confirm", method="POST"
):
result, code = cast(_Endpoint[tuple[Import, int]], api.post).__handler__(
api,
RequestContext("test-request", None, account.id, tenant.id),
tenant.id,
import_id,
)
assert code == 400
assert result.status == ImportStatus.FAILED
class TestDslExport:
def test_export_returns_dsl_yaml(
self, app: Flask, db_session_with_containers: Session, external_deps: dict[str, object]
) -> None:
app_model, account = _app_and_account(db_session_with_containers, mode="chat")
model_config = AppModelConfig(
app_id=app_model.id,
provider="openai",
model_id="gpt-3.5-turbo",
model=json.dumps({"provider": "openai", "name": "gpt-3.5-turbo", "mode": "chat", "completion_params": {}}),
pre_prompt="You are a helpful assistant.",
prompt_type="simple", # type: ignore[arg-type]
created_by=account.id,
updated_by=account.id,
)
model_config.id = str(uuid4())
app_model.app_model_config_id = model_config.id
db_session_with_containers.add(model_config)
db_session_with_containers.commit()
api = AppDslExportApi()
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"):
response, code = cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(
api,
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
app_model.id,
query=AppDslExportQuery(),
)
assert code == 200
assert isinstance(response, AppDslExportResponse)
parsed = yaml.safe_load(response.data)
assert parsed["kind"] == "app"
assert parsed["app"]["name"] == app_model.name
def test_export_workflow_app_without_draft_maps_to_404(
self, app: Flask, db_session_with_containers: Session
) -> None:
"""A workflow app with no draft workflow can't be exported → the service
raises WorkflowNotFoundError, which the controller maps to 404 draft_not_found."""
app_model = App(
id=str(uuid4()),
tenant_id=str(uuid4()),
name="Workflow without draft",
mode=AppMode.WORKFLOW,
enable_api=True,
enable_site=False,
)
db_session_with_containers.add(app_model)
db_session_with_containers.commit()
api = AppDslExportApi()
with (
app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dsl"),
pytest.raises(DraftNotFound) as exc_info,
):
cast(_Endpoint[tuple[AppDslExportResponse, int]], api.get).__handler__(
api,
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
app_model.id,
query=AppDslExportQuery(),
)
assert isinstance(exc_info.value.__cause__, WorkflowNotFoundError)
class TestDslCheckDependencies:
def test_check_dependencies_returns_result(
self, app: Flask, db_session_with_containers: Session, external_deps: dict[str, object]
) -> None:
app_model, account = _app_and_account(db_session_with_containers, mode="chat")
api = AppDslCheckDependenciesApi()
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/dependencies:check"):
result, code = cast(_Endpoint[tuple[CheckDependenciesResult, int]], api.get).__handler__(
api,
RequestContext("test-request", None, account.id, app_model.tenant_id),
app_model.id,
)
assert code == 200
assert result.leaked_dependencies == []
@@ -0,0 +1,55 @@
from __future__ import annotations
from collections.abc import Callable
from uuid import uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from controllers.openapi._errors import RunNotFound
from controllers.openapi.app_run import AppRunStopApi
from models import Account, App
from services.app_service import AppService, CreateAppParams
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
def _create_app(db_session: Session, account: Account, *, name: str = "Runner") -> App:
tenant = account.current_tenant
assert tenant is not None
params = CreateAppParams(
name=name,
description="",
mode="workflow",
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
)
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
db_session.commit()
return app_model
class TestAppRunStop:
def test_run_stop_rejects_an_unknown_run(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
app_model = _create_app(db_session_with_containers, account)
run_id = str(uuid4())
api = AppRunStopApi()
with (
app.test_request_context(f"/openapi/v1/apps/{app_model.id}/runs/{run_id}:stop", method="POST"),
pytest.raises(RunNotFound),
):
api.post.__handler__( # pyrefly: ignore[missing-attribute]
api,
context_for(
account,
session=db_session_with_containers,
view_args={"app_id": app_model.id, "run_id": run_id},
),
app_model.id,
run_id,
)
@@ -0,0 +1,161 @@
from __future__ import annotations
from collections.abc import Callable
from typing import Protocol, cast
from uuid import uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound
from controllers.openapi._models import AppDescribeQuery, AppDescribeResponse, AppListQuery, AppListResponse
from controllers.openapi.apps import AppDescribeApi, AppListApi
from machinery.context import AppRequestContext, RequestContext
from models import Account, App
from services.app_service import AppService, CreateAppParams
class _Endpoint[T](Protocol):
__handler__: Callable[..., T]
def _create_app(
db_session: Session,
account: Account,
*,
name: str,
enable_api: bool = True,
) -> App:
"""Create a workflow app in the account's owner tenant.
Workflow mode is used because its template seeds no ``model_config``, so
``AppService.create_app`` never reaches ``ModelManager`` — keeping the
fixture free of model-runtime patching.
"""
tenant = account.current_tenant
assert tenant is not None
params = CreateAppParams(
name=name,
description="",
mode="workflow",
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
)
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
# The openapi surface gate keys off ``enable_api``; flip it explicitly so
# the test states the visibility precondition rather than relying on the
# template default.
app_model.enable_api = enable_api
db_session.add(app_model)
db_session.commit()
return app_model
class TestAppList:
def test_lists_only_api_enabled_apps_in_workspace(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
visible = _create_app(db_session_with_containers, account, name="Visible", enable_api=True)
_create_app(db_session_with_containers, account, name="Hidden", enable_api=False)
api = AppListApi()
with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}"):
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
api,
RequestContext("request", None, account.id, tenant.id),
query=AppListQuery(workspace_id=str(tenant.id)),
)
# The api-disabled app is gated out, so it counts neither in `data`
# nor in `total` (the gate is pushed into the query for stable paging).
assert result.total == 1
assert [row.id for row in result.data] == [visible.id]
assert result.has_more is False
def test_uuid_name_filter_returns_matching_app(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
target = _create_app(db_session_with_containers, account, name="Target", enable_api=True)
api = AppListApi()
with app.test_request_context(f"/openapi/v1/apps?workspace_id={tenant.id}&name={target.id}"):
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
api,
RequestContext("request", None, account.id, tenant.id),
query=AppListQuery(workspace_id=str(tenant.id), name=str(target.id)),
)
assert result.total == 1
assert result.data[0].id == target.id
assert result.data[0].workspace_id == str(tenant.id)
def test_uuid_name_filter_for_foreign_app_returns_empty(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""A UUID that resolves to an app in another workspace must not leak
across tenants — the list returns empty rather than the foreign app."""
owner = make_account()
outsider = make_account()
foreign_app = _create_app(db_session_with_containers, owner, name="Foreign", enable_api=True)
outsider_tenant = outsider.current_tenant
assert outsider_tenant is not None
api = AppListApi()
with app.test_request_context(f"/openapi/v1/apps?workspace_id={outsider_tenant.id}&name={foreign_app.id}"):
result = cast(_Endpoint[AppListResponse], api.get).__handler__(
api,
RequestContext("request", None, outsider.id, outsider_tenant.id),
query=AppListQuery(workspace_id=str(outsider_tenant.id), name=str(foreign_app.id)),
)
assert result.total == 0
assert result.data == []
class TestAppDescribe:
def test_describe_info_returns_metadata(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
app_model = _create_app(db_session_with_containers, account, name="Describe Me", enable_api=True)
api = AppDescribeApi()
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}?fields=info"):
result = cast(_Endpoint[AppDescribeResponse], api.get).__handler__(
api,
AppRequestContext(tenant_id=app_model.tenant_id, app_id=app_model.id),
app_model.id,
query=AppDescribeQuery(fields="info"),
)
assert result.info is not None
assert result.info.id == app_model.id
assert result.info.name == "Describe Me"
assert result.info.service_api_enabled is True
# Only the requested block is materialized.
assert result.parameters is None
assert result.input_schema is None
def test_describe_unknown_app_is_404(self, app: Flask, make_account: Callable[..., Account]) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
missing_id = str(uuid4())
api = AppDescribeApi()
with app.test_request_context(f"/openapi/v1/apps/{missing_id}"):
with pytest.raises(NotFound):
cast(_Endpoint[AppDescribeResponse], api.get).__handler__(
api,
AppRequestContext(tenant_id=tenant.id, app_id=missing_id),
missing_id,
query=AppDescribeQuery(),
)
@@ -0,0 +1,68 @@
from __future__ import annotations
from collections.abc import Callable
from io import BytesIO
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.datastructures import FileStorage
from controllers.openapi._models import FileUploadPayload
from controllers.openapi.auth.requirements import CheckWorkspaceMember
from controllers.openapi.files import AppFileUploadApi
from models import Account, App
from services.app_service import AppService, CreateAppParams
from tests.e2e_tests.containers.controllers.openapi.conftest import context_for
def _create_app(db_session: Session, account: Account, *, name: str = "Uploader") -> App:
"""Create a workflow app (no model_config → no ModelManager) for the upload context."""
tenant = account.current_tenant
assert tenant is not None
params = CreateAppParams(
name=name,
description="",
mode="workflow",
icon_type="emoji",
icon="🤖",
icon_background="#FF6B6B",
)
app_model = AppService().create_app(tenant.id, params, account, session=db_session)
db_session.commit()
return app_model
class TestAppFileUpload:
def test_upload_persists_and_returns_metadata(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
app_model = _create_app(db_session_with_containers, account)
content = b"hello integration world"
api = AppFileUploadApi()
body = FileUploadPayload(
file=FileStorage(stream=BytesIO(content), filename="note.txt", content_type="text/plain")
)
with app.test_request_context(f"/openapi/v1/apps/{app_model.id}/files", method="POST"):
result = vars(api.post)["__handler__"](
api,
context_for(
account,
session=db_session_with_containers,
view_args={"app_id": app_model.id},
requirements=(CheckWorkspaceMember(),),
),
app_model.id,
body=body,
)
assert result.id
assert result.name == "note.txt"
assert result.size == len(content)
assert result.extension == "txt"
assert result.mime_type == "text/plain"
# Persisted under the caller's tenant.
assert result.tenant_id == str(tenant.id)
@@ -0,0 +1,95 @@
from __future__ import annotations
from collections.abc import Callable
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound
from controllers.openapi._models import WorkspaceListQuery
from controllers.openapi.workspaces import WorkspaceByIdApi, WorkspacesApi
from models import Account
from models.account import TenantAccountRole
from tests.e2e_tests.containers.controllers.openapi.conftest import add_tenant_for_account, context_for
class TestWorkspacesList:
def test_lists_only_members_workspaces_with_role(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
api = WorkspacesApi()
with app.test_request_context("/openapi/v1/workspaces"):
result = api.get.__handler__(
api, context_for(account, session=db_session_with_containers), query=WorkspaceListQuery()
)
ids = {w.id for w in result.data}
assert ids == {owner_tenant.id}
only = result.data[0]
assert only.role == TenantAccountRole.OWNER.value
assert only.status == "normal"
def test_lists_all_joined_workspaces(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
owner_tenant = account.current_tenant
assert owner_tenant is not None
second = add_tenant_for_account(account, session=db_session_with_containers, role="normal", name="Second WS")
api = WorkspacesApi()
with app.test_request_context("/openapi/v1/workspaces"):
result = api.get.__handler__(
api, context_for(account, session=db_session_with_containers), query=WorkspaceListQuery()
)
assert {w.id for w in result.data} == {owner_tenant.id, second.id}
class TestWorkspaceDetail:
def test_member_can_read_detail(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
account = make_account()
tenant = account.current_tenant
assert tenant is not None
api = WorkspaceByIdApi()
with app.test_request_context(f"/openapi/v1/workspaces/{tenant.id}"):
detail = api.get.__handler__(
api,
context_for(account, session=db_session_with_containers, view_args={"workspace_id": tenant.id}),
tenant.id,
)
assert detail.id == tenant.id
assert detail.role == TenantAccountRole.OWNER.value
assert detail.created_at is not None
def test_non_member_detail_is_404_not_403(
self, app: Flask, db_session_with_containers: Session, make_account: Callable[..., Account]
) -> None:
"""A workspace the caller doesn't belong to must be indistinguishable
from a missing one (404), so IDs can't be probed across tenants."""
owner = make_account()
outsider = make_account()
someone_elses_ws = owner.current_tenant
assert someone_elses_ws is not None
api = WorkspaceByIdApi()
with app.test_request_context(f"/openapi/v1/workspaces/{someone_elses_ws.id}"):
with pytest.raises(NotFound):
api.get.__handler__(
api,
context_for(
outsider,
session=db_session_with_containers,
view_args={"workspace_id": someone_elses_ws.id},
),
someone_elses_ws.id,
)
@@ -0,0 +1,638 @@
"""Real Service API HTTP admission, PostgreSQL, Redis and Celery publications.
Workers are not executed: the memory broker verifies published messages without
calling embedding providers or vector stores. Container execution belongs to CI.
"""
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass, replace
from queue import Empty
from typing import Literal
from uuid import UUID, uuid4
import pytest
from celery import Celery, Task
from celery.signals import before_task_publish
from flask import Flask, g
from flask_login import user_logged_in
from kombu.simple import SimpleQueue
from sqlalchemy import Connection, ExecutionContext, delete, event, func, select, text, update
from sqlalchemy.orm import Session, SessionTransaction, sessionmaker
from werkzeug.test import TestResponse
from constants import COOKIE_NAME_CSRF_TOKEN, HEADER_NAME_CSRF_TOKEN
from constants.resource_access_token import ResourceAccessTokenResourceType
from controllers.console.wraps import _is_setup_completed
from enums import DeploymentEdition
from enums.account import TenantAccountRole
from extensions.ext_application_services import ApplicationServices
from extensions.ext_database import db
from extensions.ext_redis import RedisClientWrapper
from libs.datetime_utils import naive_utc_now
from libs.passport import PassportService
from libs.token import generate_csrf_token
from machinery.context import RequestContext
from models import Account, App, Tenant
from models.account import AccountStatus, TenantAccountJoin, TenantStatus
from models.enums import ApiTokenType
from models.model import ApiToken, AppAnnotationSetting, DifySetup, EndUser, MessageAnnotation
from repositories.annotation_reply_job_repository import (
RedisAnnotationReplyJobRepository,
annotation_reply_job_owner_key,
)
from repositories.annotation_repository import AnnotationRepository
from services.annotation_command_service import AnnotationCommandService
from services.annotation_reply_service import AnnotationReplyAction, AnnotationReplyService
from services.api_token_service import ApiTokenCache
from services.auth.resource_access_token_contracts import ResourceAccessTokenCreateResult, ResourceAccessTokenResource
from tasks.annotation.add_annotation_to_index_task import add_annotation_to_index_task
from tasks.annotation.delete_annotation_index_task import delete_annotation_index_task
from tasks.annotation.disable_annotation_reply_task import disable_annotation_reply_task
from tasks.annotation.enable_annotation_reply_task import enable_annotation_reply_task
from tasks.annotation.update_annotation_to_index_task import update_annotation_to_index_task
from tests.helpers.unit.config_override import config_overrides_context
from tests.helpers.unit.model_factories import make_account, make_app
_REPLY_PAYLOAD: dict[str, object] = {
"score_threshold": 0.75,
"embedding_provider_name": "openai",
"embedding_model_name": "text-embedding-3-small",
}
_ANNOTATION_PAYLOAD: dict[str, object] = {"question": "Question", "answer": "Answer"}
_ENDPOINTS = [
("GET", "/annotations"),
("POST", "/annotations"),
("PUT", "/annotations/{id}"),
("DELETE", "/annotations/{id}"),
("POST", "/annotation-reply/enable"),
("GET", "/annotation-reply/enable/status/{id}"),
]
type Credential = Literal["key", "resource"]
@dataclass(frozen=True)
class _Harness:
app: Flask
services: ApplicationServices
account: Account
target: App
other: App
foreign: App
api_key: ApiToken
other_key: ApiToken
factory: sessionmaker[Session]
redis: RedisClientWrapper
celery: Celery
tasks: dict[str, Task[..., None]]
queue: str
sessions: list[Session]
publications: list[bool]
logins: list[object]
token_reads: list[str]
@property
def context(self) -> RequestContext:
return RequestContext("annotation-test", None, self.account.id, self.target.tenant_id)
def request(
self,
method: str,
path: str,
*,
payload: dict[str, object] | None = None,
token: str | None = None,
authorization: str | None = None,
app_id: str | None = None,
) -> TestResponse:
headers = {
"Authorization": authorization if authorization is not None else f"Bearer {token or self.api_key.token}"
}
if authorization == "":
headers.clear()
if app_id is not None:
headers["X-Dify-App-ID"] = app_id
with self.app.test_client() as client:
response = client.open(f"/v1/apps{path}", method=method, json=payload, headers=headers)
assert not isinstance(g.get("_login_user"), (Account, EndUser))
with self.factory() as session:
assert session.scalar(select(func.count()).select_from(EndUser)) == 0
if response.status_code != 204:
assert response.headers["Content-Type"] == "application/json"
assert all(not session.in_transaction() and not session.identity_map for session in self.sessions)
assert self.logins == []
return response
def resource_token(self, *app_ids: str) -> ResourceAccessTokenCreateResult:
return self.services.resource_access_tokens.create(
self.context,
name="Annotation integration key",
resources=tuple(
ResourceAccessTokenResource(type=ResourceAccessTokenResourceType.APP, id=app_id)
for app_id in app_ids or (self.target.id,)
),
)
def credential(self, kind: Credential) -> str:
return self.api_key.token if kind == "key" else self.resource_token().token
def consume_task(self, name: str, expected: dict[str, object]) -> None:
with self.celery.connection_for_read() as connection, SimpleQueue(connection, self.queue) as messages:
message = messages.get(block=False)
assert message.headers["task"] == self.tasks[name].name
assert message.payload[0] == []
assert message.payload[1] == expected
message.ack()
with pytest.raises(Empty):
messages.get(block=False)
@pytest.fixture
def harness(flask_app_with_containers: Flask) -> Iterator[_Harness]:
app = flask_app_with_containers
services = app.extensions["application_services"]
assert isinstance(services, ApplicationServices)
redis = app.extensions["redis"]
assert isinstance(redis, RedisClientWrapper)
with app.app_context():
engine = db.engine
factory = sessionmaker(bind=engine, expire_on_commit=False)
workspace = Tenant(name="Service API annotation workspace")
foreign_workspace = Tenant(name="Other annotation workspace")
account = make_account(account_id=str(uuid4()), email=f"{uuid4()}@example.com")
account.last_active_at = naive_utc_now()
target = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
other = make_app(app_id=str(uuid4()), tenant_id=workspace.id)
foreign = make_app(app_id=str(uuid4()), tenant_id=foreign_workspace.id)
api_key = ApiToken(app_id=target.id, tenant_id=workspace.id, type=ApiTokenType.APP, token=f"app-{uuid4()}")
other_key = ApiToken(app_id=other.id, tenant_id=workspace.id, type=ApiTokenType.APP, token=f"app-{uuid4()}")
with factory.begin() as session:
session.add_all(
[
workspace,
foreign_workspace,
account,
target,
other,
foreign,
api_key,
other_key,
TenantAccountJoin(
tenant_id=workspace.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True
),
DifySetup(version="test"),
]
)
queue = f"service-api-annotation-{uuid4()}"
celery = Celery(queue, broker="memory://", set_as_current=False)
celery.conf.update(task_default_queue=queue, task_ignore_result=True, task_publish_retry=False)
tasks: dict[str, Task[..., None]] = {
"add": celery.task(name=add_annotation_to_index_task.name, shared=False)(add_annotation_to_index_task.run),
"update": celery.task(name=update_annotation_to_index_task.name, shared=False)(
update_annotation_to_index_task.run
),
"delete": celery.task(name=delete_annotation_index_task.name, shared=False)(delete_annotation_index_task.run),
"enable": celery.task(name=enable_annotation_reply_task.name, shared=False)(enable_annotation_reply_task.run),
"disable": celery.task(name=disable_annotation_reply_task.name, shared=False)(
disable_annotation_reply_task.run
),
}
annotations = AnnotationRepository(session_factory=factory)
app.extensions["application_services"] = replace(
services,
annotation_queries=annotations,
annotation_commands=AnnotationCommandService(
annotations=annotations,
add_index=tasks["add"].delay,
update_index=tasks["update"].delay,
delete_index=tasks["delete"].delay,
),
annotation_reply=AnnotationReplyService(
apps=annotations,
jobs=RedisAnnotationReplyJobRepository(redis=redis),
enable_task=tasks["enable"].delay,
disable_task=tasks["disable"].delay,
),
)
sessions: list[Session] = []
publications: list[bool] = []
logins: list[object] = []
token_reads: list[str] = []
def track(session: Session, _transaction: SessionTransaction, _connection: Connection) -> None:
sessions.append(session)
def observe_publish(**_kwargs: object) -> None:
publications.append(all(not session.in_transaction() and not session.identity_map for session in sessions))
def observe_login(_sender: object, user: object) -> None:
logins.append(user)
def observe_query(
_connection: Connection,
_cursor: object,
statement: str,
_parameters: object,
_context: ExecutionContext,
_executemany: bool,
) -> None:
if statement.lstrip().upper().startswith("SELECT") and "api_tokens" in statement:
token_reads.append(statement)
event.listen(Session, "after_begin", track)
event.listen(engine, "before_cursor_execute", observe_query)
before_task_publish.connect(observe_publish, weak=True)
user_logged_in.connect(observe_login, weak=True)
_is_setup_completed.reset_success()
try:
with config_overrides_context(
DEPLOYMENT_EDITION=DeploymentEdition.COMMUNITY,
SECRET_KEY="service-api-annotation-passport-key-32-bytes",
LOGIN_DISABLED=False,
INIT_PASSWORD="",
CONSOLE_API_URL="http://localhost",
CONSOLE_WEB_URL="http://localhost",
COOKIE_DOMAIN="",
RBAC_ENABLED=False,
):
with app.app_context():
assert _is_setup_completed()
db.session.remove()
yield _Harness(
app,
services,
account,
target,
other,
foreign,
api_key,
other_key,
factory,
redis,
celery,
tasks,
queue,
sessions,
publications,
logins,
token_reads,
)
finally:
app.extensions["application_services"] = services
del observe_publish
user_logged_in.disconnect(observe_login)
event.remove(Session, "after_begin", track)
event.remove(engine, "before_cursor_execute", observe_query)
with celery.connection_for_read() as connection, SimpleQueue(connection, queue) as messages:
messages.clear()
celery.close()
_is_setup_completed.reset_success()
with app.app_context():
db.session.remove()
@pytest.mark.parametrize("credential", ["key", "resource"])
def test_crud_publishes_scoped_index_tasks_after_sessions_close(harness: _Harness, credential: Credential) -> None:
token = harness.credential(credential)
binding_id = str(uuid4())
with harness.factory.begin() as session:
session.add(
AppAnnotationSetting(
app_id=harness.target.id,
score_threshold=0.75,
collection_binding_id=binding_id,
created_user_id=harness.account.id,
updated_user_id=harness.account.id,
)
)
created = harness.request("POST", "/annotations", payload=_ANNOTATION_PAYLOAD, token=token)
assert created.status_code == 201
body = created.get_json()
annotation_id = body["id"]
assert str(UUID(annotation_id)) == annotation_id
assert body == {
"id": annotation_id,
"question": "Question",
"answer": "Answer",
"hit_count": 0,
"created_at": body["created_at"],
}
assert isinstance(body["created_at"], int)
task_scope: dict[str, object] = {
"annotation_id": annotation_id,
"tenant_id": harness.target.tenant_id,
"app_id": harness.target.id,
"collection_binding_id": binding_id,
}
harness.consume_task("add", {**task_scope, "question": "Question"})
listed = harness.request("GET", "/annotations", token=token)
assert listed.status_code == 200
assert listed.get_json() == {"data": [body], "has_more": False, "limit": 20, "total": 1, "page": 1}
updated = harness.request(
"PUT", f"/annotations/{annotation_id}", payload={"question": "", "answer": "Updated answer"}, token=token
)
assert updated.status_code == 200
assert updated.get_json() == {**body, "question": "", "answer": "Updated answer"}
harness.consume_task("update", {**task_scope, "question": "Updated answer"})
with harness.factory() as session:
annotation = session.get(MessageAnnotation, annotation_id)
assert annotation is not None
assert (annotation.question, annotation.content, annotation.account_id) == (
"",
"Updated answer",
harness.account.id,
)
removed = harness.request("DELETE", f"/annotations/{annotation_id}", token=token)
assert removed.status_code == 204
assert removed.data == b""
harness.consume_task("delete", task_scope)
assert harness.publications == [True, True, True]
with harness.factory() as session:
assert session.get(MessageAnnotation, annotation_id) is None
assert harness.request("GET", "/annotations", token=token).get_json()["total"] == 0
@pytest.mark.parametrize(("question", "answer"), [("", ""), ("", "Answer"), ("Question", "")])
def test_create_preserves_service_api_empty_strings(harness: _Harness, question: str, answer: str) -> None:
response = harness.request("POST", "/annotations", payload={"question": question, "answer": answer})
assert response.status_code == 201
body = response.get_json()
assert body["question"] == question
assert body["answer"] == answer
with harness.factory() as session:
annotation = session.get(MessageAnnotation, body["id"])
assert annotation is not None
assert (annotation.question, annotation.content, annotation.account_id) == (
question,
answer,
harness.account.id,
)
assert harness.publications == []
def test_list_scopes_annotations_and_preserves_pagination_and_literal_search(harness: _Harness) -> None:
with harness.factory.begin() as session:
session.add_all(
MessageAnnotation(app_id=app_id, question=question, content="Answer", account_id=harness.account.id)
for app_id, question in (
(harness.target.id, "100% complete"),
(harness.target.id, "Ordinary question"),
(harness.other.id, "Other app 100% complete"),
(harness.foreign.id, "Foreign workspace 100% complete"),
)
)
first = harness.request("GET", "/annotations?page=1&limit=1").get_json()
second = harness.request("GET", "/annotations?page=2&limit=1").get_json()
assert (first["total"], first["page"], first["limit"], first["has_more"]) == (2, 1, 1, True)
assert (second["total"], second["page"], second["limit"], second["has_more"]) == (2, 2, 1, False)
assert first["data"][0]["id"] != second["data"][0]["id"]
filtered = harness.request("GET", "/annotations?keyword=%25&limit=999").get_json()
assert (filtered["total"], filtered["limit"], filtered["has_more"]) == (1, 100, False)
assert filtered["data"][0]["question"] == "100% complete"
@pytest.mark.parametrize("method", ["PUT", "DELETE"])
@pytest.mark.parametrize("scope", ["app", "tenant"])
def test_annotation_mutations_reject_other_owners(harness: _Harness, method: str, scope: str) -> None:
annotation = MessageAnnotation(
app_id=harness.other.id if scope == "app" else harness.foreign.id,
question="Other question",
content="Other answer",
account_id=harness.account.id,
)
with harness.factory.begin() as session:
session.add(annotation)
response = harness.request(method, f"/annotations/{annotation.id}", payload=_ANNOTATION_PAYLOAD)
assert response.status_code == 404
assert response.get_json()["code"] == "not_found"
assert harness.publications == []
with harness.factory() as session:
preserved = session.get(MessageAnnotation, annotation.id)
assert preserved is not None
assert (preserved.question, preserved.content) == ("Other question", "Other answer")
@pytest.mark.parametrize(("method", "path"), _ENDPOINTS)
@pytest.mark.parametrize("credential_state", ["missing", "invalid", "revoked"])
def test_every_handler_requires_a_valid_bearer_key(
harness: _Harness, method: str, path: str, credential_state: str
) -> None:
authorization = "" if credential_state == "missing" else f"Bearer app-{uuid4()}"
if credential_state == "revoked":
assert harness.request("GET", "/annotations").status_code == 200
harness.services.app_api_keys.delete_key(harness.context, harness.target.id, harness.api_key.id)
authorization = f"Bearer {harness.api_key.token}"
response = harness.request(
method, path.format(id=uuid4()), payload={**_ANNOTATION_PAYLOAD, **_REPLY_PAYLOAD}, authorization=authorization
)
assert response.status_code == 401
assert response.get_json()["code"] == "unauthorized"
assert harness.publications == []
def test_api_key_cache_hit_avoids_token_query_and_revocation_invalidates_cache(harness: _Harness) -> None:
assert harness.request("GET", "/annotations").status_code == 200
assert len(harness.token_reads) == 1
cached = ApiTokenCache.get(harness.api_key.token, "app")
assert cached is not None
assert (cached.id, cached.app_id) == (harness.api_key.id, harness.target.id)
assert harness.request("GET", "/annotations").status_code == 200
assert len(harness.token_reads) == 1
harness.services.app_api_keys.delete_key(harness.context, harness.target.id, harness.api_key.id)
response = harness.request("GET", "/annotations")
assert response.status_code == 401
assert response.get_json()["code"] == "unauthorized"
@pytest.mark.parametrize(
("state", "status", "code"),
[
("app_missing", 403, "app_not_found"),
("api_disabled", 403, "app_api_disabled"),
("app_abnormal", 403, "app_abnormal_status"),
("tenant_missing", 403, "workspace_not_found"),
("tenant_archived", 403, "workspace_archived"),
("owner_role", 401, "unauthorized"),
("owner_missing", 401, "unauthorized"),
],
)
def test_cached_key_rechecks_application_workspace_and_owner(
harness: _Harness, state: str, status: int, code: str
) -> None:
assert harness.request("GET", "/annotations").status_code == 200
with harness.factory.begin() as session:
match state:
case "app_missing":
session.execute(delete(App).where(App.id == harness.target.id))
case "api_disabled":
session.execute(update(App).where(App.id == harness.target.id).values(enable_api=False))
case "app_abnormal":
session.execute(text("UPDATE apps SET status = 'disabled' WHERE id = :id"), {"id": harness.target.id})
case "tenant_missing":
session.execute(delete(Tenant).where(Tenant.id == harness.target.tenant_id))
case "tenant_archived":
session.execute(
update(Tenant).where(Tenant.id == harness.target.tenant_id).values(status=TenantStatus.ARCHIVE)
)
case "owner_role":
session.execute(
update(TenantAccountJoin)
.where(TenantAccountJoin.account_id == harness.account.id)
.values(role=TenantAccountRole.EDITOR)
)
case "owner_missing":
session.execute(delete(Account).where(Account.id == harness.account.id))
response = harness.request("GET", "/annotations")
assert response.status_code == status
assert response.get_json()["code"] == code
assert harness.publications == []
@pytest.mark.parametrize("token_scope", ["matching", "legacy_missing", "foreign"])
def test_api_key_admission_checks_token_workspace_and_preserves_legacy_keys(
harness: _Harness, token_scope: str
) -> None:
tenant_id = {
"matching": harness.target.tenant_id,
"legacy_missing": None,
"foreign": harness.foreign.tenant_id,
}[token_scope]
with harness.factory.begin() as session:
session.execute(update(ApiToken).where(ApiToken.id == harness.api_key.id).values(tenant_id=tenant_id))
for _ in range(2):
response = harness.request("POST", "/annotations", payload=_ANNOTATION_PAYLOAD)
if token_scope == "foreign":
assert response.status_code == 403
assert response.get_json()["code"] == "app_not_found"
else:
assert response.status_code == 201
with harness.factory() as session:
annotation = session.get(MessageAnnotation, response.get_json()["id"])
assert annotation is not None
assert (annotation.app_id, annotation.account_id) == (harness.target.id, harness.account.id)
assert len(harness.token_reads) == 1
assert harness.publications == []
def test_api_key_admission_does_not_require_console_account_login_state(harness: _Harness) -> None:
with harness.factory.begin() as session:
session.execute(update(Account).where(Account.id == harness.account.id).values(status=AccountStatus.BANNED))
session.execute(
update(TenantAccountJoin).where(TenantAccountJoin.account_id == harness.account.id).values(current=False)
)
response = harness.request("POST", "/annotations", payload=_ANNOTATION_PAYLOAD)
assert response.status_code == 201
assert harness.publications == []
def test_resource_token_selection_and_revocation(harness: _Harness) -> None:
resource = harness.resource_token(harness.target.id, harness.other.id)
missing_selection = harness.request("GET", "/annotations", token=resource.token)
assert missing_selection.status_code == 400
assert missing_selection.get_json()["code"] == "invalid_param"
forbidden = harness.request("GET", "/annotations", token=resource.token, app_id=harness.foreign.id)
assert forbidden.status_code == 403
assert forbidden.get_json()["code"] == "forbidden"
created = harness.request(
"POST", "/annotations", token=resource.token, app_id=harness.other.id, payload=_ANNOTATION_PAYLOAD
)
assert created.status_code == 201
assert (
harness.request("GET", "/annotations", token=resource.token, app_id=harness.target.id).get_json()["total"] == 0
)
assert (
harness.request("GET", "/annotations", token=resource.token, app_id=harness.other.id).get_json()["total"] == 1
)
harness.services.resource_access_tokens.delete_relation(
harness.context, token_id=resource.token_id, relation_id=resource.rows[0].relation_id
)
assert harness.request("GET", "/annotations", token=resource.token, app_id=harness.other.id).status_code == 401
@pytest.mark.parametrize("action", ["enable", "disable"])
@pytest.mark.parametrize("credential", ["key", "resource"])
def test_reply_jobs_share_console_ownership_and_publish_after_sessions_close(
harness: _Harness, action: AnnotationReplyAction, credential: Credential
) -> None:
token = harness.credential(credential)
response = harness.request("POST", f"/annotation-reply/{action}", payload=_REPLY_PAYLOAD, token=token)
assert response.status_code == 200
body = response.get_json()
job_id = body["job_id"]
assert str(UUID(job_id)) == job_id
assert body == {"job_id": job_id, "job_status": "waiting"}
assert harness.redis.get(annotation_reply_job_owner_key(action=action, job_id=job_id)) == (
f"{harness.target.tenant_id}:{harness.target.id}".encode()
)
expected: dict[str, object] = {"job_id": job_id, "app_id": harness.target.id, "tenant_id": harness.target.tenant_id}
if action == "enable":
expected.update(_REPLY_PAYLOAD, user_id=harness.account.id)
harness.consume_task(action, expected)
assert harness.publications == [True]
status = harness.request("GET", f"/annotation-reply/{action}/status/{job_id}", token=token)
assert status.status_code == 200
expected_status = {"job_id": job_id, "job_status": "waiting", "error_msg": ""}
assert status.get_json() == expected_status
client = harness.app.test_client()
csrf = generate_csrf_token(harness.account.id)
client.set_cookie(COOKIE_NAME_CSRF_TOKEN, csrf)
console_status = client.get(
f"/console/api/apps/{harness.target.id}/annotation-reply/{action}/status/{job_id}",
headers={
HEADER_NAME_CSRF_TOKEN: csrf,
"Authorization": f"Bearer {PassportService().issue({'user_id': harness.account.id})}",
},
)
assert console_status.status_code == 200
assert console_status.get_json() == expected_status
@pytest.mark.parametrize("action", ["enable", "disable"])
@pytest.mark.parametrize("mismatch", ["app", "tenant", "action", "legacy", "missing"])
def test_reply_status_rejects_unverifiable_ownership(
harness: _Harness, action: AnnotationReplyAction, mismatch: str
) -> None:
job_id = str(uuid4())
stored_action: AnnotationReplyAction = (
("disable" if action == "enable" else "enable") if mismatch == "action" else action
)
if mismatch != "missing":
harness.redis.set(f"{stored_action}_app_annotation_job_{job_id}", "completed")
if mismatch not in {"legacy", "missing"}:
tenant_id = str(uuid4()) if mismatch == "tenant" else harness.target.tenant_id
harness.redis.set(
annotation_reply_job_owner_key(action=stored_action, job_id=job_id), f"{tenant_id}:{harness.target.id}"
)
response = harness.request(
"GET",
f"/annotation-reply/{action}/status/{job_id}",
token=harness.other_key.token if mismatch == "app" else harness.api_key.token,
)
assert response.status_code == 404
assert response.get_json()["code"] == "not_found"
assert response.get_json()["message"] == "The job does not exist."
assert harness.publications == []
@@ -0,0 +1,52 @@
"""Container integration coverage for Service API dataset controllers."""
from unittest.mock import MagicMock, patch
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from models.account import Account
from models.enums import TagType
from models.model import Tag
from tests.e2e_tests.containers.controllers.console.helpers import create_console_account_and_tenant
@pytest.fixture
def app(flask_app_with_containers: Flask) -> Flask:
return flask_app_with_containers
class TestDatasetTagsApiGet:
"""Exercise the unmocked tag query against the container database."""
@patch("controllers.service_api.dataset.dataset.current_user")
def test_list_tags_from_db(
self,
mock_current_user: MagicMock,
app: Flask,
db_session_with_containers: Session,
) -> None:
account, tenant = create_console_account_and_tenant(db_session_with_containers)
tag = Tag(
name="Integration Tag",
type=TagType.KNOWLEDGE,
created_by=account.id,
tenant_id=tenant.id,
)
db_session_with_containers.add(tag)
db_session_with_containers.commit()
mock_current_user.__class__ = Account
mock_current_user.current_tenant_id = tenant.id
from controllers.service_api.dataset.dataset import DatasetTagsApi
with app.test_request_context("/datasets/tags", method="GET"):
response, status = DatasetTagsApi().get(_=None)
assert status == 200
assert isinstance(response, list)
assert any(item["name"] == "Integration Tag" for item in response)
assert all(set(item) == {"id", "name", "type", "binding_count"} for item in response)
assert all(isinstance(item["binding_count"], str) for item in response)
@@ -0,0 +1,153 @@
"""DB-backed integration tests for service API dataset segment endpoints."""
from __future__ import annotations
from uuid import uuid4
from flask.testing import FlaskClient
from sqlalchemy.orm import Session
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
from models.dataset import ChildChunk, Dataset, Document, DocumentSegment, DocumentSegmentSummary
from models.enums import (
ApiTokenType,
DataSourceType,
DocumentCreatedFrom,
IndexingStatus,
SegmentStatus,
SegmentType,
SummaryStatus,
)
from models.model import ApiToken
from tests.e2e_tests.containers.controllers.console.helpers import create_console_account_and_tenant
def _create_dataset_graph(db_session: Session) -> tuple[Dataset, Document, DocumentSegment]:
account, tenant = create_console_account_and_tenant(db_session)
dataset = Dataset(
tenant_id=tenant.id,
name=f"Segment Dataset {uuid4()}",
description="Segment integration dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
indexing_technique=IndexTechniqueType.ECONOMY,
created_by=account.id,
permission="only_me",
provider="vendor",
enable_api=True,
)
db_session.add(dataset)
db_session.commit()
document = Document(
tenant_id=tenant.id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=f"batch-{uuid4()}",
name="segment-doc.txt",
created_from=DocumentCreatedFrom.API,
created_by=account.id,
enabled=True,
archived=False,
indexing_status=IndexingStatus.COMPLETED,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
word_count=4,
tokens=5,
)
db_session.add(document)
db_session.commit()
segment = DocumentSegment(
tenant_id=tenant.id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Segment content for integration",
word_count=4,
tokens=5,
keywords=["segment", "integration"],
status=SegmentStatus.COMPLETED,
created_by=account.id,
)
db_session.add(segment)
db_session.commit()
summary = DocumentSegmentSummary(
dataset_id=dataset.id,
document_id=document.id,
chunk_id=segment.id,
summary_content="DB summary",
status=SummaryStatus.COMPLETED,
)
db_session.add(summary)
api_token = ApiToken(
tenant_id=tenant.id,
type=ApiTokenType.DATASET,
token=f"dataset-{uuid4().hex}",
)
db_session.add(api_token)
db_session.commit()
return dataset, document, segment
def _auth_headers(db_session: Session, dataset: Dataset) -> dict[str, str]:
token = db_session.query(ApiToken).filter_by(tenant_id=dataset.tenant_id, type=ApiTokenType.DATASET).one()
return {"Authorization": f"Bearer {token.token}"}
def test_list_segments_uses_real_services_and_service_api_shape(
test_client_with_containers: FlaskClient,
db_session_with_containers: Session,
) -> None:
dataset, document, segment = _create_dataset_graph(db_session_with_containers)
segment_id = segment.id
response = test_client_with_containers.get(
f"/v1/datasets/{dataset.id}/documents/{document.id}/segments"
"?page=1&limit=20&status=completed&keyword=integration",
headers=_auth_headers(db_session_with_containers, dataset),
)
assert response.status_code == 200
body = response.get_json()
assert set(body) == {"data", "doc_form", "total", "has_more", "limit", "page"}
assert body["doc_form"] == "text_model"
assert body["total"] == 1
assert "total_pages" not in body
assert body["data"][0]["id"] == segment_id
assert body["data"][0]["summary"] == "DB summary"
assert body["data"][0]["attachments"] == []
assert body["data"][0]["child_chunks"] == []
def test_list_child_chunks_uses_real_segment_service(
test_client_with_containers: FlaskClient,
db_session_with_containers: Session,
) -> None:
dataset, document, segment = _create_dataset_graph(db_session_with_containers)
child_chunk = ChildChunk(
tenant_id=dataset.tenant_id,
dataset_id=dataset.id,
document_id=document.id,
segment_id=segment.id,
position=1,
content="Child integration content",
word_count=3,
type=SegmentType.CUSTOMIZED,
created_by=document.created_by,
)
db_session_with_containers.add(child_chunk)
db_session_with_containers.commit()
response = test_client_with_containers.get(
f"/v1/datasets/{dataset.id}/documents/{document.id}/segments/{segment.id}/child_chunks"
"?page=1&limit=20&keyword=integration",
headers=_auth_headers(db_session_with_containers, dataset),
)
assert response.status_code == 200
body = response.get_json()
assert set(body) == {"data", "total", "total_pages", "page", "limit"}
assert body["total"] == 1
assert body["data"][0]["content"] == "Child integration content"
@@ -0,0 +1,237 @@
from __future__ import annotations
import json
from datetime import UTC, datetime, timedelta
from uuid import uuid4
import pytest
from flask.testing import FlaskClient
from sqlalchemy import Engine
from sqlalchemy.orm import Session, sessionmaker
from core.app.app_config.entities import WorkflowUIBasedAppConfig
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom, WorkflowAppGenerateEntity
from core.app.layers.pause_state_persist_layer import WorkflowResumptionContext, _WorkflowGenerateEntityWrapper
from core.workflow.human_input_adapter import DeliveryMethodType
from core.workflow.nodes.human_input.entities import (
FormDefinition,
SelectInputConfig,
StringListSource,
UserActionConfig,
)
from core.workflow.nodes.human_input.enums import HumanInputFormKind, HumanInputFormStatus, ValueSourceType
from core.workflow.nodes.human_input.pause_reason import HumanInputRequired
from graphon.enums import WorkflowExecutionStatus
from graphon.runtime import RuntimeState, VariablePool
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.human_input import (
HumanInputDelivery,
HumanInputForm,
HumanInputFormRecipient,
RecipientType,
StandaloneWebAppRecipientPayload,
)
from models.model import App, AppMode, CustomizeTokenStrategy, IconType, Site
from models.workflow import WorkflowRun, WorkflowType
from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
from services.entities.feature_entities import FeatureModel
def _create_app_with_site(session: Session) -> tuple[App, Account]:
tenant = Tenant(name="Test Tenant")
account = Account(name="Tester", email=f"tester-{uuid4()}@example.com")
session.add_all([tenant, account])
session.flush()
session.add(
TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
current=True,
role=TenantAccountRole.OWNER,
)
)
app = App(
tenant_id=tenant.id,
name="Test App",
description="",
mode=AppMode.WORKFLOW,
icon_type=IconType.EMOJI,
icon="app",
icon_background="#ffffff",
enable_site=True,
enable_api=True,
created_by=account.id,
updated_by=account.id,
)
session.add(app)
session.flush()
site = Site(
app_id=app.id,
title="Test Site",
icon_type=IconType.EMOJI,
icon="robot",
icon_background="#ffffff",
description="desc",
default_language="en",
chat_color_theme="light",
chat_color_theme_inverted=False,
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
code=f"code-{uuid4().hex[:8]}",
prompt_public=False,
show_workflow_steps=True,
use_icon_as_answer_icon=False,
)
session.add(site)
session.flush()
return app, account
def _build_resumption_context(*, app: App, workflow_run: WorkflowRun, options: list[str]) -> WorkflowResumptionContext:
app_config = WorkflowUIBasedAppConfig(
tenant_id=app.tenant_id,
app_id=app.id,
app_mode=AppMode.WORKFLOW,
workflow_id=workflow_run.workflow_id,
)
generate_entity = WorkflowAppGenerateEntity(
user_from=UserFrom.END_USER,
task_id="task-1",
app_config=app_config,
inputs={},
files=[],
user_id=str(uuid4()),
stream=True,
invoke_from=InvokeFrom.WEB_APP,
call_depth=0,
workflow_execution_id=workflow_run.id,
)
runtime_state = RuntimeState(workflow_id="test-workflow", variable_pool=VariablePool(), start_at=0.0)
runtime_state.variable_pool.add(("start", "options"), options)
return WorkflowResumptionContext(
generate_entity=_WorkflowGenerateEntityWrapper(entity=generate_entity),
serialized_graph_runtime_state=runtime_state.dumps(),
)
def test_get_human_input_form_resolves_runtime_select_options(
db_session_with_containers: Session,
test_client_with_containers: FlaskClient,
monkeypatch: pytest.MonkeyPatch,
) -> None:
app, account = _create_app_with_site(db_session_with_containers)
workflow_run = WorkflowRun(
tenant_id=app.tenant_id,
app_id=app.id,
workflow_id=str(uuid4()),
type=WorkflowType.WORKFLOW,
triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
version="v1",
graph=None,
inputs="{}",
status=WorkflowExecutionStatus.RUNNING,
outputs="{}",
error=None,
elapsed_time=0.0,
total_tokens=0,
total_steps=0,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=account.id,
)
workflow_run.created_at = datetime.now(UTC).replace(tzinfo=None)
db_session_with_containers.add(workflow_run)
db_session_with_containers.flush()
configured_input = SelectInputConfig(
output_variable_name="decision",
option_source=StringListSource(
type=ValueSourceType.VARIABLE,
selector=["start", "options"],
value=["configured"],
),
)
expiration_time = datetime.now(UTC).replace(tzinfo=None) + timedelta(hours=1)
form_definition = FormDefinition(
form_content="Choose",
rendered_content="Choose",
inputs=[configured_input],
user_actions=[UserActionConfig(id="approve", title="Approve")],
expiration_time=expiration_time,
)
form = HumanInputForm(
tenant_id=app.tenant_id,
app_id=app.id,
workflow_run_id=workflow_run.id,
form_kind=HumanInputFormKind.RUNTIME,
node_id="human-node",
form_definition=form_definition.model_dump_json(),
rendered_content="Choose",
status=HumanInputFormStatus.WAITING,
expiration_time=expiration_time,
)
db_session_with_containers.add(form)
db_session_with_containers.flush()
delivery = HumanInputDelivery(
form_id=form.id,
delivery_method_type=DeliveryMethodType.WEBAPP,
channel_payload="{}",
)
db_session_with_containers.add(delivery)
db_session_with_containers.flush()
access_token = f"hitl{uuid4().hex[:18]}"
recipient = HumanInputFormRecipient(
form_id=form.id,
delivery_id=delivery.id,
recipient_type=RecipientType.STANDALONE_WEB_APP,
recipient_payload=StandaloneWebAppRecipientPayload().model_dump_json(),
access_token=access_token,
)
db_session_with_containers.add(recipient)
db_session_with_containers.commit()
context = _build_resumption_context(
app=app,
workflow_run=workflow_run,
options=["approve", "reject"],
)
reason = HumanInputRequired(
form_id=form.id,
form_content="Choose",
inputs=[configured_input],
actions=[UserActionConfig(id="approve", title="Approve")],
node_id="human-node",
node_title="Human Input",
)
engine = db_session_with_containers.get_bind()
assert isinstance(engine, Engine)
workflow_run_repo = DifyAPISQLAlchemyWorkflowRunRepository(
session_maker=sessionmaker(bind=engine, expire_on_commit=False)
)
workflow_run_repo.create_workflow_pause(
workflow_run_id=workflow_run.id,
state_owner_user_id=account.id,
state=context.dumps(),
pause_reasons=[reason],
)
def mock_get_features(tenant_id: str, exclude_vector_space: bool = False) -> FeatureModel:
features = FeatureModel(can_replace_logo=True, webapp_copyright_enabled=True)
return features
monkeypatch.setattr(
"controllers.web.human_input_form.FeatureService.get_features",
mock_get_features,
)
response = test_client_with_containers.get(f"/api/form/human_input/{access_token}")
assert response.status_code == 200, response.get_data(as_text=True)
body = json.loads(response.get_data(as_text=True))
assert body["inputs"][0]["option_source"]["type"] == "constant"
assert body["inputs"][0]["option_source"]["selector"] == []
assert body["inputs"][0]["option_source"]["value"] == ["approve", "reject"]
@@ -0,0 +1,32 @@
"""Web login rejection with the account application service and real persistence."""
from uuid import uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import Unauthorized
from configs import dify_config
from controllers.console import wraps
from controllers.web.login import EmailCodeLoginSendEmailApi
from enums import DeploymentEdition
from models.account import Account, AccountStatus
def test_email_code_login_rejects_persisted_banned_account(
flask_app_with_containers: Flask, db_session_with_containers: Session, monkeypatch: pytest.MonkeyPatch
) -> None:
account = Account(name="Banned", email=f"banned-{uuid4()}@example.com", status=AccountStatus.BANNED)
db_session_with_containers.add(account)
db_session_with_containers.commit()
monkeypatch.setattr(dify_config, "DEPLOYMENT_EDITION", DeploymentEdition.ENTERPRISE)
monkeypatch.setattr(wraps, "_is_setup_completed", lambda: True)
with (
flask_app_with_containers.test_request_context(
"/api/email-code-login", method="POST", json={"email": account.email, "language": "en-US"}
),
pytest.raises(Unauthorized, match="Account is banned."),
):
EmailCodeLoginSendEmailApi().post()
@@ -0,0 +1,247 @@
"""Testcontainers integration tests for controllers.web.site endpoints."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from controllers.web.error import WebAppNotFoundError
from controllers.web.site import AppSiteApi, WebAppSiteResponse, WebModelConfigResponse
from models import Tenant, TenantStatus
from models.account import TenantCustomConfigDict
from models.model import App, AppMode, AppModelConfig, CustomizeTokenStrategy, EndUser, Site
from services.entities.feature_entities import FeatureModel
@pytest.fixture
def app(flask_app_with_containers: Flask) -> Flask:
return flask_app_with_containers
def _create_tenant(db_session: Session, *, status: TenantStatus = TenantStatus.NORMAL) -> Tenant:
tenant = Tenant(name="test-tenant", status=status)
db_session.add(tenant)
db_session.commit()
return tenant
def _create_app(db_session: Session, tenant_id: str, *, enable_site: bool = True) -> App:
app_model = App(
tenant_id=tenant_id,
mode=AppMode.CHAT,
name="test-app",
enable_site=enable_site,
enable_api=True,
)
db_session.add(app_model)
db_session.commit()
return app_model
def _create_site(db_session: Session, app_id: str) -> Site:
site = _site_model(app_id=app_id)
db_session.add(site)
db_session.commit()
return site
def _end_user(tenant_id: str, app_id: str) -> EndUser:
return EndUser(
tenant_id=tenant_id,
app_id=app_id,
type="browser",
session_id=f"session-{app_id}",
)
def _site_model(*, app_id: str) -> Site:
return Site(
app_id=app_id,
title="Site",
icon_type="emoji",
icon="robot",
icon_background="#fff",
description="desc",
input_placeholder="Ask the app",
default_language="en",
chat_color_theme="light",
chat_color_theme_inverted=False,
custom_disclaimer="",
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
code=f"code-{app_id[-6:]}",
prompt_public=False,
show_workflow_steps=True,
use_icon_as_answer_icon=False,
)
class TestAppSiteApi:
@patch("services.feature_service.FeatureService.get_features")
def test_happy_path(self, mock_features: MagicMock, app: Flask, db_session_with_containers: Session) -> None:
app.config["RESTX_MASK_HEADER"] = "X-Fields"
tenant = _create_tenant(db_session_with_containers)
app_model = _create_app(db_session_with_containers, tenant.id)
_create_site(db_session_with_containers, app_model.id)
end_user = _end_user(tenant.id, app_model.id)
mock_features.return_value = FeatureModel(can_replace_logo=False)
with app.test_request_context("/site"):
result = AppSiteApi().get(app_model, end_user)
assert result["app_id"] == app_model.id
assert result["end_user_id"] == end_user.id
assert result["plan"] == "basic"
assert result["enable_site"] is True
assert result["mode"] == AppMode.CHAT
def test_missing_site_raises_not_found(self, app: Flask, db_session_with_containers: Session) -> None:
app.config["RESTX_MASK_HEADER"] = "X-Fields"
tenant = _create_tenant(db_session_with_containers)
app_model = _create_app(db_session_with_containers, tenant.id)
end_user = _end_user(tenant.id, app_model.id)
with app.test_request_context("/site"):
with pytest.raises(WebAppNotFoundError):
AppSiteApi().get(app_model, end_user)
def test_archived_tenant_raises_not_found(self, app: Flask, db_session_with_containers: Session) -> None:
app.config["RESTX_MASK_HEADER"] = "X-Fields"
tenant = _create_tenant(db_session_with_containers, status=TenantStatus.ARCHIVE)
app_model = _create_app(db_session_with_containers, tenant.id)
_create_site(db_session_with_containers, app_model.id)
end_user = _end_user(tenant.id, app_model.id)
with app.test_request_context("/site"):
with pytest.raises(WebAppNotFoundError):
AppSiteApi().get(app_model, end_user)
def _tenant_model(*, plan: str = "basic", custom_config: TenantCustomConfigDict | None = None) -> Tenant:
tenant = Tenant(name="test-tenant", plan=plan)
tenant.custom_config_dict = custom_config or {}
return tenant
def _app_model(*, tenant: Tenant, enable_site: bool = True) -> App:
app_model = App(
tenant_id=tenant.id,
mode=AppMode.CHAT,
name="test-app",
enable_site=enable_site,
enable_api=True,
)
app_model.id = "app-test"
return app_model
class TestWebAppSiteResponse:
def test_basic_fields(self) -> None:
tenant = _tenant_model()
app_model = _app_model(tenant=tenant)
response = WebAppSiteResponse.from_app_site(
tenant=tenant,
app_model=app_model,
mode=AppMode.CHAT,
site=_site_model(app_id=app_model.id),
end_user_id="eu-1",
features=FeatureModel(can_replace_logo=False, webapp_copyright_enabled=True),
can_replace_logo=False,
)
assert response.app_id == app_model.id
assert response.mode == AppMode.CHAT
assert response.end_user_id == "eu-1"
assert response.enable_site is True
assert response.plan == "basic"
assert response.can_replace_logo is False
assert response.model_config_ is None
assert response.custom_config is None
assert response.site.input_placeholder == "Ask the app"
assert response.site.custom_disclaimer == ""
def test_nullable_site_fields_preserve_none(self) -> None:
tenant = _tenant_model()
app_model = _app_model(tenant=tenant)
site = _site_model(app_id=app_model.id)
site.chat_color_theme = None
site.icon_type = None
site.icon = None
site.icon_background = None
site.description = None
site.copyright = None
site.privacy_policy = None
response = WebAppSiteResponse.from_app_site(
tenant=tenant,
app_model=app_model,
mode=AppMode.CHAT,
site=site,
end_user_id=None,
features=FeatureModel(can_replace_logo=False, webapp_copyright_enabled=True),
can_replace_logo=False,
)
dumped = response.model_dump(mode="json")
assert dumped["end_user_id"] is None
assert dumped["site"]["chat_color_theme"] is None
assert dumped["site"]["icon_type"] is None
assert dumped["site"]["icon"] is None
assert dumped["site"]["icon_background"] is None
assert dumped["site"]["description"] is None
assert dumped["site"]["copyright"] is None
assert dumped["site"]["privacy_policy"] is None
assert dumped["site"]["custom_disclaimer"] == ""
@patch("controllers.web.site.dify_config.FILES_URL", "https://files.example.com")
def test_can_replace_logo_sets_custom_config(self) -> None:
tenant = _tenant_model(
plan="pro",
custom_config={"remove_webapp_brand": True, "replace_webapp_logo": "enabled"},
)
app_model = _app_model(tenant=tenant)
response = WebAppSiteResponse.from_app_site(
tenant=tenant,
app_model=app_model,
mode=AppMode.CHAT,
site=_site_model(app_id=app_model.id),
end_user_id="eu-1",
features=FeatureModel(can_replace_logo=True, webapp_copyright_enabled=True),
can_replace_logo=True,
)
assert response.can_replace_logo is True
assert response.custom_config is not None
assert response.custom_config.remove_webapp_brand is True
assert response.custom_config.replace_webapp_logo is not None
assert "webapp-logo" in response.custom_config.replace_webapp_logo
class TestWebModelConfigResponse:
def test_serializes_internal_model_config_properties_to_public_keys(self) -> None:
model_config = AppModelConfig(
app_id="app-test",
opening_statement="Hello",
suggested_questions='["Question?"]',
suggested_questions_after_answer='{"enabled": true}',
more_like_this='{"enabled": false}',
model='{"provider": "openai", "name": "gpt-4o", "mode": "chat"}',
user_input_form='[{"text-input": {"label": "Name", "variable": "name", "required": true}}]',
pre_prompt="System prompt",
created_by="account-1",
updated_by="account-1",
)
dumped = WebModelConfigResponse.model_validate(model_config, from_attributes=True).model_dump(mode="json")
assert dumped == {
"opening_statement": "Hello",
"suggested_questions": ["Question?"],
"suggested_questions_after_answer": {"enabled": True},
"more_like_this": {"enabled": False},
"model": {"provider": "openai", "name": "gpt-4o", "mode": "chat"},
"user_input_form": [{"text-input": {"label": "Name", "variable": "name", "required": True}}],
"pre_prompt": "System prompt",
}
@@ -0,0 +1,418 @@
"""Testcontainers integration tests for controllers.web.wraps — JWT auth decorator and validation helpers."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from uuid import uuid4
import pytest
from flask import Flask
from sqlalchemy.orm import Session
from werkzeug.exceptions import NotFound, Unauthorized
from controllers.web.error import WebAppAuthAccessDeniedError, WebAppAuthRequiredError, WebAppNotFoundError
from controllers.web.wraps import (
_validate_user_accessibility,
_validate_webapp_token,
decode_jwt_token,
)
from models.enums import EndUserType
pytestmark = pytest.mark.usefixtures("db_session_with_containers")
class TestValidateWebappToken:
def test_enterprise_enabled_and_app_auth_requires_webapp_source(self) -> None:
decoded = {"token_source": "other"}
with pytest.raises(WebAppAuthRequiredError):
_validate_webapp_token(decoded, app_web_auth_enabled=True, system_webapp_auth_enabled=True)
def test_enterprise_enabled_and_app_auth_accepts_webapp_source(self) -> None:
decoded = {"token_source": "webapp"}
_validate_webapp_token(decoded, app_web_auth_enabled=True, system_webapp_auth_enabled=True)
def test_enterprise_enabled_and_app_auth_missing_source_raises(self) -> None:
decoded = {}
with pytest.raises(WebAppAuthRequiredError):
_validate_webapp_token(decoded, app_web_auth_enabled=True, system_webapp_auth_enabled=True)
def test_public_app_rejects_webapp_source(self) -> None:
decoded = {"token_source": "webapp"}
with pytest.raises(Unauthorized):
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=False)
def test_public_app_accepts_non_webapp_source(self) -> None:
decoded = {"token_source": "other"}
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=False)
def test_public_app_accepts_no_source(self) -> None:
decoded = {}
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=False)
def test_system_enabled_but_app_public(self) -> None:
decoded = {"token_source": "webapp"}
with pytest.raises(Unauthorized):
_validate_webapp_token(decoded, app_web_auth_enabled=False, system_webapp_auth_enabled=True)
class TestValidateUserAccessibility:
def test_skips_when_auth_disabled(self) -> None:
_validate_user_accessibility(
decoded={},
app_code="code",
app_web_auth_enabled=False,
system_webapp_auth_enabled=False,
webapp_settings=None,
)
def test_missing_user_id_raises(self) -> None:
decoded = {}
with pytest.raises(WebAppAuthRequiredError):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=SimpleNamespace(access_mode="internal"),
)
def test_missing_webapp_settings_raises(self) -> None:
decoded = {"user_id": "u1"}
with pytest.raises(WebAppAuthRequiredError, match="settings not found"):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=None,
)
def test_missing_auth_type_raises(self) -> None:
decoded = {"user_id": "u1", "granted_at": 1}
settings = SimpleNamespace(access_mode="private")
with pytest.raises(WebAppAuthRequiredError, match="auth_type"):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=settings,
)
def test_missing_granted_at_raises(self) -> None:
decoded = {"user_id": "u1", "auth_type": "external"}
settings = SimpleNamespace(access_mode="sso_verified")
with pytest.raises(WebAppAuthAccessDeniedError, match="granted_at"):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=settings,
)
@patch("controllers.web.wraps.EnterpriseService.get_app_sso_settings_last_update_time")
@patch(
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=False
)
def test_external_auth_type_checks_sso_update_time(
self, mock_perm_check: MagicMock, mock_sso_time: MagicMock
) -> None:
mock_sso_time.return_value = datetime.now(UTC)
old_granted = int((datetime.now(UTC) - timedelta(hours=1)).timestamp())
decoded = {"user_id": "u1", "auth_type": "external", "granted_at": old_granted}
settings = SimpleNamespace(access_mode="sso_verified")
with pytest.raises(WebAppAuthAccessDeniedError, match="SSO settings"):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=settings,
)
@patch("controllers.web.wraps.EnterpriseService.get_workspace_sso_settings_last_update_time")
@patch(
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=False
)
def test_internal_auth_type_checks_workspace_sso_update_time(
self, mock_perm_check: MagicMock, mock_workspace_sso: MagicMock
) -> None:
mock_workspace_sso.return_value = datetime.now(UTC)
old_granted = int((datetime.now(UTC) - timedelta(hours=1)).timestamp())
decoded = {"user_id": "u1", "auth_type": "internal", "granted_at": old_granted}
settings = SimpleNamespace(access_mode="private")
with pytest.raises(WebAppAuthAccessDeniedError, match="SSO settings"):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=settings,
)
@patch("controllers.web.wraps.EnterpriseService.get_app_sso_settings_last_update_time")
@patch(
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=False
)
def test_external_auth_passes_when_granted_after_sso_update(
self, mock_perm_check: MagicMock, mock_sso_time: MagicMock
) -> None:
mock_sso_time.return_value = datetime.now(UTC) - timedelta(hours=2)
recent_granted = int(datetime.now(UTC).timestamp())
decoded = {"user_id": "u1", "auth_type": "external", "granted_at": recent_granted}
settings = SimpleNamespace(access_mode="sso_verified")
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=settings,
)
@patch("controllers.web.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp", return_value=False)
@patch("services.webapp_access_query_service.WebAppAccessQueryService.get_app_id_by_code", return_value="app-id-1")
@patch(
"services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required", return_value=True
)
def test_permission_check_denies_unauthorized_user(
self, mock_perm: MagicMock, mock_app_id: MagicMock, mock_allowed: MagicMock
) -> None:
decoded = {"user_id": "u1", "auth_type": "internal", "granted_at": int(datetime.now(UTC).timestamp())}
settings = SimpleNamespace(access_mode="private")
with pytest.raises(WebAppAuthAccessDeniedError):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=settings,
)
@pytest.mark.parametrize(
("access_mode", "auth_type"),
[
pytest.param("private", "external", id="private-rejects-external"),
pytest.param("private_all", "external", id="private-all-rejects-external"),
pytest.param("sso_verified", "internal", id="sso-verified-rejects-internal"),
],
)
@patch("controllers.web.wraps.EnterpriseService.WebAppAuth.is_user_allowed_to_access_webapp")
@patch("services.webapp_access_query_service.WebAppAccessQueryService.is_permission_check_required")
def test_auth_type_must_match_current_access_mode(
self,
mock_permission_check: MagicMock,
mock_allowed: MagicMock,
access_mode: str,
auth_type: str,
) -> None:
decoded = {"user_id": "u1", "auth_type": auth_type, "granted_at": int(datetime.now(UTC).timestamp())}
with pytest.raises(WebAppAuthRequiredError):
_validate_user_accessibility(
decoded=decoded,
app_code="code",
app_web_auth_enabled=True,
system_webapp_auth_enabled=True,
webapp_settings=SimpleNamespace(access_mode=access_mode),
)
mock_permission_check.assert_not_called()
mock_allowed.assert_not_called()
class TestDecodeJwtToken:
@pytest.fixture
def app(self, flask_app_with_containers: Flask):
return flask_app_with_containers
def _create_app_site_enduser(self, db_session: Session, *, enable_site: bool = True):
from models.model import App, AppMode, AppModelConfig, CustomizeTokenStrategy, EndUser, Site
tenant_id = str(uuid4())
app_model = App(
tenant_id=tenant_id,
mode=AppMode.CHAT.value,
name="test-app",
enable_site=enable_site,
enable_api=True,
)
db_session.add(app_model)
db_session.commit()
db_session.expire_all()
# The happy-path fixture represents a published public App.
config = AppModelConfig(app_id=app_model.id)
db_session.add(config)
db_session.flush()
app_model.app_model_config_id = config.id
db_session.commit()
site = Site(
app_id=app_model.id,
title="test-site",
default_language="en-US",
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
code="code1",
)
db_session.add(site)
db_session.commit()
db_session.expire_all()
end_user = EndUser(
tenant_id=tenant_id,
app_id=app_model.id,
type=EndUserType.BROWSER,
session_id="sess-1",
)
db_session.add(end_user)
db_session.commit()
db_session.expire_all()
return app_model, site, end_user
@patch("controllers.web.wraps._validate_user_accessibility")
@patch("controllers.web.wraps._validate_webapp_token")
@patch("controllers.web.wraps.EnterpriseService.WebAppAuth.get_app_access_mode_by_id")
@patch("services.webapp_access_query_service.WebAppAccessQueryService.get_app_id_by_code")
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
@patch("controllers.web.wraps.PassportService")
@patch("controllers.web.wraps.extract_webapp_passport")
def test_happy_path(
self,
mock_extract: MagicMock,
mock_passport_cls: MagicMock,
mock_features: MagicMock,
mock_app_id: MagicMock,
mock_access_mode: MagicMock,
mock_validate_token: MagicMock,
mock_validate_user: MagicMock,
app: Flask,
db_session_with_containers: Session,
) -> None:
app_model, site, end_user = self._create_app_site_enduser(db_session_with_containers)
mock_extract.return_value = "jwt-token"
mock_passport_cls.return_value.verify.return_value = {
"app_code": site.code,
"app_id": app_model.id,
"end_user_id": end_user.id,
}
mock_features.return_value = False
with app.test_request_context("/", headers={"X-App-Code": site.code}):
result_app, result_user = decode_jwt_token()
assert result_app.id == app_model.id
assert result_user.id == end_user.id
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
@patch("controllers.web.wraps.extract_webapp_passport")
def test_missing_token_raises_unauthorized(self, mock_extract: MagicMock, mock_features: MagicMock, app) -> None:
mock_features.return_value = False
mock_extract.return_value = None
with app.test_request_context("/", headers={"X-App-Code": "code1"}):
with pytest.raises(Unauthorized):
decode_jwt_token()
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
@patch("controllers.web.wraps.PassportService")
@patch("controllers.web.wraps.extract_webapp_passport")
def test_missing_app_raises_not_found(
self,
mock_extract: MagicMock,
mock_passport_cls: MagicMock,
mock_features: MagicMock,
app: Flask,
) -> None:
non_existent_id = str(uuid4())
mock_extract.return_value = "jwt-token"
mock_passport_cls.return_value.verify.return_value = {
"app_code": "code1",
"app_id": non_existent_id,
"end_user_id": str(uuid4()),
}
mock_features.return_value = False
with app.test_request_context("/", headers={"X-App-Code": "code1"}):
with pytest.raises(WebAppNotFoundError):
decode_jwt_token()
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
@patch("controllers.web.wraps.PassportService")
@patch("controllers.web.wraps.extract_webapp_passport")
def test_disabled_site_raises_app_not_found(
self,
mock_extract: MagicMock,
mock_passport_cls: MagicMock,
mock_features: MagicMock,
app: Flask,
db_session_with_containers: Session,
) -> None:
app_model, site, end_user = self._create_app_site_enduser(db_session_with_containers, enable_site=False)
mock_extract.return_value = "jwt-token"
mock_passport_cls.return_value.verify.return_value = {
"app_code": site.code,
"app_id": app_model.id,
"end_user_id": end_user.id,
}
mock_features.return_value = False
with app.test_request_context("/", headers={"X-App-Code": site.code}):
with pytest.raises(WebAppNotFoundError):
decode_jwt_token()
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
@patch("controllers.web.wraps.PassportService")
@patch("controllers.web.wraps.extract_webapp_passport")
def test_missing_end_user_raises_not_found(
self,
mock_extract: MagicMock,
mock_passport_cls: MagicMock,
mock_features: MagicMock,
app: Flask,
db_session_with_containers: Session,
) -> None:
app_model, site, _ = self._create_app_site_enduser(db_session_with_containers)
non_existent_eu = str(uuid4())
mock_extract.return_value = "jwt-token"
mock_passport_cls.return_value.verify.return_value = {
"app_code": site.code,
"app_id": app_model.id,
"end_user_id": non_existent_eu,
}
mock_features.return_value = False
with app.test_request_context("/", headers={"X-App-Code": site.code}):
with pytest.raises(NotFound):
decode_jwt_token()
@patch("controllers.web.wraps.SystemFeatureService.is_webapp_auth_enabled")
@patch("controllers.web.wraps.PassportService")
@patch("controllers.web.wraps.extract_webapp_passport")
def test_user_id_mismatch_raises_unauthorized(
self,
mock_extract: MagicMock,
mock_passport_cls: MagicMock,
mock_features: MagicMock,
app: Flask,
db_session_with_containers: Session,
) -> None:
app_model, site, end_user = self._create_app_site_enduser(db_session_with_containers)
mock_extract.return_value = "jwt-token"
mock_passport_cls.return_value.verify.return_value = {
"app_code": site.code,
"app_id": app_model.id,
"end_user_id": end_user.id,
}
mock_features.return_value = False
with app.test_request_context("/", headers={"X-App-Code": site.code}):
with pytest.raises(Unauthorized, match="expired"):
decode_jwt_token(user_id="different-user")
@@ -0,0 +1 @@
# Core integration tests package
@@ -0,0 +1 @@
# App integration tests package
@@ -0,0 +1 @@
# Layers integration tests package
@@ -0,0 +1,279 @@
"""Workflow pause orchestration against real Engine, PostgreSQL, Redis, and storage."""
import json
from collections.abc import Mapping
from contextlib import closing
from dataclasses import dataclass
from time import perf_counter
from uuid import uuid4
import pytest
from sqlalchemy import Engine, select
from sqlalchemy.orm import Session, sessionmaker
from core.app.app_config.entities import WorkflowUIBasedAppConfig
from core.app.apps.workflow.app_queue_manager import WorkflowAppQueueManager
from core.app.apps.workflow_app_runner import PreparedWorkflowRun, WorkflowBasedAppRunner
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom, WorkflowAppGenerateEntity
from core.app.layers.pause_state_persist_layer import PauseStateLayerConfig, WorkflowResumptionContext
from core.repositories.sqlalchemy_workflow_execution_repository import SQLAlchemyWorkflowExecutionRepository
from core.repositories.sqlalchemy_workflow_node_execution_repository import SQLAlchemyWorkflowNodeExecutionRepository
from core.workflow.system_variables import build_system_variables
from core.workflow.workflow_entry import WorkflowEntry
from extensions.ext_storage import storage
from graphon.engine.command import InMemoryChannel, PauseCommand
from graphon.engine_events import GraphRunFailedEvent, GraphRunPausedEvent, GraphRunStartedEvent, GraphRunSucceededEvent
from graphon.enums import WorkflowExecutionStatus, WorkflowType
from graphon.model_runtime.entities.llm_entities import LLMUsage
from graphon.nodes.start.entities import StartNodeData
from graphon.runtime import RuntimeState, VariablePool
from models import Account
from models.account import Tenant, TenantAccountJoin, TenantAccountRole
from models.enums import WorkflowRunTriggeredFrom
from models.model import AppMode
from models.workflow import Workflow, WorkflowNodeExecutionTriggeredFrom, WorkflowPause, WorkflowRun
from models.workflow import WorkflowType as ModelWorkflowType
from repositories.sqlalchemy_api_workflow_run_repository import DifyAPISQLAlchemyWorkflowRunRepository
from services.workflow_run_agg import WorkflowRunAgg
@dataclass
class WorkflowCase:
session: Session
engine: Engine
account: Account
workflow: Workflow
run_id: str
def prepare(
self,
*,
outputs: Mapping[str, object] | None = None,
variables: Mapping[tuple[str, str], object] | None = None,
total_tokens: int = 0,
node_run_steps: int = 0,
pause: bool = True,
) -> tuple[PreparedWorkflowRun, WorkflowRunAgg]:
entity = WorkflowAppGenerateEntity(
user_from=UserFrom.ACCOUNT,
task_id=str(uuid4()),
app_config=WorkflowUIBasedAppConfig(
tenant_id=self.workflow.tenant_id,
app_id=self.workflow.app_id,
app_mode=AppMode.WORKFLOW,
workflow_id=self.workflow.id,
),
inputs={},
files=[],
user_id=self.account.id,
stream=True,
invoke_from=InvokeFrom.DEBUGGER,
workflow_execution_id=self.run_id,
)
queue = WorkflowAppQueueManager(entity.task_id, self.account.id, entity.invoke_from, AppMode.WORKFLOW)
runner = WorkflowBasedAppRunner(queue_manager=queue, app_id=self.workflow.app_id)
variable_pool = VariablePool.from_bootstrap(
system_variables=build_system_variables(
app_id=self.workflow.app_id, workflow_id=self.workflow.id, workflow_execution_id=self.run_id
)
)
for selector, value in (variables or {}).items():
variable_pool.add(selector, value)
usage = LLMUsage.empty_usage()
usage.total_tokens = total_tokens
runtime = RuntimeState(
workflow_id=self.workflow.id,
variable_pool=variable_pool,
start_at=perf_counter(),
llm_usage=usage,
outputs=dict(outputs or {}),
node_run_steps=node_run_steps,
)
graph = runner._init_graph(
graph_config=self.workflow.graph_dict,
graph_runtime_state=runtime,
workflow_id=self.workflow.id,
tenant_id=self.workflow.tenant_id,
user_id=self.account.id,
user_from=UserFrom.ACCOUNT,
invoke_from=InvokeFrom.DEBUGGER,
call_depth=0,
)
runs = SQLAlchemyWorkflowExecutionRepository(
self.engine,
tenant_id=self.workflow.tenant_id,
user=self.account,
app_id=self.workflow.app_id,
triggered_from=WorkflowRunTriggeredFrom.DEBUGGING,
)
nodes = SQLAlchemyWorkflowNodeExecutionRepository(
self.engine,
tenant_id=self.workflow.tenant_id,
user=self.account,
app_id=self.workflow.app_id,
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
)
commands = InMemoryChannel()
if pause:
commands.send_command(PauseCommand(reason="integration pause"))
entry = WorkflowEntry(
graph=graph,
graph_config=self.workflow.graph_dict,
call_depth=0,
graph_runtime_state=runtime,
command_channel=commands,
)
prepared = PreparedWorkflowRun(entry, WorkflowType.WORKFLOW, self.workflow.version, entity, ())
aggregate = WorkflowRunAgg(
prepared,
runner,
PauseStateLayerConfig(self.engine, self.workflow.created_by),
workflow_execution_repository=runs,
workflow_node_execution_repository=nodes,
)
return prepared, aggregate
def stored_pause(self) -> WorkflowPause:
self.session.expire_all()
pause = self.session.scalar(select(WorkflowPause).where(WorkflowPause.workflow_run_id == self.run_id))
assert pause is not None
return pause
@pytest.fixture
def workflow_case(db_session_with_containers: Session) -> WorkflowCase:
session = db_session_with_containers
engine = session.get_bind()
assert isinstance(engine, Engine)
tenant = Tenant(name="Pause integration tenant")
account = Account(name="Pause integration user", email=f"{uuid4()}@example.com")
session.add_all([tenant, account])
session.flush()
session.add(
TenantAccountJoin(tenant_id=tenant.id, account_id=account.id, role=TenantAccountRole.OWNER, current=True)
)
graph: dict[str, object] = {
"nodes": [{"id": "start", "data": StartNodeData(title="Start").model_dump(mode="json")}],
"edges": [],
}
workflow = Workflow(
id=str(uuid4()),
tenant_id=tenant.id,
app_id=str(uuid4()),
type=ModelWorkflowType("workflow"),
version="draft",
graph=json.dumps(graph),
_features="{}",
created_by=account.id,
)
session.add(workflow)
session.commit()
return WorkflowCase(session, engine, account, workflow, str(uuid4()))
def test_complete_pause_flow_with_real_dependencies(workflow_case: WorkflowCase) -> None:
prepared, aggregate = workflow_case.prepare(outputs={"result": "intermediate"}, total_tokens=100, node_run_steps=5)
with closing(aggregate.iter_events()) as events:
assert isinstance(next(events), GraphRunStartedEvent)
workflow_case.session.expire_all()
run = workflow_case.session.get(WorkflowRun, workflow_case.run_id)
assert run is not None
assert run.status == WorkflowExecutionStatus.RUNNING
assert workflow_case.session.scalar(select(WorkflowPause)) is None
remaining = list(events)
assert isinstance(remaining[-1], GraphRunPausedEvent)
pause = workflow_case.stored_pause()
workflow_case.session.refresh(run)
assert run.status == WorkflowExecutionStatus.PAUSED
assert run.finished_at is None
assert run.outputs_dict == {"result": "intermediate"}
assert run.total_tokens == 100
assert run.total_steps == prepared.entry.graph_engine.runtime_state.node_run_steps
assert pause.workflow_id == workflow_case.workflow.id
assert pause.resumed_at is None
snapshot = WorkflowResumptionContext.loads(storage.load(pause.state_object_key).decode())
assert snapshot.serialized_graph_runtime_state == prepared.entry.graph_engine.runtime_state.dumps()
assert snapshot.get_response_stream_filter().dumps() == prepared.entry.response_stream_filter.dumps()
entity = snapshot.get_generate_entity()
assert isinstance(entity, WorkflowAppGenerateEntity)
assert entity.workflow_execution_id == workflow_case.run_id
def test_state_persistence_and_retrieval(workflow_case: WorkflowCase) -> None:
outputs = {"nested": {"key": "value", "number": 42}, "list": [1, 2, 3, {"nested": "item"}], "null": None}
variables = {("node", "text"): "value", ("node", "object"): {"complex": "object"}, ("node", "list"): [1, 2, 3]}
prepared, aggregate = workflow_case.prepare(
outputs=outputs, variables=variables, total_tokens=250, node_run_steps=10
)
events = list(aggregate.iter_events())
assert isinstance(events[-1], GraphRunPausedEvent)
repository = DifyAPISQLAlchemyWorkflowRunRepository(sessionmaker(workflow_case.engine))
pause = repository.get_workflow_pause(workflow_case.run_id)
assert pause is not None
assert pause.workflow_execution_id == workflow_case.run_id
snapshot = WorkflowResumptionContext.loads(pause.get_state().decode())
restored = RuntimeState.from_snapshot(snapshot.serialized_graph_runtime_state)
assert restored.graph_execution.pause_reasons == events[-1].reasons
assert restored.outputs == outputs
assert restored.total_tokens == 250
assert restored.node_run_steps == prepared.entry.graph_engine.runtime_state.node_run_steps
for selector, expected in variables.items():
variable = restored.variable_pool.get(selector)
assert variable is not None
assert variable.to_object() == expected
def test_database_transaction_handling(workflow_case: WorkflowCase) -> None:
_, aggregate = workflow_case.prepare(outputs={"test": "transaction"})
assert isinstance(list(aggregate.iter_events())[-1], GraphRunPausedEvent)
with Session(workflow_case.engine) as session:
run = session.get(WorkflowRun, workflow_case.run_id)
assert run is not None
assert run.status == WorkflowExecutionStatus.PAUSED
pause = session.scalar(select(WorkflowPause).where(WorkflowPause.workflow_run_id == run.id))
assert pause is not None
assert pause.resumed_at is None
assert storage.load(pause.state_object_key)
def test_workflow_with_different_creators(workflow_case: WorkflowCase) -> None:
creator = Account(name="Workflow creator", email=f"{uuid4()}@example.com")
workflow_case.session.add(creator)
workflow_case.session.flush()
workflow_case.workflow.created_by = creator.id
workflow_case.session.commit()
_, aggregate = workflow_case.prepare()
assert isinstance(list(aggregate.iter_events())[-1], GraphRunPausedEvent)
pause = workflow_case.stored_pause()
snapshot = WorkflowResumptionContext.loads(storage.load(pause.state_object_key).decode())
run = workflow_case.session.get(WorkflowRun, workflow_case.run_id)
assert run is not None
assert run.created_by == workflow_case.account.id
assert run.created_by != workflow_case.workflow.created_by
assert snapshot.get_generate_entity().user_id == workflow_case.account.id
def test_successful_execution_creates_no_pause(workflow_case: WorkflowCase) -> None:
_, aggregate = workflow_case.prepare(pause=False)
events = list(aggregate.iter_events())
assert isinstance(events[-1], GraphRunSucceededEvent)
assert not any(isinstance(event, GraphRunPausedEvent) for event in events)
workflow_case.session.expire_all()
run = workflow_case.session.get(WorkflowRun, workflow_case.run_id)
assert run is not None
assert run.status == WorkflowExecutionStatus.SUCCEEDED
assert workflow_case.session.scalar(select(WorkflowPause)) is None
def test_active_execution_cannot_publish_a_durable_pause(workflow_case: WorkflowCase) -> None:
prepared, aggregate = workflow_case.prepare()
with prepared.entry.graph_engine.runtime_state.graph_execution.track_execution():
events = list(aggregate.iter_events())
assert isinstance(events[-1], GraphRunFailedEvent)
assert "during active execution" in events[-1].error
assert not any(isinstance(event, GraphRunPausedEvent) for event in events)
workflow_case.session.expire_all()
run = workflow_case.session.get(WorkflowRun, workflow_case.run_id)
assert run is not None
assert run.status == WorkflowExecutionStatus.FAILED
assert workflow_case.session.scalar(select(WorkflowPause)) is None
@@ -0,0 +1,317 @@
"""Live DingTalk integration tests.
These tests intentionally use real DingTalk credentials and external APIs. They
skip when the required environment variables are unavailable and never emit
credential material, Provider identifiers, or raw Provider responses.
"""
from __future__ import annotations
import os
from collections import deque
from dataclasses import dataclass
from time import monotonic, sleep
from typing import Never
from uuid import uuid4
import pytest
from alibabacloud_dingtalk.robot_1_0.models import BatchOTOQueryHeaders, BatchOTOQueryRequest
from alibabacloud_tea_util.models import RuntimeOptions
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from Tea.exceptions import RetryError, TeaException, ValidateException
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters import (
CredentialTestSuccess,
DingTalkCredentials,
Directory,
MessageAccepted,
ProviderUserId,
)
from core.human_input_v2.im_integration.adapters import dingtalk as dingtalk_module
from core.human_input_v2.im_integration.adapters.dingtalk import DingTalkIMProviderAdapter
_DEPARTMENT_LIST_URL = "https://oapi.dingtalk.com/topapi/v2/department/listsub"
_USER_LIST_URL = "https://oapi.dingtalk.com/topapi/v2/user/list"
_ROOT_DEPARTMENT_ID = 1
_FORCED_PAGE_SIZE = 1
_SDK_TIMEOUT_MILLISECONDS = 5000
_STATUS_QUERY_TIMEOUT_SECONDS = 10.0
_STATUS_QUERY_INTERVAL_SECONDS = 0.5
_SUCCESS_SEND_STATUS = "SUCCESS"
def _fail(reason: str) -> Never:
raise AssertionError(reason)
class _WireProviderResponse(BaseModel):
model_config = ConfigDict(extra="ignore", strict=True)
errcode: int
class _WireDepartment(BaseModel):
model_config = ConfigDict(extra="ignore", strict=True)
dept_id: int = Field(ge=1)
class _WireDepartmentListResponse(_WireProviderResponse):
result: tuple[_WireDepartment, ...] | None = None
class _WireDirectoryUser(BaseModel):
model_config = ConfigDict(extra="ignore", strict=True)
userid: str
name: str | None = None
email: str | None = None
class _WireUserPage(BaseModel):
model_config = ConfigDict(extra="ignore", strict=True)
has_more: bool
next_cursor: int | None = None
users: tuple[_WireDirectoryUser, ...] = Field(alias="list")
class _WireUserListResponse(_WireProviderResponse):
result: _WireUserPage | None = None
@dataclass(frozen=True, slots=True)
class _LiveDirectoryEntry:
provider_user_id: str
display_name: str | None
email: str | None
@dataclass(frozen=True, slots=True)
class _LiveDirectorySnapshot:
entries: tuple[_LiveDirectoryEntry, ...]
exercised_pagination: bool
@pytest.fixture(scope="module")
def dingtalk_credentials() -> DingTalkCredentials:
corp_id = os.getenv("DINGTALK_CORP_ID")
client_id = os.getenv("DINGTALK_CLIENT_ID")
client_secret = os.getenv("DINGTALK_CLIENT_SECRET")
if not corp_id or not client_id or not client_secret:
pytest.skip("DingTalk live credentials are not configured")
return DingTalkCredentials(
provider=IMProvider.DING_TALK,
corp_id=corp_id,
client_id=client_id,
client_secret=client_secret,
)
@pytest.fixture
def dingtalk_test_recipient_id() -> ProviderUserId:
recipient_id = os.getenv("DINGTALK_TEST_RECIPIENT_ID")
if not recipient_id:
pytest.skip("DINGTALK_TEST_RECIPIENT_ID is not configured")
return ProviderUserId(recipient_id)
def test_live_credentials_verify_complete_member_authorization(
dingtalk_credentials: DingTalkCredentials,
) -> None:
adapter = DingTalkIMProviderAdapter(dingtalk_credentials)
try:
result = adapter.test_credentials()
finally:
adapter.close()
adapter.close()
if not isinstance(result, CredentialTestSuccess):
_fail("DingTalk live credential testing did not verify complete member authorization")
if result.provider_tenant_id != dingtalk_credentials.corp_id:
_fail("DingTalk live credential testing returned an unexpected tenant boundary")
def test_live_directory_reads_complete_non_empty_entries_across_real_pages(
dingtalk_credentials: DingTalkCredentials,
) -> None:
expected_snapshot = _read_live_directory_with_forced_pagination(dingtalk_credentials)
adapter = DingTalkIMProviderAdapter(dingtalk_credentials)
try:
actual_snapshot = adapter.directory.read_directory()
finally:
adapter.close()
adapter.close()
if not isinstance(actual_snapshot, Directory):
_fail("DingTalk live Directory did not return a complete snapshot")
if not actual_snapshot.entries:
_fail("DingTalk live Directory returned an empty snapshot")
if not expected_snapshot.exercised_pagination:
_fail("DingTalk live Directory fixture did not exercise a real pagination boundary")
if not all(
str(entry.provider_user_id).strip()
and entry.display_name is not None
and entry.display_name.strip()
and entry.email is not None
and entry.email.strip()
for entry in actual_snapshot.entries
):
_fail("DingTalk live Directory returned an entry with an empty shared field")
expected_by_user_id = {
entry.provider_user_id: (entry.display_name, entry.email) for entry in expected_snapshot.entries
}
actual_by_user_id = {
str(entry.provider_user_id): (entry.display_name, entry.email) for entry in actual_snapshot.entries
}
if actual_by_user_id != expected_by_user_id:
_fail("DingTalk live Directory snapshot did not match the independently paginated snapshot")
def test_live_messaging_reports_provider_send_success(
dingtalk_credentials: DingTalkCredentials,
dingtalk_test_recipient_id: ProviderUserId,
) -> None:
message_body = f"Dify DingTalk live integration {uuid4()}"
adapter = DingTalkIMProviderAdapter(dingtalk_credentials)
try:
send_result = adapter.messaging.send_text(dingtalk_test_recipient_id, message_body)
finally:
adapter.close()
adapter.close()
if not isinstance(send_result, MessageAccepted):
_fail("DingTalk did not confirm live message acceptance")
try:
locator_payload = dingtalk_module._DingTalkLocatorPayload.decode(str(send_result.locator))
except Exception as exc:
raise AssertionError("DingTalk live message did not return a valid opaque locator") from exc
# DingTalk exposes send/read status for OTO robot messages, but not the
# persisted message body. Exact msgParam content is therefore asserted in
# the SDK-boundary unit test while this test verifies the real mutation.
_wait_for_message_send_success(
dingtalk_credentials,
dingtalk_test_recipient_id,
locator_payload.process_query_key,
)
def _read_live_directory_with_forced_pagination(
credentials: DingTalkCredentials,
) -> _LiveDirectorySnapshot:
access_token = dingtalk_module._get_access_token(dingtalk_module._new_oauth_client(), credentials)
http_client = dingtalk_module._UrllibDirectoryHTTPClient()
entries: list[_LiveDirectoryEntry] = []
seen_user_ids: set[str] = set()
pending_departments: deque[int] = deque((_ROOT_DEPARTMENT_ID,))
discovered_departments = {_ROOT_DEPARTMENT_ID}
exercised_pagination = False
try:
while pending_departments:
department_id = pending_departments.popleft()
department_response = _parse_wire_response(
http_client.post(
_DEPARTMENT_LIST_URL,
access_token=access_token,
body={"dept_id": department_id},
).body,
_WireDepartmentListResponse,
)
if department_response.result is None:
_fail("DingTalk live department response omitted its result")
for child in department_response.result:
if child.dept_id in discovered_departments:
continue
discovered_departments.add(child.dept_id)
pending_departments.append(child.dept_id)
cursor = 0
seen_cursors = {cursor}
while True:
user_response = _parse_wire_response(
http_client.post(
_USER_LIST_URL,
access_token=access_token,
body={
"dept_id": department_id,
"cursor": cursor,
"size": _FORCED_PAGE_SIZE,
},
).body,
_WireUserListResponse,
)
if user_response.result is None:
_fail("DingTalk live user response omitted its result")
page = user_response.result
for user in page.users:
if user.userid in seen_user_ids:
continue
seen_user_ids.add(user.userid)
entries.append(_LiveDirectoryEntry(user.userid, user.name, user.email))
if not page.has_more:
break
exercised_pagination = True
next_cursor = page.next_cursor
if next_cursor is None or next_cursor in seen_cursors:
_fail("DingTalk live Directory returned an invalid pagination cursor")
seen_cursors.add(next_cursor)
cursor = next_cursor
finally:
http_client.close()
return _LiveDirectorySnapshot(tuple(entries), exercised_pagination)
def _parse_wire_response[ResponseT: _WireProviderResponse](
response_body: bytes,
response_type: type[ResponseT],
) -> ResponseT:
try:
response = response_type.model_validate_json(response_body)
except (ValidationError, ValueError):
_fail("DingTalk live Directory returned an invalid response")
if response.errcode != 0:
_fail("DingTalk live Directory rejected the request")
return response
def _wait_for_message_send_success(
credentials: DingTalkCredentials,
recipient_id: ProviderUserId,
process_query_key: str,
) -> None:
access_token = dingtalk_module._get_access_token(dingtalk_module._new_oauth_client(), credentials)
robot_client = dingtalk_module._new_robot_client()
deadline = monotonic() + _STATUS_QUERY_TIMEOUT_SECONDS
while True:
try:
response = robot_client.batch_otoquery_with_options(
BatchOTOQueryRequest(
process_query_key=process_query_key,
robot_code=credentials.client_id,
),
BatchOTOQueryHeaders(x_acs_dingtalk_access_token=access_token),
RuntimeOptions(
autoretry=False,
max_attempts=1,
connect_timeout=_SDK_TIMEOUT_MILLISECONDS,
read_timeout=_SDK_TIMEOUT_MILLISECONDS,
),
)
except (RetryError, TeaException, ValidateException):
_fail("DingTalk live message status query failed")
if not isinstance(response.status_code, int) or not 200 <= response.status_code < 300:
_fail("DingTalk live message status query returned a non-success status")
response_body = response.body
if response_body is None:
_fail("DingTalk live message status query returned no body")
recipient_observed = any(
read_info.user_id == str(recipient_id) for read_info in response_body.message_read_info_list or ()
)
if response_body.send_status == _SUCCESS_SEND_STATUS and recipient_observed:
return
if monotonic() >= deadline:
_fail("DingTalk did not report successful live message delivery before timeout")
sleep(_STATUS_QUERY_INTERVAL_SECONDS)
@@ -0,0 +1,112 @@
from __future__ import annotations
import os
from uuid import uuid4
import pytest
from alibabacloud_dingtalk.oauth2_1_0.models import GetTokenRequest, GetTokenResponse, GetTokenResponseBody
from redis import Redis
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters import DingTalkCredentials, dingtalk_redis
class _FakeOAuthClient:
def __init__(self, response: GetTokenResponse | None = None) -> None:
self.response = response
self.calls: list[tuple[str, GetTokenRequest]] = []
def get_token(self, corp_id: str, request: GetTokenRequest) -> GetTokenResponse:
self.calls.append((corp_id, request))
if self.response is None:
pytest.fail("cached provider unexpectedly requested a DingTalk token")
return self.response
def _token_response(token: str, *, expires_in: int = 180) -> GetTokenResponse:
return GetTokenResponse(
status_code=200,
body=GetTokenResponseBody(access_token=token, expires_in=expires_in),
)
def test_real_redis_reuses_tokens_for_the_same_client_id(
monkeypatch: pytest.MonkeyPatch,
) -> None:
redis_url = os.getenv("REDIS_URL")
if redis_url is None or not redis_url.strip():
pytest.skip("REDIS_URL is unavailable")
identity = uuid4().hex
credentials = DingTalkCredentials(
provider=IMProvider.DING_TALK,
corp_id=f"fake-corp-{identity}",
client_id=f"fake-client-{identity}",
client_secret=f"fake-secret-{identity}",
)
changed_credentials = credentials.model_copy(update={"client_secret": f"fake-changed-secret-{identity}"})
short_lived_credentials = credentials.model_copy(update={"client_id": f"fake-short-client-{identity}"})
first_client = _FakeOAuthClient(_token_response("fake-fresh-token-primary"))
cached_client = _FakeOAuthClient()
changed_client = _FakeOAuthClient()
text_cached_client = _FakeOAuthClient()
malformed_client = _FakeOAuthClient(_token_response("fake-recovered-token-malformed"))
persistent_client = _FakeOAuthClient(_token_response("fake-recovered-token-persistent"))
short_lived_client = _FakeOAuthClient(_token_response("fake-short-lived-token", expires_in=60))
clients = iter(
(
first_client,
cached_client,
changed_client,
text_cached_client,
malformed_client,
persistent_client,
short_lived_client,
)
)
monkeypatch.setattr(dingtalk_redis, "_new_oauth_client", lambda: next(clients))
cache = Redis.from_url(redis_url, decode_responses=False)
text_cache = Redis.from_url(redis_url, decode_responses=True)
primary_key = dingtalk_redis._cache_key(credentials.client_id)
changed_key = dingtalk_redis._cache_key(changed_credentials.client_id)
short_lived_key = dingtalk_redis._cache_key(short_lived_credentials.client_id)
try:
first_provider = dingtalk_redis.RedisCacheAccessTokenProvider(credentials, cache)
cached_provider = dingtalk_redis.RedisCacheAccessTokenProvider(credentials, cache)
changed_provider = dingtalk_redis.RedisCacheAccessTokenProvider(changed_credentials, cache)
assert first_provider.get() == "fake-fresh-token-primary"
primary_ttl = cache.ttl(primary_key)
assert 0 < primary_ttl <= 120
assert cached_provider.get() == "fake-fresh-token-primary"
assert cached_client.calls == []
assert changed_provider.get() == "fake-fresh-token-primary"
assert changed_client.calls == []
assert changed_key == primary_key
assert cache.get(primary_key) == b"fake-fresh-token-primary"
text_cached_provider = dingtalk_redis.RedisCacheAccessTokenProvider(credentials, text_cache)
assert text_cached_provider.get() == "fake-fresh-token-primary"
assert text_cached_client.calls == []
cache.set(changed_key, b"\xff", ex=120)
malformed_provider = dingtalk_redis.RedisCacheAccessTokenProvider(changed_credentials, cache)
assert malformed_provider.get() == "fake-recovered-token-malformed"
assert len(malformed_client.calls) == 1
cache.set(changed_key, "fake-persistent-token")
persistent_provider = dingtalk_redis.RedisCacheAccessTokenProvider(changed_credentials, cache)
assert persistent_provider.get() == "fake-recovered-token-persistent"
assert len(persistent_client.calls) == 1
short_lived_provider = dingtalk_redis.RedisCacheAccessTokenProvider(short_lived_credentials, cache)
assert short_lived_provider.get() == "fake-short-lived-token"
assert len(short_lived_client.calls) == 1
assert cache.exists(short_lived_key) == 0
finally:
cache.delete(primary_key, short_lived_key)
assert cache.exists(primary_key, short_lived_key) == 0
text_cache.close()
cache.close()
@@ -0,0 +1,679 @@
from __future__ import annotations
import json
import os
from collections.abc import Callable, Mapping
from datetime import datetime
from pathlib import Path
from uuid import uuid4
import pytest
from lark_oapi.event.callback.model.p2_card_action_trigger import (
P2CardActionTrigger,
P2CardActionTriggerResponse,
)
from core.human_input import ButtonStyle
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters import (
AuthenticatedIMEvent,
CorrelationToken,
DynamicCardMessagingError,
EventAcceptance,
IMCardEvent,
IMCardEventDecodingError,
IMEventIngressKind,
MessageAccepted,
ProviderUserId,
StaticCardIntent,
UnrecognizedIMEvent,
WebhookRequest,
feishu_lark,
)
from core.human_input_v2.im_integration.adapters.credentials import FeishuCredentials
from core.human_input_v2.im_integration.adapters.feishu_lark import (
FeishuIMProviderAdapter,
)
from core.human_input_v2.resolved_form import MarkdownFragment, ParagraphInput, ResolvedForm, SelectInput, UserAction
_FIXTURE_DIRECTORY = Path(__file__).resolve().parents[5] / "unit_tests/core/human_input_v2/im_provider/fixtures"
_WEBHOOK_FIXTURE = _FIXTURE_DIRECTORY / "feishu_lark_card_action_webhook.json"
_STREAM_FIXTURE = _FIXTURE_DIRECTORY / "feishu_lark_card_action_stream.json"
_RECEIVED_AT = datetime(2026, 8, 12, 10, 0, 0)
_DIFY_ACTION_MARKER = "__dify.human_input.action"
_LEGACY_WEBHOOK_PAYLOAD_KEY = "__dify_feishu_lark.webhook"
_LEGACY_STREAM_PAYLOAD_KEY = "__dify_feishu_lark.stream"
class _RecordingGateway:
def __init__(self) -> None:
self.card_content: dict[str, object] | None = None
def query_tenant(self) -> Mapping[str, object]:
return {"code": 0, "data": {"tenant": {"tenant_key": "tenant_test_only"}}}
def list_scope(self, _page_token: str | None) -> Mapping[str, object]:
raise AssertionError("unexpected directory call")
def list_departments(
self,
_department: feishu_lark._DepartmentIdentity,
_page_token: str | None,
) -> Mapping[str, object]:
raise AssertionError("unexpected directory call")
def list_users(
self,
_department: feishu_lark._DepartmentIdentity,
_page_token: str | None,
) -> Mapping[str, object]:
raise AssertionError("unexpected directory call")
def create_message(self, _receive_id: str, msg_type: str, content: str) -> Mapping[str, object]:
assert msg_type == "interactive"
decoded_content = json.loads(content)
assert isinstance(decoded_content, dict)
self.card_content = decoded_content
return {"code": 0, "data": {"message_id": "message_test_only"}}
def patch_message(self, _message_id: str, _content: str) -> Mapping[str, object]:
raise AssertionError("unexpected replacement call")
class _LiveRecordingGateway:
def __init__(self, delegate: feishu_lark._SDKGateway) -> None:
self._delegate = delegate
self.card_content: dict[str, object] | None = None
def query_tenant(self) -> Mapping[str, object]:
return self._delegate.query_tenant()
def list_scope(self, page_token: str | None) -> Mapping[str, object]:
return self._delegate.list_scope(page_token)
def list_departments(
self,
department: feishu_lark._DepartmentIdentity,
page_token: str | None,
) -> Mapping[str, object]:
return self._delegate.list_departments(department, page_token)
def list_users(
self,
department: feishu_lark._DepartmentIdentity,
page_token: str | None,
) -> Mapping[str, object]:
return self._delegate.list_users(department, page_token)
def create_message(self, receive_id: str, msg_type: str, content: str) -> Mapping[str, object]:
decoded_content = json.loads(content)
assert isinstance(decoded_content, dict)
self.card_content = decoded_content
return self._delegate.create_message(receive_id, msg_type, content)
def patch_message(self, message_id: str, content: str) -> Mapping[str, object]:
return self._delegate.patch_message(message_id, content)
class _EventConsumer:
def __init__(self) -> None:
self.event: AuthenticatedIMEvent | None = None
def accept(self, event: AuthenticatedIMEvent, *, request_ip_address: str | None = None) -> EventAcceptance:
del request_ip_address
self.event = event
return EventAcceptance.ACCEPTED
class _FixtureSDKObjectStreamClient:
def __init__(
self,
credentials: FeishuCredentials,
domain: str,
callback: Callable[[feishu_lark._SDKEventEnvelope, Callable[[], None]], None],
sdk_event: P2CardActionTrigger,
) -> None:
self._channel = feishu_lark._SynchronousEventChannel(
credentials=credentials,
domain=domain,
callback=callback,
)
self._sdk_event = sdk_event
self.response: P2CardActionTriggerResponse | None = None
def start(self) -> None:
self.response = self._channel._on_card_action(self._sdk_event)
def stop(self) -> None:
return None
def _intent(marker: str = "test-only") -> ResolvedForm:
return ResolvedForm(
title=f"Feishu/Lark card agreement [{marker}]",
parts=(
MarkdownFragment(text="Review the provider wire card."),
ParagraphInput(output_variable_name="comment", default_value="Initial review"),
SelectInput(output_variable_name="decision", options=("ship", "hold"), default_value="hold"),
),
actions=(UserAction(id="approve", title="Approve", button_style=ButtonStyle.PRIMARY),),
legacy_form_content="unused",
)
def _credentials() -> FeishuCredentials:
return FeishuCredentials(
provider=IMProvider.FEISHU,
app_id="cli_test_only",
app_secret="secret_test_only",
verification_token="verification_test_only",
encrypt_key="encrypt_key_test_only",
)
def _load_fixture(path: Path) -> dict[str, object]:
fixture = json.loads(path.read_text(encoding="utf-8"))
assert isinstance(fixture, dict)
return fixture
def _fixture_payload(fixture: Mapping[str, object]) -> dict[str, object]:
authenticated_event = fixture["authenticated_event"]
assert isinstance(authenticated_event, dict)
callback = authenticated_event["payload"]
assert isinstance(callback, dict)
return callback
def _decrypted_webhook_payload(fixture: Mapping[str, object]) -> str:
http = fixture["http"]
assert isinstance(http, dict)
request = http["request"]
assert isinstance(request, dict)
body = request["body"]
assert isinstance(body, str)
encrypted_envelope = json.loads(body)
assert isinstance(encrypted_envelope, dict)
encrypted_payload = encrypted_envelope["encrypt"]
assert isinstance(encrypted_payload, str)
return feishu_lark._decrypt_webhook_payload(encrypted_payload, "encrypt_key_test_only").decode()
def _replayed_sdk_native_payload(fixture: Mapping[str, object]) -> str:
stream_evidence = fixture["stream"]
assert isinstance(stream_evidence, dict)
serialization = stream_evidence["sdk_serialization"]
assert isinstance(serialization, dict)
captured_payload = serialization["value"]
assert isinstance(captured_payload, str)
sdk_event_mapping = json.loads(captured_payload)
assert isinstance(sdk_event_mapping, dict)
native_payload = feishu_lark.lark.JSON.marshal(P2CardActionTrigger(sdk_event_mapping))
assert isinstance(native_payload, str)
return native_payload
def _fixture_action(callback: Mapping[str, object]) -> dict[str, object]:
event = callback["event"]
assert isinstance(event, dict)
action = event["action"]
assert isinstance(action, dict)
return action
def _replay_webhook(
adapter: FeishuIMProviderAdapter,
fixture: Mapping[str, object],
) -> AuthenticatedIMEvent:
http = fixture["http"]
assert isinstance(http, dict)
request = http["request"]
expected_response = http["response"]
assert isinstance(request, dict)
assert isinstance(expected_response, dict)
raw_headers = request["headers"]
assert isinstance(raw_headers, list)
headers: list[tuple[str, str]] = []
for raw_header in raw_headers:
assert isinstance(raw_header, dict)
name = raw_header["name"]
value = raw_header["value"]
assert isinstance(name, str)
assert isinstance(value, str)
headers.append((name, value))
method = request["method"]
body = request["body"]
received_at = request["received_at"]
assert isinstance(method, str)
assert isinstance(body, str)
assert isinstance(received_at, str)
consumer = _EventConsumer()
response = adapter.create_webhook_handler(consumer).handle(
WebhookRequest(
method=method,
headers=tuple(headers),
body=body.encode(),
received_at=datetime.fromisoformat(received_at),
)
)
assert response.status_code == expected_response["status"]
assert response.body.decode() == expected_response["body"]
assert consumer.event is not None
return consumer.event
def _replay_stream(
monkeypatch: pytest.MonkeyPatch,
adapter: FeishuIMProviderAdapter,
fixture: Mapping[str, object],
) -> AuthenticatedIMEvent:
stream_evidence = fixture["stream"]
assert isinstance(stream_evidence, dict)
serialization = stream_evidence["sdk_serialization"]
callback_response = stream_evidence["callback_response"]
assert isinstance(serialization, dict)
assert isinstance(callback_response, dict)
serialized_event = serialization["value"]
assert isinstance(serialized_event, str)
sdk_event_mapping = json.loads(serialized_event)
assert isinstance(sdk_event_mapping, dict)
sdk_event = P2CardActionTrigger(sdk_event_mapping)
clients: list[_FixtureSDKObjectStreamClient] = []
def create_stream_client(
credentials: FeishuCredentials,
domain: str,
callback: Callable[[feishu_lark._SDKEventEnvelope, Callable[[], None]], None],
) -> _FixtureSDKObjectStreamClient:
client = _FixtureSDKObjectStreamClient(credentials, domain, callback, sdk_event)
clients.append(client)
return client
monkeypatch.setattr(feishu_lark, "_create_sdk_stream_client", create_stream_client)
consumer = _EventConsumer()
stream = adapter.create_stream_handler(consumer)
stream.start()
stream.stop()
assert len(clients) == 1
response = clients[0].response
assert isinstance(response, P2CardActionTriggerResponse)
response_serialization = callback_response["sdk_serialization"]
assert isinstance(response_serialization, dict)
assert feishu_lark.lark.JSON.marshal(response) == response_serialization["value"]
assert consumer.event is not None
return consumer.event
def _event(
callback: Mapping[str, object],
provider: IMProvider = IMProvider.FEISHU,
*,
ingress_kind: IMEventIngressKind = IMEventIngressKind.WEBHOOK,
payload: str | None = None,
) -> AuthenticatedIMEvent:
serialized_payload = payload
if serialized_payload is None:
serialized_payload = json.dumps(callback, ensure_ascii=False)
return AuthenticatedIMEvent(
provider=provider,
provider_tenant_id="tenant_test_only",
event_id="event_test_only",
event_type="card.action.trigger",
occurred_at=None,
received_at=_RECEIVED_AT,
ingress_kind=ingress_kind,
payload=serialized_payload,
)
def _button_metadata(card: Mapping[str, object]) -> dict[str, object]:
body = card["body"]
assert isinstance(body, dict)
body_elements = body["elements"]
assert isinstance(body_elements, list)
form = body_elements[0]
assert isinstance(form, dict)
form_elements = form["elements"]
assert isinstance(form_elements, list)
action_row = form_elements[-1]
assert isinstance(action_row, dict)
columns = action_row["columns"]
assert isinstance(columns, list)
column = columns[0]
assert isinstance(column, dict)
buttons = column["elements"]
assert isinstance(buttons, list)
button = buttons[0]
assert isinstance(button, dict)
behaviors = button["behaviors"]
assert isinstance(behaviors, list)
behavior = behaviors[0]
assert isinstance(behavior, dict)
metadata = behavior["value"]
assert isinstance(metadata, dict)
return metadata
def _callback(metadata: Mapping[str, object], actor: str = "union_test_only") -> dict[str, object]:
marked_metadata = metadata.get(_DIFY_ACTION_MARKER)
raw_action_id = marked_metadata.get("action_id") if isinstance(marked_metadata, Mapping) else None
action_id = raw_action_id if isinstance(raw_action_id, str) else "foreign"
return {
"schema": "2.0",
"header": {"event_type": "card.action.trigger", "tenant_key": "tenant_test_only"},
"event": {
"operator": {"union_id": actor, "open_id": "open_id_must_not_be_used"},
"action": {
"tag": "button",
"name": action_id,
"value": dict(metadata),
"form_value": {"comment": "Reviewed ✅", "decision": "ship"},
},
},
}
def test_webhook_transport_preserves_exact_decrypted_payload_until_decode(
monkeypatch: pytest.MonkeyPatch,
) -> None:
fixture = _load_fixture(_WEBHOOK_FIXTURE)
native_payload = _decrypted_webhook_payload(fixture)
gateway = _RecordingGateway()
monkeypatch.setattr(feishu_lark, "_create_sdk_gateway", lambda _credentials, _domain: gateway)
adapter = FeishuIMProviderAdapter(_credentials())
try:
authenticated_event = _replay_webhook(adapter, fixture)
decoded = FeishuIMProviderAdapter.card_event_decoder().decode(authenticated_event)
finally:
adapter.close()
assert authenticated_event.ingress_kind is IMEventIngressKind.WEBHOOK
assert authenticated_event.payload == native_payload
assert json.loads(native_payload) == _fixture_payload(fixture)
assert _LEGACY_WEBHOOK_PAYLOAD_KEY not in authenticated_event.payload
assert isinstance(decoded, IMCardEvent)
def test_stream_transport_preserves_exact_sdk_payload_until_decode(
monkeypatch: pytest.MonkeyPatch,
) -> None:
fixture = _load_fixture(_STREAM_FIXTURE)
stream_evidence = fixture["stream"]
assert isinstance(stream_evidence, dict)
serialization = stream_evidence["sdk_serialization"]
assert isinstance(serialization, dict)
native_payload = _replayed_sdk_native_payload(fixture)
object_type = stream_evidence["object_type"]
assert isinstance(object_type, str)
gateway = _RecordingGateway()
monkeypatch.setattr(feishu_lark, "_create_sdk_gateway", lambda _credentials, _domain: gateway)
adapter = FeishuIMProviderAdapter(_credentials())
try:
authenticated_event = _replay_stream(monkeypatch, adapter, fixture)
decoded = FeishuIMProviderAdapter.card_event_decoder().decode(authenticated_event)
finally:
adapter.close()
assert authenticated_event.ingress_kind is IMEventIngressKind.STREAM
assert authenticated_event.payload == native_payload
assert _LEGACY_STREAM_PAYLOAD_KEY not in authenticated_event.payload
assert object_type not in authenticated_event.payload
assert isinstance(decoded, IMCardEvent)
def test_sender_wire_agrees_with_sanitized_webhook_and_stream_boundaries(
monkeypatch: pytest.MonkeyPatch,
) -> None:
gateway = _RecordingGateway()
monkeypatch.setattr(feishu_lark, "_create_sdk_gateway", lambda _credentials, _domain: gateway)
adapter = FeishuIMProviderAdapter(_credentials())
token = CorrelationToken("feishu-lark-card-evidence-token")
webhook_fixture = _load_fixture(_WEBHOOK_FIXTURE)
stream_fixture = _load_fixture(_STREAM_FIXTURE)
try:
assert adapter.dynamic_card_messaging.assess(_intent()).representable is True
empty_intent = ResolvedForm(title="", parts=(), actions=(), legacy_form_content="unused")
assert adapter.dynamic_card_messaging.assess(empty_intent).representable is False
result = adapter.dynamic_card_messaging.send_card(
ProviderUserId("union_test_only"),
_intent(),
token,
)
assert isinstance(result, MessageAccepted)
assert gateway.card_content is not None
sender_metadata = _button_metadata(gateway.card_content)
sender_marker = sender_metadata[_DIFY_ACTION_MARKER]
assert isinstance(sender_marker, dict)
action_id = sender_marker["action_id"]
correlation_token = sender_marker["correlation_token"]
assert isinstance(action_id, str)
assert correlation_token == token
webhook_callback = _fixture_payload(webhook_fixture)
stream_callback = _fixture_payload(stream_fixture)
webhook_action = _fixture_action(webhook_callback)
stream_action = _fixture_action(stream_callback)
assert webhook_action["value"] == sender_metadata
assert stream_action["value"] == sender_metadata
submitted_inputs = webhook_action["form_value"]
assert isinstance(submitted_inputs, dict)
assert stream_action["form_value"] == submitted_inputs
webhook_event = _replay_webhook(adapter, webhook_fixture)
stream_event = _replay_stream(monkeypatch, adapter, stream_fixture)
webhook_decoded = FeishuIMProviderAdapter.card_event_decoder().decode(webhook_event)
stream_decoded = FeishuIMProviderAdapter.card_event_decoder().decode(stream_event)
finally:
adapter.close()
expected = IMCardEvent(
provider_user_id=ProviderUserId("union_test_only"),
action_id=action_id,
inputs=submitted_inputs,
correlation_token=token,
)
assert webhook_decoded == expected
assert stream_decoded == expected
def test_stream_evidence_decodes_through_both_provider_variants() -> None:
fixture = json.loads(_STREAM_FIXTURE.read_text(encoding="utf-8"))
assert isinstance(fixture, dict)
authenticated_event = fixture["authenticated_event"]
assert isinstance(authenticated_event, dict)
callback = authenticated_event["payload"]
assert isinstance(callback, dict)
feishu_result = FeishuIMProviderAdapter.card_event_decoder().decode(_event(callback))
lark_result = feishu_lark.LarkIMProviderAdapter.card_event_decoder().decode(_event(callback, IMProvider.LARK))
assert feishu_result == lark_result
assert isinstance(feishu_result, IMCardEvent)
assert feishu_result.provider_user_id == ProviderUserId("union_test_only")
def test_stream_transport_rejects_whitespace_union_id_with_safe_diagnostic(
monkeypatch: pytest.MonkeyPatch,
) -> None:
fixture = _load_fixture(_STREAM_FIXTURE)
callback = _fixture_payload(fixture)
callback_event = callback["event"]
assert isinstance(callback_event, dict)
operator = callback_event["operator"]
assert isinstance(operator, dict)
operator["union_id"] = " \t "
stream_evidence = fixture["stream"]
assert isinstance(stream_evidence, dict)
serialization = stream_evidence["sdk_serialization"]
assert isinstance(serialization, dict)
serialization["value"] = json.dumps(callback, ensure_ascii=False)
gateway = _RecordingGateway()
monkeypatch.setattr(feishu_lark, "_create_sdk_gateway", lambda _credentials, _domain: gateway)
adapter = FeishuIMProviderAdapter(_credentials())
try:
authenticated_event = _replay_stream(monkeypatch, adapter, fixture)
with pytest.raises(
IMCardEventDecodingError,
match=r"^Feishu/Lark card event schema is invalid\.$",
) as raised:
FeishuIMProviderAdapter.card_event_decoder().decode(authenticated_event)
finally:
adapter.close()
assert raised.value.args == ("Feishu/Lark card event schema is invalid.",)
assert raised.value.__cause__ is None
assert raised.value.__context__ is None
def test_protocol_failure_and_routing_boundaries_remain_distinct() -> None:
codec = feishu_lark._MSFeishuLarkCardCodec()
foreign = _callback({"foreign": True})
assert isinstance(codec.decode(_event(foreign)), UnrecognizedIMEvent)
assert isinstance(codec.decode(_event(foreign, IMProvider.SLACK)), UnrecognizedIMEvent)
with pytest.raises(IMCardEventDecodingError, match="schema is invalid"):
codec.decode(_event({"schema": "1.0"}))
with pytest.raises(IMCardEventDecodingError, match="payload is invalid"):
codec.decode(_event({}, payload="[]"))
recognized = _callback(
{
_DIFY_ACTION_MARKER: {
"version": 1,
"action_id": "approve",
"correlation_token": "token",
}
},
actor="",
)
with pytest.raises(IMCardEventDecodingError, match="schema is invalid"):
codec.decode(_event(recognized))
with pytest.raises(IMCardEventDecodingError, match="payload is invalid"):
codec.decode(_event({}, payload="not-json"))
oversized = ResolvedForm(
title="",
parts=(MarkdownFragment(text="x" * (31 * 1024)),),
actions=(),
legacy_form_content="unused",
)
with pytest.raises(DynamicCardMessagingError, match="Provider payload limit"):
codec.encode(oversized, CorrelationToken("token"))
@pytest.mark.parametrize(
("payload", "expected_message"),
[
pytest.param(
json.dumps(
{
"schema": "2.0",
"header": {"event_type": "card.action.trigger"},
"event": {},
}
),
"Feishu/Lark card event schema is invalid.",
id="malformed-direct-callback",
),
pytest.param(
json.dumps({_LEGACY_WEBHOOK_PAYLOAD_KEY: {"encrypted": True}}),
"Feishu/Lark card event schema is invalid.",
id="malformed-webhook-wrapper",
),
pytest.param(
json.dumps(
{
_LEGACY_STREAM_PAYLOAD_KEY: {
"native_payload": "{}",
"object_type": "unexpected.sdk.Event",
}
}
),
"Feishu/Lark card event schema is invalid.",
id="wrong-stream-object-type",
),
pytest.param(
json.dumps(
{
_LEGACY_WEBHOOK_PAYLOAD_KEY: {
"encrypted": True,
"native_payload": "not-json",
}
}
),
"Feishu/Lark card event schema is invalid.",
id="invalid-native-payload",
),
],
)
def test_direct_payload_protocol_rejects_obsolete_wrappers_and_malformed_callbacks(
payload: str,
expected_message: str,
) -> None:
codec = feishu_lark._MSFeishuLarkCardCodec()
with pytest.raises(IMCardEventDecodingError) as raised:
codec.decode(_event({}, payload=payload))
assert raised.value.args == (expected_message,)
def test_live_feishu_sender_is_accepted_and_replaced_without_callback_synthesis(
monkeypatch: pytest.MonkeyPatch,
) -> None:
app_id = os.getenv("FEISHU_APP_ID")
app_secret = os.getenv("FEISHU_APP_SECRET")
verification_token = os.getenv("FEISHU_VERIFICATION_TOKEN")
encrypt_key = os.getenv("FEISHU_ENCRYPT_KEY")
recipient_id = os.getenv("FEISHU_TEST_RECIPIENT_ID")
if not all((app_id, app_secret, verification_token, encrypt_key, recipient_id)):
pytest.skip("Feishu live card sender credentials or recipient are unavailable")
assert app_id is not None
assert app_secret is not None
assert verification_token is not None
assert encrypt_key is not None
assert recipient_id is not None
credentials = FeishuCredentials(
provider=IMProvider.FEISHU,
app_id=app_id,
app_secret=app_secret,
verification_token=verification_token,
encrypt_key=encrypt_key,
)
live_gateway = _LiveRecordingGateway(feishu_lark._OfficialSDKGateway(credentials, feishu_lark._FEISHU_DOMAIN))
monkeypatch.setattr(feishu_lark, "_create_sdk_gateway", lambda _credentials, _domain: live_gateway)
adapter = FeishuIMProviderAdapter(credentials)
marker = f"codex-feishu-lark-card-event-{uuid4()}"
token = CorrelationToken(f"{marker}-correlation")
try:
result = adapter.dynamic_card_messaging.send_card(
ProviderUserId(recipient_id),
_intent(marker),
token,
)
assert isinstance(result, MessageAccepted)
assert live_gateway.card_content is not None
marker_metadata = _button_metadata(live_gateway.card_content)[_DIFY_ACTION_MARKER]
assert isinstance(marker_metadata, dict)
assert marker_metadata["action_id"] == "approve"
assert marker_metadata["correlation_token"] == token
assert (
adapter.dynamic_card_messaging.replace_with_static(
result.locator,
StaticCardIntent(f"Feishu/Lark card integration completed [{marker}]"),
)
is None
)
finally:
adapter.close()
@@ -0,0 +1,185 @@
from __future__ import annotations
import json
from collections.abc import Mapping
from datetime import datetime
import pytest
from core.human_input import ButtonStyle
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters import (
AuthenticatedIMEvent,
CorrelationToken,
DynamicCardMessagingError,
IMCardEvent,
IMCardEventDecodingError,
IMEventIngressKind,
ProviderUserId,
UnrecognizedIMEvent,
)
from core.human_input_v2.im_integration.adapters.ms_teams import MSTeamsIMProviderAdapter, _MSTeamsCardCodec
from core.human_input_v2.resolved_form import MarkdownFragment, ParagraphInput, ResolvedForm, SelectInput, UserAction
_RECEIVED_AT = datetime(2026, 8, 12, 2, 26, 40)
def _form(*, comment_input_name: str = "review_comment") -> ResolvedForm:
return ResolvedForm(
title="Microsoft Teams card integration",
parts=(
MarkdownFragment(text="Review the encoded form."),
ParagraphInput(output_variable_name=comment_input_name, default_value="Initial review"),
SelectInput(output_variable_name="risk_level", options=("low", "high"), default_value="low"),
),
actions=(
UserAction(id="approve-✅", title="Approve", button_style=ButtonStyle.PRIMARY),
UserAction(id="reject", title="Reject", button_style=ButtonStyle.ACCENT),
),
legacy_form_content="unused",
)
def _event(callback: Mapping[str, object], *, event_type: str = "message") -> AuthenticatedIMEvent:
return AuthenticatedIMEvent(
provider=IMProvider.MS_TEAMS,
provider_tenant_id="integration-tenant",
event_id="integration-card-event",
event_type=event_type,
occurred_at=None,
received_at=_RECEIVED_AT,
ingress_kind=IMEventIngressKind.WEBHOOK,
payload=json.dumps(callback, ensure_ascii=False, separators=(",", ":")),
)
def test_ms_teams_sender_metadata_and_callback_decoder_round_trip() -> None:
codec = MSTeamsIMProviderAdapter.card_event_decoder()
assert isinstance(codec, _MSTeamsCardCodec)
correlation_token = CorrelationToken("integration-correlation-🔐")
card = codec.encode(_form(), correlation_token)
actions = card["actions"]
assert isinstance(actions, list)
invoked_action = actions[0]
assert isinstance(invoked_action, dict)
action_data = invoked_action["data"]
assert isinstance(action_data, dict)
callback_value = {
**action_data,
"review_comment": "Reviewed exactly ✅",
"risk_level": "high",
}
callback = {
"type": "message",
"from": {
"id": "29:integration-teams-user",
"aadObjectId": "11111111-2222-4333-8444-abcdefabcdef",
},
"value": callback_value,
}
decoded = MSTeamsIMProviderAdapter.card_event_decoder().decode(_event(callback))
assert decoded == IMCardEvent(
provider_user_id=ProviderUserId("11111111-2222-4333-8444-abcdefabcdef"),
action_id="approve-✅",
inputs={"review_comment": "Reviewed exactly ✅", "risk_level": "high"},
correlation_token=correlation_token,
)
def test_ms_teams_codec_rejects_collision_and_malformed_recognized_callback() -> None:
codec = MSTeamsIMProviderAdapter.card_event_decoder()
assert isinstance(codec, _MSTeamsCardCodec)
colliding_form = _form(comment_input_name="__dify.human_input")
assert codec.assess(_form()).representable is True
assert codec.assess(colliding_form).representable is False
with pytest.raises(DynamicCardMessagingError):
codec.encode(colliding_form, CorrelationToken("integration-correlation"))
malformed_callback = {
"type": "invoke",
"from": {
"id": "29:integration-teams-user",
"aadObjectId": "11111111-2222-4333-8444-abcdefabcdef",
},
"value": {
"__dify.human_input": {
"version": 1,
"action_id": True,
"correlation_token": "integration-correlation",
}
},
}
with pytest.raises(IMCardEventDecodingError):
codec.decode(_event(malformed_callback, event_type="invoke"))
def test_ms_teams_codec_routes_foreign_and_invalid_transport_events() -> None:
decoder = MSTeamsIMProviderAdapter.card_event_decoder()
foreign_callback = {
"type": "message",
"from": {"id": "foreign-user"},
"value": {"foreign": "interaction"},
}
assert isinstance(decoder.decode(_event(foreign_callback)), UnrecognizedIMEvent)
non_card_event = AuthenticatedIMEvent(
provider=IMProvider.MS_TEAMS,
provider_tenant_id="integration-tenant",
event_id="integration-card-event",
event_type="conversationUpdate",
occurred_at=None,
received_at=_RECEIVED_AT,
ingress_kind=IMEventIngressKind.WEBHOOK,
payload="not-json",
)
assert isinstance(decoder.decode(non_card_event), UnrecognizedIMEvent)
foreign_value_callback: dict[str, object] = {"type": "message", "value": []}
assert isinstance(decoder.decode(_event(foreign_value_callback)), UnrecognizedIMEvent)
mismatched_type_callback = {
"type": "invoke",
"from": {
"id": "29:integration-teams-user",
"aadObjectId": "11111111-2222-4333-8444-abcdefabcdef",
},
"value": {
"__dify.human_input": {
"version": 1,
"action_id": "approve",
"correlation_token": "integration-correlation",
}
},
}
with pytest.raises(IMCardEventDecodingError):
decoder.decode(_event(mismatched_type_callback))
invalid_transport = AuthenticatedIMEvent(
provider=IMProvider.MS_TEAMS,
provider_tenant_id="integration-tenant",
event_id="integration-card-event",
event_type="message",
occurred_at=None,
received_at=_RECEIVED_AT,
ingress_kind=IMEventIngressKind.WEBHOOK,
payload="not-json",
)
with pytest.raises(IMCardEventDecodingError):
decoder.decode(invalid_transport)
with pytest.raises(IMCardEventDecodingError):
decoder.decode(
AuthenticatedIMEvent(
provider=IMProvider.MS_TEAMS,
provider_tenant_id="integration-tenant",
event_id="integration-card-event",
event_type="message",
occurred_at=None,
received_at=_RECEIVED_AT,
ingress_kind=IMEventIngressKind.WEBHOOK,
payload="[]",
)
)
@@ -0,0 +1,401 @@
from __future__ import annotations
import logging
import os
import time
from collections.abc import Iterator, Mapping
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from html import escape
from typing import Literal, NoReturn
from urllib.parse import quote, urlsplit
from uuid import uuid4
import httpx
import pytest
from azure.core.exceptions import AzureError
from azure.identity import ClientSecretCredential
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters import (
Directory,
MessageAccepted,
MSTeamsCredentials,
ProviderUserId,
)
from core.human_input_v2.im_integration.adapters.ms_teams import MSTeamsIMProviderAdapter
_GRAPH_SCOPE = "https://graph.microsoft.com/.default"
_GRAPH_USERS_URL = "https://graph.microsoft.com/v1.0/users"
_GRAPH_HTTP_TIMEOUT_SECONDS = 10.0
_GRAPH_CONTROL_PAGE_SIZE = 1
_MESSAGE_LOOKBACK = timedelta(minutes=1)
_MESSAGE_LOOKAHEAD = timedelta(minutes=10)
_MESSAGE_RETRIEVAL_TIMEOUT_SECONDS = 60.0
_MESSAGE_RETRIEVAL_POLL_SECONDS = 2.0
_MESSAGE_RETRIEVAL_PAGE_SIZE = 50
_MESSAGE_RETRIEVAL_MAX_PAGES_PER_POLL = 8
_MESSAGE_RETRIEVAL_MAX_REQUESTS = 64
_EXTERNAL_CLIENT_LOGGER_NAMES = (
"azure",
"botbuilder",
"botframework",
"httpcore",
"httpx",
"msrest",
"requests",
"urllib3",
)
_SUPPRESSED_CLIENT_LOG_LEVEL = logging.CRITICAL + 1
@dataclass(frozen=True, slots=True, repr=False)
class _MSTeamsTestEnvironment:
tenant_id: str
client_id: str
client_secret: str
recipient_id: str | None
def credentials(self) -> MSTeamsCredentials:
try:
return MSTeamsCredentials(
provider=IMProvider.MS_TEAMS,
tenant_id=self.tenant_id,
client_id=self.client_id,
client_secret=self.client_secret,
)
except ValidationError:
pass
pytest.fail("Microsoft Teams integration credentials are invalid.", pytrace=False)
@dataclass(slots=True)
class _MessageRetrievalBudget:
deadline: float
remaining_requests: int = _MESSAGE_RETRIEVAL_MAX_REQUESTS
def next_request_timeout(self) -> float:
if self.remaining_requests <= 0:
pytest.fail("Microsoft Graph message retrieval exceeded its request budget.", pytrace=False)
remaining_seconds = self.deadline - time.monotonic()
if remaining_seconds <= 0:
pytest.fail("Microsoft Graph message retrieval exceeded its time budget.", pytrace=False)
self.remaining_requests -= 1
return min(_GRAPH_HTTP_TIMEOUT_SECONDS, remaining_seconds)
class _GraphModel(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True, populate_by_name=True)
class _GraphDirectoryUser(_GraphModel):
id: str = Field(min_length=1)
display_name: str | None = Field(default=None, alias="displayName")
email: str | None = Field(default=None, alias="mail")
@field_validator("display_name", "email", mode="before")
@classmethod
def normalize_optional_text(cls, value: object) -> object:
if isinstance(value, str) and not value.strip():
return None
return value
class _GraphDirectoryPage(_GraphModel):
users: tuple[_GraphDirectoryUser, ...] = Field(alias="value")
next_link: str | None = Field(default=None, alias="@odata.nextLink")
class _GraphMessageBody(_GraphModel):
content: str
content_type: Literal["html", "text"] = Field(alias="contentType")
class _GraphMessage(_GraphModel):
body: _GraphMessageBody
class _GraphMessagePage(_GraphModel):
messages: tuple[_GraphMessage, ...] = Field(alias="value")
next_link: str | None = Field(default=None, alias="@odata.nextLink")
@pytest.fixture(autouse=True)
def _suppress_external_client_logs() -> Iterator[None]:
client_loggers = tuple(logging.getLogger(name) for name in _EXTERNAL_CLIENT_LOGGER_NAMES)
original_levels = tuple(logger.level for logger in client_loggers)
for logger in client_loggers:
logger.setLevel(_SUPPRESSED_CLIENT_LOG_LEVEL)
try:
yield
finally:
for logger, original_level in zip(client_loggers, original_levels, strict=True):
logger.setLevel(original_level)
def _test_environment(*, require_recipient: bool) -> _MSTeamsTestEnvironment:
tenant_id = os.environ.get("MS_TEAMS_TENANT_ID")
client_id = os.environ.get("MS_TEAMS_CLIENT_ID")
client_secret = os.environ.get("MS_TEAMS_CLIENT_SECRET")
if not tenant_id or not client_id or not client_secret:
pytest.skip("Real Microsoft Teams integration credentials are not configured.")
recipient_id = os.environ.get("MS_TEAMS_TEST_RECIPIENT_ID")
if require_recipient and not recipient_id:
pytest.skip("MS_TEAMS_TEST_RECIPIENT_ID is not configured for the Messaging integration test.")
return _MSTeamsTestEnvironment(tenant_id, client_id, client_secret, recipient_id)
def _graph_access_token(environment: _MSTeamsTestEnvironment) -> str:
credential = ClientSecretCredential(
environment.tenant_id,
environment.client_id,
environment.client_secret,
)
try:
try:
access_token = credential.get_token(_GRAPH_SCOPE).token
except AzureError:
access_token = None
finally:
credential.close()
if access_token is None:
pytest.fail("Microsoft Graph authentication failed.", pytrace=False)
return access_token
def _fail_invalid_graph_response(operation: str) -> NoReturn:
pytest.fail(f"Microsoft Graph {operation} returned an invalid response.", pytrace=False)
def _graph_response_json(
client: httpx.Client,
url: str,
access_token: str,
*,
operation: str,
request_timeout: float,
params: Mapping[str, str] | None = None,
) -> object:
try:
response = client.get(
url,
headers={"Authorization": f"Bearer {access_token}"},
params=params,
timeout=request_timeout,
)
except httpx.HTTPError:
response = None
if response is None:
pytest.fail(f"Microsoft Graph {operation} could not be completed.", pytrace=False)
if response.is_error:
pytest.fail(
f"Microsoft Graph {operation} failed with HTTP {response.status_code}.",
pytrace=False,
)
try:
return response.json()
except ValueError:
pass
pytest.fail(f"Microsoft Graph {operation} could not be completed.", pytrace=False)
def _trusted_graph_users_url(url: str) -> bool:
parsed = urlsplit(url)
return parsed.scheme == "https" and parsed.netloc == "graph.microsoft.com" and parsed.path == "/v1.0/users"
def _trusted_graph_messages_url(url: str) -> bool:
parsed = urlsplit(url)
return (
parsed.scheme == "https"
and parsed.netloc == "graph.microsoft.com"
and parsed.path.casefold().endswith("/chats/getallmessages")
)
def _real_graph_directory(environment: _MSTeamsTestEnvironment) -> tuple[tuple[_GraphDirectoryUser, ...], int]:
access_token = _graph_access_token(environment)
users: list[_GraphDirectoryUser] = []
page_count = 0
next_url: str | None = _GRAPH_USERS_URL
seen_urls: set[str] = set()
params: Mapping[str, str] | None = {
"$select": "id,displayName,mail",
"$top": str(_GRAPH_CONTROL_PAGE_SIZE),
}
with httpx.Client(timeout=_GRAPH_HTTP_TIMEOUT_SECONDS) as client:
while next_url is not None:
if not _trusted_graph_users_url(next_url) or next_url in seen_urls:
pytest.fail("Microsoft Graph returned an untrusted directory continuation.", pytrace=False)
seen_urls.add(next_url)
response_body = _graph_response_json(
client,
next_url,
access_token,
operation="directory control enumeration",
request_timeout=_GRAPH_HTTP_TIMEOUT_SECONDS,
params=params,
)
try:
page = _GraphDirectoryPage.model_validate(response_body)
except ValidationError:
page = None
if page is None:
_fail_invalid_graph_response("directory control enumeration")
users.extend(page.users)
page_count += 1
next_url = page.next_link
params = None
return tuple(users), page_count
def _graph_datetime(value: datetime) -> str:
return value.astimezone(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def _recent_graph_messages(
environment: _MSTeamsTestEnvironment,
access_token: str,
modified_after: datetime,
modified_before: datetime,
retrieval_budget: _MessageRetrievalBudget,
) -> tuple[_GraphMessage, ...]:
if environment.recipient_id is None:
pytest.fail("Microsoft Teams Messaging test configuration is invalid.", pytrace=False)
recipient = quote(environment.recipient_id, safe="")
next_url: str | None = f"https://graph.microsoft.com/v1.0/users/{recipient}/chats/getAllMessages"
params: Mapping[str, str] | None = {
"$top": str(_MESSAGE_RETRIEVAL_PAGE_SIZE),
"$filter": (
f"lastModifiedDateTime gt {_graph_datetime(modified_after)} "
f"and lastModifiedDateTime lt {_graph_datetime(modified_before)}"
),
}
messages: list[_GraphMessage] = []
seen_urls: set[str] = set()
page_count = 0
with httpx.Client(timeout=_GRAPH_HTTP_TIMEOUT_SECONDS) as client:
while next_url is not None:
if not _trusted_graph_messages_url(next_url) or next_url in seen_urls:
pytest.fail("Microsoft Graph returned an untrusted message continuation.", pytrace=False)
if page_count >= _MESSAGE_RETRIEVAL_MAX_PAGES_PER_POLL:
pytest.fail("Microsoft Graph message retrieval exceeded its pagination limit.", pytrace=False)
seen_urls.add(next_url)
response_body = _graph_response_json(
client,
next_url,
access_token,
operation="message retrieval",
request_timeout=retrieval_budget.next_request_timeout(),
params=params,
)
try:
page = _GraphMessagePage.model_validate(response_body)
except ValidationError:
page = None
if page is None:
_fail_invalid_graph_response("message retrieval")
messages.extend(page.messages)
page_count += 1
next_url = page.next_link
params = None
return tuple(messages)
def _validate_directory_snapshot(
directory_result: object,
control_users: tuple[_GraphDirectoryUser, ...],
control_page_count: int,
) -> None:
if not isinstance(directory_result, Directory):
pytest.fail("Microsoft Teams production directory could not be read.", pytrace=False)
if control_page_count < 2:
pytest.fail("Microsoft Graph directory control did not traverse multiple pages.", pytrace=False)
if not directory_result.entries:
pytest.fail("Microsoft Teams production directory was empty.", pytrace=False)
if any(not str(entry.provider_user_id).strip() for entry in directory_result.entries):
pytest.fail("Microsoft Teams production directory contained an incomplete entry.", pytrace=False)
if any(entry.display_name is None or not entry.display_name.strip() for entry in directory_result.entries):
pytest.fail("Microsoft Teams production directory contained an incomplete entry.", pytrace=False)
if any(entry.email is None or not entry.email.strip() for entry in directory_result.entries):
pytest.fail("Microsoft Teams production directory contained an incomplete entry.", pytrace=False)
adapter_facts = {
(str(entry.provider_user_id), entry.display_name, entry.email) for entry in directory_result.entries
}
control_facts = {(user.id, user.display_name, user.email) for user in control_users}
if len(adapter_facts) != len(directory_result.entries) or len(control_facts) != len(control_users):
pytest.fail("Microsoft Teams directory comparison contained duplicate entries.", pytrace=False)
if adapter_facts != control_facts:
pytest.fail("Microsoft Teams production and control directories did not match.", pytrace=False)
def _exact_graph_message_found(
messages: tuple[_GraphMessage, ...],
exact_graph_bodies: frozenset[tuple[str, str]],
) -> bool:
match_count = sum((message.body.content_type, message.body.content) in exact_graph_bodies for message in messages)
if match_count > 1:
pytest.fail("Microsoft Graph returned multiple exact accepted Teams messages.", pytrace=False)
return match_count == 1
def test_directory_matches_complete_real_graph_multi_page_control() -> None:
environment = _test_environment(require_recipient=False)
adapter = MSTeamsIMProviderAdapter(environment.credentials())
try:
directory_result = adapter.directory.read_directory()
finally:
adapter.close()
control_users, control_page_count = _real_graph_directory(environment)
_validate_directory_snapshot(directory_result, control_users, control_page_count)
def test_send_text_is_retrievable_with_exact_content_from_real_graph() -> None:
environment = _test_environment(require_recipient=True)
if environment.recipient_id is None:
pytest.fail("Microsoft Teams Messaging test configuration is invalid.", pytrace=False)
exact_body = f"Dify Microsoft Teams integration verification {uuid4()}"
modified_after = datetime.now(UTC) - _MESSAGE_LOOKBACK
adapter = MSTeamsIMProviderAdapter(environment.credentials())
try:
send_result = adapter.messaging.send_text(
ProviderUserId(environment.recipient_id),
exact_body,
)
finally:
adapter.close()
if not isinstance(send_result, MessageAccepted):
pytest.fail("Microsoft Teams did not confirm message acceptance.", pytrace=False)
modified_before = datetime.now(UTC) + _MESSAGE_LOOKAHEAD
access_token = _graph_access_token(environment)
retrieval_deadline = time.monotonic() + _MESSAGE_RETRIEVAL_TIMEOUT_SECONDS
retrieval_budget = _MessageRetrievalBudget(retrieval_deadline)
exact_graph_bodies = frozenset(
(
("html", f"<p>{escape(exact_body)}</p>"),
("text", exact_body),
)
)
while True:
messages = _recent_graph_messages(
environment,
access_token,
modified_after,
modified_before,
retrieval_budget,
)
if _exact_graph_message_found(messages, exact_graph_bodies):
return
remaining_seconds = retrieval_deadline - time.monotonic()
if remaining_seconds <= 0:
pytest.fail("Microsoft Graph did not return the exact accepted Teams message.", pytrace=False)
time.sleep(min(_MESSAGE_RETRIEVAL_POLL_SECONDS, remaining_seconds))
@@ -0,0 +1,292 @@
"""Live WeCom integration tests using only explicitly authorized credentials."""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Never
from uuid import uuid4
import pytest
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError
from wechatpy.enterprise import WeChatClient
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters import (
CredentialTestSuccess,
Directory,
MessageAccepted,
ProviderUserId,
WeComCredentials,
)
from core.human_input_v2.im_integration.adapters.wecom import WeComIMProviderAdapter
_SDK_TIMEOUT_SECONDS = 5.0
def _fail(reason: str) -> Never:
pytest.fail(reason, pytrace=False)
class _ScopedUser(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
userid: StrictStr
class _AllowedDepartments(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
partyid: tuple[StrictInt, ...] = ()
class _AllowedUsers(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
user: tuple[_ScopedUser, ...] = ()
class _AllowedTags(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
tagid: tuple[StrictInt, ...] = ()
class _AgentScope(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
agentid: StrictInt = Field(gt=0)
allow_partys: _AllowedDepartments = Field(default_factory=_AllowedDepartments)
allow_userinfos: _AllowedUsers = Field(default_factory=_AllowedUsers)
allow_tags: _AllowedTags = Field(default_factory=_AllowedTags)
class _Department(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
id: StrictInt = Field(gt=0)
class _DirectoryUser(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
userid: StrictStr
name: StrictStr | None = None
email: StrictStr | None = None
class _TagScope(BaseModel):
model_config = ConfigDict(extra="ignore", frozen=True)
userlist: tuple[_ScopedUser, ...] = ()
partylist: tuple[StrictInt, ...] = ()
@dataclass(frozen=True, slots=True)
class _ExpectedDirectoryEntry:
provider_user_id: str
display_name: str | None
email: str | None
@dataclass(frozen=True, slots=True)
class _LiveCredentials:
value: WeComCredentials = field(repr=False)
@dataclass(frozen=True, slots=True)
class _LiveRecipient:
provider_user_id: ProviderUserId = field(repr=False)
@pytest.fixture(scope="module")
def wecom_credentials() -> _LiveCredentials:
corp_id = os.getenv("WECOM_CORP_ID")
agent_id = os.getenv("WECOM_AGENT_ID")
secret = os.getenv("WECOM_SECRET")
if not corp_id or not agent_id or not secret:
pytest.skip("WeCom live credentials are not configured")
try:
return _LiveCredentials(
WeComCredentials(
provider=IMProvider.WE_COM,
corp_id=corp_id,
agent_id=agent_id,
secret=secret,
)
)
except ValidationError:
_fail("WeCom live credentials failed local validation")
@pytest.fixture
def wecom_test_recipient_id() -> _LiveRecipient:
recipient_id = os.getenv("WECOM_TEST_RECIPIENT_ID")
if not recipient_id:
pytest.skip("WECOM_TEST_RECIPIENT_ID is not configured")
return _LiveRecipient(ProviderUserId(recipient_id))
def test_live_credentials_confirm_the_configured_corporation(
wecom_credentials: _LiveCredentials,
) -> None:
credential_repr = repr(wecom_credentials)
if any(
sensitive_value in credential_repr
for sensitive_value in (
wecom_credentials.value.corp_id,
wecom_credentials.value.agent_id,
wecom_credentials.value.secret,
)
):
_fail("WeCom live credential fixture repr is not sanitized")
adapter = WeComIMProviderAdapter(wecom_credentials.value)
try:
result = adapter.test_credentials()
finally:
adapter.close()
if not isinstance(result, CredentialTestSuccess):
_fail("WeCom live credential testing did not succeed")
if result.provider is not IMProvider.WE_COM:
_fail("WeCom live credential testing returned the wrong Provider")
if result.provider_tenant_id != wecom_credentials.value.corp_id:
_fail("WeCom live credential testing returned the wrong corporation boundary")
def test_live_directory_matches_an_independent_complete_sdk_traversal(
wecom_credentials: _LiveCredentials,
) -> None:
expected_entries = _read_expected_directory(wecom_credentials)
adapter = WeComIMProviderAdapter(wecom_credentials.value)
try:
actual = adapter.directory.read_directory()
finally:
adapter.close()
if not isinstance(actual, Directory):
_fail("WeCom live Directory did not return a complete snapshot")
if not expected_entries:
_fail("WeCom live Directory scope did not expose any members")
expected = tuple((entry.provider_user_id, entry.display_name, entry.email) for entry in expected_entries)
observed = tuple((str(entry.provider_user_id), entry.display_name, entry.email) for entry in actual.entries)
if observed != expected:
_fail("WeCom live Directory did not match the independent SDK traversal")
if any(not entry.provider_user_id.strip() for entry in expected_entries):
_fail("WeCom live Directory returned an invalid identity")
def test_live_messaging_confirms_provider_acceptance(
wecom_credentials: _LiveCredentials,
wecom_test_recipient_id: _LiveRecipient,
) -> None:
message_body = f"Dify WeCom live integration {uuid4()}"
if str(wecom_test_recipient_id.provider_user_id) in repr(wecom_test_recipient_id):
_fail("WeCom live recipient fixture repr is not sanitized")
adapter = WeComIMProviderAdapter(wecom_credentials.value)
try:
result = adapter.messaging.send_text(wecom_test_recipient_id.provider_user_id, message_body)
finally:
adapter.close()
if not isinstance(result, MessageAccepted):
_fail("WeCom did not confirm live message acceptance")
def _read_expected_directory(
live_credentials: _LiveCredentials,
) -> tuple[_ExpectedDirectoryEntry, ...]:
try:
credentials = live_credentials.value
client = WeChatClient(
credentials.corp_id,
credentials.secret,
timeout=_SDK_TIMEOUT_SECONDS,
auto_retry=False,
)
client.fetch_access_token()
scope = _AgentScope.model_validate(client.agent.get(int(credentials.agent_id)))
if scope.agentid != int(credentials.agent_id):
_fail("WeCom live agent scope did not match the configured application")
entries: list[_ExpectedDirectoryEntry] = []
seen_users: set[str] = set()
seen_departments: set[int] = set()
for department_id in scope.allow_partys.partyid:
_read_expected_department(client, department_id, entries, seen_users, seen_departments)
for scoped_user in scope.allow_userinfos.user:
_read_expected_user(client, scoped_user.userid, entries, seen_users)
for tag_id in scope.allow_tags.tagid:
tag = _TagScope.model_validate(client.tag.get_users(tag_id))
for scoped_user in tag.userlist:
_read_expected_user(client, scoped_user.userid, entries, seen_users)
for department_id in tag.partylist:
_read_expected_department(client, department_id, entries, seen_users, seen_departments)
return tuple(entries)
except AssertionError:
raise
except Exception:
_fail("Independent WeCom live Directory traversal failed")
def _read_expected_department(
client: WeChatClient,
root_department_id: int,
entries: list[_ExpectedDirectoryEntry],
seen_users: set[str],
seen_departments: set[int],
) -> None:
if root_department_id in seen_departments:
return
departments = tuple(_Department.model_validate(value) for value in client.department.get(root_department_id))
if not any(department.id == root_department_id for department in departments):
_fail("WeCom live department traversal omitted its requested root")
for department in departments:
if department.id in seen_departments:
continue
seen_departments.add(department.id)
users = tuple(
_DirectoryUser.model_validate(value)
for value in client.user.list(department.id, fetch_child=False, status=0, simple=False)
)
for user in users:
_append_expected_user(user, entries, seen_users)
def _read_expected_user(
client: WeChatClient,
user_id: str,
entries: list[_ExpectedDirectoryEntry],
seen_users: set[str],
) -> None:
if user_id in seen_users:
return
user = _DirectoryUser.model_validate(client.user.get(user_id))
if user.userid != user_id:
_fail("WeCom live user lookup returned a different identity")
_append_expected_user(user, entries, seen_users)
def _append_expected_user(
user: _DirectoryUser,
entries: list[_ExpectedDirectoryEntry],
seen_users: set[str],
) -> None:
if not user.userid.strip():
_fail("WeCom live Directory returned a blank identity")
if user.userid in seen_users:
return
seen_users.add(user.userid)
entries.append(
_ExpectedDirectoryEntry(
provider_user_id=user.userid,
display_name=_optional_non_blank(user.name),
email=_optional_non_blank(user.email),
)
)
def _optional_non_blank(value: str | None) -> str | None:
if value is None or not value.strip():
return None
return value
@@ -0,0 +1,600 @@
"""
Integration tests for TenantIsolatedTaskQueue using testcontainers.
These tests verify the Redis-based task queue functionality with real Redis instances,
testing tenant isolation, task serialization, and queue operations in a realistic environment.
Includes compatibility tests for migrating from legacy string-only queues.
All tests use generic naming to avoid coupling to specific business implementations.
"""
import time
from dataclasses import dataclass
from typing import Any
from uuid import uuid4
import pytest
from faker import Faker
from sqlalchemy.orm import Session
from core.rag.pipeline.queue import TaskWrapper, TenantIsolatedTaskQueue
from extensions.ext_redis import redis_client
from models import Account, AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus
TenantAndAccount = tuple[Tenant, Account]
@dataclass
class TestTask:
"""Test task data structure for testing complex object serialization."""
task_id: str
tenant_id: str
data: dict[str, Any]
metadata: dict[str, Any]
class TestTenantIsolatedTaskQueueIntegration:
"""Integration tests for TenantIsolatedTaskQueue using testcontainers."""
@pytest.fixture
def fake(self):
"""Faker instance for generating test data."""
return Faker()
@pytest.fixture
def test_tenant_and_account(self, db_session_with_containers: Session, fake: Faker):
"""Create test tenant and account for testing."""
# Create account
account = Account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
status=AccountStatus.ACTIVE,
)
db_session_with_containers.add(account)
db_session_with_containers.commit()
# Create tenant
tenant = Tenant(
name=fake.company(),
status=TenantStatus.NORMAL,
)
db_session_with_containers.add(tenant)
db_session_with_containers.commit()
# Create tenant-account join
join = TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role=TenantAccountRole.OWNER,
current=True,
)
db_session_with_containers.add(join)
db_session_with_containers.commit()
return tenant, account
@pytest.fixture
def test_queue(self, test_tenant_and_account: TenantAndAccount):
"""Create a generic test queue for testing."""
tenant, _ = test_tenant_and_account
return TenantIsolatedTaskQueue(tenant.id, "test_queue")
@pytest.fixture
def secondary_queue(self, test_tenant_and_account: TenantAndAccount):
"""Create a secondary test queue for testing isolation."""
tenant, _ = test_tenant_and_account
return TenantIsolatedTaskQueue(tenant.id, "secondary_queue")
def test_queue_initialization(self, test_tenant_and_account: TenantAndAccount):
"""Test queue initialization with correct key generation."""
tenant, _ = test_tenant_and_account
queue = TenantIsolatedTaskQueue(tenant.id, "test-key")
assert queue._tenant_id == tenant.id
assert queue._unique_key == "test-key"
assert queue._queue == f"tenant_self_test-key_task_queue:{tenant.id}"
assert queue._task_key == f"tenant_test-key_task:{tenant.id}"
def test_tenant_isolation(
self, test_tenant_and_account: TenantAndAccount, db_session_with_containers: Session, fake: Faker
):
"""Test that different tenants have isolated queues."""
tenant1, _ = test_tenant_and_account
# Create second tenant
tenant2 = Tenant(
name=fake.company(),
status=TenantStatus.NORMAL,
)
db_session_with_containers.add(tenant2)
db_session_with_containers.commit()
queue1 = TenantIsolatedTaskQueue(tenant1.id, "same-key")
queue2 = TenantIsolatedTaskQueue(tenant2.id, "same-key")
assert queue1._queue != queue2._queue
assert queue1._task_key != queue2._task_key
assert queue1._queue == f"tenant_self_same-key_task_queue:{tenant1.id}"
assert queue2._queue == f"tenant_self_same-key_task_queue:{tenant2.id}"
def test_key_isolation(self, test_tenant_and_account: TenantAndAccount):
"""Test that different keys have isolated queues."""
tenant, _ = test_tenant_and_account
queue1 = TenantIsolatedTaskQueue(tenant.id, "key1")
queue2 = TenantIsolatedTaskQueue(tenant.id, "key2")
assert queue1._queue != queue2._queue
assert queue1._task_key != queue2._task_key
assert queue1._queue == f"tenant_self_key1_task_queue:{tenant.id}"
assert queue2._queue == f"tenant_self_key2_task_queue:{tenant.id}"
def test_task_key_operations(self, test_queue):
"""Test task key operations (get, set, delete)."""
# Initially no task key should exist
assert test_queue.get_task_key() is None
# Set task waiting time with default TTL
test_queue.set_task_waiting_time()
task_key = test_queue.get_task_key()
# Redis returns bytes, convert to string for comparison
assert task_key in (b"1", "1")
# Set task waiting time with custom TTL
custom_ttl = 30
test_queue.set_task_waiting_time(custom_ttl)
task_key = test_queue.get_task_key()
assert task_key in (b"1", "1")
# Delete task key
test_queue.delete_task_key()
assert test_queue.get_task_key() is None
def test_push_and_pull_string_tasks(self, test_queue):
"""Test pushing and pulling string tasks."""
tasks = ["task1", "task2", "task3"]
# Push tasks
test_queue.push_tasks(tasks)
# Pull tasks (FIFO order)
pulled_tasks = test_queue.pull_tasks(3)
# Should get tasks in FIFO order (lpush + rpop = FIFO)
assert pulled_tasks == ["task1", "task2", "task3"]
def test_push_and_pull_multiple_tasks(self, test_queue):
"""Test pushing and pulling multiple tasks at once."""
tasks = ["task1", "task2", "task3", "task4", "task5"]
# Push tasks
test_queue.push_tasks(tasks)
# Pull multiple tasks
pulled_tasks = test_queue.pull_tasks(3)
assert len(pulled_tasks) == 3
assert pulled_tasks == ["task1", "task2", "task3"]
# Pull remaining tasks
remaining_tasks = test_queue.pull_tasks(5)
assert len(remaining_tasks) == 2
assert remaining_tasks == ["task4", "task5"]
def test_push_and_pull_complex_objects(self, test_queue, fake: Faker):
"""Test pushing and pulling complex object tasks."""
# Create complex task objects as dictionaries (not dataclass instances)
tasks = [
{
"task_id": str(uuid4()),
"tenant_id": test_queue._tenant_id,
"data": {
"file_id": str(uuid4()),
"content": fake.text(),
"metadata": {"size": fake.random_int(1000, 10000)},
},
"metadata": {"created_at": fake.iso8601(), "tags": fake.words(3)},
},
{
"task_id": str(uuid4()),
"tenant_id": test_queue._tenant_id,
"data": {
"file_id": str(uuid4()),
"content": "测试中文内容",
"metadata": {"size": fake.random_int(1000, 10000)},
},
"metadata": {"created_at": fake.iso8601(), "tags": ["中文", "测试", "emoji🚀"]},
},
]
# Push complex tasks
test_queue.push_tasks(tasks)
# Pull tasks
pulled_tasks = test_queue.pull_tasks(2)
assert len(pulled_tasks) == 2
# Verify deserialized tasks match original (FIFO order)
for i, pulled_task in enumerate(pulled_tasks):
original_task = tasks[i] # FIFO order
assert isinstance(pulled_task, dict)
assert pulled_task["task_id"] == original_task["task_id"]
assert pulled_task["tenant_id"] == original_task["tenant_id"]
assert pulled_task["data"] == original_task["data"]
assert pulled_task["metadata"] == original_task["metadata"]
def test_mixed_task_types(self, test_queue, fake: Faker):
"""Test pushing and pulling mixed string and object tasks."""
string_task = "simple_string_task"
object_task = {
"task_id": str(uuid4()),
"dataset_id": str(uuid4()),
"document_ids": [str(uuid4()) for _ in range(3)],
}
tasks = [string_task, object_task, "another_string"]
# Push mixed tasks
test_queue.push_tasks(tasks)
# Pull all tasks
pulled_tasks = test_queue.pull_tasks(3)
assert len(pulled_tasks) == 3
# Verify types and content
assert pulled_tasks[0] == string_task
assert isinstance(pulled_tasks[1], dict)
assert pulled_tasks[1] == object_task
assert pulled_tasks[2] == "another_string"
def test_empty_queue_operations(self, test_queue):
"""Test operations on empty queue."""
# Pull from empty queue
tasks = test_queue.pull_tasks(5)
assert tasks == []
# Pull zero or negative count
assert test_queue.pull_tasks(0) == []
assert test_queue.pull_tasks(-1) == []
def test_task_ttl_expiration(self, test_queue):
"""Test task key TTL expiration."""
# Set task with short TTL
short_ttl = 2
test_queue.set_task_waiting_time(short_ttl)
# Verify task key exists
assert test_queue.get_task_key() == b"1" or test_queue.get_task_key() == "1"
# Wait for TTL to expire
time.sleep(short_ttl + 1)
# Verify task key has expired
assert test_queue.get_task_key() is None
def test_large_task_batch(self, test_queue, fake: Faker):
"""Test handling large batches of tasks."""
# Create large batch of tasks
large_batch = []
for i in range(100):
task = {
"task_id": str(uuid4()),
"index": i,
"data": fake.text(max_nb_chars=100),
"metadata": {"batch_id": str(uuid4())},
}
large_batch.append(task)
# Push large batch
test_queue.push_tasks(large_batch)
# Pull all tasks
pulled_tasks = test_queue.pull_tasks(100)
assert len(pulled_tasks) == 100
# Verify all tasks were retrieved correctly (FIFO order)
for i, task in enumerate(pulled_tasks):
assert isinstance(task, dict)
assert task["index"] == i # FIFO order
def test_queue_operations_isolation(self, test_tenant_and_account: TenantAndAccount, fake: Faker):
"""Test concurrent operations on different queues."""
tenant, _ = test_tenant_and_account
# Create multiple queues for the same tenant
queue1 = TenantIsolatedTaskQueue(tenant.id, "queue1")
queue2 = TenantIsolatedTaskQueue(tenant.id, "queue2")
# Push tasks to different queues
queue1.push_tasks(["task1_queue1", "task2_queue1"])
queue2.push_tasks(["task1_queue2", "task2_queue2"])
# Verify queues are isolated
tasks1 = queue1.pull_tasks(2)
tasks2 = queue2.pull_tasks(2)
assert tasks1 == ["task1_queue1", "task2_queue1"]
assert tasks2 == ["task1_queue2", "task2_queue2"]
assert tasks1 != tasks2
def test_task_wrapper_serialization_roundtrip(self, test_queue, fake: Faker):
"""Test TaskWrapper serialization and deserialization roundtrip."""
# Create complex nested data
complex_data = {
"id": str(uuid4()),
"nested": {"deep": {"value": "test", "numbers": [1, 2, 3, 4, 5], "unicode": "测试中文", "emoji": "🚀"}},
"metadata": {"created_at": fake.iso8601(), "tags": ["tag1", "tag2", "tag3"]},
}
# Create wrapper and serialize
wrapper = TaskWrapper(data=complex_data)
serialized = wrapper.serialize()
# Verify serialization
assert isinstance(serialized, str)
assert "测试中文" in serialized
assert "🚀" in serialized
# Deserialize and verify
deserialized_wrapper = TaskWrapper.deserialize(serialized)
assert deserialized_wrapper.data == complex_data
def test_error_handling_invalid_json(self, test_queue):
"""Test error handling for invalid JSON in wrapped tasks."""
# Manually create invalid JSON task (not a valid TaskWrapper JSON)
invalid_json_task = "invalid json data"
# Push invalid task directly to Redis
redis_client.lpush(test_queue._queue, invalid_json_task)
# Pull task - should fall back to string since it's not valid JSON
task = test_queue.pull_tasks(1)
assert task[0] == invalid_json_task
def test_real_world_batch_processing_scenario(self, test_queue, fake: Faker):
"""Test realistic batch processing scenario."""
# Simulate batch processing tasks
batch_tasks = []
for _i in range(3):
task = {
"file_id": str(uuid4()),
"tenant_id": test_queue._tenant_id,
"user_id": str(uuid4()),
"processing_config": {
"model": fake.random_element(["model_a", "model_b", "model_c"]),
"temperature": fake.random.uniform(0.1, 1.0),
"max_tokens": fake.random_int(1000, 4000),
},
"metadata": {
"source": fake.random_element(["upload", "api", "webhook"]),
"priority": fake.random_element(["low", "normal", "high"]),
},
}
batch_tasks.append(task)
# Push tasks
test_queue.push_tasks(batch_tasks)
# Process tasks in batches
batch_size = 2
processed_tasks = []
while True:
batch = test_queue.pull_tasks(batch_size)
if not batch:
break
processed_tasks.extend(batch)
# Verify all tasks were processed
assert len(processed_tasks) == 3
# Verify task structure
for task in processed_tasks:
assert isinstance(task, dict)
assert "file_id" in task
assert "tenant_id" in task
assert "processing_config" in task
assert "metadata" in task
assert task["tenant_id"] == test_queue._tenant_id
class TestTenantIsolatedTaskQueueCompatibility:
"""Compatibility tests for migrating from legacy string-only queues."""
@pytest.fixture
def fake(self):
"""Faker instance for generating test data."""
return Faker()
@pytest.fixture
def test_tenant_and_account(self, db_session_with_containers: Session, fake: Faker):
"""Create test tenant and account for testing."""
# Create account
account = Account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
status=AccountStatus.ACTIVE,
)
db_session_with_containers.add(account)
db_session_with_containers.commit()
# Create tenant
tenant = Tenant(
name=fake.company(),
status=TenantStatus.NORMAL,
)
db_session_with_containers.add(tenant)
db_session_with_containers.commit()
# Create tenant-account join
join = TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role=TenantAccountRole.OWNER,
current=True,
)
db_session_with_containers.add(join)
db_session_with_containers.commit()
return tenant, account
def test_legacy_string_queue_compatibility(self, test_tenant_and_account: TenantAndAccount, fake: Faker):
"""
Test compatibility with legacy queues containing only string data.
This simulates the scenario where Redis queues already contain string data
from the old architecture, and we need to ensure the new code can read them.
"""
tenant, _ = test_tenant_and_account
queue = TenantIsolatedTaskQueue(tenant.id, "legacy_queue")
# Simulate legacy string data in Redis queue (using old format)
legacy_strings = ["legacy_task_1", "legacy_task_2", "legacy_task_3", "legacy_task_4", "legacy_task_5"]
# Manually push legacy strings directly to Redis (simulating old system)
for legacy_string in legacy_strings:
redis_client.lpush(queue._queue, legacy_string)
# Verify new code can read legacy string data
pulled_tasks = queue.pull_tasks(5)
assert len(pulled_tasks) == 5
# Verify all tasks are strings (not wrapped)
for task in pulled_tasks:
assert isinstance(task, str)
assert task.startswith("legacy_task_")
# Verify order (FIFO from Redis list)
expected_order = ["legacy_task_1", "legacy_task_2", "legacy_task_3", "legacy_task_4", "legacy_task_5"]
assert pulled_tasks == expected_order
def test_legacy_queue_migration_scenario(self, test_tenant_and_account: TenantAndAccount, fake: Faker):
"""
Test complete migration scenario from legacy to new system.
This simulates the real-world scenario where:
1. Legacy system has string data in Redis
2. New system starts processing the same queue
3. Both legacy and new tasks coexist during migration
4. New system can handle both formats seamlessly
"""
tenant, _ = test_tenant_and_account
queue = TenantIsolatedTaskQueue(tenant.id, "migration_queue")
# Phase 1: Legacy system has data
legacy_tasks = [f"legacy_resource_{i}" for i in range(1, 6)]
redis_client.lpush(queue._queue, *legacy_tasks)
# Phase 2: New system starts processing legacy data
processed_legacy = []
while True:
tasks = queue.pull_tasks(1)
if not tasks:
break
processed_legacy.extend(tasks)
# Verify legacy data was processed correctly
assert len(processed_legacy) == 5
for task in processed_legacy:
assert isinstance(task, str)
assert task.startswith("legacy_resource_")
# Phase 3: New system adds new tasks (mixed types)
new_string_tasks = ["new_resource_1", "new_resource_2"]
new_object_tasks = [
{
"resource_id": str(uuid4()),
"tenant_id": tenant.id,
"processing_type": "new_system",
"metadata": {"version": "2.0", "features": ["ai", "ml"]},
},
{
"resource_id": str(uuid4()),
"tenant_id": tenant.id,
"processing_type": "new_system",
"metadata": {"version": "2.0", "features": ["ai", "ml"]},
},
]
# Push new tasks using new system
queue.push_tasks(new_string_tasks)
queue.push_tasks(new_object_tasks)
# Phase 4: Process all new tasks
processed_new = []
while True:
tasks = queue.pull_tasks(1)
if not tasks:
break
processed_new.extend(tasks)
# Verify new tasks were processed correctly
assert len(processed_new) == 4
string_tasks = [task for task in processed_new if isinstance(task, str)]
object_tasks = [task for task in processed_new if isinstance(task, dict)]
assert len(string_tasks) == 2
assert len(object_tasks) == 2
# Verify string tasks
for task in string_tasks:
assert task.startswith("new_resource_")
# Verify object tasks
for task in object_tasks:
assert isinstance(task, dict)
assert "resource_id" in task
assert "tenant_id" in task
assert task["tenant_id"] == tenant.id
assert task["processing_type"] == "new_system"
def test_legacy_queue_error_recovery(self, test_tenant_and_account: TenantAndAccount, fake: Faker):
"""
Test error recovery when legacy queue contains malformed data.
This ensures the new system can gracefully handle corrupted or
malformed legacy data without crashing.
"""
tenant, _ = test_tenant_and_account
queue = TenantIsolatedTaskQueue(tenant.id, "error_recovery_queue")
# Create mix of valid and malformed legacy data
mixed_legacy_data = [
"valid_legacy_task_1",
"valid_legacy_task_2",
"malformed_data_string", # This should be treated as string
"valid_legacy_task_3",
"invalid_json_not_taskwrapper_format", # This should fall back to string (not valid TaskWrapper JSON)
"valid_legacy_task_4",
]
# Manually push mixed data directly to Redis
redis_client.lpush(queue._queue, *mixed_legacy_data)
# Process all tasks
processed_tasks = []
while True:
tasks = queue.pull_tasks(1)
if not tasks:
break
processed_tasks.extend(tasks)
# Verify all tasks were processed (no crashes)
assert len(processed_tasks) == 6
# Verify all tasks are strings (malformed data falls back to string)
for task in processed_tasks:
assert isinstance(task, str)
# Verify valid tasks are preserved
valid_tasks = [task for task in processed_tasks if task.startswith("valid_legacy_task_")]
assert len(valid_tasks) == 4
# Verify malformed data is handled gracefully
malformed_tasks = [task for task in processed_tasks if not task.startswith("valid_legacy_task_")]
assert len(malformed_tasks) == 2
assert "malformed_data_string" in malformed_tasks
assert "invalid_json_not_taskwrapper_format" in malformed_tasks
@@ -0,0 +1,631 @@
import uuid
from unittest.mock import patch
import pytest
from faker import Faker
from sqlalchemy.orm import Session
from core.rag.index_processor.constant.index_type import IndexStructureType, IndexTechniqueType
from core.rag.retrieval.dataset_retrieval import DatasetRetrieval
from core.workflow.nodes.knowledge_retrieval.retrieval import KnowledgeRetrievalRequest
from models.dataset import Dataset, Document
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus
from tests.e2e_tests.containers.helpers import accounts as account_fixtures
from tests.e2e_tests.containers.helpers import generate_valid_password
class TestGetAvailableDatasetsIntegration:
def test_returns_datasets_with_available_documents(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
# Create account and tenant
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
# Create dataset
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
description=fake.text(max_nb_chars=100),
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
# Create documents with completed status, enabled, not archived
for i in range(3):
document = Document(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
dataset_id=dataset.id,
position=i,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=str(uuid.uuid4()), # Required field
name=f"Document {i}",
created_from=DocumentCreatedFrom.WEB,
created_by=account.id,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
doc_language="en",
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
archived=False,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
# Act
dataset_retrieval = DatasetRetrieval()
result = dataset_retrieval._get_available_datasets(tenant.id, [dataset.id])
# Assert
assert len(result) == 1
assert result[0].id == dataset.id
assert result[0].tenant_id == tenant.id
assert result[0].name == dataset.name
def test_filters_out_datasets_with_only_archived_documents(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
)
db_session_with_containers.add(dataset)
# Create only archived documents
for i in range(2):
document = Document(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
dataset_id=dataset.id,
position=i,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=str(uuid.uuid4()), # Required field
created_from=DocumentCreatedFrom.WEB,
name=f"Archived Document {i}",
created_by=account.id,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
archived=True, # Archived
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
# Act
dataset_retrieval = DatasetRetrieval()
result = dataset_retrieval._get_available_datasets(tenant.id, [dataset.id])
# Assert
assert len(result) == 0
def test_filters_out_datasets_with_only_disabled_documents(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
)
db_session_with_containers.add(dataset)
# Create only disabled documents
for i in range(2):
document = Document(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
dataset_id=dataset.id,
position=i,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=str(uuid.uuid4()), # Required field
created_from=DocumentCreatedFrom.WEB,
name=f"Disabled Document {i}",
created_by=account.id,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
indexing_status=IndexingStatus.COMPLETED,
enabled=False, # Disabled
archived=False,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
# Act
dataset_retrieval = DatasetRetrieval()
result = dataset_retrieval._get_available_datasets(tenant.id, [dataset.id])
# Assert
assert len(result) == 0
def test_filters_out_datasets_with_non_completed_documents(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
)
db_session_with_containers.add(dataset)
# Create documents with non-completed status
for i, status in enumerate([IndexingStatus.INDEXING, IndexingStatus.PARSING, IndexingStatus.SPLITTING]):
document = Document(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
dataset_id=dataset.id,
position=i,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=str(uuid.uuid4()), # Required field
created_from=DocumentCreatedFrom.WEB,
name=f"Document {status}",
created_by=account.id,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
indexing_status=status, # Not completed
enabled=True,
archived=False,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
# Act
dataset_retrieval = DatasetRetrieval()
result = dataset_retrieval._get_available_datasets(tenant.id, [dataset.id])
# Assert
assert len(result) == 0
def test_includes_external_datasets_without_documents(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
"""
Test that external datasets are returned even with no available documents.
External datasets (e.g., from external knowledge bases) don't have
documents stored in Dify's database, so they should always be available.
Verifies:
- External datasets are included in results
- No document count check for external datasets
"""
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
provider="external", # External provider
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
)
db_session_with_containers.add(dataset)
db_session_with_containers.commit()
# Act
dataset_retrieval = DatasetRetrieval()
result = dataset_retrieval._get_available_datasets(tenant.id, [dataset.id])
# Assert
assert len(result) == 1
assert result[0].id == dataset.id
assert result[0].provider == "external"
def test_filters_by_tenant_id(self, db_session_with_containers: Session, mock_external_service_dependencies):
# Arrange
fake = Faker()
# Create two accounts/tenants
account1 = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account1, name=fake.company(), session=db_session_with_containers)
tenant1 = account1.current_tenant
account2 = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account2, name=fake.company(), session=db_session_with_containers)
tenant2 = account2.current_tenant
# Create dataset for tenant1
dataset1 = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant1.id,
name="Tenant 1 Dataset",
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account1.id,
)
db_session_with_containers.add(dataset1)
# Create dataset for tenant2
dataset2 = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant2.id,
name="Tenant 2 Dataset",
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account2.id,
)
db_session_with_containers.add(dataset2)
# Add documents to both datasets
for dataset, account in [(dataset1, account1), (dataset2, account2)]:
document = Document(
id=str(uuid.uuid4()),
tenant_id=dataset.tenant_id,
dataset_id=dataset.id,
position=0,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=str(uuid.uuid4()), # Required field
created_from=DocumentCreatedFrom.WEB,
name=f"Document for {dataset.name}",
created_by=account.id,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
archived=False,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
# Act - request from tenant1, should only get tenant1's dataset
dataset_retrieval = DatasetRetrieval()
result = dataset_retrieval._get_available_datasets(tenant1.id, [dataset1.id, dataset2.id])
# Assert
assert len(result) == 1
assert result[0].id == dataset1.id
assert result[0].tenant_id == tenant1.id
def test_returns_empty_list_when_no_datasets_found(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
# Don't create any datasets
# Act
dataset_retrieval = DatasetRetrieval()
result = dataset_retrieval._get_available_datasets(tenant.id, [str(uuid.uuid4())])
# Assert
assert result == []
def test_returns_only_requested_dataset_ids(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
# Create multiple datasets
datasets = []
for i in range(3):
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=f"Dataset {i}",
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
)
db_session_with_containers.add(dataset)
datasets.append(dataset)
# Add document
document = Document(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
dataset_id=dataset.id,
position=0,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=str(uuid.uuid4()), # Required field
created_from=DocumentCreatedFrom.WEB,
name=f"Document {i}",
created_by=account.id,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
archived=False,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
# Act - request only dataset 0 and 2, not dataset 1
dataset_retrieval = DatasetRetrieval()
requested_ids = [datasets[0].id, datasets[2].id]
result = dataset_retrieval._get_available_datasets(tenant.id, requested_ids)
# Assert
assert len(result) == 2
returned_ids = {d.id for d in result}
assert returned_ids == {datasets[0].id, datasets[2].id}
class TestKnowledgeRetrievalIntegration:
def test_knowledge_retrieval_with_available_datasets(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
indexing_technique=IndexTechniqueType.HIGH_QUALITY,
)
db_session_with_containers.add(dataset)
document = Document(
tenant_id=tenant.id,
dataset_id=dataset.id,
position=0,
data_source_type=DataSourceType.UPLOAD_FILE,
batch=str(uuid.uuid4()), # Required field
created_from=DocumentCreatedFrom.WEB,
name=fake.sentence(),
created_by=account.id,
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
archived=False,
doc_form=IndexStructureType.PARAGRAPH_INDEX,
)
db_session_with_containers.add(document)
db_session_with_containers.commit()
# Create request
request = KnowledgeRetrievalRequest(
tenant_id=tenant.id,
user_id=account.id,
app_id=str(uuid.uuid4()),
user_from="web",
dataset_ids=[dataset.id],
query="test query",
retrieval_mode="multiple",
top_k=5,
)
dataset_retrieval = DatasetRetrieval()
# Mock rate limit check and retrieval
with patch.object(dataset_retrieval, "_check_knowledge_rate_limit"):
with patch.object(dataset_retrieval, "get_metadata_filter_condition", return_value=(None, None)):
with patch.object(dataset_retrieval, "multiple_retrieve", return_value=[]):
# Act
result = dataset_retrieval.knowledge_retrieval(db_session_with_containers, request)
# Assert
assert isinstance(result, list)
def test_knowledge_retrieval_no_available_datasets(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
# Create dataset but no documents
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
)
db_session_with_containers.add(dataset)
db_session_with_containers.commit()
request = KnowledgeRetrievalRequest(
tenant_id=tenant.id,
user_id=account.id,
app_id=str(uuid.uuid4()),
user_from="web",
dataset_ids=[dataset.id],
query="test query",
retrieval_mode="multiple",
top_k=5,
)
dataset_retrieval = DatasetRetrieval()
# Mock rate limit check
with patch.object(dataset_retrieval, "_check_knowledge_rate_limit"):
# Act
result = dataset_retrieval.knowledge_retrieval(db_session_with_containers, request)
# Assert
assert result == []
def test_knowledge_retrieval_rate_limit_exceeded(
self, db_session_with_containers: Session, mock_external_service_dependencies
):
# Arrange
fake = Faker()
account = account_fixtures.create_account(
email=fake.email(),
name=fake.name(),
interface_language="en-US",
password=generate_valid_password(fake),
session=db_session_with_containers,
)
account_fixtures.create_owner_workspace(account, name=fake.company(), session=db_session_with_containers)
tenant = account.current_tenant
dataset = Dataset(
id=str(uuid.uuid4()),
tenant_id=tenant.id,
name=fake.company(),
provider="dify",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=account.id,
)
db_session_with_containers.add(dataset)
db_session_with_containers.commit()
request = KnowledgeRetrievalRequest(
tenant_id=tenant.id,
user_id=account.id,
app_id=str(uuid.uuid4()),
user_from="web",
dataset_ids=[dataset.id],
query="test query",
retrieval_mode="multiple",
top_k=5,
)
dataset_retrieval = DatasetRetrieval()
# Mock rate limit check to raise exception
with patch.object(
dataset_retrieval,
"_check_knowledge_rate_limit",
side_effect=Exception("Rate limit exceeded"),
):
# Act & Assert
with pytest.raises(Exception, match="Rate limit exceeded"):
dataset_retrieval.knowledge_retrieval(db_session_with_containers, request)
@pytest.fixture
def mock_external_service_dependencies():
with (
patch("services.account.login_adapters.SystemFeatureService") as mock_account_feature_service,
):
# Setup default mock returns for account service
mock_account_feature_service.is_registration_allowed.return_value = True
yield {
"account_feature_service": mock_account_feature_service,
}
@@ -0,0 +1,241 @@
"""TestContainers integration tests for HumanInputFormRepositoryImpl."""
from __future__ import annotations
from uuid import uuid4
from sqlalchemy import Engine, select
from sqlalchemy.orm import Session
from core.repositories.human_input_repository import FormCreateParams, HumanInputFormRepositoryImpl
from core.workflow.human_input_adapter import (
DeliveryChannelConfig,
EmailDeliveryConfig,
EmailDeliveryMethod,
EmailRecipients,
ExternalRecipient,
MemberRecipient,
WebAppDeliveryMethod,
)
from core.workflow.nodes.human_input.entities import FormDefinition, HumanInputNodeData, UserActionConfig
from models.account import (
Account,
AccountStatus,
Tenant,
TenantAccountJoin,
TenantAccountRole,
TenantStatus,
)
from models.human_input import (
EmailExternalRecipientPayload,
EmailMemberRecipientPayload,
HumanInputForm,
HumanInputFormRecipient,
RecipientType,
)
def _create_tenant_with_members(session: Session, member_emails: list[str]) -> tuple[Tenant, list[Account]]:
tenant = Tenant(name="Test Tenant", status=TenantStatus.NORMAL)
session.add(tenant)
session.flush()
members: list[Account] = []
for index, email in enumerate(member_emails):
account = Account(
email=email,
name=f"Member {index}",
interface_language="en-US",
status=AccountStatus.ACTIVE,
)
session.add(account)
session.flush()
tenant_join = TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role=TenantAccountRole.NORMAL,
current=True,
)
session.add(tenant_join)
members.append(account)
session.commit()
return tenant, members
def _build_form_params(delivery_methods: list[DeliveryChannelConfig]) -> FormCreateParams:
form_config = HumanInputNodeData(
title="Human Approval",
delivery_methods=delivery_methods,
form_content="<p>Approve?</p>",
user_actions=[UserActionConfig(id="approve", title="Approve")],
)
return FormCreateParams(
workflow_execution_id=str(uuid4()),
node_id="human-input-node",
form_config=form_config,
rendered_content="<p>Approve?</p>",
delivery_methods=delivery_methods,
display_in_ui=False,
resolved_default_values={},
)
def _build_email_delivery(
whole_workspace: bool, recipients: list[MemberRecipient | ExternalRecipient]
) -> EmailDeliveryMethod:
return EmailDeliveryMethod(
config=EmailDeliveryConfig(
recipients=EmailRecipients(include_bound_group=whole_workspace, items=recipients),
subject="Approval Needed",
body="Please review",
)
)
class TestHumanInputFormRepositoryImplWithContainers:
def test_create_form_with_whole_workspace_recipients(self, db_session_with_containers: Session) -> None:
engine = db_session_with_containers.get_bind()
assert isinstance(engine, Engine)
tenant, members = _create_tenant_with_members(
db_session_with_containers,
member_emails=["member1@example.com", "member2@example.com"],
)
repository = HumanInputFormRepositoryImpl(tenant_id=tenant.id, app_id=str(uuid4()))
params = _build_form_params(
delivery_methods=[_build_email_delivery(whole_workspace=True, recipients=[])],
)
form_entity = repository.create_form(params)
with Session(engine) as verification_session:
recipients = verification_session.scalars(
select(HumanInputFormRecipient).where(HumanInputFormRecipient.form_id == form_entity.id)
).all()
assert len(recipients) == len(members)
member_payloads = [
EmailMemberRecipientPayload.model_validate_json(recipient.recipient_payload)
for recipient in recipients
if recipient.recipient_type == RecipientType.EMAIL_MEMBER
]
member_emails = {payload.email for payload in member_payloads}
assert member_emails == {member.email for member in members}
def test_create_form_with_specific_members_and_external(self, db_session_with_containers: Session) -> None:
engine = db_session_with_containers.get_bind()
assert isinstance(engine, Engine)
tenant, members = _create_tenant_with_members(
db_session_with_containers,
member_emails=["primary@example.com", "secondary@example.com"],
)
repository = HumanInputFormRepositoryImpl(tenant_id=tenant.id, app_id=str(uuid4()))
params = _build_form_params(
delivery_methods=[
_build_email_delivery(
whole_workspace=False,
recipients=[
MemberRecipient(reference_id=members[0].id),
ExternalRecipient(email="external@example.com"),
],
)
],
)
form_entity = repository.create_form(params)
with Session(engine) as verification_session:
recipients = verification_session.scalars(
select(HumanInputFormRecipient).where(HumanInputFormRecipient.form_id == form_entity.id)
).all()
member_recipient_payloads = [
EmailMemberRecipientPayload.model_validate_json(recipient.recipient_payload)
for recipient in recipients
if recipient.recipient_type == RecipientType.EMAIL_MEMBER
]
assert len(member_recipient_payloads) == 1
assert member_recipient_payloads[0].user_id == members[0].id
external_payloads = [
EmailExternalRecipientPayload.model_validate_json(recipient.recipient_payload)
for recipient in recipients
if recipient.recipient_type == RecipientType.EMAIL_EXTERNAL
]
assert len(external_payloads) == 1
assert external_payloads[0].email == "external@example.com"
def test_create_form_persists_default_values(self, db_session_with_containers: Session) -> None:
engine = db_session_with_containers.get_bind()
assert isinstance(engine, Engine)
tenant, _ = _create_tenant_with_members(
db_session_with_containers,
member_emails=["prefill@example.com"],
)
repository = HumanInputFormRepositoryImpl(tenant_id=tenant.id, app_id=str(uuid4()))
resolved_values = {"greeting": "Hello!"}
params = FormCreateParams(
workflow_execution_id=str(uuid4()),
node_id="human-input-node",
form_config=HumanInputNodeData(
title="Human Approval",
form_content="<p>Approve?</p>",
inputs=[],
user_actions=[UserActionConfig(id="approve", title="Approve")],
),
rendered_content="<p>Approve?</p>",
delivery_methods=[],
display_in_ui=False,
resolved_default_values=resolved_values,
)
form_entity = repository.create_form(params)
with Session(engine) as verification_session:
form_model = verification_session.scalars(
select(HumanInputForm).where(HumanInputForm.id == form_entity.id)
).first()
assert form_model is not None
definition = FormDefinition.model_validate_json(form_model.form_definition)
assert definition.default_values == resolved_values
def test_create_form_persists_display_in_ui(self, db_session_with_containers: Session) -> None:
engine = db_session_with_containers.get_bind()
assert isinstance(engine, Engine)
tenant, _ = _create_tenant_with_members(
db_session_with_containers,
member_emails=["ui@example.com"],
)
repository = HumanInputFormRepositoryImpl(tenant_id=tenant.id, app_id=str(uuid4()))
params = FormCreateParams(
workflow_execution_id=str(uuid4()),
node_id="human-input-node",
form_config=HumanInputNodeData(
title="Human Approval",
form_content="<p>Approve?</p>",
inputs=[],
user_actions=[UserActionConfig(id="approve", title="Approve")],
delivery_methods=[WebAppDeliveryMethod()],
),
rendered_content="<p>Approve?</p>",
delivery_methods=[WebAppDeliveryMethod()],
display_in_ui=True,
resolved_default_values={},
)
form_entity = repository.create_form(params)
with Session(engine) as verification_session:
form_model = verification_session.scalars(
select(HumanInputForm).where(HumanInputForm.id == form_entity.id)
).first()
assert form_model is not None
definition = FormDefinition.model_validate_json(form_model.form_definition)
assert definition.display_in_ui is True
@@ -0,0 +1,107 @@
"""PostgreSQL concurrency contracts for Human Input v2 form persistence."""
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from threading import Barrier, Event
from uuid import uuid4
import sqlalchemy as sa
from sqlalchemy.orm import Session
from core.human_input_v2.resolved_form import ResolvedForm
from core.human_input_v2.shared.values import RecipientId, TenantId
from libs.datetime_utils import naive_utc_now
from models.human_input_v2 import HumanInputForm
from repositories.human_input_v2.form_repository import Form, FormCreateParams, FormSubmissionFailure
from repositories.human_input_v2.sqlalchemy_form_repository import SQLAlchemyFormRepository
def _params() -> FormCreateParams:
now = naive_utc_now()
return FormCreateParams(
workflow_run_id=str(uuid4()),
node_execution_id=str(uuid4()),
resolved_form=ResolvedForm(title="Approval", parts=(), actions=(), legacy_form_content="Review this."),
expiration_time=now + timedelta(hours=1),
global_timeout_deadline=now + timedelta(hours=2),
)
def test_concurrent_creation_reuses_the_committed_form(db_session_with_containers: Session) -> None:
engine = db_session_with_containers.get_bind()
tenant_id = TenantId(str(uuid4()))
app_id = str(uuid4())
params = _params()
barrier = Barrier(2)
def create() -> Form:
with Session(engine) as session, session.begin():
barrier.wait(timeout=10)
return SQLAlchemyFormRepository(session, tenant_id, app_id).create_form(params)
with ThreadPoolExecutor(max_workers=2) as executor:
futures = [executor.submit(create) for _ in range(2)]
forms = [future.result(timeout=15) for future in futures]
assert forms[0] == forms[1]
def test_waiting_form_discovery_does_not_wait_for_form_locks(db_session_with_containers: Session) -> None:
engine = db_session_with_containers.get_bind()
tenant_id = TenantId(str(uuid4()))
app_id = str(uuid4())
params = _params()
assert params.workflow_run_id is not None
with Session(engine) as session, session.begin():
form = SQLAlchemyFormRepository(session, tenant_id, app_id).create_form(params)
with Session(engine) as blocker, blocker.begin():
blocker.scalars(sa.select(HumanInputForm).where(HumanInputForm.id == form.id).with_for_update()).one()
with Session(engine) as reader, reader.begin():
# Discovery must read committed facts even while a form is locked;
# only its eventual state transition needs to wait for that lock.
reader.execute(sa.text("SET LOCAL lock_timeout = '1s'"))
batch = SQLAlchemyFormRepository(reader, tenant_id, app_id).list_waiting_forms_for_run(
params.workflow_run_id
)
assert batch.forms == (form,)
def test_submission_rechecks_facts_and_clock_after_the_lock(db_session_with_containers: Session) -> None:
engine = db_session_with_containers.get_bind()
tenant_id = TenantId(str(uuid4()))
app_id = str(uuid4())
with Session(engine) as session, session.begin():
form = SQLAlchemyFormRepository(session, tenant_id, app_id).create_form(_params())
read_before_deadline_change = Event()
def submit() -> Form | FormSubmissionFailure:
with Session(engine) as session, session.begin():
repo = SQLAlchemyFormRepository(session, tenant_id, app_id)
assert repo.get_form_by_id(form.id) == form
read_before_deadline_change.set()
return repo.submit_form(
form.id,
submitted_by_recipient_id=RecipientId(str(uuid4())),
submitted_by_delivery_id=str(uuid4()),
selected_action_id="approve",
raw_submission_inputs={},
normalized_submission_data={},
)
with ThreadPoolExecutor(max_workers=1) as executor:
with Session(engine) as blocker, blocker.begin():
blocker.scalars(sa.select(HumanInputForm).where(HumanInputForm.id == form.id).with_for_update()).one()
future = executor.submit(submit)
assert read_before_deadline_change.wait(timeout=10)
# The submitter's transaction already started with the original future
# deadline. Commit a reached deadline while still holding the lock:
# neither its earlier snapshot nor transaction-start time may be used.
blocker.execute(
sa.update(HumanInputForm)
.where(HumanInputForm.id == form.id)
.values(
expiration_time=sa.func.timezone("UTC", sa.func.clock_timestamp()),
)
)
assert future.result(timeout=15) == FormSubmissionFailure.FORM_EXPIRED
@@ -0,0 +1,371 @@
import time
import uuid
import pytest
from sqlalchemy import delete, select
from sqlalchemy.orm import Session, sessionmaker
from core.app.app_config.entities import WorkflowUIBasedAppConfig
from core.app.entities.app_invoke_entities import InvokeFrom, UserFrom, WorkflowAppGenerateEntity
from core.repositories.human_input_repository import HumanInputFormRepository, HumanInputFormRepositoryImpl
from core.repositories.sqlalchemy_workflow_execution_repository import SQLAlchemyWorkflowExecutionRepository
from core.repositories.sqlalchemy_workflow_node_execution_repository import SQLAlchemyWorkflowNodeExecutionRepository
from core.workflow.nodes.human_input.callback import (
DifyHITLCallback,
)
from core.workflow.nodes.human_input.entities import HumanInputNodeData, UserActionConfig
from core.workflow.nodes.human_input.enums import HumanInputFormStatus
from core.workflow.system_variables import build_system_variables
from graphon.engine import Engine
from graphon.engine.command import InMemoryChannel
from graphon.enums import WorkflowType
from graphon.graph import Graph
from graphon.nodes.end.end_node import EndNode
from graphon.nodes.end.entities import EndNodeData
from graphon.nodes.human_input.entities import HumanInputNodeData as GraphonHumanInputNodeData
from graphon.nodes.human_input.human_input_node import HumanInputNode
from graphon.nodes.start.entities import StartNodeData
from graphon.nodes.start.start_node import StartNode
from graphon.runtime import RuntimeState, VariablePool
from libs.datetime_utils import naive_utc_now
from models import Account
from models.account import AccountStatus, Tenant, TenantAccountJoin, TenantAccountRole, TenantStatus
from models.enums import CreatorUserRole, WorkflowRunTriggeredFrom
from models.human_input import HumanInputDelivery, HumanInputForm, HumanInputFormRecipient
from models.model import App, AppMode, IconType
from models.workflow import Workflow, WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom, WorkflowRun
from models.workflow import WorkflowType as ModelWorkflowType
from services.workflow_persistence import PersistenceWorkflowInfo, WorkflowPersistenceLayer
from services.workflow_run_index import WorkflowRunIndex
from tests.workflow_test_utils import build_test_graph_init_params
def _build_runtime_state(workflow_execution_id: str, app_id: str, workflow_id: str, user_id: str) -> RuntimeState:
variable_pool = VariablePool.from_bootstrap(
system_variables=build_system_variables(
workflow_execution_id=workflow_execution_id,
app_id=app_id,
workflow_id=workflow_id,
user_id=user_id,
),
user_inputs={},
conversation_variables=[],
)
return RuntimeState(workflow_id="test-workflow", variable_pool=variable_pool, start_at=time.perf_counter())
def _build_graph(
runtime_state: RuntimeState,
tenant_id: str,
app_id: str,
workflow_id: str,
user_id: str,
form_repository: HumanInputFormRepository,
) -> Graph:
graph_config: dict[str, object] = {"nodes": [], "edges": []}
params = build_test_graph_init_params(
workflow_id=workflow_id,
graph_config=graph_config,
tenant_id=tenant_id,
app_id=app_id,
user_id=user_id,
user_from="account",
invoke_from="debugger",
call_depth=0,
)
start_data = StartNodeData(title="start", variables=[])
start_node = StartNode(
node_id="start",
data=start_data,
init_params=params,
runtime_state=runtime_state,
)
human_data = HumanInputNodeData(
title="human",
form_content="Awaiting human input",
inputs=[],
user_actions=[
UserActionConfig(id="continue", title="Continue"),
],
)
hitl_callback = DifyHITLCallback(
form_repository=form_repository,
node_data=human_data,
)
human_node = HumanInputNode(
node_id="human",
data=GraphonHumanInputNodeData(title=human_data.title),
init_params=params,
runtime_state=runtime_state,
hitl_callback=hitl_callback,
)
end_data = EndNodeData(
title="end",
outputs=[],
desc=None,
)
end_node = EndNode(
node_id="end",
data=end_data,
init_params=params,
runtime_state=runtime_state,
)
return (
Graph.new()
.add_root(start_node)
.add_node(human_node)
.add_node(end_node, from_node_id="human", source_handle="continue")
.build()
)
def _build_generate_entity(
tenant_id: str,
app_id: str,
workflow_id: str,
workflow_execution_id: str,
user_id: str,
) -> WorkflowAppGenerateEntity:
app_config = WorkflowUIBasedAppConfig(
tenant_id=tenant_id,
app_id=app_id,
app_mode=AppMode.WORKFLOW,
workflow_id=workflow_id,
)
return WorkflowAppGenerateEntity(
user_from=UserFrom.ACCOUNT,
task_id=str(uuid.uuid4()),
app_config=app_config,
inputs={},
files=[],
user_id=user_id,
stream=False,
invoke_from=InvokeFrom.DEBUGGER,
workflow_execution_id=workflow_execution_id,
)
class TestHumanInputResumeNodeExecutionIntegration:
@pytest.fixture(autouse=True)
def setup_test_data(self, db_session_with_containers: Session):
tenant = Tenant(
name="Test Tenant",
status=TenantStatus.NORMAL,
)
db_session_with_containers.add(tenant)
db_session_with_containers.commit()
account = Account(
email="test@example.com",
name="Test User",
interface_language="en-US",
status=AccountStatus.ACTIVE,
)
db_session_with_containers.add(account)
db_session_with_containers.commit()
tenant_join = TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role=TenantAccountRole.OWNER,
current=True,
)
db_session_with_containers.add(tenant_join)
db_session_with_containers.commit()
account.set_current_tenant_with_session(tenant, session=db_session_with_containers)
app = App(
tenant_id=tenant.id,
name="Test App",
description="",
mode=AppMode.WORKFLOW,
icon_type=IconType.EMOJI.value,
icon="rocket",
icon_background="#4ECDC4",
enable_site=False,
enable_api=False,
api_rpm=0,
api_rph=0,
is_demo=False,
is_public=False,
is_universal=False,
max_active_requests=None,
created_by=account.id,
updated_by=account.id,
)
db_session_with_containers.add(app)
db_session_with_containers.commit()
workflow = Workflow(
tenant_id=tenant.id,
app_id=app.id,
type=ModelWorkflowType("workflow"),
version="draft",
graph='{"nodes": [], "edges": []}',
_features='{"file_upload": {"enabled": false}}',
created_by=account.id,
)
workflow.created_at = naive_utc_now()
db_session_with_containers.add(workflow)
db_session_with_containers.commit()
self.session = db_session_with_containers
self.tenant = tenant
self.account = account
self.app = app
self.workflow = workflow
yield
form_ids = select(HumanInputForm.id).where(
HumanInputForm.tenant_id == self.tenant.id, HumanInputForm.app_id == self.app.id
)
self.session.execute(delete(HumanInputFormRecipient).where(HumanInputFormRecipient.form_id.in_(form_ids)))
self.session.execute(delete(HumanInputDelivery).where(HumanInputDelivery.form_id.in_(form_ids)))
self.session.execute(
delete(HumanInputForm).where(
HumanInputForm.tenant_id == self.tenant.id, HumanInputForm.app_id == self.app.id
)
)
self.session.execute(delete(WorkflowNodeExecutionModel))
self.session.execute(delete(WorkflowRun))
self.session.execute(delete(Workflow).where(Workflow.id == self.workflow.id))
self.session.execute(delete(App).where(App.id == self.app.id))
self.session.execute(delete(TenantAccountJoin).where(TenantAccountJoin.tenant_id == self.tenant.id))
self.session.execute(delete(Account).where(Account.id == self.account.id))
self.session.execute(delete(Tenant).where(Tenant.id == self.tenant.id))
self.session.commit()
def _build_run_layers(
self, execution_id: str, *, resuming: bool
) -> tuple[WorkflowRunIndex, WorkflowPersistenceLayer]:
generate_entity = _build_generate_entity(
tenant_id=self.tenant.id,
app_id=self.app.id,
workflow_id=self.workflow.id,
workflow_execution_id=execution_id,
user_id=self.account.id,
)
session_factory = sessionmaker(bind=self.session.get_bind(), expire_on_commit=False)
execution_repo = SQLAlchemyWorkflowExecutionRepository(
session_factory=session_factory,
tenant_id=self.tenant.id,
user=self.account,
app_id=self.app.id,
triggered_from=WorkflowRunTriggeredFrom.DEBUGGING,
)
node_execution_repo = SQLAlchemyWorkflowNodeExecutionRepository(
session_factory=session_factory,
tenant_id=self.tenant.id,
user=self.account,
app_id=self.app.id,
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
)
history = node_execution_repo.get_by_workflow_execution(execution_id, include_paused=True) if resuming else ()
run_index = WorkflowRunIndex(history)
persistence = WorkflowPersistenceLayer(
application_generate_entity=generate_entity,
workflow_info=PersistenceWorkflowInfo(
workflow_id=self.workflow.id,
workflow_type=WorkflowType.WORKFLOW,
version=self.workflow.version,
graph_data=self.workflow.graph_dict,
),
workflow_execution_repository=execution_repo,
workflow_node_execution_repository=node_execution_repo,
trace_scope=None,
)
persistence.set_node_run_indices(run_index.indices)
persistence.set_node_execution_history(history)
return run_index, persistence
def _run_graph(self, graph: Graph, runtime_state: RuntimeState, execution_id: str) -> None:
engine = Engine(
graph=graph,
runtime_state=runtime_state,
command_channel=InMemoryChannel(),
)
for layer in self._build_run_layers(execution_id, resuming=runtime_state.graph_execution.paused):
engine.add_layer(layer)
for _ in engine.run():
continue
def test_resume_human_input_does_not_create_duplicate_node_execution(self):
execution_id = str(uuid.uuid4())
runtime_state = _build_runtime_state(
workflow_execution_id=execution_id,
app_id=self.app.id,
workflow_id=self.workflow.id,
user_id=self.account.id,
)
form_repository = HumanInputFormRepositoryImpl(
tenant_id=self.tenant.id, app_id=self.app.id, workflow_execution_id=execution_id
)
paused_graph = _build_graph(
runtime_state,
self.tenant.id,
self.app.id,
self.workflow.id,
self.account.id,
form_repository,
)
self._run_graph(paused_graph, runtime_state, execution_id)
human_execution_id = self.session.scalar(
select(WorkflowNodeExecutionModel.id).where(
WorkflowNodeExecutionModel.workflow_run_id == execution_id,
WorkflowNodeExecutionModel.node_id == "human",
)
)
assert human_execution_id is not None
snapshot = runtime_state.dumps()
resumed_state = RuntimeState.from_snapshot(snapshot)
form = self.session.scalar(
select(HumanInputForm).where(
HumanInputForm.tenant_id == self.tenant.id,
HumanInputForm.workflow_run_id == execution_id,
HumanInputForm.node_id == "human",
)
)
assert form is not None
assert form.status == HumanInputFormStatus.WAITING
form.selected_action_id = "continue"
form.submitted_data = "{}"
form.submitted_at = naive_utc_now()
form.status = HumanInputFormStatus.SUBMITTED
self.session.commit()
resumed_graph = _build_graph(
resumed_state,
self.tenant.id,
self.app.id,
self.workflow.id,
self.account.id,
form_repository,
)
self._run_graph(resumed_graph, resumed_state, execution_id)
stmt = select(WorkflowNodeExecutionModel).where(
WorkflowNodeExecutionModel.workflow_run_id == execution_id,
WorkflowNodeExecutionModel.node_id == "human",
)
records = self.session.execute(stmt).scalars().all()
assert len(records) == 1
assert records[0].id == human_execution_id
assert records[0].status == "succeeded"
assert records[0].triggered_from == WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN
assert records[0].created_by_role == CreatorUserRole.ACCOUNT
executions = self.session.scalars(
select(WorkflowNodeExecutionModel)
.where(WorkflowNodeExecutionModel.workflow_run_id == execution_id)
.order_by(WorkflowNodeExecutionModel.index)
).all()
assert [(execution.node_id, execution.index) for execution in executions] == [
("start", 1),
("human", 2),
("end", 3),
]
Whitespace-only changes.
@@ -0,0 +1,389 @@
from __future__ import annotations
from datetime import UTC, datetime
from unittest.mock import patch
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from core.app.file_access import DatabaseFileAccessController
from extensions.ext_database import db
from extensions.storage.storage_type import StorageType
from factories.file_factory import StorageKeyLoader
from graphon.file import File, FileTransferMethod, FileType
from models import ToolFile, UploadFile
from models.enums import CreatorUserRole
@pytest.mark.usefixtures("flask_req_ctx_with_containers")
class TestStorageKeyLoader:
"""
Integration tests for StorageKeyLoader class.
Tests the batched loading of storage keys from the database for files
with different transfer methods: LOCAL_FILE, REMOTE_URL, and TOOL_FILE.
"""
# ------------------------------------------------------------------
# Per-test helpers (use db_session_with_containers as parameter)
# ------------------------------------------------------------------
@staticmethod
def _create_upload_file(
session: Session,
tenant_id: str,
user_id: str,
*,
file_id: str | None = None,
storage_key: str | None = None,
override_tenant_id: str | None = None,
) -> UploadFile:
"""Create and flush an UploadFile record for testing."""
upload_file = UploadFile(
tenant_id=override_tenant_id if override_tenant_id is not None else tenant_id,
storage_type=StorageType.LOCAL,
key=storage_key or f"test_storage_key_{uuid4()}",
name="test_file.txt",
size=1024,
extension=".txt",
mime_type="text/plain",
created_by_role=CreatorUserRole.ACCOUNT,
created_by=user_id,
created_at=datetime.now(UTC),
used=False,
)
upload_file.id = file_id or str(uuid4())
session.add(upload_file)
session.flush()
return upload_file
@staticmethod
def _create_tool_file(
session: Session,
tenant_id: str,
user_id: str,
conversation_id: str,
*,
file_id: str | None = None,
file_key: str | None = None,
override_tenant_id: str | None = None,
) -> ToolFile:
"""Create and flush a ToolFile record for testing."""
tool_file = ToolFile(
user_id=user_id,
tenant_id=override_tenant_id if override_tenant_id is not None else tenant_id,
conversation_id=conversation_id,
file_key=file_key or f"test_file_key_{uuid4()}",
mimetype="text/plain",
original_url="http://example.com/file.txt",
name="test_tool_file.txt",
size=2048,
)
tool_file.id = file_id or str(uuid4())
session.add(tool_file)
session.flush()
return tool_file
@staticmethod
def _create_file(
tenant_id: str,
related_id: str,
transfer_method: FileTransferMethod,
*,
override_tenant_id: str | None = None,
) -> File:
"""Build a File value-object for testing."""
remote_url = "https://example.com/test_file.txt" if transfer_method == FileTransferMethod.REMOTE_URL else None
return File(
file_id=str(uuid4()),
tenant_id=override_tenant_id if override_tenant_id is not None else tenant_id,
file_type=FileType.DOCUMENT,
transfer_method=transfer_method,
related_id=related_id,
remote_url=remote_url,
filename="test_file.txt",
extension=".txt",
mime_type="text/plain",
size=1024,
storage_key="initial_key",
)
# ------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------
def test_load_storage_keys_local_file(self, db_session_with_containers: Session):
"""Test loading storage keys for LOCAL_FILE transfer method."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file = self._create_file(tenant_id, related_id=upload_file.id, transfer_method=FileTransferMethod.LOCAL_FILE)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
loader.load_storage_keys([file])
assert file._storage_key == upload_file.key
def test_load_storage_keys_remote_url(self, db_session_with_containers: Session):
"""Test loading storage keys for REMOTE_URL transfer method."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file = self._create_file(tenant_id, related_id=upload_file.id, transfer_method=FileTransferMethod.REMOTE_URL)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
loader.load_storage_keys([file])
assert file._storage_key == upload_file.key
def test_load_storage_keys_tool_file(self, db_session_with_containers: Session):
"""Test loading storage keys for TOOL_FILE transfer method."""
tenant_id = str(uuid4())
user_id = str(uuid4())
conversation_id = str(uuid4())
tool_file = self._create_tool_file(db_session_with_containers, tenant_id, user_id, conversation_id)
file = self._create_file(tenant_id, related_id=tool_file.id, transfer_method=FileTransferMethod.TOOL_FILE)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
loader.load_storage_keys([file])
assert file._storage_key == tool_file.file_key
def test_load_storage_keys_mixed_methods(self, db_session_with_containers: Session):
"""Test batch loading with mixed transfer methods."""
tenant_id = str(uuid4())
user_id = str(uuid4())
conversation_id = str(uuid4())
upload_file1 = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
upload_file2 = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
tool_file = self._create_tool_file(db_session_with_containers, tenant_id, user_id, conversation_id)
file1 = self._create_file(tenant_id, related_id=upload_file1.id, transfer_method=FileTransferMethod.LOCAL_FILE)
file2 = self._create_file(tenant_id, related_id=upload_file2.id, transfer_method=FileTransferMethod.REMOTE_URL)
file3 = self._create_file(tenant_id, related_id=tool_file.id, transfer_method=FileTransferMethod.TOOL_FILE)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
loader.load_storage_keys([file1, file2, file3])
assert file1._storage_key == upload_file1.key
assert file2._storage_key == upload_file2.key
assert file3._storage_key == tool_file.file_key
def test_load_storage_keys_empty_list(self, db_session_with_containers: Session):
"""Test with empty file list — should not raise."""
tenant_id = str(uuid4())
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
loader.load_storage_keys([])
def test_load_storage_keys_ignores_legacy_file_tenant_id(self, db_session_with_containers: Session):
"""Legacy file tenant_id should not override the loader tenant scope."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file = self._create_file(
tenant_id,
related_id=upload_file.id,
transfer_method=FileTransferMethod.LOCAL_FILE,
override_tenant_id=str(uuid4()),
)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
loader.load_storage_keys([file])
assert file._storage_key == upload_file.key
def test_load_storage_keys_missing_file_id(self, db_session_with_containers: Session):
"""Test with None file.related_id — should raise ValueError."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file = self._create_file(tenant_id, related_id=upload_file.id, transfer_method=FileTransferMethod.LOCAL_FILE)
file.related_id = None
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
with pytest.raises(ValueError, match="file id should not be None."):
loader.load_storage_keys([file])
def test_load_storage_keys_nonexistent_upload_file_records(self, db_session_with_containers: Session):
"""Test with missing UploadFile database records — should raise ValueError."""
tenant_id = str(uuid4())
file = self._create_file(tenant_id, related_id=str(uuid4()), transfer_method=FileTransferMethod.LOCAL_FILE)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
with pytest.raises(ValueError, match="Upload file not found for id:"):
loader.load_storage_keys([file])
def test_load_storage_keys_nonexistent_tool_file_records(self, db_session_with_containers: Session):
"""Test with missing ToolFile database records — should raise ValueError."""
tenant_id = str(uuid4())
file = self._create_file(tenant_id, related_id=str(uuid4()), transfer_method=FileTransferMethod.TOOL_FILE)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
with pytest.raises(ValueError, match="Tool file not found for id:"):
loader.load_storage_keys([file])
def test_load_storage_keys_invalid_uuid(self, db_session_with_containers: Session):
"""Test with invalid UUID format — should raise ValueError."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file = self._create_file(tenant_id, related_id=upload_file.id, transfer_method=FileTransferMethod.LOCAL_FILE)
file.related_id = "invalid-uuid-format"
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
with pytest.raises(ValueError, match="badly formed hexadecimal UUID string"):
loader.load_storage_keys([file])
def test_load_storage_keys_batch_efficiency(self, db_session_with_containers: Session):
"""Batched operations should issue exactly 2 queries for mixed file types."""
tenant_id = str(uuid4())
user_id = str(uuid4())
conversation_id = str(uuid4())
upload_files = [self._create_upload_file(db_session_with_containers, tenant_id, user_id) for _ in range(3)]
tool_files = [
self._create_tool_file(db_session_with_containers, tenant_id, user_id, conversation_id) for _ in range(2)
]
files = [
self._create_file(tenant_id, related_id=uf.id, transfer_method=FileTransferMethod.LOCAL_FILE)
for uf in upload_files
] + [
self._create_file(tenant_id, related_id=tf.id, transfer_method=FileTransferMethod.TOOL_FILE)
for tf in tool_files
]
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
with patch.object(
db_session_with_containers, "scalars", wraps=db_session_with_containers.scalars
) as mock_scalars:
loader.load_storage_keys(files)
# Exactly 2 DB round-trips: one for UploadFile, one for ToolFile
assert mock_scalars.call_count == 2
for i, file in enumerate(files[:3]):
assert file._storage_key == upload_files[i].key
for i, file in enumerate(files[3:]):
assert file._storage_key == tool_files[i].file_key
def test_load_storage_keys_tenant_isolation(self, db_session_with_containers: Session):
"""Loader should not surface records belonging to a different tenant."""
tenant_id = str(uuid4())
other_tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file_current = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file_current = self._create_file(
tenant_id, related_id=upload_file_current.id, transfer_method=FileTransferMethod.LOCAL_FILE
)
upload_file_other = self._create_upload_file(
db_session_with_containers,
tenant_id,
user_id,
override_tenant_id=other_tenant_id,
)
file_other = self._create_file(
tenant_id,
related_id=upload_file_other.id,
transfer_method=FileTransferMethod.LOCAL_FILE,
override_tenant_id=other_tenant_id,
)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
with pytest.raises(ValueError, match="Upload file not found for id:"):
loader.load_storage_keys([file_other])
# Current-tenant file still resolves correctly
loader.load_storage_keys([file_current])
assert file_current._storage_key == upload_file_current.key
def test_load_storage_keys_mixed_tenant_batch(self, db_session_with_containers: Session):
"""A batch containing a foreign-tenant file should fail on the mismatch."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file_current = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file_current = self._create_file(
tenant_id, related_id=upload_file_current.id, transfer_method=FileTransferMethod.LOCAL_FILE
)
file_other = self._create_file(
tenant_id,
related_id=str(uuid4()),
transfer_method=FileTransferMethod.LOCAL_FILE,
override_tenant_id=str(uuid4()),
)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
with pytest.raises(ValueError, match="Upload file not found for id:"):
loader.load_storage_keys([file_current, file_other])
def test_load_storage_keys_duplicate_file_ids(self, db_session_with_containers: Session):
"""Duplicate file IDs in the batch should be handled gracefully."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file1 = self._create_file(tenant_id, related_id=upload_file.id, transfer_method=FileTransferMethod.LOCAL_FILE)
file2 = self._create_file(tenant_id, related_id=upload_file.id, transfer_method=FileTransferMethod.LOCAL_FILE)
loader = StorageKeyLoader(
db_session_with_containers, tenant_id, access_controller=DatabaseFileAccessController()
)
loader.load_storage_keys([file1, file2])
assert file1._storage_key == upload_file.key
assert file2._storage_key == upload_file.key
def test_load_storage_keys_session_isolation(self, db_session_with_containers: Session):
"""A loader backed by an uncommitted session should not see data from another session."""
tenant_id = str(uuid4())
user_id = str(uuid4())
upload_file = self._create_upload_file(db_session_with_containers, tenant_id, user_id)
file = self._create_file(tenant_id, related_id=upload_file.id, transfer_method=FileTransferMethod.LOCAL_FILE)
# A loader with a fresh, separate session cannot see uncommitted rows from db_session_with_containers
with Session(bind=db.engine) as other_session:
other_loader = StorageKeyLoader(
other_session,
tenant_id,
access_controller=DatabaseFileAccessController(),
)
with pytest.raises(ValueError, match="Upload file not found for id:"):
other_loader.load_storage_keys([file])
@@ -0,0 +1,26 @@
"""Helper utilities for integration tests."""
import re
from faker import Faker
def generate_valid_password(fake: Faker, length: int = 12) -> str:
"""Generate a password that always satisfies the project's password validation rules.
The password validation rule in ``api/libs/password.py`` requires passwords to
contain **both letters and digits** with a minimum length of 8:
``^(?=.*[a-zA-Z])(?=.*\\d).{8,}$``
``Faker.password()`` does **not** guarantee that the generated password will
contain both character types, which can cause intermittent test failures.
This helper re-generates until the result is valid (typically first attempt).
"""
for _ in range(100):
pwd = fake.password(length=length)
if re.search(r"[a-zA-Z]", pwd) and re.search(r"\d", pwd):
return pwd
# Fallback: should never be reached in practice
return fake.password(length=max(length - 2, 6)) + "a1"
@@ -0,0 +1,45 @@
"""Build persisted test identities through the account application services."""
from sqlalchemy.orm import Session
from extensions.ext_application_services import application_services
from models.account import Account, Tenant, TenantAccountRole
def create_account(
*, email: str, name: str, interface_language: str, session: Session, password: str | None = None
) -> Account:
snapshot = application_services().accounts.lifecycle.create_account(
email, name, interface_language, password=password
)
account = session.get(Account, snapshot.id)
assert account is not None
return account
def create_owner_workspace(account: Account, name: str | None = None, *, session: Session) -> None:
"""Seed a test identity even when self-service workspace creation is disabled."""
application_services().workspaces.provisioning.create_owner_workspace(
account.id, name=name, is_setup=True, if_missing=True
)
memberships = application_services().workspaces.management.list_memberships(account.id)
assert memberships
account.set_tenant_id_with_session(memberships[0].id, session=session)
def create_workspace(*, name: str, session: Session) -> Tenant:
workspace = application_services().workspaces.provisioning.create(name=name)
tenant = session.get(Tenant, workspace.id)
assert tenant is not None
return tenant
def join_workspace(tenant: Tenant, account: Account, session: Session, role: str) -> None:
application_services().workspaces.members.join_member(
workspace_id=tenant.id,
account_id=account.id,
email=account.email,
role=TenantAccountRole(role),
operator_account_id=None,
)
session.expire_all()
@@ -0,0 +1,157 @@
from __future__ import annotations
from dataclasses import dataclass
from datetime import timedelta
from decimal import Decimal
from uuid import uuid4
from core.workflow.nodes.human_input.entities import FormDefinition, UserActionConfig
from libs.datetime_utils import naive_utc_now
from models.account import Account, Tenant, TenantAccountJoin
from models.enums import ConversationFromSource, InvokeFrom
from models.execution_extra_content import HumanInputContent
from models.human_input import HumanInputForm, HumanInputFormStatus
from models.model import App, Conversation, Message
@dataclass
class HumanInputMessageFixture:
app: App
account: Account
conversation: Conversation
message: Message
form: HumanInputForm
action_id: str
action_text: str
node_title: str
def create_human_input_message_fixture(db_session) -> HumanInputMessageFixture:
tenant = Tenant(name=f"Tenant {uuid4()}")
db_session.add(tenant)
db_session.flush()
account = Account(
name=f"Account {uuid4()}",
email=f"human_input_{uuid4()}@example.com",
password="hashed-password",
password_salt="salt",
interface_language="en-US",
timezone="UTC",
)
db_session.add(account)
db_session.flush()
tenant_join = TenantAccountJoin(
tenant_id=tenant.id,
account_id=account.id,
role="owner",
current=True,
)
db_session.add(tenant_join)
db_session.flush()
app = App(
tenant_id=tenant.id,
name=f"App {uuid4()}",
description="",
mode="chat",
icon_type="emoji",
icon="🤖",
icon_background="#FFFFFF",
enable_site=False,
enable_api=True,
api_rpm=100,
api_rph=100,
is_demo=False,
is_public=False,
is_universal=False,
created_by=account.id,
updated_by=account.id,
)
db_session.add(app)
db_session.flush()
conversation = Conversation(
app_id=app.id,
mode="chat",
name="Test Conversation",
summary="",
introduction="",
system_instruction="",
status="normal",
invoke_from=InvokeFrom.EXPLORE,
from_source=ConversationFromSource.CONSOLE,
from_account_id=account.id,
from_end_user_id=None,
)
conversation.inputs = {}
db_session.add(conversation)
db_session.flush()
workflow_run_id = str(uuid4())
message = Message(
app_id=app.id,
conversation_id=conversation.id,
_inputs={},
query="Human input query",
message={"messages": []},
answer="Human input answer",
message_tokens=50,
message_unit_price=Decimal("0.001"),
answer_tokens=80,
answer_unit_price=Decimal("0.001"),
provider_response_latency=0.5,
currency="USD",
from_source=ConversationFromSource.CONSOLE,
from_account_id=account.id,
workflow_run_id=workflow_run_id,
)
db_session.add(message)
db_session.flush()
action_id = "approve"
action_text = "Approve request"
node_title = "Approval"
form_definition = FormDefinition(
form_content="content",
inputs=[],
user_actions=[UserActionConfig(id=action_id, title=action_text)],
rendered_content="Rendered block",
expiration_time=naive_utc_now() + timedelta(days=1),
node_title=node_title,
display_in_ui=True,
)
form = HumanInputForm(
tenant_id=tenant.id,
app_id=app.id,
workflow_run_id=workflow_run_id,
node_id="node-id",
form_definition=form_definition.model_dump_json(),
rendered_content="Rendered block",
status=HumanInputFormStatus.SUBMITTED,
expiration_time=naive_utc_now() + timedelta(days=1),
selected_action_id=action_id,
submitted_data='{"name": "Alice"}',
)
db_session.add(form)
db_session.flush()
content = HumanInputContent(
workflow_run_id=workflow_run_id,
message_id=message.id,
form_id=form.id,
)
db_session.add(content)
db_session.commit()
return HumanInputMessageFixture(
app=app,
account=account,
conversation=conversation,
message=message,
form=form,
action_id=action_id,
action_text=action_text,
node_title=node_title,
)
@@ -0,0 +1,426 @@
"""CI-only OTP behavior through the service with real Redis and PostgreSQL."""
from __future__ import annotations
from collections.abc import Callable, Iterator
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from datetime import timedelta
from hashlib import sha256
from threading import Barrier
from uuid import uuid4
import pytest
from sqlalchemy import Engine, delete, select
from sqlalchemy.orm import Session, sessionmaker
from core.human_input_v2.resolved_form import ResolvedForm
from core.human_input_v2.shared.values import ContactId, NormalizedEmail, TenantId
from core.workflow.nodes.human_input.enums import HumanInputFormKind
from core.workflow.nodes.human_input_v2.entities import OnetimeEmail
from extensions.ext_redis import redis_client
from extensions.redis_names import serialize_redis_name
from libs.datetime_utils import naive_utc_now
from libs.helper import RateLimiter
from models.account import Tenant
from models.human_input_v2 import (
HumanInputAuditEvent,
HumanInputDelivery,
HumanInputExternalContactProfile,
HumanInputForm,
HumanInputRecipient,
OtpSendEvent,
OtpVerificationEvent,
)
from models.model import App, AppMode
from repositories.human_input_v2.contact import ExternalContact
from repositories.human_input_v2.delivery_repository import (
Delivery,
DeliveryCreateParams,
EmailTargetSnapshot,
SubmissionAuthType,
)
from repositories.human_input_v2.form_repository import Form, FormCreateParams, FormSubmissionFailure
from repositories.human_input_v2.recipient_repository import (
ContactRecipientSubject,
EmailRecipientSubject,
RecipientCreateParams,
)
from repositories.human_input_v2.sqlalchemy_contact_repository import SQLAlchemyContactRepository
from repositories.human_input_v2.sqlalchemy_delivery_repository import SQLAlchemyDeliveryRepository
from repositories.human_input_v2.sqlalchemy_form_repository import SQLAlchemyFormRepository
from repositories.human_input_v2.sqlalchemy_recipient_repository import SQLAlchemyRecipientRepository
from services.human_input_v2.email_otp_service import EmailOtpError, EmailOtpService, OtpFailure, OtpMail, VerifiedEmail
pytestmark = pytest.mark.usefixtures("flask_app_with_containers")
def test_challenges_are_independent_and_fifth_mismatch_deletes_only_one(
otp_case: OtpCase,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr("services.human_input_v2.email_otp_service.secrets.randbelow", lambda _bound: 1234)
first_node, second_node = otp_case.service(), otp_case.service()
first = first_node.request_access(otp_case.token)
otp_case.release_cooldown()
second = second_node.request_access(otp_case.token)
assert otp_case.sent[0][1] == "001234"
other_token = str(uuid4())
with otp_case.sessions.begin() as session:
SQLAlchemyDeliveryRepository(session).create_delivery(
tenant_id=otp_case.form.tenant_id,
form_id=otp_case.form.id,
params=DeliveryCreateParams(
recipient_id=otp_case.delivery.recipient_id,
token_hash=sha256(other_token.encode()).hexdigest(),
auth_type=SubmissionAuthType.EMAIL_OTP,
target_snapshot=EmailTargetSnapshot(email_address="ci@example.com"),
),
)
with pytest.raises(EmailOtpError) as error:
second_node.verify(other_token, challenge_token=first.challenge_token, otp_code="001234", ip_address=None)
assert error.value.reason == OtpFailure.CHALLENGE_EXPIRED
second_node.verify(otp_case.token, challenge_token=first.challenge_token, otp_code="001234", ip_address=None)
for _ in range(4):
with pytest.raises(EmailOtpError) as error:
second_node.verify(otp_case.token, challenge_token=first.challenge_token, otp_code="1234", ip_address=None)
assert error.value.reason == OtpFailure.INVALID
first_node.verify(otp_case.token, challenge_token=first.challenge_token, otp_code="001234", ip_address=None)
with pytest.raises(EmailOtpError) as error:
first_node.verify(otp_case.token, challenge_token=first.challenge_token, otp_code="000000", ip_address=None)
assert error.value.reason == OtpFailure.STALE
assert not redis_client.exists(f"hitl:otp:challenge:{{{otp_case.delivery.id}:{first.challenge_token}}}")
with pytest.raises(EmailOtpError) as error:
second_node.verify(otp_case.token, challenge_token=first.challenge_token, otp_code="001234", ip_address=None)
assert error.value.reason == OtpFailure.CHALLENGE_EXPIRED
second_node.verify(otp_case.token, challenge_token=second.challenge_token, otp_code="001234", ip_address=None)
@pytest.mark.parametrize("otp_case", ["external_contact"], indirect=True)
def test_contact_email_change_does_not_consume_guesses(otp_case: OtpCase) -> None:
service = otp_case.service()
challenge = service.request_access(otp_case.token)
with otp_case.sessions.begin() as session:
profile = session.scalars(select(HumanInputExternalContactProfile)).one()
profile.email = "changed@example.com"
for _ in range(6):
with pytest.raises(EmailOtpError) as error:
service.verify(
otp_case.token, challenge_token=challenge.challenge_token, otp_code=otp_case.sent[0][1], ip_address=None
)
assert error.value.reason == OtpFailure.STALE
with otp_case.sessions.begin() as session:
profile = session.scalars(select(HumanInputExternalContactProfile)).one()
profile.email = "ci@example.com"
service.verify(
otp_case.token, challenge_token=challenge.challenge_token, otp_code=otp_case.sent[0][1], ip_address=None
)
def test_concurrent_guesses_cannot_exceed_budget(otp_case: OtpCase) -> None:
service = otp_case.service()
challenge = service.request_access(otp_case.token)
barrier = Barrier(12)
def guess(_: int) -> OtpFailure:
barrier.wait()
try:
service.verify(
otp_case.token, challenge_token=challenge.challenge_token, otp_code="wrong-code", ip_address=None
)
except EmailOtpError as error:
return error.reason
pytest.fail("An incorrect code was accepted")
with ThreadPoolExecutor(max_workers=12) as executor:
results = list(executor.map(guess, range(12)))
assert results.count(OtpFailure.INVALID) == 4
assert results.count(OtpFailure.STALE) == 1
assert results.count(OtpFailure.CHALLENGE_EXPIRED) == 7
def test_concurrent_sends_consume_one_slot_and_rejections_do_not_count() -> None:
limiter = RateLimiter(prefix=f"otp-test:{uuid4()}", max_attempts=5, time_window=3600)
barrier = Barrier(12)
def acquire(_: int) -> int:
barrier.wait()
return limiter.acquire("delivery", cooldown_seconds=60)
with ThreadPoolExecutor(max_workers=12) as executor:
results = list(executor.map(acquire, range(12)))
assert results.count(0) == 1
assert all(0 < wait <= 60 for wait in results if wait)
assert redis_client.zcard(f"{limiter.prefix}:delivery") == 1
assert limiter.acquire("other-delivery", cooldown_seconds=60) == 0
redis_client.delete(f"{limiter.prefix}:delivery", f"{limiter.prefix}:other-delivery")
def test_hourly_window_and_cooldown_return_combined_delay() -> None:
limiter = RateLimiter(prefix=f"otp-test:{uuid4()}", max_attempts=5, time_window=3600)
key = serialize_redis_name(f"{limiter.prefix}:delivery")
# Redis controls time; seed recent history without waiting an hour in CI.
redis_client.eval(
"""
local now = tonumber(redis.call('TIME')[1])
for i = 0, 4 do redis.call('ZADD', KEYS[1], now - 300 + i * 60, tostring(i)) end
redis.call('EXPIRE', KEYS[1], 3600)
""",
1,
key,
)
assert 3298 <= limiter.acquire("delivery", cooldown_seconds=60) <= 3300
assert redis_client.zcard(f"{limiter.prefix}:delivery") == 5
redis_client.delete(f"{limiter.prefix}:delivery")
def test_verification_does_not_refresh_ttl(otp_case: OtpCase) -> None:
service = otp_case.service()
challenge = service.request_access(otp_case.token)
key = f"hitl:otp:challenge:{{{otp_case.delivery.id}:{challenge.challenge_token}}}"
redis_client.expire(key, 20)
with pytest.raises(EmailOtpError) as error:
service.verify(
otp_case.token, challenge_token=challenge.challenge_token, otp_code="wrong-code", ip_address=None
)
assert error.value.reason == OtpFailure.INVALID
assert 0 < redis_client.ttl(key) <= 20
redis_client.expire(key, 0)
with pytest.raises(EmailOtpError) as error:
service.verify(
otp_case.token, challenge_token=challenge.challenge_token, otp_code=otp_case.sent[0][1], ip_address=None
)
assert error.value.reason == OtpFailure.CHALLENGE_EXPIRED
@dataclass
class OtpCase:
sessions: sessionmaker[Session]
form: Form
delivery: Delivery
token: str
limiter: RateLimiter
sent: list[tuple[str, str]]
def service(self, send: Callable[[str, str], None] | None = None) -> EmailOtpService:
return EmailOtpService(
session_factory=self.sessions,
redis=redis_client,
limiter=self.limiter,
mail=OtpMail(available=lambda: True, send=send or (lambda email, code: self.sent.append((email, code)))),
)
def release_cooldown(self) -> None:
# Move the successful-send history beyond its minute cooldown without
# changing the challenge TTL or discarding the hourly send budget.
key = serialize_redis_name(f"{self.limiter.prefix}:{self.delivery.id}")
redis_client.eval(
"""
local now = tonumber(redis.call('TIME')[1])
local members = redis.call('ZRANGE', KEYS[1], 0, -1)
for _, member in ipairs(members) do redis.call('ZADD', KEYS[1], now - 61, member) end
""",
1,
key,
)
@pytest.fixture(params=["email", "external_contact"])
def otp_case(db_session_with_containers: Session, request: pytest.FixtureRequest) -> Iterator[OtpCase]:
engine = db_session_with_containers.get_bind()
assert isinstance(engine, Engine)
sessions = sessionmaker(engine, expire_on_commit=False)
tenant_id, app_id, token = TenantId(str(uuid4())), str(uuid4()), str(uuid4())
now = naive_utc_now()
with sessions.begin() as session:
tenant = Tenant(name="OTP CI")
tenant.id = tenant_id
session.add(tenant)
session.add(
App(id=app_id, tenant_id=tenant_id, name="OTP CI", mode=AppMode.WORKFLOW, enable_site=True, enable_api=True)
)
session.flush()
form = SQLAlchemyFormRepository(session, tenant_id, app_id).create_form(
FormCreateParams(
workflow_run_id=None,
node_execution_id=None,
form_kind=HumanInputFormKind.DELIVERY_TEST,
resolved_form=ResolvedForm(title="Approval", parts=(), actions=(), legacy_form_content="Review"),
expiration_time=now + timedelta(hours=1),
global_timeout_deadline=now + timedelta(hours=2),
)
)
if request.param == "external_contact":
contact = SQLAlchemyContactRepository(session).save_external_contact(
tenant_id,
ExternalContact(
id=ContactId(str(uuid4())),
name="CI approver",
email="ci@example.com",
avatar_file_id=None,
created_at=now,
),
)
subject = ContactRecipientSubject(contact.id)
else:
subject = EmailRecipientSubject(NormalizedEmail("ci@example.com"))
recipient = SQLAlchemyRecipientRepository(session, tenant_id, form.id).create_recipients(
[
RecipientCreateParams(
subject=subject,
sources=(OnetimeEmail(email="ci@example.com"),),
name=None,
)
]
)[0]
delivery = SQLAlchemyDeliveryRepository(session).create_delivery(
tenant_id=tenant_id,
form_id=form.id,
params=DeliveryCreateParams(
recipient_id=recipient.id,
token_hash=sha256(token.encode()).hexdigest(),
auth_type=SubmissionAuthType.EMAIL_OTP,
target_snapshot=EmailTargetSnapshot(email_address="ci@example.com"),
),
)
limiter = RateLimiter(prefix=f"otp-ci:{uuid4()}", max_attempts=5, time_window=3600)
try:
yield OtpCase(sessions, form, delivery, token, limiter, [])
finally:
# Remove all test-issued challenges without adding a production list API.
pattern = serialize_redis_name(f"hitl:otp:challenge:{{{delivery.id}:*")
for key in redis_client.scan_iter(match=pattern):
redis_client.delete(key)
redis_client.delete(f"{limiter.prefix}:{delivery.id}")
with sessions.begin() as session:
for model in (HumanInputAuditEvent, HumanInputDelivery, HumanInputRecipient):
session.execute(delete(model).where(model.form_id == form.id))
session.execute(delete(HumanInputForm).where(HumanInputForm.id == form.id))
session.execute(delete(App).where(App.id == app_id))
session.execute(delete(Tenant).where(Tenant.id == tenant_id))
def test_verified_challenges_accept_one_form_on_postgres(otp_case: OtpCase) -> None:
delivery, form, token = otp_case.delivery, otp_case.form, otp_case.token
sessions = otp_case.sessions
tenant_id, app_id, recipient_id = form.tenant_id, form.app_id, delivery.recipient_id
service = otp_case.service()
challenges = [service.request_access(token)]
otp_case.release_cooldown()
challenges.append(service.request_access(token))
proofs = [
service.verify(token, challenge_token=challenge.challenge_token, otp_code=sent[1], ip_address=None)
for challenge, sent in zip(challenges, otp_case.sent, strict=True)
]
barrier = Barrier(2)
def submit(proof: VerifiedEmail) -> Form | FormSubmissionFailure:
barrier.wait()
with sessions.begin() as session:
result = SQLAlchemyFormRepository(session, tenant_id, app_id).submit_form(
form.id,
submitted_by_recipient_id=recipient_id,
submitted_by_delivery_id=proof.delivery.id,
selected_action_id="approve",
raw_submission_inputs={},
normalized_submission_data={},
)
if isinstance(result, Form):
proof.add_submission_audit(session, ip_address=None)
return result
with ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(submit, proofs))
assert sum(isinstance(result, Form) for result in results) == 1
assert results.count(FormSubmissionFailure.ALREADY_SUBMITTED) == 1
with sessions() as session:
audits = session.scalars(select(HumanInputAuditEvent).where(HumanInputAuditEvent.form_id == form.id)).all()
sends = [audit.payload for audit in audits if isinstance(audit.payload, OtpSendEvent)]
submissions = [audit.payload for audit in audits if isinstance(audit.payload, OtpVerificationEvent)]
assert len(audits) == 3
assert sends == [
OtpSendEvent(recipient_id=recipient_id, recipient_email="ci@example.com", sender_ip_address=None),
OtpSendEvent(recipient_id=recipient_id, recipient_email="ci@example.com", sender_ip_address=None),
]
assert submissions == [
OtpVerificationEvent(
recipient_id=recipient_id,
recipient_email="ci@example.com",
succeeded=True,
submitter_ip_address=None,
reason="submitted",
)
]
def test_lost_response_and_failed_resend_preserve_earlier_proof_and_budget(otp_case: OtpCase) -> None:
service = otp_case.service()
first = service.request_access(otp_case.token)
first_code = otp_case.sent[0][1]
otp_case.release_cooldown()
service.request_access(otp_case.token) # The browser loses this successful response.
assert (
service.verify(
otp_case.token, challenge_token=first.challenge_token, otp_code=first_code, ip_address=None
).delivery.id
== otp_case.delivery.id
)
otp_case.release_cooldown()
def fail(_email: str, _code: str) -> None:
raise EmailOtpError(OtpFailure.DELIVERY)
with pytest.raises(EmailOtpError) as error:
otp_case.service(fail).request_access(otp_case.token)
assert error.value.reason == OtpFailure.DELIVERY
assert error.value.retry_after is not None
assert error.value.retry_after > 0
service.verify(otp_case.token, challenge_token=first.challenge_token, otp_code=first_code, ip_address=None)
assert redis_client.zcard(f"{otp_case.limiter.prefix}:{otp_case.delivery.id}") == 3
pattern = serialize_redis_name(f"hitl:otp:challenge:{{{otp_case.delivery.id}:*")
assert len(list(redis_client.scan_iter(match=pattern))) == 4
def test_older_mail_finishing_last_does_not_replace_newer_challenge(otp_case: OtpCase) -> None:
from threading import Event
started, release = Event(), Event()
first_code = []
def slow_send(_email: str, code: str) -> None:
first_code.append(code)
started.set()
assert release.wait(10)
with ThreadPoolExecutor(max_workers=1) as executor:
older = executor.submit(otp_case.service(slow_send).request_access, otp_case.token)
assert started.wait(10)
try:
otp_case.release_cooldown()
newer = otp_case.service().request_access(otp_case.token)
finally:
release.set()
first = older.result(timeout=10)
service = otp_case.service()
service.verify(otp_case.token, challenge_token=first.challenge_token, otp_code=first_code[0], ip_address=None)
service.verify(otp_case.token, challenge_token=newer.challenge_token, otp_code=otp_case.sent[0][1], ip_address=None)
def test_hourly_slot_recovers_without_discarding_recent_sends() -> None:
limiter = RateLimiter(prefix=f"otp-test:{uuid4()}", max_attempts=5, time_window=3600)
key = serialize_redis_name(f"{limiter.prefix}:delivery")
redis_client.eval(
"""
local now = tonumber(redis.call('TIME')[1])
redis.call('ZADD', KEYS[1], now - 3600, 'boundary')
for i = 1, 4 do redis.call('ZADD', KEYS[1], now - 300 + i * 30, tostring(i)) end
redis.call('EXPIRE', KEYS[1], 3600)
""",
1,
key,
)
assert limiter.acquire("delivery", cooldown_seconds=60) == 0
assert redis_client.zcard(f"{limiter.prefix}:delivery") == 5
assert limiter.retry_after("delivery", cooldown_seconds=60) > 60
redis_client.delete(f"{limiter.prefix}:delivery")
@@ -0,0 +1,366 @@
"""
Integration tests for Redis broadcast channel implementation using TestContainers.
This test suite covers real Redis interactions including:
- Multiple producer/consumer scenarios
- Network failure scenarios
- Performance under load
- Real-world usage patterns
"""
import threading
import time
import uuid
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor, as_completed
import pytest
import redis
from testcontainers.redis import RedisContainer
from libs.broadcast_channel.channel import BroadcastChannel, Subscription
from libs.broadcast_channel.exc import SubscriptionClosedError
from libs.broadcast_channel.redis.pubsub_channel import BroadcastChannel as RedisBroadcastChannel
class TestRedisBroadcastChannelIntegration:
"""Integration tests for Redis broadcast channel with real Redis instance."""
@pytest.fixture(scope="class")
def redis_container(self) -> Iterator[RedisContainer]:
"""Create a Redis container for integration testing."""
with RedisContainer(image="redis:6-alpine") as container:
yield container
@pytest.fixture(scope="class")
def redis_client(self, redis_container: RedisContainer) -> redis.Redis:
"""Create a Redis client connected to the test container."""
host = redis_container.get_container_host_ip()
port = redis_container.get_exposed_port(6379)
return redis.Redis(host=host, port=port, decode_responses=False)
@pytest.fixture
def broadcast_channel(self, redis_client: redis.Redis) -> BroadcastChannel:
"""Create a BroadcastChannel instance with real Redis client."""
return RedisBroadcastChannel(redis_client)
@classmethod
def _get_test_topic_name(cls):
return f"test_topic_{uuid.uuid4()}"
# ==================== Basic Functionality Tests ===================='
def test_close_an_active_subscription_should_stop_iteration(self, broadcast_channel):
topic_name = self._get_test_topic_name()
topic = broadcast_channel.topic(topic_name)
subscription = topic.subscribe()
consuming_event = threading.Event()
def consume():
msgs = []
consuming_event.set()
for msg in subscription:
msgs.append(msg)
return msgs
with ThreadPoolExecutor(max_workers=1) as executor:
producer_future = executor.submit(consume)
consuming_event.wait()
subscription.close()
msgs = producer_future.result(timeout=1)
assert msgs == []
def test_end_to_end_messaging(self, broadcast_channel: BroadcastChannel):
"""Test complete end-to-end messaging flow."""
topic_name = "test-topic"
message = b"hello world"
# Create producer and subscriber
topic = broadcast_channel.topic(topic_name)
producer = topic.as_producer()
subscription = topic.subscribe()
# Publish and receive message
def producer_thread():
time.sleep(0.1) # Small delay to ensure subscriber is ready
producer.publish(message)
time.sleep(0.1)
subscription.close()
def consumer_thread() -> list[bytes]:
received_messages = []
for msg in subscription:
received_messages.append(msg)
return received_messages
# Run producer and consumer
with ThreadPoolExecutor(max_workers=2) as executor:
producer_future = executor.submit(producer_thread)
consumer_future = executor.submit(consumer_thread)
# Wait for completion
producer_future.result(timeout=5.0)
received_messages = consumer_future.result(timeout=5.0)
assert len(received_messages) == 1
assert received_messages[0] == message
def test_multiple_subscribers_same_topic(self, broadcast_channel: BroadcastChannel):
"""Test message broadcasting to multiple subscribers.
This test ensures the publisher only sends after all subscribers have actually started
their Redis Pub/Sub subscriptions to avoid race conditions/flakiness.
"""
topic_name = "broadcast-topic"
message = b"broadcast message"
subscriber_count = 5
# Create producer and multiple subscribers
topic = broadcast_channel.topic(topic_name)
producer = topic.as_producer()
subscriptions = [topic.subscribe() for _ in range(subscriber_count)]
ready_events = [threading.Event() for _ in range(subscriber_count)]
def producer_thread():
# Wait for all subscribers to start (with a reasonable timeout)
deadline = time.time() + 5.0
for ev in ready_events:
remaining = deadline - time.time()
if remaining <= 0:
break
ev.wait(timeout=max(0.0, remaining))
# Now publish the message
producer.publish(message)
time.sleep(0.2)
for sub in subscriptions:
sub.close()
def consumer_thread(subscription: Subscription, ready_event: threading.Event) -> list[bytes]:
received_msgs = []
# Prime the subscription to ensure the underlying Pub/Sub is started
try:
_ = subscription.receive(0.01)
except SubscriptionClosedError:
ready_event.set()
return received_msgs
# Signal readiness after first receive returns (subscription started)
ready_event.set()
while True:
try:
msg = subscription.receive(0.1)
except SubscriptionClosedError:
break
if msg is None:
continue
received_msgs.append(msg)
if len(received_msgs) >= 1:
break
return received_msgs
# Run producer and consumers
with ThreadPoolExecutor(max_workers=subscriber_count + 1) as executor:
producer_future = executor.submit(producer_thread)
consumer_futures = [
executor.submit(consumer_thread, subscription, ready_events[idx])
for idx, subscription in enumerate(subscriptions)
]
# Wait for completion
producer_future.result(timeout=10.0)
msgs_by_consumers = []
for future in as_completed(consumer_futures, timeout=10.0):
msgs_by_consumers.append(future.result())
# Close all subscriptions
for subscription in subscriptions:
subscription.close()
# Verify all subscribers received the message
for msgs in msgs_by_consumers:
assert len(msgs) == 1
assert msgs[0] == message
def test_topic_isolation(self, broadcast_channel: BroadcastChannel):
"""Test that different topics are isolated from each other."""
topic1_name = "topic1"
topic2_name = "topic2"
message1 = b"message for topic1"
message2 = b"message for topic2"
topic1 = broadcast_channel.topic(topic1_name)
topic2 = broadcast_channel.topic(topic2_name)
# Subscriptions are created here so they can be closed from the finally block
# if a future times out, preventing consumers from blocking executor shutdown.
subscription1 = topic1.subscribe()
subscription2 = topic2.subscribe()
ready_event1 = threading.Event()
ready_event2 = threading.Event()
def producer_thread():
# Wait until both subscriptions are provably active before publishing.
# Redis Pub/Sub does not replay a message published before SUBSCRIBE is active.
deadline = time.time() + 5.0
for ev in (ready_event1, ready_event2):
remaining = deadline - time.time()
ev.wait(timeout=max(0.0, remaining))
topic1.publish(message1)
topic2.publish(message2)
def consumer_by_thread(subscription: Subscription, ready_event: threading.Event) -> list[bytes]:
received: list[bytes] = []
# Prime the subscription so the underlying SUBSCRIBE is sent to Redis,
# then signal readiness before the producer publishes.
try:
_ = subscription.receive(0.01)
except SubscriptionClosedError:
ready_event.set()
return received
ready_event.set()
while True:
try:
msg = subscription.receive(0.1)
except SubscriptionClosedError:
break
if msg is None:
continue
received.append(msg)
if len(received) >= 1:
break
return received
with ThreadPoolExecutor(max_workers=3) as executor:
consumer1_future = executor.submit(consumer_by_thread, subscription1, ready_event1)
consumer2_future = executor.submit(consumer_by_thread, subscription2, ready_event2)
producer_future = executor.submit(producer_thread)
try:
producer_future.result(timeout=10.0)
received_by_topic1 = consumer1_future.result(timeout=10.0)
received_by_topic2 = consumer2_future.result(timeout=10.0)
finally:
# Closing here unblocks any consumer still in receive() so the
# executor can shut down cleanly even when a future timed out.
subscription1.close()
subscription2.close()
assert len(received_by_topic1) == 1
assert len(received_by_topic2) == 1
assert received_by_topic1[0] == message1
assert received_by_topic2[0] == message2
# ==================== Performance Tests ====================
def test_concurrent_producers(self, broadcast_channel: BroadcastChannel):
"""Test multiple producers publishing to the same topic."""
topic_name = "concurrent-producers-topic"
producer_count = 5
messages_per_producer = 5
topic = broadcast_channel.topic(topic_name)
subscription = topic.subscribe()
expected_total = producer_count * messages_per_producer
consumer_ready = threading.Event()
def producer_thread(producer_idx: int) -> set[bytes]:
producer = topic.as_producer()
produced = set()
for i in range(messages_per_producer):
message = f"producer_{producer_idx}_msg_{i}".encode()
produced.add(message)
producer.publish(message)
time.sleep(0.001) # Small delay to avoid overwhelming
return produced
def consumer_thread() -> set[bytes]:
received_msgs: set[bytes] = set()
with subscription:
# Prime the subscription before producers publish. Redis Pub/Sub does not
# replay messages sent before the subscribe command is active.
subscription.receive(timeout=0.1)
consumer_ready.set()
while True:
try:
msg = subscription.receive(timeout=0.1)
except SubscriptionClosedError:
break
if msg is None:
if len(received_msgs) >= expected_total:
break
else:
continue
received_msgs.add(msg)
return received_msgs
# Run producers and consumer
with ThreadPoolExecutor(max_workers=producer_count + 1) as executor:
consumer_future = executor.submit(consumer_thread)
consumer_ready.wait()
producer_futures = [executor.submit(producer_thread, i) for i in range(producer_count)]
sent_msgs: set[bytes] = set()
# Wait for completion
for future in as_completed(producer_futures, timeout=30.0):
sent_msgs.update(future.result())
try:
consumer_received_msgs = consumer_future.result(timeout=30.0)
finally:
subscription.close()
# Verify message content
assert sent_msgs == consumer_received_msgs
# ==================== Resource Management Tests ====================
def test_subscription_cleanup(self, broadcast_channel: BroadcastChannel, redis_client: redis.Redis):
"""Test proper cleanup of subscription resources."""
topic_name = "cleanup-test-topic"
# Create multiple subscriptions
topic = broadcast_channel.topic(topic_name)
def _consume(sub: Subscription):
for _i in sub:
pass
subscriptions = []
for _i in range(5):
subscription = topic.subscribe()
subscriptions.append(subscription)
# Start all subscriptions
thread = threading.Thread(target=_consume, args=(subscription,))
thread.start()
time.sleep(0.01)
# Verify subscriptions are active
pubsub_info = redis_client.pubsub_numsub(topic_name)
# pubsub_numsub returns list of tuples, find our topic
topic_subscribers = 0
for channel, count in pubsub_info:
# the channel name returned by redis is bytes.
if channel == topic_name.encode():
topic_subscribers = count
break
assert topic_subscribers >= 5
# Close all subscriptions
for subscription in subscriptions:
subscription.close()
# Wait a bit for cleanup
time.sleep(1)
# Verify subscriptions are cleaned up
pubsub_info_after = redis_client.pubsub_numsub(topic_name)
topic_subscribers_after = 0
for channel, count in pubsub_info_after:
if channel == topic_name.encode():
topic_subscribers_after = count
break
assert topic_subscribers_after == 0
@@ -0,0 +1,439 @@
"""
Integration tests for Redis sharded broadcast channel implementation using TestContainers.
Covers real Redis 7+ sharded pub/sub interactions including:
- Multiple producer/consumer scenarios
- Topic isolation
- Concurrency under load
- Resource cleanup accounting via PUBSUB SHARDNUMSUB
"""
import socket
import threading
import time
import uuid
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor, as_completed
import pytest
import redis
from redis.cluster import RedisCluster
from testcontainers.redis import RedisContainer
from libs.broadcast_channel.channel import BroadcastChannel, Subscription, Topic
from libs.broadcast_channel.exc import SubscriptionClosedError
from libs.broadcast_channel.redis.sharded_channel import (
ShardedRedisBroadcastChannel,
)
class TestShardedRedisBroadcastChannelIntegration:
"""Integration tests for Redis sharded broadcast channel with real Redis 7 instance."""
@pytest.fixture(scope="class")
def redis_container(self) -> Iterator[RedisContainer]:
"""Create a Redis 7 container for integration testing (required for sharded pub/sub)."""
# Redis 7+ is required for SPUBLISH/SSUBSCRIBE
with RedisContainer(image="redis:7-alpine") as container:
yield container
@pytest.fixture(scope="class")
def redis_client(self, redis_container: RedisContainer) -> redis.Redis:
"""Create a Redis client connected to the test container."""
host = redis_container.get_container_host_ip()
port = redis_container.get_exposed_port(6379)
return redis.Redis(host=host, port=port, decode_responses=False)
@pytest.fixture
def broadcast_channel(self, redis_client: redis.Redis) -> BroadcastChannel:
"""Create a ShardedRedisBroadcastChannel instance with real Redis client."""
return ShardedRedisBroadcastChannel(redis_client)
@classmethod
def _get_test_topic_name(cls) -> str:
return f"test_sharded_topic_{uuid.uuid4()}"
# ==================== Basic Functionality Tests ====================
def test_close_an_active_subscription_should_stop_iteration(self, broadcast_channel: BroadcastChannel):
topic_name = self._get_test_topic_name()
topic = broadcast_channel.topic(topic_name)
subscription = topic.subscribe()
consuming_event = threading.Event()
def consume():
msgs = []
consuming_event.set()
for msg in subscription:
msgs.append(msg)
return msgs
with ThreadPoolExecutor(max_workers=1) as executor:
consumer_future = executor.submit(consume)
consuming_event.wait()
subscription.close()
msgs = consumer_future.result(timeout=2)
assert msgs == []
def test_end_to_end_messaging(self, broadcast_channel: BroadcastChannel):
"""Test complete end-to-end messaging flow (sharded)."""
topic_name = self._get_test_topic_name()
message = b"hello sharded world"
topic = broadcast_channel.topic(topic_name)
producer = topic.as_producer()
subscription = topic.subscribe()
def producer_thread():
time.sleep(0.1) # Small delay to ensure subscriber is ready
producer.publish(message)
time.sleep(0.1)
subscription.close()
def consumer_thread() -> list[bytes]:
received_messages = []
for msg in subscription:
received_messages.append(msg)
return received_messages
with ThreadPoolExecutor(max_workers=2) as executor:
producer_future = executor.submit(producer_thread)
consumer_future = executor.submit(consumer_thread)
producer_future.result(timeout=5.0)
received_messages = consumer_future.result(timeout=5.0)
assert len(received_messages) == 1
assert received_messages[0] == message
def test_multiple_subscribers_same_topic(self, broadcast_channel: BroadcastChannel):
"""Test message broadcasting to multiple sharded subscribers."""
topic_name = self._get_test_topic_name()
message = b"broadcast sharded message"
subscriber_count = 5
topic = broadcast_channel.topic(topic_name)
producer = topic.as_producer()
subscriptions = [topic.subscribe() for _ in range(subscriber_count)]
ready_events = [threading.Event() for _ in range(subscriber_count)]
def producer_thread():
deadline = time.time() + 5.0
for ev in ready_events:
remaining = deadline - time.time()
if remaining <= 0:
break
if not ev.wait(timeout=max(0.0, remaining)):
pytest.fail("subscriber did not become ready before publish deadline")
producer.publish(message)
time.sleep(0.2)
for sub in subscriptions:
sub.close()
def consumer_thread(subscription: Subscription, ready_event: threading.Event) -> list[bytes]:
received_msgs = []
# Prime subscription so the underlying Pub/Sub listener thread starts before publishing
try:
_ = subscription.receive(0.01)
except SubscriptionClosedError:
return received_msgs
finally:
ready_event.set()
while True:
try:
msg = subscription.receive(0.1)
except SubscriptionClosedError:
break
if msg is None:
continue
received_msgs.append(msg)
if len(received_msgs) >= 1:
break
return received_msgs
with ThreadPoolExecutor(max_workers=subscriber_count + 1) as executor:
producer_future = executor.submit(producer_thread)
consumer_futures = [
executor.submit(consumer_thread, subscription, ready_events[idx])
for idx, subscription in enumerate(subscriptions)
]
producer_future.result(timeout=10.0)
msgs_by_consumers = []
for future in as_completed(consumer_futures, timeout=10.0):
msgs_by_consumers.append(future.result())
for subscription in subscriptions:
subscription.close()
for msgs in msgs_by_consumers:
assert len(msgs) == 1
assert msgs[0] == message
def test_topic_isolation(self, broadcast_channel: BroadcastChannel):
"""Test that different sharded topics are isolated from each other."""
topic1_name = self._get_test_topic_name()
topic2_name = self._get_test_topic_name()
message1 = b"message for sharded topic1"
message2 = b"message for sharded topic2"
topic1 = broadcast_channel.topic(topic1_name)
topic2 = broadcast_channel.topic(topic2_name)
def producer_thread():
time.sleep(0.1)
topic1.publish(message1)
topic2.publish(message2)
def consumer_by_thread(topic: Topic) -> list[bytes]:
subscription = topic.subscribe()
received = []
with subscription:
for msg in subscription:
received.append(msg)
if len(received) >= 1:
break
return received
with ThreadPoolExecutor(max_workers=3) as executor:
producer_future = executor.submit(producer_thread)
consumer1_future = executor.submit(consumer_by_thread, topic1)
consumer2_future = executor.submit(consumer_by_thread, topic2)
producer_future.result(timeout=5.0)
received_by_topic1 = consumer1_future.result(timeout=5.0)
received_by_topic2 = consumer2_future.result(timeout=5.0)
assert len(received_by_topic1) == 1
assert len(received_by_topic2) == 1
assert received_by_topic1[0] == message1
assert received_by_topic2[0] == message2
# ==================== Performance / Concurrency ====================
def test_concurrent_producers(self, broadcast_channel: BroadcastChannel):
"""Test multiple producers publishing to the same sharded topic."""
topic_name = self._get_test_topic_name()
producer_count = 5
messages_per_producer = 5
topic = broadcast_channel.topic(topic_name)
subscription = topic.subscribe()
expected_total = producer_count * messages_per_producer
consumer_ready = threading.Event()
def producer_thread(producer_idx: int) -> set[bytes]:
producer = topic.as_producer()
produced = set()
for i in range(messages_per_producer):
message = f"producer_{producer_idx}_msg_{i}".encode()
produced.add(message)
producer.publish(message)
time.sleep(0.001)
return produced
def consumer_thread() -> set[bytes]:
received_msgs: set[bytes] = set()
with subscription:
subscription.receive(timeout=0.1)
consumer_ready.set()
while True:
try:
msg = subscription.receive(timeout=0.1)
except SubscriptionClosedError:
break
if msg is None:
if len(received_msgs) >= expected_total:
break
else:
continue
received_msgs.add(msg)
return received_msgs
with ThreadPoolExecutor(max_workers=producer_count + 1) as executor:
consumer_future = executor.submit(consumer_thread)
consumer_ready.wait()
producer_futures = [executor.submit(producer_thread, i) for i in range(producer_count)]
sent_msgs: set[bytes] = set()
for future in as_completed(producer_futures, timeout=30.0):
sent_msgs.update(future.result())
try:
consumer_received_msgs = consumer_future.result(timeout=60.0)
finally:
subscription.close()
assert sent_msgs == consumer_received_msgs
# ==================== Resource Management ====================
def _get_sharded_numsub(self, redis_client: redis.Redis, topic_name: str) -> int:
"""Return number of sharded subscribers for a given topic using PUBSUB SHARDNUMSUB.
Redis returns a flat list like [channel1, count1, channel2, count2, ...].
We request a single channel, so parse accordingly.
"""
try:
res = redis_client.execute_command("PUBSUB", "SHARDNUMSUB", topic_name)
except Exception:
return 0
# Normalize different possible return shapes from drivers
if isinstance(res, (list, tuple)):
# Expect [channel, count] (bytes/str, int)
if len(res) >= 2:
key = res[0]
cnt = res[1]
if key == topic_name or (isinstance(key, (bytes, bytearray)) and key == topic_name.encode()):
try:
return int(cnt)
except Exception:
return 0
# Fallback parse pairs
count = 0
for i in range(0, len(res) - 1, 2):
key = res[i]
cnt = res[i + 1]
if key == topic_name or (isinstance(key, (bytes, bytearray)) and key == topic_name.encode()):
try:
count = int(cnt)
except Exception:
count = 0
break
return count
return 0
def test_subscription_cleanup(self, broadcast_channel: BroadcastChannel, redis_client: redis.Redis):
"""Test proper cleanup of sharded subscription resources via SHARDNUMSUB."""
topic_name = self._get_test_topic_name()
topic = broadcast_channel.topic(topic_name)
def _consume(sub: Subscription):
for _ in sub:
pass
subscriptions = []
for _ in range(5):
subscription = topic.subscribe()
subscriptions.append(subscription)
thread = threading.Thread(target=_consume, args=(subscription,))
thread.start()
time.sleep(0.01)
# Verify subscriptions are active using SHARDNUMSUB
topic_subscribers = self._get_sharded_numsub(redis_client, topic_name)
assert topic_subscribers >= 5
# Close all subscriptions
for subscription in subscriptions:
subscription.close()
# Wait a bit for cleanup
time.sleep(1)
# Verify subscriptions are cleaned up
topic_subscribers_after = self._get_sharded_numsub(redis_client, topic_name)
assert topic_subscribers_after == 0
class TestShardedRedisBroadcastChannelClusterIntegration:
"""Integration tests for sharded pub/sub with RedisCluster client."""
@pytest.fixture(scope="class")
def redis_cluster_container(self) -> Iterator[RedisContainer]:
"""Create a Redis 7 container with cluster mode enabled."""
command = (
"redis-server --port 6379 "
"--cluster-enabled yes "
"--cluster-config-file nodes.conf "
"--cluster-node-timeout 5000 "
"--appendonly no "
"--protected-mode no"
)
with RedisContainer(image="redis:7-alpine").with_command(command) as container:
yield container
@classmethod
def _get_test_topic_name(cls) -> str:
return f"test_sharded_cluster_topic_{uuid.uuid4()}"
@staticmethod
def _resolve_announced_ip(host: str) -> str:
"""Resolve the container host name to a literal IP accepted by Redis cluster config."""
return socket.getaddrinfo(host, None, type=socket.SOCK_STREAM)[0][4][0]
@staticmethod
def _ensure_single_node_cluster(host: str, port: int) -> None:
"""Bootstrap a single-node cluster using a literal IP for Redis node advertisement."""
client = redis.Redis(host=host, port=port, decode_responses=False)
announced_ip = TestShardedRedisBroadcastChannelClusterIntegration._resolve_announced_ip(host)
client.config_set("cluster-announce-ip", announced_ip)
client.config_set("cluster-announce-port", port)
slots = client.execute_command("CLUSTER", "SLOTS")
if not slots:
client.execute_command("CLUSTER", "ADDSLOTSRANGE", 0, 16383)
deadline = time.time() + 5.0
while time.time() < deadline:
info = client.execute_command("CLUSTER", "INFO")
info_text = info.decode("utf-8") if isinstance(info, (bytes, bytearray)) else str(info)
if "cluster_state:ok" in info_text:
return
time.sleep(0.05)
raise RuntimeError("Redis cluster did not become ready in time")
@pytest.fixture(scope="class")
def redis_cluster_client(self, redis_cluster_container: RedisContainer) -> RedisCluster:
host = redis_cluster_container.get_container_host_ip()
port = int(redis_cluster_container.get_exposed_port(6379))
self._ensure_single_node_cluster(host, port)
return RedisCluster(host=host, port=port, decode_responses=False)
@pytest.fixture
def broadcast_channel(self, redis_cluster_client: RedisCluster) -> BroadcastChannel:
return ShardedRedisBroadcastChannel(redis_cluster_client)
def test_cluster_sharded_pubsub_delivers_message(self, broadcast_channel: BroadcastChannel):
"""Ensure sharded subscription receives messages when using RedisCluster client."""
topic_name = self._get_test_topic_name()
message = b"cluster sharded message"
topic = broadcast_channel.topic(topic_name)
producer = topic.as_producer()
subscription = topic.subscribe()
ready_event = threading.Event()
def consumer_thread() -> list[bytes]:
received = []
try:
_ = subscription.receive(0.01)
except SubscriptionClosedError:
return received
ready_event.set()
deadline = time.time() + 5.0
while time.time() < deadline:
msg = subscription.receive(timeout=0.1)
if msg is None:
continue
received.append(msg)
break
subscription.close()
return received
def producer_thread():
if not ready_event.wait(timeout=2.0):
pytest.fail("subscriber did not become ready before publish")
producer.publish(message)
with ThreadPoolExecutor(max_workers=2) as executor:
consumer_future = executor.submit(consumer_thread)
producer_future = executor.submit(producer_thread)
producer_future.result(timeout=5.0)
received_messages = consumer_future.result(timeout=5.0)
assert received_messages == [message]
@@ -0,0 +1,261 @@
"""
Integration tests for Redis Streams broadcast channel implementation using TestContainers.
This suite focuses on the semantics that differ from Redis Pub/Sub:
- Every active subscription should receive each newly published message.
- Each subscription should only observe messages published after its listener starts.
- Prepared subscriptions should observe messages published after preparation but before listener startup.
"""
import threading
import time
import uuid
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor, as_completed
import pytest
import redis
from testcontainers.redis import RedisContainer
from libs.broadcast_channel.channel import BroadcastChannel, Subscription, SupportsPreparedSubscription, Topic
from libs.broadcast_channel.exc import SubscriptionClosedError
from libs.broadcast_channel.redis.streams_channel import StreamsBroadcastChannel, _StreamsSubscription
class TestRedisStreamsBroadcastChannelIntegration:
"""Integration tests for Redis Streams broadcast channel with a real Redis instance."""
@pytest.fixture(scope="class")
def redis_container(self) -> Iterator[RedisContainer]:
"""Create a Redis container for integration testing."""
with RedisContainer(image="redis:6-alpine") as container:
yield container
@pytest.fixture(scope="class")
def redis_client(self, redis_container: RedisContainer) -> redis.Redis:
"""Create a Redis client connected to the test container."""
host = redis_container.get_container_host_ip()
port = redis_container.get_exposed_port(6379)
return redis.Redis(host=host, port=port, decode_responses=False)
@pytest.fixture
def broadcast_channel(self, redis_client: redis.Redis) -> BroadcastChannel:
"""Create a StreamsBroadcastChannel instance with a real Redis client."""
return StreamsBroadcastChannel(redis_client)
@classmethod
def _get_test_topic_name(cls) -> str:
return f"test_streams_topic_{uuid.uuid4()}"
@staticmethod
def _start_subscription(subscription: Subscription) -> None:
"""Start the background listener and confirm the subscription queue is empty."""
assert subscription.receive(timeout=0.05) is None
@staticmethod
def _receive_message(subscription: Subscription, *, timeout_seconds: float = 2.0) -> bytes:
"""Poll until a message is received or the timeout expires."""
deadline = time.monotonic() + timeout_seconds
while time.monotonic() < deadline:
message = subscription.receive(timeout=0.1)
if message is not None:
return message
pytest.fail("Timed out waiting for a message")
def test_close_an_active_subscription_should_stop_iteration(self, broadcast_channel: BroadcastChannel) -> None:
"""Closing an active subscription should terminate the iterator cleanly."""
topic = broadcast_channel.topic(self._get_test_topic_name())
subscription = topic.subscribe()
consuming_event = threading.Event()
def consume() -> list[bytes]:
messages: list[bytes] = []
consuming_event.set()
for message in subscription:
messages.append(message)
return messages
with ThreadPoolExecutor(max_workers=1) as executor:
consumer_future = executor.submit(consume)
assert consuming_event.wait(timeout=1.0)
subscription.close()
assert consumer_future.result(timeout=2.0) == []
def test_end_to_end_messaging(self, broadcast_channel: BroadcastChannel) -> None:
"""A producer should publish a message that a live subscription can consume."""
topic = broadcast_channel.topic(self._get_test_topic_name())
producer = topic.as_producer()
subscription = topic.subscribe()
message = b"hello streams"
try:
self._start_subscription(subscription)
producer.publish(message)
assert self._receive_message(subscription) == message
assert subscription.receive(timeout=0.1) is None
finally:
subscription.close()
def test_multiple_subscriptions_each_receive_each_new_message(self, broadcast_channel: BroadcastChannel) -> None:
"""Each active subscription should receive the same newly published message."""
topic = broadcast_channel.topic(self._get_test_topic_name())
subscriptions = [topic.subscribe() for _ in range(3)]
new_message = b"message-visible-to-every-subscriber"
try:
for subscription in subscriptions:
self._start_subscription(subscription)
topic.publish(new_message)
for subscription in subscriptions:
assert self._receive_message(subscription) == new_message
assert subscription.receive(timeout=0.1) is None
finally:
for subscription in subscriptions:
subscription.close()
def test_each_subscription_only_receives_messages_published_after_it_starts(
self,
broadcast_channel: BroadcastChannel,
) -> None:
"""A late subscription should not replay messages that existed before its listener started."""
topic = broadcast_channel.topic(self._get_test_topic_name())
first_subscription = topic.subscribe()
second_subscription = topic.subscribe()
message_before_any_subscription = b"before-any-subscription"
message_after_first_subscription = b"after-first-subscription"
message_after_second_subscription = b"after-second-subscription"
try:
topic.publish(message_before_any_subscription)
self._start_subscription(first_subscription)
topic.publish(message_after_first_subscription)
assert self._receive_message(first_subscription) == message_after_first_subscription
assert first_subscription.receive(timeout=0.1) is None
self._start_subscription(second_subscription)
topic.publish(message_after_second_subscription)
assert self._receive_message(first_subscription) == message_after_second_subscription
assert self._receive_message(second_subscription) == message_after_second_subscription
assert first_subscription.receive(timeout=0.1) is None
assert second_subscription.receive(timeout=0.1) is None
finally:
first_subscription.close()
second_subscription.close()
def test_prepare_subscription_fixes_boundary_before_listener_starts(
self,
broadcast_channel: BroadcastChannel,
) -> None:
topic = broadcast_channel.topic(self._get_test_topic_name())
topic.publish(b"before-prepare")
subscriber = topic.as_subscriber()
assert isinstance(subscriber, SupportsPreparedSubscription)
subscription = subscriber.prepare_subscription()
topic.publish(b"after-prepare-before-start")
try:
assert self._receive_message(subscription) == b"after-prepare-before-start"
assert subscription.receive(timeout=0.1) is None
finally:
subscription.close()
def test_subscription_with_injected_start_id_reads_only_later_entries(
self,
redis_client: redis.Redis,
) -> None:
stream_key = self._get_test_topic_name()
start_id = redis_client.xadd(stream_key, {b"data": b"at-boundary"})
redis_client.xadd(stream_key, {b"data": b"after-boundary"})
subscription = _StreamsSubscription(redis_client, stream_key, start_id=start_id)
try:
assert self._receive_message(subscription) == b"after-boundary"
assert subscription.receive(timeout=0.1) is None
finally:
subscription.close()
def test_topic_isolation(self, broadcast_channel: BroadcastChannel) -> None:
"""Messages from different topics should remain isolated."""
topic1 = broadcast_channel.topic(self._get_test_topic_name())
topic2 = broadcast_channel.topic(self._get_test_topic_name())
message1 = b"message-for-topic-1"
message2 = b"message-for-topic-2"
def consume_single_message(topic: Topic) -> bytes:
subscription = topic.subscribe()
try:
self._start_subscription(subscription)
return self._receive_message(subscription)
finally:
subscription.close()
with ThreadPoolExecutor(max_workers=3) as executor:
consumer1_future = executor.submit(consume_single_message, topic1)
consumer2_future = executor.submit(consume_single_message, topic2)
time.sleep(0.1)
topic1.publish(message1)
topic2.publish(message2)
assert consumer1_future.result(timeout=5.0) == message1
assert consumer2_future.result(timeout=5.0) == message2
def test_concurrent_producers_publish_all_messages(self, broadcast_channel: BroadcastChannel) -> None:
"""Concurrent producers should not lose messages for a live subscription."""
topic = broadcast_channel.topic(self._get_test_topic_name())
subscription = topic.subscribe()
producer_count = 4
messages_per_producer = 4
expected_total = producer_count * messages_per_producer
consumer_ready = threading.Event()
def produce_messages(producer_idx: int) -> set[bytes]:
producer = topic.as_producer()
produced: set[bytes] = set()
for message_idx in range(messages_per_producer):
payload = f"producer-{producer_idx}-message-{message_idx}".encode()
produced.add(payload)
producer.publish(payload)
time.sleep(0.001)
return produced
def consume_messages() -> set[bytes]:
received: set[bytes] = set()
try:
self._start_subscription(subscription)
consumer_ready.set()
while len(received) < expected_total:
message = subscription.receive(timeout=0.2)
if message is not None:
received.add(message)
return received
finally:
subscription.close()
with ThreadPoolExecutor(max_workers=producer_count + 1) as executor:
consumer_future = executor.submit(consume_messages)
assert consumer_ready.wait(timeout=2.0)
producer_futures = [executor.submit(produce_messages, idx) for idx in range(producer_count)]
expected_messages: set[bytes] = set()
for future in as_completed(producer_futures, timeout=10.0):
expected_messages.update(future.result())
assert consumer_future.result(timeout=10.0) == expected_messages
def test_receive_raises_subscription_closed_after_close(self, broadcast_channel: BroadcastChannel) -> None:
"""Calling receive on a closed subscription should raise SubscriptionClosedError."""
topic = broadcast_channel.topic(self._get_test_topic_name())
subscription = topic.subscribe()
self._start_subscription(subscription)
subscription.close()
with pytest.raises(SubscriptionClosedError):
subscription.receive(timeout=0.1)
@@ -0,0 +1,219 @@
"""Redis-backed integration coverage for the API-token cache."""
import concurrent.futures
import time
from datetime import datetime, timedelta
import pytest
from extensions.ext_redis import redis_client
from models.enums import ApiTokenType
from models.model import ApiToken
from services.api_token_service import ApiTokenCache, CachedApiToken, record_token_usage
pytestmark = pytest.mark.usefixtures("set_up_containers_and_env")
def _api_token(
token: str,
*,
token_id: str = "test-id",
app_id: str = "test-app",
tenant_id: str = "test-tenant",
last_used_at: datetime | None = None,
created_at: datetime | None = None,
) -> ApiToken:
"""Build a real mapped token without requiring database persistence for cache-only behavior."""
api_token = ApiToken()
api_token.id = token_id
api_token.app_id = app_id
api_token.tenant_id = tenant_id
api_token.type = ApiTokenType.APP
api_token.token = token
api_token.last_used_at = last_used_at
api_token.created_at = created_at or datetime.now()
return api_token
class TestApiTokenCacheRedisIntegration:
"""Cache semantics that require a real Redis server."""
test_token = "test-integration-token-123"
test_scope = "app"
@property
def cache_key(self) -> str:
return f"api_token:{self.test_scope}:{self.test_token}"
def setup_method(self) -> None:
self._cleanup()
def teardown_method(self) -> None:
self._cleanup()
def _cleanup(self) -> None:
redis_client.delete(self.cache_key)
redis_client.delete(ApiTokenCache._make_tenant_index_key("test-tenant-id"))
redis_client.delete(ApiTokenCache._make_tenant_index_key("test-tenant"))
redis_client.delete(ApiTokenCache._make_tenant_index_key("test-tenant-789"))
redis_client.delete(ApiTokenCache.make_active_key(self.test_token, self.test_scope))
for index in range(3):
redis_client.delete(f"api_token:app:test-token-{index}")
def test_cache_set_and_get_with_real_redis(self) -> None:
token = _api_token(
self.test_token,
token_id="test-id-123",
app_id="test-app-456",
tenant_id="test-tenant-789",
last_used_at=datetime.now(),
created_at=datetime.now() - timedelta(days=30),
)
assert ApiTokenCache.set(self.test_token, self.test_scope, token) is True
assert redis_client.get(self.cache_key) is not None
cached_token = ApiTokenCache.get(self.test_token, self.test_scope)
assert isinstance(cached_token, CachedApiToken)
assert cached_token.id == "test-id-123"
assert cached_token.app_id == "test-app-456"
assert cached_token.tenant_id == "test-tenant-789"
assert cached_token.type == "app"
assert cached_token.token == self.test_token
def test_cache_ttl_with_real_redis(self) -> None:
ApiTokenCache.set(self.test_token, self.test_scope, _api_token(self.test_token))
assert 595 <= redis_client.ttl(self.cache_key) <= 600
def test_cache_null_value_for_invalid_token(self) -> None:
assert ApiTokenCache.set(self.test_token, self.test_scope, None) is True
assert redis_client.get(self.cache_key) == b"null"
assert ApiTokenCache.get(self.test_token, self.test_scope) is None
assert 55 <= redis_client.ttl(self.cache_key) <= 60
def test_cache_delete_with_real_redis(self) -> None:
ApiTokenCache.set(self.test_token, self.test_scope, _api_token(self.test_token))
assert redis_client.exists(self.cache_key) == 1
assert ApiTokenCache.delete(self.test_token, self.test_scope) is True
assert redis_client.exists(self.cache_key) == 0
def test_tenant_index_creation(self) -> None:
tenant_id = "test-tenant-id"
ApiTokenCache.set(self.test_token, self.test_scope, _api_token(self.test_token, tenant_id=tenant_id))
index_key = ApiTokenCache._make_tenant_index_key(tenant_id)
assert redis_client.exists(index_key) == 1
assert self.cache_key.encode() in redis_client.smembers(index_key)
def test_invalidate_by_tenant_via_index(self) -> None:
tenant_id = "test-tenant-id"
for index in range(3):
token_value = f"test-token-{index}"
ApiTokenCache.set(
token_value,
"app",
_api_token(token_value, token_id=f"test-id-{index}", tenant_id=tenant_id),
)
assert ApiTokenCache.invalidate_by_tenant(tenant_id) is True
for index in range(3):
assert redis_client.exists(f"api_token:app:test-token-{index}") == 0
assert redis_client.exists(ApiTokenCache._make_tenant_index_key(tenant_id)) == 0
def test_concurrent_cache_access(self) -> None:
ApiTokenCache.set(self.test_token, self.test_scope, _api_token(self.test_token))
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(ApiTokenCache.get, self.test_token, self.test_scope) for _ in range(50)]
results = [future.result() for future in concurrent.futures.as_completed(futures)]
assert len(results) == 50
assert all(isinstance(result, CachedApiToken) for result in results)
class TestTokenUsageRecording:
"""Active-token recording semantics that require Redis TTL behavior."""
test_token = "test-usage-token"
test_scope = "app"
@property
def active_key(self) -> str:
return ApiTokenCache.make_active_key(self.test_token, self.test_scope)
def teardown_method(self) -> None:
redis_client.delete(self.active_key)
def test_record_token_usage_sets_redis_key(self) -> None:
record_token_usage(self.test_token, self.test_scope)
assert redis_client.exists(self.active_key) == 1
value = redis_client.get(self.active_key)
assert value is not None
datetime.fromisoformat(value.decode() if isinstance(value, bytes) else value)
def test_record_token_usage_has_ttl(self) -> None:
record_token_usage(self.test_token, self.test_scope)
assert 3595 <= redis_client.ttl(self.active_key) <= 3600
def test_record_token_usage_overwrites(self) -> None:
record_token_usage(self.test_token, self.test_scope)
first_value = redis_client.get(self.active_key)
time.sleep(0.01)
record_token_usage(self.test_token, self.test_scope)
assert redis_client.exists(self.active_key) == 1
assert redis_client.get(self.active_key) != first_value
class TestEndToEndCacheFlow:
"""Complete Redis cache flows using real mapped tokens."""
def test_complete_flow_cache_miss_then_hit(self) -> None:
token_value = "test-e2e-token"
scope = "app"
token = _api_token(token_value, token_id="test-e2e-id", tenant_id="test-e2e-tenant")
cache_key = f"api_token:{scope}:{token_value}"
assert token.tenant_id is not None
index_key = ApiTokenCache._make_tenant_index_key(token.tenant_id)
try:
assert ApiTokenCache.set(token_value, scope, token) is True
assert redis_client.exists(cache_key) == 1
cached_token = ApiTokenCache.get(token_value, scope)
assert isinstance(cached_token, CachedApiToken)
assert cached_token.id == token.id
assert cached_token.token == token_value
assert cache_key.encode() in redis_client.smembers(index_key)
assert ApiTokenCache.delete(token_value, scope) is True
assert redis_client.exists(cache_key) == 0
assert cache_key.encode() not in redis_client.smembers(index_key)
finally:
redis_client.delete(cache_key)
redis_client.delete(index_key)
def test_high_concurrency_simulation(self) -> None:
token_value = "test-concurrent-token"
scope = "app"
token = _api_token(token_value, token_id="concurrent-id")
assert token.tenant_id is not None
index_key = ApiTokenCache._make_tenant_index_key(token.tenant_id)
ApiTokenCache.set(token_value, scope, token)
try:
started_at = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:
futures = [executor.submit(ApiTokenCache.get, token_value, scope) for _ in range(100)]
results = [future.result() for future in concurrent.futures.as_completed(futures)]
assert len(results) == 100
assert all(isinstance(result, CachedApiToken) for result in results)
assert time.time() - started_at < 1.0
finally:
ApiTokenCache.delete(token_value, scope)
redis_client.delete(index_key)
@@ -0,0 +1,38 @@
"""
Integration tests for DbMigrationAutoRenewLock using real Redis via TestContainers.
"""
import time
import uuid
import pytest
from extensions.ext_redis import redis_client
from libs.db_migration_lock import DbMigrationAutoRenewLock
@pytest.mark.usefixtures("flask_app_with_containers")
def test_db_migration_lock_renews_ttl_and_releases() -> None:
lock_name = f"test:db_migration_auto_renew_lock:{uuid.uuid4().hex}"
# Keep base TTL very small, and renew frequently so the test is stable even on slower CI.
lock = DbMigrationAutoRenewLock(
redis_client=redis_client,
name=lock_name,
ttl_seconds=1.0,
renew_interval_seconds=0.2,
log_context="test_db_migration_lock",
)
acquired = lock.acquire(blocking=True, blocking_timeout=5)
assert acquired is True
# Wait beyond the base TTL; key should still exist due to renewal.
time.sleep(1.5)
ttl = redis_client.ttl(lock_name)
assert ttl > 0
lock.release_safely(status="successful")
# After release, the key should not exist.
assert redis_client.exists(lock_name) == 0
@@ -0,0 +1,119 @@
"""
Integration tests for RateLimiter using testcontainers Redis.
"""
import uuid
from collections.abc import Callable
import pytest
from extensions.ext_redis import redis_client
from libs import helper as helper_module
@pytest.mark.usefixtures("flask_app_with_containers")
def test_rate_limiter_counts_multiple_attempts_in_same_second(monkeypatch: pytest.MonkeyPatch) -> None:
prefix = f"test_rate_limit:{uuid.uuid4().hex}"
limiter = helper_module.RateLimiter(prefix=prefix, max_attempts=2, time_window=60)
key = limiter._get_key("203.0.113.10")
redis_client.delete(key)
monkeypatch.setattr(helper_module.time, "time", lambda: 1_700_000_000)
limiter.increment_rate_limit("203.0.113.10")
limiter.increment_rate_limit("203.0.113.10")
assert limiter.is_rate_limited("203.0.113.10") is True
@pytest.mark.usefixtures("flask_app_with_containers")
def test_reservation_admits_only_one_parallel_send() -> None:
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)
ready = Barrier(16)
def reserve(_index: int) -> bool:
ready.wait(timeout=10)
with limiter.reserve("user@example.com") as acquired:
return acquired
with ThreadPoolExecutor(max_workers=16) as executor:
admitted = list(executor.map(reserve, range(16)))
assert sum(admitted) == 1
assert redis_client.zcard(limiter._get_key("user@example.com")) == 1
@pytest.mark.usefixtures("flask_app_with_containers")
def test_reservation_preserves_window_expiry_and_failed_send_retry(monkeypatch: pytest.MonkeyPatch) -> None:
limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)
email = "user@example.com"
key = limiter._get_key(email)
monkeypatch.setattr(helper_module.time, "time", lambda: 1000)
def failed_send() -> None:
with limiter.reserve(email) as acquired:
assert acquired
raise RuntimeError("queue unavailable")
with pytest.raises(RuntimeError, match="queue unavailable"):
failed_send()
assert redis_client.zcard(key) == 0
with limiter.reserve(email) as acquired:
assert acquired
with limiter.reserve(email) as acquired:
assert not acquired
assert 0 < redis_client.ttl(key) <= 120
monkeypatch.setattr(helper_module.time, "time", lambda: 1059)
with limiter.reserve(email) as acquired:
assert not acquired
monkeypatch.setattr(helper_module.time, "time", lambda: 1060)
with limiter.reserve(email) as acquired:
assert acquired
assert redis_client.zcard(key) == 1
@pytest.mark.usefixtures("flask_app_with_containers")
def test_expired_reservation_failure_does_not_remove_later_send(monkeypatch: pytest.MonkeyPatch) -> None:
limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)
email = "user@example.com"
monkeypatch.setattr(helper_module.time, "time", lambda: 1000)
def overlapping_sends() -> None:
with limiter.reserve(email) as acquired:
assert acquired
monkeypatch.setattr(helper_module.time, "time", lambda: 1060)
with limiter.reserve(email) as new_acquired:
assert new_acquired
raise RuntimeError("original send failed")
with pytest.raises(RuntimeError, match="original send failed"):
overlapping_sends()
with limiter.reserve(email) as acquired:
assert not acquired
assert redis_client.zcard(limiter._get_key(email)) == 1
@pytest.mark.usefixtures("flask_app_with_containers")
def test_reservation_command_retry_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:
limiter = helper_module.RateLimiter(prefix=f"test_rate_limit:{uuid.uuid4().hex}", max_attempts=1, time_window=60)
register_script = redis_client.register_script
def replay_registration(script: str) -> Callable[..., object]:
execute = register_script(script)
def execute_twice(*, keys: list[str], args: list[object]) -> object:
execute(keys=keys, args=args)
return execute(keys=keys, args=args)
return execute_twice
monkeypatch.setattr(redis_client, "register_script", replay_registration)
with limiter.reserve("user@example.com") as acquired:
assert acquired
assert redis_client.zcard(limiter._get_key("user@example.com")) == 1
@@ -0,0 +1,52 @@
"""Behavior of TTL-preserving scalar counters on real Redis (CI only)."""
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
from uuid import uuid4
import pytest
from extensions.ext_redis import redis_client
pytestmark = pytest.mark.usefixtures("flask_app_with_containers")
def test_increment_preserves_counter_ttl_without_resetting_it() -> None:
key = f"counter-test:{uuid4()}"
redis_client.set(key, 0, ex=60)
try:
for expected in range(1, 7):
assert redis_client.incr_if_exists(key) == expected
assert redis_client.get(key) == str(expected).encode()
assert 0 < redis_client.ttl(key) <= 60
finally:
redis_client.delete(key)
assert redis_client.incr_if_exists(key) is None
assert not redis_client.exists(key)
def test_expired_counter_is_not_recreated() -> None:
key = f"counter-test:{uuid4()}"
redis_client.set(key, 0, ex=60)
redis_client.expire(key, 0)
assert redis_client.incr_if_exists(key) is None
assert not redis_client.exists(key)
def test_concurrent_increments_do_not_lose_updates() -> None:
key = f"counter-test:{uuid4()}"
redis_client.set(key, 0, ex=60)
barrier = Barrier(12)
def increment(_: int) -> int | None:
barrier.wait()
return redis_client.incr_if_exists(key)
try:
with ThreadPoolExecutor(max_workers=12) as executor:
counts = list(executor.map(increment, range(12)))
assert sorted(count for count in counts if count is not None) == list(range(1, 13))
assert redis_client.get(key) == b"12"
assert 0 < redis_client.ttl(key) <= 60
finally:
redis_client.delete(key)
@@ -0,0 +1,192 @@
"""
Integration tests for Account and Tenant model methods that interact with the database.
Migrated from unit_tests/models/test_account_models.py, replacing
@patch("models.account.db") mock patches with real PostgreSQL operations.
Also absorbs unit_tests/models/test_account.py role helper coverage.
Covers:
- Account.set_current_tenant_with_session (sets _current_tenant and role from TenantAccountJoin)
- Account.set_tenant_id_with_session (resolves tenant + role from real join row)
- Tenant.get_accounts (returns accounts linked via TenantAccountJoin)
"""
from collections.abc import Generator
from typing import cast
from uuid import uuid4
import pytest
from sqlalchemy import delete
from sqlalchemy.orm import Session
from models.account import Account, Tenant, TenantAccountJoin, TenantAccountRole
TrackedRow = Account | Tenant | TenantAccountJoin
def _cleanup_tracked_rows(db_session: Session, tracked: list[TrackedRow]) -> None:
"""Delete rows tracked during the test so committed state does not leak into the DB.
Rolls back any pending (uncommitted) session state first, then issues DELETE
statements by primary key for each tracked entity (in reverse creation order)
and commits. This cleans up rows created via either flush() or commit().
"""
db_session.rollback()
for entity in reversed(tracked):
db_session.execute(delete(type(entity)).where(type(entity).id == entity.id))
db_session.commit()
def _build_tenant() -> Tenant:
return Tenant(name=f"Tenant {uuid4()}")
def _build_account(email_prefix: str = "account") -> Account:
return Account(
name=f"Account {uuid4()}",
email=f"{email_prefix}_{uuid4()}@example.com",
password="hashed-password",
password_salt="salt",
interface_language="en-US",
timezone="UTC",
)
class _DBTrackingTestBase:
"""Base class providing a tracker list and shared row factories for account/tenant tests."""
_tracked: list[TrackedRow]
@pytest.fixture(autouse=True)
def _setup_cleanup(self, db_session_with_containers: Session) -> Generator[None]:
self._tracked = []
yield
_cleanup_tracked_rows(db_session_with_containers, self._tracked)
def _create_tenant(self, db_session: Session) -> Tenant:
tenant = _build_tenant()
db_session.add(tenant)
db_session.flush()
self._tracked.append(tenant)
return tenant
def _create_account(self, db_session: Session, email_prefix: str = "account") -> Account:
account = _build_account(email_prefix)
db_session.add(account)
db_session.flush()
self._tracked.append(account)
return account
def _create_join(
self, db_session: Session, tenant_id: str, account_id: str, role: TenantAccountRole, current: bool = True
) -> TenantAccountJoin:
join = TenantAccountJoin(tenant_id=tenant_id, account_id=account_id, role=role, current=current)
db_session.add(join)
db_session.flush()
self._tracked.append(join)
return join
class TestTenantAccountRole:
"""Tests for TenantAccountRole helper methods."""
def test_account_is_privileged_role(self) -> None:
assert TenantAccountRole.ADMIN == "admin"
assert TenantAccountRole.OWNER == "owner"
assert TenantAccountRole.EDITOR == "editor"
assert TenantAccountRole.NORMAL == "normal"
assert TenantAccountRole.is_privileged_role(TenantAccountRole.ADMIN)
assert TenantAccountRole.is_privileged_role(TenantAccountRole.OWNER)
assert not TenantAccountRole.is_privileged_role(TenantAccountRole.NORMAL)
assert not TenantAccountRole.is_privileged_role(TenantAccountRole.EDITOR)
assert not TenantAccountRole.is_privileged_role(cast(TenantAccountRole, ""))
class TestAccountSetCurrentTenant(_DBTrackingTestBase):
"""Integration tests for Account.current_tenant and set_current_tenant_with_session."""
def test_current_tenant_property_returns_cached_tenant(self, db_session_with_containers: Session) -> None:
"""current_tenant getter returns the in-memory _current_tenant without DB access."""
account = self._create_account(db_session_with_containers)
tenant = self._create_tenant(db_session_with_containers)
account._current_tenant = tenant
assert account.current_tenant is tenant
def test_set_current_tenant_with_session_sets_tenant_and_role_when_join_exists(
self, db_session_with_containers: Session
) -> None:
"""set_current_tenant_with_session loads the join row and assigns role when relationship exists."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
self._create_join(db_session_with_containers, tenant.id, account.id, TenantAccountRole.OWNER)
db_session_with_containers.commit()
account.set_current_tenant_with_session(tenant, session=db_session_with_containers)
assert account._current_tenant is not None
assert account._current_tenant.id == tenant.id
assert account.role == TenantAccountRole.OWNER
def test_set_current_tenant_with_session_sets_none_when_no_join_exists(
self, db_session_with_containers: Session
) -> None:
"""set_current_tenant_with_session results in _current_tenant=None when no join row exists."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
db_session_with_containers.commit()
account.set_current_tenant_with_session(tenant, session=db_session_with_containers)
assert account._current_tenant is None
class TestAccountSetTenantId(_DBTrackingTestBase):
"""Integration tests for Account.set_tenant_id_with_session method."""
def test_set_tenant_id_with_session_sets_tenant_and_role_when_relationship_exists(
self, db_session_with_containers: Session
) -> None:
"""set_tenant_id_with_session loads the tenant and assigns role when a join row exists."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
self._create_join(db_session_with_containers, tenant.id, account.id, TenantAccountRole.ADMIN)
db_session_with_containers.commit()
account.set_tenant_id_with_session(tenant.id, session=db_session_with_containers)
assert account._current_tenant is not None
assert account._current_tenant.id == tenant.id
assert account.role == TenantAccountRole.ADMIN
def test_set_tenant_id_with_session_does_not_set_tenant_when_no_relationship_exists(
self, db_session_with_containers: Session
) -> None:
"""set_tenant_id_with_session does nothing when no join row matches the tenant."""
tenant = self._create_tenant(db_session_with_containers)
account = self._create_account(db_session_with_containers)
db_session_with_containers.commit()
account.set_tenant_id_with_session(tenant.id, session=db_session_with_containers)
assert account._current_tenant is None
class TestTenantGetAccounts(_DBTrackingTestBase):
"""Integration tests for Tenant.get_accounts method."""
def test_get_accounts_returns_linked_accounts(self, db_session_with_containers: Session) -> None:
"""get_accounts returns all accounts linked to the tenant via TenantAccountJoin."""
tenant = self._create_tenant(db_session_with_containers)
account1 = self._create_account(db_session_with_containers, email_prefix="tenant_member")
account2 = self._create_account(db_session_with_containers, email_prefix="tenant_member")
self._create_join(db_session_with_containers, tenant.id, account1.id, TenantAccountRole.OWNER, current=False)
self._create_join(db_session_with_containers, tenant.id, account2.id, TenantAccountRole.NORMAL, current=False)
accounts = tenant.get_accounts(session=db_session_with_containers)
assert len(accounts) == 2
account_ids = {a.id for a in accounts}
assert account1.id in account_ids
assert account2.id in account_ids
@@ -0,0 +1,32 @@
"""
Integration tests for AppModelConfig using testcontainers.
These tests validate database-backed model behavior without mocking SQLAlchemy queries.
"""
from uuid import uuid4
from sqlalchemy.orm import Session
from models.model import AppModelConfig, load_annotation_reply_config
class TestAppModelConfig:
"""Integration tests for AppModelConfig."""
def test_load_annotation_reply_config_disabled_without_setting(self, db_session_with_containers: Session) -> None:
"""Return disabled annotation reply config when no AppAnnotationSetting exists."""
# Arrange
config = AppModelConfig(app_id=str(uuid4()))
db_session_with_containers.add(config)
db_session_with_containers.commit()
# Act
result = load_annotation_reply_config(db_session_with_containers, config.app_id)
# Assert
assert result == {"enabled": False}
# Cleanup
db_session_with_containers.delete(config)
db_session_with_containers.commit()
@@ -0,0 +1,149 @@
"""
Integration tests for Conversation.inputs and Message.inputs tenant resolution.
Migrated from unit_tests/models/test_model.py, replacing db.session.scalar monkeypatching
with a real App in PostgreSQL so the _resolve_app_tenant_id lookup executes against the DB.
"""
from collections.abc import Generator
from unittest.mock import patch
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from core.workflow.file_reference import build_file_reference
from graphon.file import FILE_MODEL_IDENTITY, FileTransferMethod
from models.model import App, AppMode, Conversation, Message
def _build_local_file_mapping(record_id: str, *, tenant_id: str | None = None) -> dict:
mapping: dict = {
"dify_model_identity": FILE_MODEL_IDENTITY,
"transfer_method": FileTransferMethod.LOCAL_FILE,
"reference": build_file_reference(record_id=record_id),
"type": "document",
"filename": "example.txt",
"extension": ".txt",
"mime_type": "text/plain",
"size": 1,
}
if tenant_id is not None:
mapping["tenant_id"] = tenant_id
return mapping
class TestConversationMessageInputsTenantResolution:
"""Integration tests for Conversation/Message.inputs tenant resolution via real DB lookup."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def _create_app(self, db_session: Session) -> App:
tenant_id = str(uuid4())
app = App(
tenant_id=tenant_id,
name=f"App {uuid4()}",
mode=AppMode.CHAT,
enable_site=False,
enable_api=True,
is_demo=False,
is_public=False,
is_universal=False,
created_by=str(uuid4()),
updated_by=str(uuid4()),
)
db_session.add(app)
db_session.flush()
return app
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
def test_inputs_resolves_tenant_via_db_for_local_file(
self,
db_session_with_containers: Session,
owner_cls: type,
) -> None:
"""Inputs resolves tenant_id from real App row when file mapping has no tenant_id."""
app = self._create_app(db_session_with_containers)
build_calls: list[tuple[dict, str]] = []
def fake_build_from_mapping(
*, mapping, tenant_id, config=None, strict_type_validation=False, access_controller
):
build_calls.append((dict(mapping), tenant_id))
return {"tenant_id": tenant_id, "upload_file_id": mapping.get("upload_file_id")}
with patch("factories.file_factory.build_from_mapping", fake_build_from_mapping):
owner = owner_cls(app_id=app.id)
owner.inputs = {"file": _build_local_file_mapping("upload-1")}
restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
# The tenant_id should come from the real App row in the DB
assert restored_inputs["file"] == {"tenant_id": app.tenant_id, "upload_file_id": "upload-1"}
assert len(build_calls) == 1
assert build_calls[0][1] == app.tenant_id
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
def test_inputs_uses_serialized_tenant_id_skipping_db_lookup(
self,
db_session_with_containers: Session,
owner_cls: type,
) -> None:
"""Inputs uses tenant_id from the file mapping payload without hitting the DB."""
app = self._create_app(db_session_with_containers)
payload_tenant_id = "tenant-from-payload"
build_calls: list[tuple[dict, str]] = []
def fake_build_from_mapping(
*, mapping, tenant_id, config=None, strict_type_validation=False, access_controller
):
build_calls.append((dict(mapping), tenant_id))
return {"tenant_id": tenant_id, "upload_file_id": mapping.get("upload_file_id")}
with patch("factories.file_factory.build_from_mapping", fake_build_from_mapping):
owner = owner_cls(app_id=app.id)
owner.inputs = {"file": _build_local_file_mapping("upload-1", tenant_id=payload_tenant_id)}
restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
assert restored_inputs["file"] == {"tenant_id": payload_tenant_id, "upload_file_id": "upload-1"}
assert len(build_calls) == 1
assert build_calls[0][1] == payload_tenant_id
@pytest.mark.parametrize("owner_cls", [Conversation, Message])
def test_inputs_resolves_tenant_for_file_list(
self,
db_session_with_containers: Session,
owner_cls: type,
) -> None:
"""Inputs resolves tenant_id for a list of file mappings."""
app = self._create_app(db_session_with_containers)
build_calls: list[tuple[dict, str]] = []
def fake_build_from_mapping(
*, mapping, tenant_id, config=None, strict_type_validation=False, access_controller
):
build_calls.append((dict(mapping), tenant_id))
return {"tenant_id": tenant_id, "upload_file_id": mapping.get("upload_file_id")}
with patch("factories.file_factory.build_from_mapping", fake_build_from_mapping):
owner = owner_cls(app_id=app.id)
owner.inputs = {
"files": [
_build_local_file_mapping("upload-1"),
_build_local_file_mapping("upload-2"),
]
}
restored_inputs = owner.inputs_with_session(session=db_session_with_containers)
assert len(build_calls) == 2
assert all(call[1] == app.tenant_id for call in build_calls)
assert restored_inputs["files"] == [
{"tenant_id": app.tenant_id, "upload_file_id": "upload-1"},
{"tenant_id": app.tenant_id, "upload_file_id": "upload-2"},
]
@@ -0,0 +1,315 @@
"""
Integration tests for Conversation.status_count_with_session and Site.generate_code.
Migrated from unit_tests/models/test_app_models.py TestConversationStatusCount and
test_site_generate_code, replacing db.session.scalars mocks with real PostgreSQL queries.
"""
from collections.abc import Generator
from decimal import Decimal
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from graphon.enums import WorkflowExecutionStatus
from models.enums import ConversationFromSource, ConversationStatus, CreatorUserRole, CustomizeTokenStrategy, InvokeFrom
from models.model import App, AppMode, Conversation, Message, Site
from models.workflow import Workflow, WorkflowRun, WorkflowRunTriggeredFrom, WorkflowType
class TestConversationStatusCount:
"""Integration tests for Conversation.status_count_with_session."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def _create_app(self, db_session: Session, tenant_id: str, created_by: str) -> App:
app = App(
tenant_id=tenant_id,
name=f"App {uuid4()}",
mode=AppMode.ADVANCED_CHAT,
enable_site=False,
enable_api=True,
is_demo=False,
is_public=False,
is_universal=False,
created_by=created_by,
updated_by=created_by,
)
db_session.add(app)
db_session.flush()
return app
def _create_conversation(self, db_session: Session, app: App) -> Conversation:
conversation = Conversation(
app_id=app.id,
mode=app.mode,
name=f"Conversation {uuid4()}",
summary="",
_inputs={},
introduction="",
system_instruction="",
system_instruction_tokens=0,
status=ConversationStatus.NORMAL,
invoke_from=InvokeFrom.WEB_APP,
from_source=ConversationFromSource.API,
dialogue_count=0,
is_deleted=False,
)
conversation.inputs = {}
db_session.add(conversation)
db_session.flush()
return conversation
def _create_workflow(self, db_session: Session, app: App, created_by: str) -> Workflow:
workflow = Workflow(
tenant_id=app.tenant_id,
app_id=app.id,
type=WorkflowType.CHAT,
version="draft",
graph="{}",
created_by=created_by,
)
workflow._features = "{}"
db_session.add(workflow)
db_session.flush()
return workflow
def _create_workflow_run(
self, db_session: Session, app: App, workflow: Workflow, status: WorkflowExecutionStatus, created_by: str
) -> WorkflowRun:
run = WorkflowRun(
tenant_id=app.tenant_id,
app_id=app.id,
workflow_id=workflow.id,
type=WorkflowType.CHAT,
triggered_from=WorkflowRunTriggeredFrom.APP_RUN,
version="draft",
status=status,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=created_by,
)
db_session.add(run)
db_session.flush()
return run
def _create_message(
self, db_session: Session, app: App, conversation: Conversation, workflow_run_id: str | None = None
) -> Message:
message = Message(
app_id=app.id,
conversation_id=conversation.id,
_inputs={},
query="Test query",
message={"role": "user", "content": "Test query"},
answer="Test answer",
model_provider="openai",
model_id="gpt-4",
message_tokens=10,
message_unit_price=Decimal(0),
answer_tokens=10,
answer_unit_price=Decimal(0),
total_price=Decimal(0),
currency="USD",
from_source=ConversationFromSource.API,
invoke_from=InvokeFrom.WEB_APP,
workflow_run_id=workflow_run_id,
)
db_session.add(message)
db_session.flush()
return message
def test_status_count_returns_none_when_no_messages(self, db_session_with_containers: Session) -> None:
"""status_count returns None when conversation has no messages with workflow_run_id."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is None
def test_status_count_returns_none_when_messages_have_no_workflow_run_id(
self, db_session_with_containers: Session
) -> None:
"""status_count returns None when messages exist but none have workflow_run_id."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=None)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is None
def test_status_count_counts_succeeded_workflow_run(self, db_session_with_containers: Session) -> None:
"""status_count correctly counts succeeded workflow runs."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
run = self._create_workflow_run(
db_session_with_containers, app, workflow, WorkflowExecutionStatus.SUCCEEDED, created_by
)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 1
assert result["failed"] == 0
assert result["partial_success"] == 0
assert result["paused"] == 0
def test_status_count_counts_failed_workflow_run(self, db_session_with_containers: Session) -> None:
"""status_count correctly counts failed workflow runs."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
run = self._create_workflow_run(
db_session_with_containers, app, workflow, WorkflowExecutionStatus.FAILED, created_by
)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 0
assert result["failed"] == 1
assert result["partial_success"] == 0
assert result["paused"] == 0
def test_status_count_counts_paused_workflow_run(self, db_session_with_containers: Session) -> None:
"""status_count correctly counts paused workflow runs."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
run = self._create_workflow_run(
db_session_with_containers, app, workflow, WorkflowExecutionStatus.PAUSED, created_by
)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 0
assert result["failed"] == 0
assert result["partial_success"] == 0
assert result["paused"] == 1
def test_status_count_multiple_statuses(self, db_session_with_containers: Session) -> None:
"""status_count counts multiple workflow runs with different statuses."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, app, created_by)
for status in [
WorkflowExecutionStatus.SUCCEEDED,
WorkflowExecutionStatus.FAILED,
WorkflowExecutionStatus.PARTIAL_SUCCEEDED,
WorkflowExecutionStatus.PAUSED,
]:
run = self._create_workflow_run(db_session_with_containers, app, workflow, status, created_by)
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
assert result is not None
assert result["success"] == 1
assert result["failed"] == 1
assert result["partial_success"] == 1
assert result["paused"] == 1
def test_status_count_filters_workflow_runs_by_app_id(self, db_session_with_containers: Session) -> None:
"""status_count excludes workflow runs belonging to a different app."""
tenant_id = str(uuid4())
created_by = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, created_by)
other_app = self._create_app(db_session_with_containers, tenant_id, created_by)
conversation = self._create_conversation(db_session_with_containers, app)
workflow = self._create_workflow(db_session_with_containers, other_app, created_by)
# Workflow run belongs to other_app, not app
other_run = self._create_workflow_run(
db_session_with_containers, other_app, workflow, WorkflowExecutionStatus.SUCCEEDED, created_by
)
# Message references that run but is in a conversation under app
self._create_message(db_session_with_containers, app, conversation, workflow_run_id=other_run.id)
result = conversation.status_count_with_session(session=db_session_with_containers)
# The run should be excluded because app_id filter doesn't match
assert result is not None
assert result["success"] == 0
class TestSiteGenerateCode:
"""Integration tests for Site.generate_code static method."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def test_generate_code_returns_string_of_correct_length(self, db_session_with_containers: Session) -> None:
"""Site.generate_code returns a code string of the requested length."""
code = Site.generate_code(8, session=db_session_with_containers)
assert isinstance(code, str)
assert len(code) == 8
def test_generate_code_avoids_duplicates(self, db_session_with_containers: Session) -> None:
"""Site.generate_code returns a code not already in use."""
tenant_id = str(uuid4())
app = App(
tenant_id=tenant_id,
name="Test App",
mode=AppMode.CHAT,
enable_site=True,
enable_api=False,
is_demo=False,
is_public=False,
is_universal=False,
created_by=str(uuid4()),
updated_by=str(uuid4()),
)
db_session_with_containers.add(app)
db_session_with_containers.flush()
site = Site(
app_id=app.id,
title="Test Site",
default_language="en-US",
customize_token_strategy=CustomizeTokenStrategy.NOT_ALLOW,
)
# Set an explicit code so generate_code must avoid it
site.code = "AAAAAAAA"
db_session_with_containers.add(site)
db_session_with_containers.flush()
code = Site.generate_code(8, session=db_session_with_containers)
assert isinstance(code, str)
assert len(code) == 8
assert code != site.code
@@ -0,0 +1,502 @@
"""
Integration tests for Dataset and Document model properties using testcontainers.
These tests validate database-backed model properties (total_documents, word_count, etc.)
without mocking SQLAlchemy queries, ensuring real query behavior against PostgreSQL.
"""
from collections.abc import Generator
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from models.dataset import Dataset, Document, DocumentSegment
from models.enums import DataSourceType, DocumentCreatedFrom, IndexingStatus, SegmentStatus
from repositories.knowledge.dataset_read_repository import (
get_dataset_available_document_count,
get_dataset_available_segment_count,
get_dataset_document_count,
get_dataset_word_count,
get_document_hit_count,
get_document_segment_count,
get_next_segment,
get_previous_segment,
get_segment_dataset,
get_segment_document,
)
class TestDatasetDocumentProperties:
"""Integration tests for Dataset and Document model properties."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def test_dataset_with_documents_relationship(self, db_session_with_containers: Session) -> None:
"""Test dataset can track its documents."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
for i in range(3):
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=i + 1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name=f"doc_{i}.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
assert get_dataset_document_count(dataset, session=db_session_with_containers) == 3
def test_dataset_available_documents_count(self, db_session_with_containers: Session) -> None:
"""Test dataset can count available documents."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc_available = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="available.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
indexing_status=IndexingStatus.COMPLETED,
enabled=True,
archived=False,
)
doc_pending = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=2,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="pending.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
indexing_status=IndexingStatus.WAITING,
enabled=True,
archived=False,
)
doc_disabled = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=3,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="disabled.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
indexing_status=IndexingStatus.COMPLETED,
enabled=False,
archived=False,
)
db_session_with_containers.add_all([doc_available, doc_pending, doc_disabled])
db_session_with_containers.flush()
assert get_dataset_available_document_count(dataset, session=db_session_with_containers) == 1
def test_dataset_word_count_aggregation(self, db_session_with_containers: Session) -> None:
"""Test dataset can aggregate word count from documents."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
for i, wc in enumerate([2000, 3000]):
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=i + 1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name=f"doc_{i}.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
word_count=wc,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
assert get_dataset_word_count(dataset, session=db_session_with_containers) == 5000
def test_dataset_available_segment_count(self, db_session_with_containers: Session) -> None:
"""Test Dataset.available_segment_count counts completed and enabled segments."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="doc.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
for i in range(2):
seg = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=i + 1,
content=f"segment {i}",
word_count=100,
tokens=50,
status=SegmentStatus.COMPLETED,
enabled=True,
created_by=created_by,
)
db_session_with_containers.add(seg)
seg_waiting = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=3,
content="waiting segment",
word_count=100,
tokens=50,
status=SegmentStatus.WAITING,
enabled=True,
created_by=created_by,
)
db_session_with_containers.add(seg_waiting)
db_session_with_containers.flush()
assert get_dataset_available_segment_count(dataset, session=db_session_with_containers) == 2
def test_document_segment_count_property(self, db_session_with_containers: Session) -> None:
"""Test document can count its segments."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="doc.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
for i in range(3):
seg = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=i + 1,
content=f"segment {i}",
word_count=100,
tokens=50,
created_by=created_by,
)
db_session_with_containers.add(seg)
db_session_with_containers.flush()
assert get_document_segment_count(doc, session=db_session_with_containers) == 3
def test_document_hit_count_aggregation(self, db_session_with_containers: Session) -> None:
"""Test document can aggregate hit count from segments."""
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id, name="Test Dataset", data_source_type=DataSourceType.UPLOAD_FILE, created_by=created_by
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
doc = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="doc.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(doc)
db_session_with_containers.flush()
for i, hits in enumerate([10, 15]):
seg = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=doc.id,
position=i + 1,
content=f"segment {i}",
word_count=100,
tokens=50,
hit_count=hits,
created_by=created_by,
)
db_session_with_containers.add(seg)
db_session_with_containers.flush()
assert get_document_hit_count(doc, session=db_session_with_containers) == 25
class TestDocumentSegmentNavigationProperties:
"""Integration tests for DocumentSegment navigation properties."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def test_document_segment_dataset_property(self, db_session_with_containers: Session) -> None:
"""Test segment can access its parent dataset."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Test",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add(segment)
db_session_with_containers.flush()
# Act
related_dataset = get_segment_dataset(segment, session=db_session_with_containers)
# Assert
assert related_dataset is not None
assert related_dataset.id == dataset.id
def test_document_segment_document_property(self, db_session_with_containers: Session) -> None:
"""Test segment can access its parent document."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Test",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add(segment)
db_session_with_containers.flush()
# Act
related_document = get_segment_document(segment, session=db_session_with_containers)
# Assert
assert related_document is not None
assert related_document.id == document.id
def test_document_segment_previous_segment(self, db_session_with_containers: Session) -> None:
"""Test segment can access previous segment."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
previous_segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Previous",
word_count=1,
tokens=2,
created_by=created_by,
)
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=2,
content="Current",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add_all([previous_segment, segment])
db_session_with_containers.flush()
# Act
prev_seg = get_previous_segment(segment, session=db_session_with_containers)
# Assert
assert prev_seg is not None
assert prev_seg.position == 1
def test_document_segment_next_segment(self, db_session_with_containers: Session) -> None:
"""Test segment can access next segment."""
# Arrange
tenant_id = str(uuid4())
created_by = str(uuid4())
dataset = Dataset(
tenant_id=tenant_id,
name="Test Dataset",
data_source_type=DataSourceType.UPLOAD_FILE,
created_by=created_by,
)
db_session_with_containers.add(dataset)
db_session_with_containers.flush()
document = Document(
tenant_id=tenant_id,
dataset_id=dataset.id,
position=1,
data_source_type=DataSourceType.UPLOAD_FILE,
batch="batch_001",
name="test.pdf",
created_from=DocumentCreatedFrom.WEB,
created_by=created_by,
)
db_session_with_containers.add(document)
db_session_with_containers.flush()
segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=1,
content="Current",
word_count=1,
tokens=2,
created_by=created_by,
)
next_segment = DocumentSegment(
tenant_id=tenant_id,
dataset_id=dataset.id,
document_id=document.id,
position=2,
content="Next",
word_count=1,
tokens=2,
created_by=created_by,
)
db_session_with_containers.add_all([segment, next_segment])
db_session_with_containers.flush()
# Act
next_seg = get_next_segment(segment, session=db_session_with_containers)
# Assert
assert next_seg is not None
assert next_seg.position == 2
@@ -0,0 +1,116 @@
from collections.abc import Iterator
from typing import Annotated, Literal
import pytest
import sqlalchemy as sa
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter
from sqlalchemy import Engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from models.types import FrozenPydanticModelColumn
class _ConcretePayload(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True, validate_default=True)
name: str
count: int
class _EmailDestination(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True, validate_default=True)
channel: Literal["email"] = "email"
address: str
class _SlackDestination(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, strict=True, validate_default=True)
channel: Literal["slack"] = "slack"
channel_id: str
type _Destination = Annotated[_EmailDestination | _SlackDestination, Field(discriminator="channel")]
class _Base(DeclarativeBase):
pass
class _PydanticJSONRecord(_Base):
__tablename__ = "integration_pydantic_json_records"
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True, autoincrement=True)
concrete: Mapped[_ConcretePayload] = mapped_column(
FrozenPydanticModelColumn(
_ConcretePayload,
),
nullable=False,
)
destination: Mapped[_Destination] = mapped_column(
FrozenPydanticModelColumn(
TypeAdapter(_Destination),
model_types=(_EmailDestination, _SlackDestination),
),
nullable=False,
)
@pytest.fixture
def pydantic_json_engine(db_session_with_containers: Session) -> Engine:
bind = db_session_with_containers.get_bind()
assert isinstance(bind, Engine)
return bind
@pytest.fixture(autouse=True)
def _pydantic_json_schema(pydantic_json_engine: Engine) -> Iterator[None]:
_Base.metadata.create_all(pydantic_json_engine)
try:
yield
finally:
_Base.metadata.drop_all(pydantic_json_engine)
def test_real_database_stores_single_encoded_json_and_round_trips_a_concrete_model(
pydantic_json_engine: Engine,
) -> None:
with Session(pydantic_json_engine) as session:
record = _PydanticJSONRecord(
concrete=_ConcretePayload(name="container", count=3),
destination=_EmailDestination(address="reviewer@example.com"),
)
session.add(record)
session.commit()
record_id = record.id
with Session(pydantic_json_engine) as session:
stored_json = session.execute(
sa.text("SELECT concrete FROM integration_pydantic_json_records WHERE id = :record_id"),
{"record_id": record_id},
).scalar_one()
restored = session.scalar(select(_PydanticJSONRecord).where(_PydanticJSONRecord.id == record_id))
assert stored_json == '{"name":"container","count":3}'
assert restored is not None
assert restored.concrete == _ConcretePayload(name="container", count=3)
assert isinstance(restored.concrete, _ConcretePayload)
def test_real_database_restores_the_discriminated_union_subtype(pydantic_json_engine: Engine) -> None:
with Session(pydantic_json_engine) as session:
record = _PydanticJSONRecord(
concrete=_ConcretePayload(name="container", count=4),
destination=_SlackDestination(channel_id="C123"),
)
session.add(record)
session.commit()
record_id = record.id
with Session(pydantic_json_engine) as session:
restored = session.scalar(select(_PydanticJSONRecord).where(_PydanticJSONRecord.id == record_id))
assert restored is not None
assert restored.destination == _SlackDestination(channel_id="C123")
assert isinstance(restored.destination, _SlackDestination)
@@ -0,0 +1,230 @@
import re
from collections.abc import Callable, Iterable
from enum import StrEnum
from typing import Any, NamedTuple
import pytest
import sqlalchemy as sa
from sqlalchemy import exc as sa_exc
from sqlalchemy import insert, select
from sqlalchemy.engine import Connection, Engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
from sqlalchemy.sql.sqltypes import VARCHAR
from graphon.model_runtime.entities.model_entities import ModelType
from models.types import EnumText
_USER_TABLE = "enum_text_users"
_COLUMN_TABLE = "enum_text_column_test"
_user_type_admin = "admin"
_user_type_normal = "normal"
class _Base(DeclarativeBase):
pass
class _UserType(StrEnum):
admin = _user_type_admin
normal = _user_type_normal
class _EnumWithLongValue(StrEnum):
unknown = "unknown"
a_really_long_enum_values = "a_really_long_enum_values"
class _User(_Base):
__tablename__ = _USER_TABLE
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
name: Mapped[str] = mapped_column(sa.String(length=255), nullable=False)
user_type: Mapped[_UserType] = mapped_column(
EnumText(enum_class=_UserType), nullable=False, default=_UserType.normal
)
user_type_nullable: Mapped[_UserType | None] = mapped_column(EnumText(enum_class=_UserType), nullable=True)
class _ColumnTest(_Base):
__tablename__ = _COLUMN_TABLE
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
user_type: Mapped[_UserType] = mapped_column(
EnumText(enum_class=_UserType), nullable=False, default=_UserType.normal
)
explicit_length: Mapped[_UserType | None] = mapped_column(
EnumText(_UserType, length=50), nullable=True, default=_UserType.normal
)
long_value: Mapped[_EnumWithLongValue] = mapped_column(EnumText(enum_class=_EnumWithLongValue), nullable=False)
class _LegacyModelTypeRecord(_Base):
__tablename__ = "enum_text_legacy_model_type_test"
id: Mapped[int] = mapped_column(sa.Integer, primary_key=True)
model_type: Mapped[ModelType] = mapped_column(EnumText(enum_class=ModelType), nullable=False)
def _first[T](it: Iterable[T]) -> T:
ls = list(it)
if not ls:
raise ValueError("List is empty")
return ls[0]
def _resolve_engine(bind: Engine | Connection) -> Engine:
if isinstance(bind, Engine):
return bind
return bind.engine
@pytest.fixture
def engine_with_containers(db_session_with_containers: Session) -> Engine:
return _resolve_engine(db_session_with_containers.get_bind())
@pytest.fixture(autouse=True)
def _enum_text_schema(engine_with_containers: Engine) -> Iterable[None]:
_Base.metadata.create_all(engine_with_containers)
try:
yield
finally:
_Base.metadata.drop_all(engine_with_containers)
class TestEnumText:
def test_column_impl(self, engine_with_containers: Engine):
inspector = sa.inspect(engine_with_containers)
columns = inspector.get_columns(_COLUMN_TABLE)
user_type_column = _first(c for c in columns if c["name"] == "user_type")
sql_type = user_type_column["type"]
assert isinstance(user_type_column["type"], VARCHAR)
assert sql_type.length == 20
assert user_type_column["nullable"] is False
explicit_length_column = _first(c for c in columns if c["name"] == "explicit_length")
sql_type = explicit_length_column["type"]
assert isinstance(sql_type, VARCHAR)
assert sql_type.length == 50
assert explicit_length_column["nullable"] is True
long_value_column = _first(c for c in columns if c["name"] == "long_value")
sql_type = long_value_column["type"]
assert isinstance(sql_type, VARCHAR)
assert sql_type.length == len(_EnumWithLongValue.a_really_long_enum_values)
def test_insert_and_select(self, engine_with_containers: Engine):
with Session(engine_with_containers) as session:
admin_user = _User(
name="admin",
user_type=_UserType.admin,
user_type_nullable=None,
)
session.add(admin_user)
session.flush()
admin_user_id = admin_user.id
normal_user = _User(
name="normal",
user_type=_UserType.normal.value,
user_type_nullable=_UserType.normal.value,
)
session.add(normal_user)
session.flush()
normal_user_id = normal_user.id
session.commit()
with Session(engine_with_containers) as session:
user = session.scalar(select(_User).where(_User.id == admin_user_id).limit(1))
assert user.user_type == _UserType.admin
assert user.user_type_nullable is None
with Session(engine_with_containers) as session:
user = session.scalar(select(_User).where(_User.id == normal_user_id).limit(1))
assert user.user_type == _UserType.normal
assert user.user_type_nullable == _UserType.normal
def test_insert_invalid_values(self, engine_with_containers: Engine):
def _session_insert_with_value(sess: Session, user_type: Any):
user = _User(name="test_user", user_type=user_type)
sess.add(user)
sess.flush()
def _insert_with_user(sess: Session, user_type: Any):
stmt = insert(_User).values(
{
"name": "test_user",
"user_type": user_type,
}
)
sess.execute(stmt)
class TestCase(NamedTuple):
name: str
action: Callable[[Session], None]
exc_type: type[Exception]
cases = [
TestCase(
name="session insert with invalid value",
action=lambda s: _session_insert_with_value(s, "invalid"),
exc_type=ValueError,
),
TestCase(
name="session insert with invalid type",
action=lambda s: _session_insert_with_value(s, 1),
exc_type=ValueError,
),
TestCase(
name="insert with invalid value",
action=lambda s: _insert_with_user(s, "invalid"),
exc_type=ValueError,
),
TestCase(
name="insert with invalid type",
action=lambda s: _insert_with_user(s, 1),
exc_type=ValueError,
),
]
for idx, c in enumerate(cases, 1):
with pytest.raises(sa_exc.StatementError) as exc:
with Session(engine_with_containers) as session:
c.action(session)
assert isinstance(exc.value.orig, c.exc_type), f"test case {idx} failed, name={c.name}"
def test_select_invalid_values(self, engine_with_containers: Engine):
insertion_sql = f"""
INSERT INTO {_USER_TABLE} (id, name, user_type) VALUES
(1, 'invalid_value', 'invalid');
"""
with Session(engine_with_containers) as session:
session.execute(sa.text(insertion_sql))
session.commit()
with pytest.raises(ValueError, match="'invalid' is not a valid _UserType") as exc:
with Session(engine_with_containers) as session:
_user = session.scalar(select(_User).where(_User.id == 1).limit(1))
assert str(exc.value) == "'invalid' is not a valid _UserType"
def test_select_rejects_legacy_model_type_values(self, engine_with_containers: Engine):
insertion_sql = """
INSERT INTO enum_text_legacy_model_type_test (id, model_type) VALUES
(1, 'text-generation'),
(2, 'embeddings'),
(3, 'reranking');
"""
with Session(engine_with_containers) as session:
session.execute(sa.text(insertion_sql))
session.commit()
for record_id, legacy_value in enumerate(("text-generation", "embeddings", "reranking"), 1):
with pytest.raises(ValueError, match=re.escape(f"'{legacy_value}' is not a valid ModelType")) as exc:
with Session(engine_with_containers) as session:
session.scalar(select(_LegacyModelTypeRecord).where(_LegacyModelTypeRecord.id == record_id))
assert str(exc.value) == f"'{legacy_value}' is not a valid ModelType"
@@ -0,0 +1,171 @@
"""
Integration tests for WorkflowNodeExecutionModel.created_by_account and .created_by_end_user.
Migrated from unit_tests/models/test_workflow_trigger_log.py, replacing
monkeypatch.setattr(db.session, "scalar", ...) with real Account/EndUser rows
persisted in PostgreSQL so the db.session.get() call executes against the DB.
"""
from collections.abc import Generator
from uuid import uuid4
import pytest
from sqlalchemy.orm import Session
from graphon.enums import WorkflowNodeExecutionStatus
from models.account import Account
from models.enums import CreatorUserRole, EndUserType
from models.model import App, AppMode, EndUser
from models.workflow import WorkflowNodeExecutionModel, WorkflowNodeExecutionTriggeredFrom
class TestWorkflowNodeExecutionModelCreatedBy:
"""Integration tests for WorkflowNodeExecutionModel creator lookup properties."""
@pytest.fixture(autouse=True)
def _auto_rollback(self, db_session_with_containers: Session) -> Generator[None]:
"""Automatically rollback session changes after each test."""
yield
db_session_with_containers.rollback()
def _create_account(self, db_session: Session) -> Account:
account = Account(
name="Test Account",
email=f"test_{uuid4()}@example.com",
password="hashed-password",
password_salt="salt",
interface_language="en-US",
timezone="UTC",
)
db_session.add(account)
db_session.flush()
return account
def _create_end_user(self, db_session: Session, tenant_id: str, app_id: str) -> EndUser:
end_user = EndUser(
tenant_id=tenant_id,
app_id=app_id,
type=EndUserType.SERVICE_API,
external_user_id=f"ext-{uuid4()}",
name="End User",
session_id=f"session-{uuid4()}",
)
end_user.is_anonymous = False
db_session.add(end_user)
db_session.flush()
return end_user
def _create_app(self, db_session: Session, tenant_id: str, created_by: str) -> App:
app = App(
tenant_id=tenant_id,
name=f"App {uuid4()}",
mode=AppMode.WORKFLOW,
enable_site=False,
enable_api=True,
is_demo=False,
is_public=False,
is_universal=False,
created_by=created_by,
updated_by=created_by,
)
db_session.add(app)
db_session.flush()
return app
def _make_execution(
self, tenant_id: str, app_id: str, created_by_role: CreatorUserRole, created_by: str
) -> WorkflowNodeExecutionModel:
return WorkflowNodeExecutionModel(
tenant_id=tenant_id,
app_id=app_id,
workflow_id=str(uuid4()),
triggered_from=WorkflowNodeExecutionTriggeredFrom.WORKFLOW_RUN,
workflow_run_id=None,
index=1,
predecessor_node_id=None,
node_execution_id=None,
node_id="n1",
node_type="start",
title="Start",
inputs=None,
process_data=None,
outputs=None,
status=WorkflowNodeExecutionStatus.SUCCEEDED,
error=None,
elapsed_time=0.0,
execution_metadata=None,
created_by_role=created_by_role,
created_by=created_by,
)
def test_created_by_account_returns_account_when_role_is_account(self, db_session_with_containers: Session) -> None:
"""created_by_account returns the Account row when role is ACCOUNT."""
account = self._create_account(db_session_with_containers)
app = self._create_app(db_session_with_containers, str(uuid4()), account.id)
execution = self._make_execution(
tenant_id=app.tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=account.id,
)
result = execution.created_by_account(session=db_session_with_containers)
assert result is not None
assert result.id == account.id
def test_created_by_account_returns_none_when_role_is_end_user(self, db_session_with_containers: Session) -> None:
"""created_by_account returns None when role is END_USER, even if an Account exists."""
account = self._create_account(db_session_with_containers)
app = self._create_app(db_session_with_containers, str(uuid4()), account.id)
execution = self._make_execution(
tenant_id=app.tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.END_USER,
created_by=account.id,
)
result = execution.created_by_account(session=db_session_with_containers)
assert result is None
def test_created_by_end_user_returns_end_user_when_role_is_end_user(
self, db_session_with_containers: Session
) -> None:
"""created_by_end_user returns the EndUser row when role is END_USER."""
account = self._create_account(db_session_with_containers)
tenant_id = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, account.id)
end_user = self._create_end_user(db_session_with_containers, tenant_id, app.id)
execution = self._make_execution(
tenant_id=tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.END_USER,
created_by=end_user.id,
)
result = execution.created_by_end_user(session=db_session_with_containers)
assert result is not None
assert result.id == end_user.id
def test_created_by_end_user_returns_none_when_role_is_account(self, db_session_with_containers: Session) -> None:
"""created_by_end_user returns None when role is ACCOUNT, even if an EndUser exists."""
account = self._create_account(db_session_with_containers)
tenant_id = str(uuid4())
app = self._create_app(db_session_with_containers, tenant_id, account.id)
end_user = self._create_end_user(db_session_with_containers, tenant_id, app.id)
execution = self._make_execution(
tenant_id=tenant_id,
app_id=app.id,
created_by_role=CreatorUserRole.ACCOUNT,
created_by=end_user.id,
)
result = execution.created_by_end_user(session=db_session_with_containers)
assert result is None
@@ -0,0 +1,115 @@
preset = "strict"
project-includes = ["."]
search-path = ["../../.."]
python-platform = "linux"
python-version = "3.13.0"
infer-with-first-use = true
min-severity = "warn"
# Existing strict-mode debt. Remove a file when bringing it under strict checking.
project-excludes = [
"commands/test_legacy_model_type_migration.py",
"controllers/console/app/test_chat_conversation_status_count_api.py",
"controllers/console/app/test_workflow_draft_variable.py",
"controllers/console/workspace/test_workspace_wraps.py",
"controllers/openapi/test_account_sessions.py",
"controllers/openapi/test_workspaces.py",
"controllers/web/test_site.py",
"controllers/web/test_wraps.py",
"core/rag/pipeline/test_queue_integration.py",
"core/rag/retrieval/test_dataset_retrieval_integration.py",
"core/workflow/test_human_input_resume_node_execution.py",
"factories/test_storage_key_loader.py",
"helpers/execution_extra_content.py",
"libs/broadcast_channel/redis/test_channel.py",
"libs/broadcast_channel/redis/test_sharded_channel.py",
"libs/broadcast_channel/redis/test_streams_channel.py",
"models/test_conversation_message_inputs.py",
"models/test_types_enum_text.py",
"repositories/test_sqlalchemy_execution_extra_content_repository.py",
"repositories/test_sqlalchemy_workflow_node_execution_repository.py",
"services/auth/test_auth_integration.py",
"services/dataset_service_update_delete.py",
"services/document_service_status.py",
"services/test_advanced_prompt_template_service.py",
"services/test_agent_service.py",
"services/test_app_dsl_service.py",
"services/test_app_generate_service.py",
"services/test_app_service.py",
"services/test_attachment_service.py",
"services/test_audio_service_db.py",
"services/test_conversation_service.py",
"services/test_dataset_permission_service.py",
"services/test_dataset_service.py",
"services/test_dataset_service_batch_update_document_status.py",
"services/test_dataset_service_create_dataset.py",
"services/test_dataset_service_document.py",
"services/test_dataset_service_permissions.py",
"services/test_dataset_service_retrieval.py",
"services/test_delete_archived_workflow_run.py",
"services/test_document_service_rename_document.py",
"services/test_end_user_service.py",
"services/test_feature_service.py",
"services/test_file_service.py",
"services/test_human_input_delivery_test.py",
"services/test_message_export_service.py",
"services/test_message_service_execution_extra_content.py",
"services/test_messages_clean_service.py",
"services/test_model_load_balancing_service.py",
"services/test_model_provider_service.py",
"services/test_schedule_service.py",
"services/test_webapp_auth_service.py",
"services/test_webhook_service.py",
"services/test_webhook_service_relationships.py",
"services/test_workflow_app_service.py",
"services/test_workflow_draft_variable_service.py",
"services/test_workflow_run_service.py",
"services/test_workflow_service.py",
"services/tools/test_mcp_tools_manage_service.py",
"services/tools/test_tools_transform_service.py",
"services/tools/test_workflow_tools_manage_service.py",
"services/workflow/test_workflow_converter.py",
"services/workflow/test_workflow_deletion.py",
"services/workflow/test_workflow_node_execution_service_repository.py",
"tasks/test_add_document_to_index_task.py",
"tasks/test_batch_clean_document_task.py",
"tasks/test_batch_create_segment_to_index_task.py",
"tasks/test_clean_dataset_task.py",
"tasks/test_clean_notion_document_task.py",
"tasks/test_create_segment_to_index_task.py",
"tasks/test_dataset_indexing_task.py",
"tasks/test_deal_dataset_vector_index_task.py",
"tasks/test_delete_segment_from_index_task.py",
"tasks/test_disable_segment_from_index_task.py",
"tasks/test_disable_segments_from_index_task.py",
"tasks/test_document_indexing_sync_task.py",
"tasks/test_document_indexing_task.py",
"tasks/test_document_indexing_update_task.py",
"tasks/test_duplicate_document_indexing_task.py",
"tasks/test_enable_segments_to_index_task.py",
"tasks/test_mail_account_deletion_task.py",
"tasks/test_mail_change_mail_task.py",
"tasks/test_mail_email_code_login_task.py",
"tasks/test_mail_human_input_delivery_task.py",
"tasks/test_mail_inner_task.py",
"tasks/test_mail_invite_member_task.py",
"tasks/test_mail_owner_transfer_task.py",
"tasks/test_mail_register_task.py",
"tasks/test_rag_pipeline_run_tasks.py",
"tasks/test_remove_app_and_related_data_task.py",
"test_workflow_pause_integration.py",
"trigger/conftest.py",
"trigger/test_trigger_e2e.py",
"workflow/nodes/code_executor/test_code_javascript.py",
"workflow/nodes/code_executor/test_code_jinja2.py",
"workflow/nodes/code_executor/test_code_python3.py",
"workflow/nodes/code_executor/test_utils.py",
]
[errors]
missing-override-decorator = "error"
redundant-cast = true
unannotated-return = true
unused-ignore = true
implicit-any-lambda = "info"
unnecessary-type-conversion = "info"
@@ -0,0 +1,160 @@
"""PostgreSQL concurrency contracts for Human Input Email configuration."""
from concurrent.futures import ThreadPoolExecutor
from dataclasses import replace
from threading import Barrier
from uuid import uuid4
from sqlalchemy.orm import Session, sessionmaker
from core.human_input_v2.shared import (
AccountId,
EmailProviderId,
NormalizedEmail,
TenantId,
)
from libs.datetime_utils import naive_utc_now
from models.account import Tenant
from repositories.human_input_v2.channel_credentials import ChannelEncryptedCredentials
from repositories.human_input_v2.email_channel import (
CreateEmailConfigurationResult,
CreateEmailConfigurationStatus,
DeleteEmailConfigurationResult,
DeleteEmailConfigurationStatus,
EmailChannelConfiguration,
UpdateEmailConfigurationResult,
UpdateEmailConfigurationStatus,
)
from repositories.human_input_v2.email_channel.repository import SQLAlchemyEmailChannelRepository
def _configuration(tenant_id: TenantId, *, configuration_id: str | None = None) -> EmailChannelConfiguration:
now = naive_utc_now()
return EmailChannelConfiguration(
EmailProviderId(configuration_id or str(uuid4())),
tenant_id,
NormalizedEmail("sender@example.com"),
"Sender",
ChannelEncryptedCredentials(ciphertext="ciphertext"),
AccountId(str(uuid4())),
now,
now,
)
def _sessions(db_session: Session) -> tuple[sessionmaker[Session], TenantId]:
tenant = Tenant(name="Email channel concurrency")
db_session.add(tenant)
db_session.commit()
tenant_id = TenantId(tenant.id)
maker = sessionmaker(bind=db_session.get_bind(), expire_on_commit=False)
return maker, tenant_id
def test_concurrent_first_creation_has_one_winner(db_session_with_containers: Session) -> None:
sessions, tenant_id = _sessions(db_session_with_containers)
barrier = Barrier(2)
def create(configuration: EmailChannelConfiguration) -> CreateEmailConfigurationResult:
barrier.wait()
with sessions.begin() as session:
return SQLAlchemyEmailChannelRepository(session).create(configuration)
with ThreadPoolExecutor(max_workers=2) as executor:
results = tuple(
executor.map(
create,
(_configuration(tenant_id), _configuration(tenant_id)),
)
)
assert sorted(result.status for result in results) == [
CreateEmailConfigurationStatus.CONFLICT,
CreateEmailConfigurationStatus.CREATED,
]
def test_concurrent_conditional_updates_have_one_winner(db_session_with_containers: Session) -> None:
sessions, tenant_id = _sessions(db_session_with_containers)
with sessions.begin() as session:
current = SQLAlchemyEmailChannelRepository(session).create(_configuration(tenant_id)).configuration
assert current is not None
barrier = Barrier(2)
def update(sender_name: str) -> UpdateEmailConfigurationResult:
barrier.wait()
with sessions.begin() as session:
return SQLAlchemyEmailChannelRepository(session).update(
replace(current, encrypted_credentials=ChannelEncryptedCredentials(ciphertext=sender_name)),
expected=current.snapshot,
now=naive_utc_now(),
)
with ThreadPoolExecutor(max_workers=2) as executor:
results = tuple(executor.map(update, ("First", "Second")))
assert sorted(result.status for result in results) == [
UpdateEmailConfigurationStatus.STALE,
UpdateEmailConfigurationStatus.UPDATED,
]
def test_update_delete_race_cannot_restore_deleted_row(db_session_with_containers: Session) -> None:
sessions, tenant_id = _sessions(db_session_with_containers)
with sessions.begin() as session:
current = SQLAlchemyEmailChannelRepository(session).create(_configuration(tenant_id)).configuration
assert current is not None
barrier = Barrier(2)
def update() -> UpdateEmailConfigurationResult:
barrier.wait()
with sessions.begin() as session:
return SQLAlchemyEmailChannelRepository(session).update(
replace(current, encrypted_credentials=ChannelEncryptedCredentials(ciphertext="replacement")),
expected=current.snapshot,
now=naive_utc_now(),
)
def delete() -> DeleteEmailConfigurationResult:
barrier.wait()
with sessions.begin() as session:
return SQLAlchemyEmailChannelRepository(session).delete(tenant_id, expected=current.snapshot)
with ThreadPoolExecutor(max_workers=2) as executor:
update_future = executor.submit(update)
delete_future = executor.submit(delete)
update_result = update_future.result()
delete_result = delete_future.result()
with sessions() as session:
persisted = SQLAlchemyEmailChannelRepository(session).load(tenant_id)
if update_result.status is UpdateEmailConfigurationStatus.UPDATED:
assert delete_result.status is DeleteEmailConfigurationStatus.STALE
assert update_result.configuration is not None
assert persisted == update_result.configuration
else:
assert update_result.status is UpdateEmailConfigurationStatus.STALE
assert delete_result.status is DeleteEmailConfigurationStatus.DELETED
assert persisted is None
def test_delete_recreate_rejects_previous_identity(db_session_with_containers: Session) -> None:
sessions, tenant_id = _sessions(db_session_with_containers)
with sessions.begin() as session:
deleted = SQLAlchemyEmailChannelRepository(session).create(_configuration(tenant_id)).configuration
assert deleted is not None
with sessions.begin() as session:
SQLAlchemyEmailChannelRepository(session).delete(tenant_id, expected=deleted.snapshot)
with sessions.begin() as session:
recreated = SQLAlchemyEmailChannelRepository(session).create(_configuration(tenant_id)).configuration
assert recreated is not None
with sessions.begin() as session:
repository = SQLAlchemyEmailChannelRepository(session)
stale = repository.update(
replace(deleted, encrypted_credentials=ChannelEncryptedCredentials(ciphertext="stale")),
expected=deleted.snapshot,
now=naive_utc_now(),
)
assert stale.status is UpdateEmailConfigurationStatus.STALE
assert repository.load(tenant_id) == recreated
@@ -0,0 +1,150 @@
"""Supported-database concurrency contracts for IM Channel creation."""
from __future__ import annotations
from collections.abc import Callable, Generator
from concurrent.futures import ThreadPoolExecutor
from threading import Barrier
from uuid import uuid4
import pytest
import sqlalchemy as sa
from sqlalchemy.engine import Engine
from sqlalchemy.orm import Session, sessionmaker
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.shared import AccountId, TenantId
from libs.datetime_utils import naive_utc_now
from models.human_input_v2 import HumanInputIMChannel
from repositories.human_input_v2.channel_credentials import ChannelEncryptedCredentials
from repositories.human_input_v2.im_channel_repository import (
IMChannel,
IMChannelAlreadyConfiguredError,
IMChannelId,
IMChannelStatus,
IMChannelWriter,
WebhookId,
)
from repositories.human_input_v2.sqlalchemy_im_channel_repository import (
DeploymentIMChannelWriter,
WorkspaceIMChannelWriter,
)
type _WriterFactory = Callable[[Session], IMChannelWriter]
@pytest.fixture(params=("postgresql", "mysql"), scope="session")
def im_channel_engine(request: pytest.FixtureRequest) -> Generator[Engine]:
if request.param == "postgresql":
testcontainers_postgres = pytest.importorskip("testcontainers.postgres")
container = testcontainers_postgres.PostgresContainer("postgres:15-alpine")
else:
testcontainers_mysql = pytest.importorskip("testcontainers.mysql")
container = testcontainers_mysql.MySqlContainer("mysql:8.0")
container.start()
raw_url = container.get_connection_url()
engine = sa.create_engine(raw_url.replace("mysql://", "mysql+pymysql://", 1))
channel_table = HumanInputIMChannel.metadata.tables[HumanInputIMChannel.__tablename__]
try:
HumanInputIMChannel.metadata.create_all(engine, tables=[channel_table])
yield engine
finally:
HumanInputIMChannel.metadata.drop_all(engine, tables=[channel_table])
engine.dispose()
container.stop()
@pytest.fixture(autouse=True)
def clean_im_channel_table(im_channel_engine: Engine) -> Generator[None]:
with im_channel_engine.begin() as connection:
connection.execute(sa.delete(HumanInputIMChannel))
yield
with im_channel_engine.begin() as connection:
connection.execute(sa.delete(HumanInputIMChannel))
def _channel() -> IMChannel:
now = naive_utc_now()
return IMChannel(
id=IMChannelId(str(uuid4())),
created_at=now,
updated_at=now,
provider=IMProvider.FEISHU,
provider_tenant_id=f"provider-tenant-{uuid4()}",
encrypted_credentials=ChannelEncryptedCredentials(ciphertext=f"opaque-{uuid4()}"),
app_identifier=f"app-{uuid4()}",
webhook_id=WebhookId(uuid4().hex),
config_version=1,
status=IMChannelStatus.CONNECTED,
)
def _concurrent_create_outcomes(
engine: Engine,
writer_factories: tuple[_WriterFactory, _WriterFactory],
) -> tuple[type[IMChannelAlreadyConfiguredError] | None, ...]:
sessions = sessionmaker(bind=engine, expire_on_commit=False)
barrier = Barrier(2)
def create(index: int) -> type[IMChannelAlreadyConfiguredError] | None:
try:
with sessions.begin() as session:
barrier.wait()
writer_factories[index](session).create(_channel())
except IMChannelAlreadyConfiguredError as error:
return type(error)
return None
with ThreadPoolExecutor(max_workers=2) as executor:
return tuple(executor.map(create, range(2)))
def test_same_workspace_concurrent_create_has_one_committed_winner(
im_channel_engine: Engine,
) -> None:
tenant_id = TenantId(str(uuid4()))
writer_factories: tuple[_WriterFactory, _WriterFactory] = (
lambda session: WorkspaceIMChannelWriter(session, tenant_id, AccountId(str(uuid4()))),
lambda session: WorkspaceIMChannelWriter(session, tenant_id, AccountId(str(uuid4()))),
)
outcomes = _concurrent_create_outcomes(im_channel_engine, writer_factories)
assert outcomes.count(None) == 1
assert outcomes.count(IMChannelAlreadyConfiguredError) == 1
with Session(im_channel_engine) as session:
assert session.scalar(sa.select(sa.func.count(HumanInputIMChannel.id))) == 1
def test_different_workspaces_concurrent_create_both_commit(
im_channel_engine: Engine,
) -> None:
tenant_ids = (TenantId(str(uuid4())), TenantId(str(uuid4())))
writer_factories: tuple[_WriterFactory, _WriterFactory] = (
lambda session: WorkspaceIMChannelWriter(session, tenant_ids[0], AccountId(str(uuid4()))),
lambda session: WorkspaceIMChannelWriter(session, tenant_ids[1], AccountId(str(uuid4()))),
)
outcomes = _concurrent_create_outcomes(im_channel_engine, writer_factories)
assert outcomes == (None, None)
with Session(im_channel_engine) as session:
owner_keys = set(session.scalars(sa.select(HumanInputIMChannel.owner_key)))
assert owner_keys == {f"workspace:{tenant_id}" for tenant_id in tenant_ids}
def test_deployment_concurrent_create_has_one_committed_winner(
im_channel_engine: Engine,
) -> None:
writer_factories: tuple[_WriterFactory, _WriterFactory] = (
DeploymentIMChannelWriter,
DeploymentIMChannelWriter,
)
outcomes = _concurrent_create_outcomes(im_channel_engine, writer_factories)
assert outcomes.count(None) == 1
assert outcomes.count(IMChannelAlreadyConfiguredError) == 1
with Session(im_channel_engine) as session:
assert session.scalar(sa.select(HumanInputIMChannel.owner_key)) == "deployment"
@@ -0,0 +1,168 @@
"""PostgreSQL tests for durable IM callback persistence."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from threading import Barrier
import pytest
import sqlalchemy as sa
from sqlalchemy.engine import Engine
from sqlalchemy.exc import DataError
from sqlalchemy.orm import Session, sessionmaker
from core.human_input_v2.entities import IMProvider
from core.human_input_v2.im_integration.adapters import AuthenticatedIMEvent, IMEventIngressKind
from core.human_input_v2.im_message_inbox import AcceptanceKind, InboxEventValidationError
from models.human_input_v2 import IMMessageEvent
from repositories.human_input_v2.im_channel_repository import IMChannelId
from services.human_input_v2.im_message_inbox.storage import IMInboxStorage
_NOW = datetime(2026, 8, 2, 8, tzinfo=UTC)
_RECEIVED_AT = datetime(2026, 8, 2, 8)
_CHANNEL_ID = IMChannelId("00000000-0000-0000-0000-000000000001")
def _event(
event_id: str | None,
*,
tenant_id: str = "tenant-1",
event_type: str | None = None,
) -> AuthenticatedIMEvent:
return AuthenticatedIMEvent(
provider=IMProvider.FEISHU,
provider_tenant_id=tenant_id,
event_id=event_id,
event_type=event_type,
occurred_at=None,
received_at=_RECEIVED_AT,
ingress_kind=IMEventIngressKind.WEBHOOK,
payload='{"secret":"must-not-log"}',
)
@pytest.fixture
def postgres_context(
db_session_with_containers: Session,
) -> tuple[Engine, IMInboxStorage, sessionmaker[Session]]:
engine = db_session_with_containers.get_bind()
assert isinstance(engine, Engine)
assert engine.dialect.name == "postgresql"
session_maker = sessionmaker(bind=engine, expire_on_commit=False)
return engine, IMInboxStorage(session_maker), session_maker
@pytest.mark.parametrize("absent_event_id", [None, "", " \t\n"])
def test_postgres_unidentified_callbacks_remain_independent(
postgres_context: tuple[Engine, IMInboxStorage, sessionmaker[Session]],
absent_event_id: str | None,
) -> None:
_, repository, session_maker = postgres_context
first = repository.insert_or_resolve(_CHANNEL_ID, _event(absent_event_id), now=_NOW)
second = repository.insert_or_resolve(_CHANNEL_ID, _event(absent_event_id), now=_NOW)
assert first.kind is AcceptanceKind.NEW
assert second.kind is AcceptanceKind.NEW
assert first.record_id != second.record_id
with session_maker() as session:
assert session.scalar(sa.select(sa.func.count(IMMessageEvent.id))) == 2
def test_postgres_preserves_max_length_provider_metadata(
postgres_context: tuple[Engine, IMInboxStorage, sessionmaker[Session]],
) -> None:
_, repository, session_maker = postgres_context
tenant_id = "t" * 128
event_id = "e" * 128
event_type = "y" * 128
accepted = repository.insert_or_resolve(
_CHANNEL_ID,
_event(event_id, tenant_id=tenant_id, event_type=event_type),
now=_NOW,
)
with session_maker() as session:
stored = session.get_one(IMMessageEvent, str(accepted.record_id))
assert stored.tenant_id == tenant_id
assert stored.event_id == event_id
assert stored.provider_event_type == event_type
def test_postgres_repository_rejects_oversized_provider_metadata_before_insert(
postgres_context: tuple[Engine, IMInboxStorage, sessionmaker[Session]],
) -> None:
_, repository, session_maker = postgres_context
with pytest.raises(InboxEventValidationError):
repository.insert_or_resolve(
_CHANNEL_ID,
_event("event-1", tenant_id="t" * 129),
now=_NOW,
)
with session_maker() as session:
assert session.scalar(sa.select(sa.func.count(IMMessageEvent.id))) == 0
def test_postgres_schema_rejects_oversized_provider_metadata(
postgres_context: tuple[Engine, IMInboxStorage, sessionmaker[Session]],
) -> None:
_, _, session_maker = postgres_context
def insert_oversized_callback() -> None:
with session_maker.begin() as session:
session.add(
IMMessageEvent(
channel_id=str(_CHANNEL_ID),
provider=IMProvider.FEISHU,
tenant_id="t" * 129,
event_id="event-1",
received_at=_RECEIVED_AT,
ingress_kind=IMEventIngressKind.WEBHOOK,
payload="{}",
)
)
session.flush()
with pytest.raises(DataError):
insert_oversized_callback()
@pytest.mark.parametrize("tenant_ids", [("tenant-1", "tenant-1"), ("tenant-1", "tenant-2")])
def test_postgres_concurrent_identified_insert_resolves_one_record(
postgres_context: tuple[Engine, IMInboxStorage, sessionmaker[Session]],
tenant_ids: tuple[str, str],
) -> None:
_, repository, session_maker = postgres_context
barrier = Barrier(2)
def insert_callback(tenant_id: str) -> tuple[AcceptanceKind, str]:
barrier.wait(timeout=5)
accepted = repository.insert_or_resolve(_CHANNEL_ID, _event("event-1", tenant_id=tenant_id), now=_NOW)
return accepted.kind, str(accepted.record_id)
with ThreadPoolExecutor(max_workers=2) as executor:
futures = [executor.submit(insert_callback, tenant_id) for tenant_id in tenant_ids]
results = [future.result(timeout=5) for future in futures]
assert {kind for kind, _ in results} == {AcceptanceKind.NEW, AcceptanceKind.DUPLICATE}
assert len({record_id for _, record_id in results}) == 1
with session_maker() as session:
assert session.scalar(sa.select(sa.func.count(IMMessageEvent.id))) == 1
def test_postgres_mark_processed_is_idempotent(
postgres_context: tuple[Engine, IMInboxStorage, sessionmaker[Session]],
) -> None:
_, repository, _ = postgres_context
accepted = repository.insert_or_resolve(_CHANNEL_ID, _event("event-1"), now=_NOW)
repository.mark_processed(accepted.record_id, processed_at=_NOW)
repository.mark_processed(accepted.record_id, processed_at=_NOW.replace(minute=1))
stored = repository.get(accepted.record_id)
assert stored is not None
assert stored.processed_at == datetime(2026, 8, 2, 8)
Loaded 100 of 15831 files, more files were not shown because too many files have changed in this diff. Show more