Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions dingtalk/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,13 +165,23 @@ def ensure_dingtalk_deps() -> bool:
re-creating the #79812 deadlock for extra-configured setups.
"""
global DINGTALK_STREAM_AVAILABLE, dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, HTTPX_AVAILABLE, httpx
global _IncomingHandler
if DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE:
return True
try: # the SDKs come with the plugin's own dependencies; a missing one stays missing
import dingtalk_stream as _ds
import httpx as _httpx
from dingtalk_stream import ChatbotMessage as _CM
from dingtalk_stream.frames import CallbackMessage as _CBM, AckMessage as _AM

# An import before the SDK was available leaves the handler without SDK dispatch.
handler = _IncomingHandler
if not issubclass(handler, _ds.ChatbotHandler):
_IncomingHandler = type(
"_IncomingHandler",
(handler, _ds.ChatbotHandler),
{"__module__": __name__, "__doc__": handler.__doc__},
)
except Exception:
return False
dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, httpx = _ds, _CM, _CBM, _AM, _httpx
Expand Down
52 changes: 52 additions & 0 deletions dingtalk/tests/test_dingtalk.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"""Tests for DingTalk platform adapter."""
import asyncio
import json
import sys
from dataclasses import replace
from importlib.util import module_from_spec
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch

Expand Down Expand Up @@ -174,6 +178,54 @@ async def test_connect_fails_without_sdk(self, monkeypatch):
result = await adapter.connect()
assert result is False

@pytest.mark.asyncio
@pytest.mark.plugin_registry
async def test_connect_dispatches_inbound_when_sdk_becomes_available(self, monkeypatch):
from dingtalk_plugin import adapter as dt
from gateway.platform_registry import PlatformRegistry, platform_registry

sdk = pytest.importorskip("dingtalk_stream")
# Load a fresh adapter while the SDK import fails, then let Python find it again.
recovered = module_from_spec(dt.__spec__)
with monkeypatch.context() as unavailable:
unavailable.setitem(sys.modules, "dingtalk_stream", None)
dt.__spec__.loader.exec_module(recovered)

registry = PlatformRegistry()
registry.register(replace(
platform_registry.get("dingtalk"),
adapter_factory=recovered.DingTalkAdapter,
check_fn=recovered.dingtalk_deps_present,
ensure_deps_fn=recovered.ensure_dingtalk_deps,
))
adapter = registry.create_adapter("dingtalk", PlatformConfig(
enabled=True, extra={"client_id": "client", "client_secret": "secret"},
))
assert adapter is not None
monkeypatch.setattr(adapter, "_run_stream", AsyncMock())
delivered = asyncio.get_running_loop().create_future()

async def on_message(message):
delivered.set_result(message.text.content)

monkeypatch.setattr(adapter, "_on_message", on_message)
try:
assert await adapter.connect()
client = adapter._stream_client
client.pre_start()
client.websocket = SimpleNamespace(send=AsyncMock(), close=AsyncMock())
await client.route_message({
"type": "CALLBACK",
"headers": {"topic": sdk.ChatbotMessage.TOPIC, "messageId": "offline-frame"},
"data": json.dumps({"msgtype": "text", "text": {"content": "hello"}}),
})
ack = json.loads(client.websocket.send.await_args.args[0])
assert ack["code"] == 200
assert ack["headers"]["messageId"] == "offline-frame"
assert await asyncio.wait_for(delivered, timeout=5) == "hello"
finally:
await adapter.disconnect()

@pytest.mark.asyncio
async def test_disconnect_finalizes_open_streaming_cards(self):
"""Streaming cards must be finalized before HTTP client closes."""
Expand Down