Files
dn20/ai_deepseek/tests/test_deepseek_bridge.py
2026-11-04 19:58:07 +08:00

122 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Part of the ai_deepseek module.
# -*- coding: utf-8 -*-
"""
集成测试:验证 ai_deepseek 传输层接管能驱动完整的 AI 会话。
运行:
E:\\odoo20\\venv\\Scripts\\python.exe E:\\odoo20\\odoo20\\odoo-bin ^
-c E:\\odoo20\\odoo20.conf -d odoo20 --test-tags ai_deepseek --stop-after-init
说明:只保留在 TransactionCase 中可靠的断言(补丁生效、配置注入、
同步补全/embedding 返回值)。异步交付(postcommit + 后台线程 + 新 cursor)
依赖真实提交,用同目录的 simulate_async_delivery.py 脚本做提交级验证。
"""
import logging
from unittest.mock import patch
from odoo.tests import tagged
from odoo.tests.common import TransactionCase
_logger = logging.getLogger(__name__)
@tagged("post_install", "-at_install", "ai_deepseek")
class TestDeepSeekBridge(TransactionCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
icp = cls.env["ir.config_parameter"].sudo()
icp.set_str("ai_deepseek.enabled", "True")
icp.set_str("ai_deepseek.api_key", "sk-test-fake")
def test_patch_installed(self):
"""传输层应已被替换(含各模块命名空间的绑定)。"""
from odoo.addons.ai.utils import ai_utils
from odoo.addons.ai.models import ai_session, ai_embedding, mail_call_artifact
from odoo.addons.ai_deepseek import transport_patch
patched = transport_patch._patched_call_odoo_ai_transport
self.assertIs(ai_utils.call_odoo_ai_transport, patched)
self.assertIs(ai_session.call_odoo_ai_transport, patched)
self.assertIs(ai_session.get_odoo_ai_connection_data,
transport_patch._patched_get_connection_data)
self.assertIs(ai_embedding.call_odoo_ai,
transport_patch._patched_call_odoo_ai)
self.assertIs(mail_call_artifact.call_odoo_ai,
transport_patch._patched_call_odoo_ai)
def test_config_injected_into_connection(self):
"""get_odoo_ai_connection_data 应把配置塞进 connection。"""
from odoo.addons.ai.models import ai_session
connection = ai_session.get_odoo_ai_connection_data(self.env)
cfg = connection.get("ai_deepseek_cfg")
self.assertTrue(cfg, "connection 未注入 ai_deepseek_cfg")
self.assertTrue(cfg["enabled"])
self.assertEqual(cfg["api_key"], "sk-test-fake")
def test_sync_completion_uses_deepseek(self):
"""同步补全应返回 DeepSeek 的响应(mock HTTP)。"""
from odoo.addons.ai.models import ai_session
with patch("odoo.addons.ai_deepseek.deepseek_client.call_chat",
return_value={"content": "你好,我是 DeepSeek。"}):
resp = ai_session.call_odoo_ai(self.env, "1/get_completions_sync", {
"messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}],
"instructions": "你是助手",
"tools": [],
})
self.assertEqual(resp["result"]["role"], "assistant")
self.assertEqual(resp["result"]["content"],
[{"type": "text", "text": "你好,我是 DeepSeek。"}])
def test_sync_completion_tool_call(self):
"""含工具调用的同步补全应正确转换。"""
from odoo.addons.ai.models import ai_session
with patch("odoo.addons.ai_deepseek.deepseek_client.call_chat",
return_value={
"content": None,
"tool_calls": [{
"id": "call_1", "type": "function",
"function": {"name": "ai_tool_search", "arguments": '{"q": "x"}'},
}],
}):
resp = ai_session.call_odoo_ai(self.env, "1/get_completions_sync", {
"messages": [{"role": "user", "content": [{"type": "text", "text": "找"}]}],
"instructions": "你是助手",
"tools": [],
})
part = resp["result"]["content"][0]
self.assertEqual(part["type"], "tool_call")
self.assertEqual(part["name"], "ai_tool_search")
self.assertEqual(part["args"], {"q": "x"})
self.assertEqual(part["call_id"], "call_1")
def test_sync_embeddings_uses_deepseek(self):
from odoo.addons.ai.models import ai_session
with patch("odoo.addons.ai_deepseek.deepseek_client.call_embeddings",
return_value=[[0.1] * 1536]):
resp = ai_session.call_odoo_ai(self.env, "1/get_embeddings", {
"input": [{"content": "hello"}], "model": "m", "mode": "query",
})
self.assertEqual(len(resp["embeddings"]), 1)
self.assertEqual(len(resp["embeddings"][0]), 1536)
def test_disabled_falls_back(self):
"""关闭模块时应回退官方实现(不调用 DeepSeek)。"""
from odoo.addons.ai.models import ai_session
self.env["ir.config_parameter"].sudo().set_str("ai_deepseek.enabled", "False")
from odoo.addons.ai.utils import ai_utils
original = ai_utils.call_odoo_ai
# 关闭后,call_odoo_ai 会走 _ORIGINALS(即 ai_utils 的原函数),
# 这里仅断言不会调用到 deepseek_client(用 mock 探测)。
with patch("odoo.addons.ai_deepseek.deepseek_client.call_chat",
side_effect=AssertionError("disabled 时不应调用 DeepSeek")):
try:
# 官方实现会尝试联网,预计抛异常;关键是没走我们的分支。
ai_session.call_odoo_ai(self.env, "1/get_default_embedding_model", {},
add_iap_token=False)
except AssertionError:
raise
except Exception:
pass
self.env["ir.config_parameter"].sudo().set_str("ai_deepseek.enabled", "True")