refactor(backend): dify, minio等迁移到integration,清除无效文件

This commit is contained in:
sophie committed 2026-09-21 09:24:45 +08:00
1 parent 7fe7a39384
commit faa554ade4
90 files changed
+7540 -9649

No files matched your search

+7 -7
View File
@@ -104,7 +104,7 @@ def test_try_fast_route_hr_leave_when_route_declared(monkeypatch):
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
'app.services.integrations.plm.oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
monkeypatch.setattr(
@@ -136,11 +136,11 @@ def test_try_fast_route_text2sql_for_erp_kb(monkeypatch):
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
'app.services.integrations.plm.oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
monkeypatch.setattr(
'app.services.text2sql.Text2SQLService.stream_chat',
'app.services.integrations.text2sql.Text2SQLService.stream_chat',
classmethod(lambda cls, *args, **kwargs: iter(['data: {"event":"message"}\n\n'])),
)
@@ -172,7 +172,7 @@ def test_try_fast_route_returns_none_for_generic_query(monkeypatch):
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
'app.services.integrations.plm.oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
@@ -200,7 +200,7 @@ def test_try_fast_route_plm_skips_when_attachments_present(monkeypatch):
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
'app.services.integrations.plm.oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: True),
)
@@ -227,7 +227,7 @@ def test_try_fast_route_skips_hr_when_route_not_declared(monkeypatch):
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
'app.services.integrations.plm.oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
@@ -254,7 +254,7 @@ def test_try_fast_route_skips_text2sql_without_route(monkeypatch):
staticmethod(lambda query, agent, session_id=None: False),
)
monkeypatch.setattr(
'app.services.plm_oracle.PLMOracleService.supports',
'app.services.integrations.plm.oracle.PLMOracleService.supports',
classmethod(lambda cls, query, agent: False),
)
+1 -1
View File
@@ -7,7 +7,7 @@ import pytest
from app import create_app, db
from app.models import Agent, ChatLog, User
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
@pytest.fixture
@@ -13,7 +13,7 @@ from types import SimpleNamespace
import pytest
import requests
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
from app.services.file_check import FileCheckService
@@ -59,7 +59,7 @@ def _mock_stream_response(monkeypatch, *, status_code: int = 200, lines: list[by
calls["count"] += 1
return _Resp()
monkeypatch.setattr("app.services.dify.requests.post", _post)
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
return calls
@@ -180,7 +180,7 @@ def test_workflow_streaming_503_retries_then_success(monkeypatch):
return _Resp()
monkeypatch.setattr("app.services.dify.requests.post", _post)
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
@@ -199,7 +199,7 @@ def test_workflow_streaming_401_does_not_retry(monkeypatch):
resp.status_code = 401
raise requests.HTTPError(response=resp)
monkeypatch.setattr("app.services.dify.requests.post", _post)
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
with pytest.raises(requests.HTTPError):
DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
@@ -353,7 +353,7 @@ def test_dedupe_exact_doubled_text_fixes_historical_records():
def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
"""连接超时的 error SSE 必须携带持久化主键,供领域 Handler 回写失败状态。"""
monkeypatch.setattr(
"app.services.dify.requests.post",
"app.services.integrations.dify.requests.post",
lambda *args, **kwargs: (_ for _ in ()).throw(requests.exceptions.ConnectTimeout("connect timed out")),
)
monkeypatch.setattr(
@@ -402,7 +402,7 @@ def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeyp
yield _sse_lines({"event": "message", "answer": "partial answer"})[0]
raise requests.exceptions.ReadTimeout("read timed out")
monkeypatch.setattr("app.services.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
monkeypatch.setattr("app.services.integrations.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
monkeypatch.setattr(
DifyService,
"_persist_stream_chat_record",
+31 -21
View File
@@ -297,7 +297,10 @@ def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -382,7 +385,10 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -619,7 +625,10 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
@@ -1224,18 +1233,13 @@ def test_file_check_tool_excel_download_uses_signed_token(app, client):
def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
started_threads = []
enqueued = []
class _Thread:
def __init__(self, *, target, daemon, name):
self.target = target
self.daemon = daemon
self.name = name
def _enqueue(*args, **kwargs):
enqueued.append({"args": args, "kwargs": kwargs})
return 1
def start(self):
started_threads.append(self.name)
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -1254,7 +1258,7 @@ def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeyp
assert data['ok'] is True
assert data['run']['task_id'] == task_id
assert data['run']['status'] == 'running'
assert started_threads == [f"file-check-run-{data['run']['run_id']}"]
assert enqueued and enqueued[0]['kwargs'].get('domain') == 'file_check'
def test_serialize_file_judgement_reads_file_key():
@@ -1816,7 +1820,10 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -1860,7 +1867,7 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
) == run_id
chat_log_id = None
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
result = DifyService._persist_stream_chat_record(
data={'conversation_id': 'sess-registry-001'},
@@ -1998,7 +2005,10 @@ def _stub_file_check_thread(monkeypatch):
def start(self):
return None
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
def _enqueue(*_args, **_kwargs):
return 1
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
def _file_check_agent_proxy(task_id: int):
@@ -2049,7 +2059,7 @@ def test_chat_tool_runs_tool_first_then_chat_log(app, client, monkeypatch):
assert res.status_code == 200
run_id = res.get_json()['run']['run_id']
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
with app.app_context():
result = DifyService._persist_stream_chat_record(
@@ -2094,7 +2104,7 @@ def test_chat_tool_runs_chat_log_first_then_tool(app, client, monkeypatch):
admin_id = admin.id
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
with app.app_context():
register_pending_turn(
@@ -2219,7 +2229,7 @@ def test_chat_tool_runs_same_message_does_not_cross_runs(app, client, monkeypatc
run_b = res_b.get_json()['run']['run_id']
assert run_b == run_a
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
with app.app_context():
result_b = DifyService._persist_stream_chat_record(
@@ -2279,7 +2289,7 @@ def test_chat_tool_runs_without_turn_id_same_message_skips_ambiguous_bind(app, c
from app.models import ChatToolRun
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
with app.app_context():
register_pending_turn(
+1 -1
View File
@@ -1,7 +1,7 @@
from types import SimpleNamespace
import xml.etree.ElementTree as ET
from app.services.oa_leave_workflow import OALeaveWorkflowService
from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService
WORKFLOW_NS = 'http://webservices.workflow.weaver'
+211 -106
View File
@@ -1,106 +1,211 @@
"""Tests for OA userInfo_view → wecom_userid sync."""␍
␍
from unittest.mock import patch␍
␍
import pytest␍
␍
from app.models import User␍
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa␍
␍
␍
@pytest.fixture␍
def oa_rows_for_local_user():␍
return [␍
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},␍
]␍
␍
␍
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):␍
with app.app_context():␍
user = User(␍
username='26030025',␍
email='26030025@test.local',␍
employee_id='26030025',␍
real_name='sophie',␍
role='user',␍
status='active',␍
)␍
user.set_password('test123')␍
from app import db␍
␍
db.session.add(user)␍
db.session.commit()␍
␍
with patch(␍
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',␍
return_value=oa_rows_for_local_user,␍
) as fetch_mock:␍
summary = sync_wecom_userids_from_oa(apply=False)␍
␍
fetch_mock.assert_called_once_with(['26030025'])␍
assert summary['local_candidates'] == 1␍
assert summary['wecom_users'] == 1␍
assert summary['local_matched'] == 1␍
assert summary['would_update'] == 1␍
assert summary['local_missing'] == 0␍
assert summary['pending_updates'][0]['wecom_userid'] == '21784'␍
␍
db.session.refresh(user)␍
assert user.wecom_userid is None␍
␍
␍
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):␍
with app.app_context():␍
user = User(␍
username='26030025',␍
email='26030025@test.local',␍
employee_id='26030025',␍
real_name='sophie',␍
role='user',␍
status='active',␍
)␍
user.set_password('test123')␍
from app import db␍
␍
db.session.add(user)␍
db.session.commit()␍
␍
with patch(␍
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',␍
return_value=oa_rows_for_local_user,␍
):␍
summary = sync_wecom_userids_from_oa(apply=True)␍
␍
assert summary['updated'] == 1␍
db.session.refresh(user)␍
assert user.wecom_userid == '21784'␍
␍
␍
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):␍
with app.app_context():␍
user = User(␍
username='missing_oa',␍
email='missing_oa@test.local',␍
employee_id='99999999',␍
real_name='missing',␍
role='user',␍
status='active',␍
)␍
user.set_password('test123')␍
from app import db␍
␍
db.session.add(user)␍
db.session.commit()␍
␍
with patch(␍
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',␍
return_value=[],␍
) as fetch_mock:␍
summary = sync_wecom_userids_from_oa(apply=False)␍
␍
fetch_mock.assert_called_once_with(['99999999'])␍
assert summary['local_candidates'] == 1␍
assert summary['wecom_users'] == 0␍
assert summary['local_matched'] == 0␍
assert summary['local_missing'] == 1␍
␍
"""Tests for OA userInfo_view → wecom_userid sync."""
from unittest.mock import patch
import pytest
from app.models import User
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
@pytest.fixture
def oa_rows_for_local_user():
return [
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},
]
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):
with app.app_context():
user = User(
username='26030025',
email='26030025@test.local',
employee_id='26030025',
real_name='sophie',
role='user',
status='active',
)
user.set_password('test123')
from app import db
db.session.add(user)
db.session.commit()
with patch(
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
return_value=oa_rows_for_local_user,
) as fetch_mock:
summary = sync_wecom_userids_from_oa(apply=False)
fetch_mock.assert_called_once_with(['26030025'])
assert summary['local_candidates'] == 1
assert summary['wecom_users'] == 1
assert summary['local_matched'] == 1
assert summary['would_update'] == 1
assert summary['local_missing'] == 0
assert summary['pending_updates'][0]['wecom_userid'] == '21784'
db.session.refresh(user)
assert user.wecom_userid is None
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):
with app.app_context():
user = User(
username='26030025',
email='26030025@test.local',
employee_id='26030025',
real_name='sophie',
role='user',
status='active',
)
user.set_password('test123')
from app import db
db.session.add(user)
db.session.commit()
with patch(
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
return_value=oa_rows_for_local_user,
):
summary = sync_wecom_userids_from_oa(apply=True)
assert summary['updated'] == 1
db.session.refresh(user)
assert user.wecom_userid == '21784'
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):
with app.app_context():
user = User(
username='missing_oa',
email='missing_oa@test.local',
employee_id='99999999',
real_name='missing',
role='user',
status='active',
)
user.set_password('test123')
from app import db
db.session.add(user)
db.session.commit()
with patch(
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
return_value=[],
) as fetch_mock:
summary = sync_wecom_userids_from_oa(apply=False)
fetch_mock.assert_called_once_with(['99999999'])
assert summary['local_candidates'] == 1
assert summary['wecom_users'] == 0
assert summary['local_matched'] == 0
assert summary['local_missing'] == 1
@@ -360,7 +360,7 @@ def test_build_schedule_run_wecom_jump_params_omits_raw_zip_without_archive(app)
def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
"""textcard 跳转应优先 HTTPS 公网域名,而非内网/端口 WECOM_NOTIFY_BASE_URL。"""
from app.services.wecom_notify import _get_notify_base_url
from app.services.integrations.wecom.notify import _get_notify_base_url
with app.app_context():
app.config["WECOM_NOTIFY_BASE_URL"] = "http://ait.well-trust.com:8890/"
@@ -371,7 +371,7 @@ def test_get_notify_base_url_prefers_wecom_public_over_notify_base_url(app):
def test_get_notify_base_url_falls_back_to_hxops_public_base_url(app):
"""未配置 WECOM_PUBLIC 时应回退 HXOPS_PUBLIC_BASE_URL,而非 WECOM_NOTIFY_BASE_URL。"""
from app.services.wecom_notify import _get_notify_base_url
from app.services.integrations.wecom.notify import _get_notify_base_url
with app.app_context():
app.config["WECOM_PUBLIC_BASE_URL"] = ""
@@ -394,19 +394,19 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
return {"errcode": 0}
monkeypatch.setattr(
"app.services.wecom_notify.send_wecom_textcard_message",
"app.services.integrations.wecom.notify.send_wecom_textcard_message",
_fake_send_textcard,
)
monkeypatch.setattr(
"app.services.wecom_notify._get_enabled_events",
"app.services.integrations.wecom.notify._get_enabled_events",
lambda: {"schedule_completed"},
)
monkeypatch.setattr(
"app.services.wecom_notify.upload_wecom_temp_media",
"app.services.integrations.wecom.notify.upload_wecom_temp_media",
lambda _data, filename: media_uploads.append(filename) or f"media-{len(media_uploads)}",
)
monkeypatch.setattr(
"app.services.wecom_notify.send_wecom_file_message",
"app.services.integrations.wecom.notify.send_wecom_file_message",
lambda _userid, media_id: file_sends.append(media_id) or {"errcode": 0},
)
+1 -1
View File
@@ -2,7 +2,7 @@ import pytest
from flask import Flask
from app import create_app, db
from app.models import ChatLog, Agent, User
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
import json
@pytest.fixture
+1 -1
View File
@@ -394,7 +394,7 @@ def test_chat_completions_stream_success(client, mocker, mock_agent_query):
mock_post.return_value.__enter__.return_value = mock_response
# Mock DB logging
mocker.patch('app.services.dify.DifyService._log_chat')
mocker.patch('app.services.integrations.dify.DifyService._log_chat')
# Setup decorator mocks
mock_user = User(id=1, username="test_user")
+1 -1
View File
@@ -1,6 +1,6 @@
import base64
from app.services.wecom_crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, encrypt_wecom_aes, sha1_hex
def test_wecom_aes_roundtrip():
@@ -24,7 +24,7 @@ if str(BACKEND_ROOT) not in sys.path:
sys.path.insert(0, str(BACKEND_ROOT))
from app import create_app # noqa: E402
from app.services.wecom_notify import _get_access_token # noqa: E402
from app.services.integrations.wecom.notify import _get_access_token # noqa: E402
def _get_userid_by_mobile(mobile: str) -> dict[str, Any]:
@@ -25,7 +25,7 @@ if str(BACKEND_ROOT) not in sys.path:
from app import create_app, db # noqa: E402
from app.models import User # noqa: E402
from app.services.wecom_notify import _get_access_token, send_wecom_textcard_message # noqa: E402
from app.services.integrations.wecom.notify import _get_access_token, send_wecom_textcard_message # noqa: E402
def _resolve_target_userid(app, target: str) -> tuple[str, dict[str, Any] | None]:
@@ -186,14 +186,14 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
sent.append((wecom_userid, title, description))
return {"errcode": 0}
monkeypatch.setattr("app.services.wecom_notify.send_wecom_textcard_message", _fake_send)
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
monkeypatch.setattr(
"app.services.wecom_notify._create_audit",
"app.services.integrations.wecom.notify._create_audit",
lambda *args, **kwargs: SimpleNamespace(
jump_url=None, status=None, error_code=None, error_message=None
),
)
monkeypatch.setattr("app.services.wecom_notify._build_jump_url", lambda *args, **kwargs: "https://jump")
monkeypatch.setattr("app.services.integrations.wecom.notify._build_jump_url", lambda *args, **kwargs: "https://jump")
with app.app_context():
app.config["WECOM_NOTIFY_ENABLED"] = True