package dingtalk import ( "context" "encoding/json" "net/http" "net/http/httptest" "testing" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" ) // --------------------------------------------------------------------------- // Helper: test server with token + create + streaming + plain update endpoints // --------------------------------------------------------------------------- type finalWriteTestServer struct { server *httptest.Server createCalls int streamCalls int updateCalls int lastCreateBody map[string]any lastStreamBody map[string]any lastUpdateBody map[string]any lastUpdateMethod string lastUpdateHeader string // callSeq records the endpoint order ("create"/"stream"/"update") so the // write ORDER of a terminal answer can be asserted, not just the counts. callSeq []string streamBodies []map[string]any streamStatus int streamResponse any updateStatus int updateResponse any createResponse any } func newFinalWriteTestServer() *finalWriteTestServer { ts := &finalWriteTestServer{ streamStatus: http.StatusOK, updateStatus: http.StatusOK, streamResponse: map[string]any{"result": "ok"}, updateResponse: map[string]any{"result": true, "success": true}, createResponse: map[string]any{"result": "ok"}, } ts.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") switch r.URL.Path { case "/token": json.NewEncoder(w).Encode(map[string]any{"accessToken": "test-access-token", "expireIn": 3600}) case "/create": ts.createCalls++ ts.callSeq = append(ts.callSeq, "create") ts.lastCreateBody = make(map[string]any) json.NewDecoder(r.Body).Decode(&ts.lastCreateBody) json.NewEncoder(w).Encode(ts.createResponse) case "/stream": ts.streamCalls++ ts.callSeq = append(ts.callSeq, "stream") ts.lastStreamBody = make(map[string]any) json.NewDecoder(r.Body).Decode(&ts.lastStreamBody) ts.streamBodies = append(ts.streamBodies, ts.lastStreamBody) if ts.streamStatus != http.StatusOK { w.WriteHeader(ts.streamStatus) return } json.NewEncoder(w).Encode(ts.streamResponse) case "/update": ts.updateCalls++ ts.callSeq = append(ts.callSeq, "update") ts.lastUpdateMethod = r.Method ts.lastUpdateHeader = r.Header.Get("x-acs-dingtalk-access-token") ts.lastUpdateBody = make(map[string]any) json.NewDecoder(r.Body).Decode(&ts.lastUpdateBody) if ts.updateStatus != http.StatusOK { w.WriteHeader(ts.updateStatus) return } json.NewEncoder(w).Encode(ts.updateResponse) default: http.NotFound(w, r) } })) return ts } func (ts *finalWriteTestServer) Close() { ts.server.Close() } func (ts *finalWriteTestServer) sender(t *testing.T, mode CardFinalWriteMode) *CardSender { t.Helper() sender, err := newCardSenderForTest("id", "secret", "tpl", ts.server.Client(), ts.server.URL+"/token", ts.server.URL+"/create", WithCardFinalWrite(mode)) if err != nil { t.Fatalf("newCardSenderForTest: %v", err) } return sender } func (ts *finalWriteTestServer) paramMap(t *testing.T) map[string]any { t.Helper() cardData, ok := ts.lastUpdateBody["cardData"].(map[string]any) if !ok { t.Fatalf("update body has no cardData: %#v", ts.lastUpdateBody) } paramMap, ok := cardData["cardParamMap"].(map[string]any) if !ok { t.Fatalf("update body has no cardParamMap: %#v", cardData) } return paramMap } // --------------------------------------------------------------------------- // Default (streaming) mode keeps the historical single-write behaviour // --------------------------------------------------------------------------- func TestCardFinalWriteStreamingModeDoesNotTouchPlainUpdate(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() sender := ts.sender(t, CardFinalWriteStreaming) if err := sender.UpdateCard(context.Background(), "track-1", "答案", true, false); err != nil { t.Fatalf("UpdateCard: %v", err) } if ts.streamCalls != 1 { t.Fatalf("streamCalls=%d, want 1", ts.streamCalls) } if ts.updateCalls != 0 { t.Fatalf("updateCalls=%d, want 0 in streaming mode", ts.updateCalls) } // The zero value (option not passed at all) must behave the same. ts2 := newFinalWriteTestServer() defer ts2.Close() plain, err := newCardSenderForTest("id", "secret", "tpl", ts2.server.Client(), ts2.server.URL+"/token", ts2.server.URL+"/create") if err != nil { t.Fatal(err) } if err := plain.UpdateCard(context.Background(), "track-2", "答案", true, false); err != nil { t.Fatalf("UpdateCard: %v", err) } if ts2.updateCalls != 0 { t.Fatalf("updateCalls=%d, want 0 with the zero-value mode", ts2.updateCalls) } } // --------------------------------------------------------------------------- // update mode: one plain write after the streaming finalize, same variables // --------------------------------------------------------------------------- func TestCardFinalWriteUpdateModeWritesPlainUpdateAfterFinalize(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() sender := ts.sender(t, CardFinalWriteUpdate) if _, err := sender.StartCard(context.Background(), CardRequest{ ConversationType: core.ConversationDirect, ExternalUserID: "user-1", Content: "占位", }); err != nil { t.Fatalf("StartCard: %v", err) } const answer = "| 型号 | 速度 |\n| --- | --- |\n| CRV3 | 180°/s |" if err := sender.UpdateCard(context.Background(), "track-1", answer, true, false); err != nil { t.Fatalf("UpdateCard: %v", err) } if ts.streamCalls != 1 || ts.updateCalls != 1 { t.Fatalf("streamCalls=%d updateCalls=%d, want 1/1", ts.streamCalls, ts.updateCalls) } if ts.lastUpdateMethod != http.MethodPut { t.Fatalf("plain update method=%q, want PUT", ts.lastUpdateMethod) } if ts.lastUpdateHeader != "test-access-token" { t.Fatalf("plain update token header=%q", ts.lastUpdateHeader) } if ts.lastUpdateBody["outTrackId"] != ts.lastStreamBody["outTrackId"] { t.Fatalf("outTrackId mismatch: update=%v stream=%v", ts.lastUpdateBody["outTrackId"], ts.lastStreamBody["outTrackId"]) } options, ok := ts.lastUpdateBody["cardUpdateOptions"].(map[string]any) if !ok || options["updateCardDataByKey"] != false { t.Fatalf("cardUpdateOptions=%#v, want updateCardDataByKey=false", ts.lastUpdateBody["cardUpdateOptions"]) } paramMap := ts.paramMap(t) if paramMap["content"] != answer { t.Fatalf("plain update content=%v, want the finished answer", paramMap["content"]) } if paramMap[cardWideScreenJSONKey] != cardWideScreenJSON { t.Fatalf("plain update lost the wide-screen config: %#v", paramMap[cardWideScreenJSONKey]) } // The plain write replaces the whole param map, so it must carry exactly the // same variables as the create call. createParamMap, ok := ts.lastCreateBody["cardData"].(map[string]any)["cardParamMap"].(map[string]any) if !ok { t.Fatalf("create body has no cardParamMap: %#v", ts.lastCreateBody) } if len(createParamMap) != len(paramMap) { t.Fatalf("param map size differs: create=%d update=%d", len(createParamMap), len(paramMap)) } for key := range createParamMap { if _, present := paramMap[key]; !present { t.Fatalf("plain update is missing create variable %q", key) } } } func TestCardFinalWriteUpdateModeSkipsNonFinalAndErrorFrames(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() sender := ts.sender(t, CardFinalWriteUpdate) if err := sender.UpdateCard(context.Background(), "track-1", "部分", false, false); err != nil { t.Fatalf("partial UpdateCard: %v", err) } if ts.updateCalls != 0 { t.Fatalf("updateCalls=%d after a partial frame, want 0", ts.updateCalls) } if err := sender.UpdateCard(context.Background(), "track-1", "出错了", true, true); err != nil { t.Fatalf("error UpdateCard: %v", err) } if ts.updateCalls != 0 { t.Fatalf("updateCalls=%d after an error card, want 0", ts.updateCalls) } } // --------------------------------------------------------------------------- // A failing follow-up write must never fail an already delivered answer // --------------------------------------------------------------------------- func TestCardFinalWriteUpdateModeSwallowsPlainUpdateFailure(t *testing.T) { for _, tt := range []struct { name string status int response any }{ {"http error", http.StatusInternalServerError, nil}, {"business failure", http.StatusOK, map[string]any{"success": false, "errcode": 40035}}, } { t.Run(tt.name, func(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() ts.updateStatus = tt.status if tt.response != nil { ts.updateResponse = tt.response } sender := ts.sender(t, CardFinalWriteUpdate) if err := sender.UpdateCard(context.Background(), "track-1", "答案", true, false); err != nil { t.Fatalf("UpdateCard must succeed once the streaming finalize landed, got %v", err) } if ts.updateCalls != 1 { t.Fatalf("updateCalls=%d, want 1", ts.updateCalls) } }) } } func TestCardFinalWriteUpdateModeSkipsPlainUpdateWhenFinalizeFails(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() ts.streamStatus = http.StatusInternalServerError sender := ts.sender(t, CardFinalWriteUpdate) if err := sender.UpdateCard(context.Background(), "track-1", "答案", true, false); err == nil { t.Fatal("expected the streaming finalize failure to surface") } if ts.updateCalls != 0 { t.Fatalf("updateCalls=%d after a failed finalize, want 0", ts.updateCalls) } } // --------------------------------------------------------------------------- // SendFinalCard (direct delivery) honours the mode too // --------------------------------------------------------------------------- func TestCardFinalWriteUpdateModeAppliesToSendFinalCard(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() sender := ts.sender(t, CardFinalWriteUpdate) if _, err := sender.SendFinalCard(context.Background(), CardRequest{ ConversationType: core.ConversationDirect, ExternalUserID: "user-1", Content: "答案", }); err != nil { t.Fatalf("SendFinalCard: %v", err) } if ts.createCalls != 1 || ts.streamCalls != 1 || ts.updateCalls != 1 { t.Fatalf("create/stream/update=%d/%d/%d, want 1/1/1", ts.createCalls, ts.streamCalls, ts.updateCalls) } if ts.paramMap(t)["content"] != "答案" { t.Fatalf("plain update content=%v", ts.paramMap(t)["content"]) } } // --------------------------------------------------------------------------- // Order modes: refresh (plain first) and close-refresh (zero-delta finalize // first). Both exist because the client replays streamed text with its own // typewriter animation, so the ORDER of the two terminal writes decides what // the user sees when the answer is ready. // --------------------------------------------------------------------------- func wantCallSeq(t *testing.T, got, want []string) { t.Helper() if len(got) != len(want) { t.Fatalf("call sequence=%v, want %v", got, want) } for i := range want { if got[i] != want[i] { t.Fatalf("call sequence=%v, want %v", got, want) } } } func TestCardFinalWriteRefreshModeRefreshesBeforeFinalize(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() sender := ts.sender(t, CardFinalWriteRefresh) if _, err := sender.StartCard(context.Background(), CardRequest{ ConversationType: core.ConversationDirect, ExternalUserID: "user-1", Content: "占位", }); err != nil { t.Fatalf("StartCard: %v", err) } if err := sender.UpdateCard(context.Background(), "track-1", "部分", false, false); err != nil { t.Fatalf("partial UpdateCard: %v", err) } if err := sender.UpdateCard(context.Background(), "track-1", "完整答案", true, false); err != nil { t.Fatalf("terminal UpdateCard: %v", err) } // The finished answer goes out through the plain update BEFORE the frame // that closes the stream. wantCallSeq(t, ts.callSeq, []string{"create", "stream", "update", "stream"}) if got := ts.paramMap(t)["content"]; got != "完整答案" { t.Fatalf("plain refresh content=%v, want the finished answer", got) } if len(ts.streamBodies) != 2 { t.Fatalf("stream frames=%d, want 2", len(ts.streamBodies)) } closing := ts.streamBodies[1] if closing["content"] != "完整答案" || closing["isFinalize"] != true { t.Fatalf("closing frame=%v, want the finished answer with isFinalize=true", closing) } } func TestCardFinalWriteRefreshModeKeepsDeliveryWhenPlainRefreshFails(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() ts.updateStatus = http.StatusInternalServerError sender := ts.sender(t, CardFinalWriteRefresh) if err := sender.UpdateCard(context.Background(), "track-1", "完整答案", true, false); err != nil { t.Fatalf("a failed plain refresh must not fail the delivery, got %v", err) } if ts.updateCalls != 1 || ts.streamCalls != 1 { t.Fatalf("update/stream=%d/%d, want 1/1 (the closing frame still goes out)", ts.updateCalls, ts.streamCalls) } if ts.lastStreamBody["isFinalize"] != true || ts.lastStreamBody["content"] != "完整答案" { t.Fatalf("closing frame=%v", ts.lastStreamBody) } } func TestCardFinalWriteCloseRefreshModeClosesOnShownTextThenRefreshes(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() sender := ts.sender(t, CardFinalWriteCloseRefresh) if _, err := sender.StartCard(context.Background(), CardRequest{ ConversationType: core.ConversationDirect, ExternalUserID: "user-1", Content: "占位", }); err != nil { t.Fatalf("StartCard: %v", err) } if err := sender.UpdateCard(context.Background(), "track-1", "部分", false, false); err != nil { t.Fatalf("partial UpdateCard: %v", err) } if err := sender.UpdateCard(context.Background(), "track-1", "完整答案", true, false); err != nil { t.Fatalf("terminal UpdateCard: %v", err) } // The closing frame carries the text the card already shows (zero delta, so // the client has nothing to animate) and the finished answer follows through // the plain update. wantCallSeq(t, ts.callSeq, []string{"create", "stream", "stream", "update"}) if len(ts.streamBodies) != 2 { t.Fatalf("stream frames=%d, want 2", len(ts.streamBodies)) } closing := ts.streamBodies[1] if closing["content"] != "部分" || closing["isFinalize"] != true { t.Fatalf("closing frame=%v, want the previously shown text with isFinalize=true", closing) } if got := ts.paramMap(t)["content"]; got != "完整答案" { t.Fatalf("plain refresh content=%v, want the finished answer", got) } } func TestCardFinalWriteCloseRefreshModeRefreshesFirstWhenNothingStreamed(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() sender := ts.sender(t, CardFinalWriteCloseRefresh) // A card that never received a partial frame has no zero-delta frame to // close on, so the refresh has to go first. if err := sender.UpdateCard(context.Background(), "track-1", "完整答案", true, false); err != nil { t.Fatalf("terminal UpdateCard: %v", err) } wantCallSeq(t, ts.callSeq, []string{"update", "stream"}) if ts.lastStreamBody["isFinalize"] != true || ts.lastStreamBody["content"] != "完整答案" { t.Fatalf("closing frame=%v", ts.lastStreamBody) } } func TestCardFinalWriteCloseRefreshModeKeepsDeliveryWhenPlainRefreshFails(t *testing.T) { ts := newFinalWriteTestServer() defer ts.Close() ts.updateStatus = http.StatusInternalServerError sender := ts.sender(t, CardFinalWriteCloseRefresh) if err := sender.UpdateCard(context.Background(), "track-1", "部分", false, false); err != nil { t.Fatalf("partial UpdateCard: %v", err) } if err := sender.UpdateCard(context.Background(), "track-1", "完整答案", true, false); err != nil { t.Fatalf("a failed plain refresh must not fail the delivery, got %v", err) } wantCallSeq(t, ts.callSeq, []string{"stream", "stream", "update"}) if ts.lastStreamBody["isFinalize"] != true || ts.lastStreamBody["content"] != "部分" { t.Fatalf("closing frame=%v", ts.lastStreamBody) } } func TestCardFinalWriteParserAcceptsOrderValues(t *testing.T) { for raw, want := range map[string]CardFinalWriteMode{ "": CardFinalWriteStreaming, "streaming": CardFinalWriteStreaming, "off": CardFinalWriteStreaming, "nonsense": CardFinalWriteStreaming, "update": CardFinalWriteUpdate, "refresh": CardFinalWriteRefresh, "plain_first": CardFinalWriteRefresh, "refresh-first": CardFinalWriteRefresh, "close_refresh": CardFinalWriteCloseRefresh, "close-refresh": CardFinalWriteCloseRefresh, "CLOSE-REFRESH ": CardFinalWriteCloseRefresh, } { if got := ParseCardFinalWriteMode(raw); got != want { t.Fatalf("ParseCardFinalWriteMode(%q)=%q, want %q", raw, got, want) } } }