Files
dobotai-platform/internal/channels/dingtalk/card_pump_test.go
2026-07-20 23:22:07 +08:00

110 lines
2.7 KiB
Go

package dingtalk
import (
"context"
"errors"
"testing"
"time"
)
func waitPumpUpdate(t *testing.T, updates <-chan string) string {
t.Helper()
select {
case got := <-updates:
return got
case <-time.After(time.Second):
t.Fatal("timed out waiting for card pump update")
return ""
}
}
func TestCardUpdatePumpCoalescesToLatestWithoutBlockingOffer(t *testing.T) {
ticks := make(chan time.Time, 2)
observed := make(chan string, 2)
pump := newCardUpdatePumpWithTicks(context.Background(), ticks, nil, func(_ context.Context, content string) error {
observed <- content
return nil
})
defer pump.Stop()
pump.Offer("one")
pump.Offer("two")
pump.Offer("latest")
ticks <- time.Now()
if got := waitPumpUpdate(t, observed); got != "latest" {
t.Fatalf("update=%q want latest", got)
}
}
func TestCardUpdatePumpCoalescesWhileDingTalkRequestIsBlocked(t *testing.T) {
ticks := make(chan time.Time, 3)
started := make(chan string, 2)
release := make(chan struct{})
pump := newCardUpdatePumpWithTicks(context.Background(), ticks, nil, func(_ context.Context, content string) error {
started <- content
<-release
return nil
})
pump.Offer("first")
ticks <- time.Now()
if got := waitPumpUpdate(t, started); got != "first" {
t.Fatalf("first update=%q", got)
}
// These offers must not block behind the in-flight HTTP request and only the
// newest state should survive.
pump.Offer("second")
pump.Offer("third")
pump.Offer("newest")
close(release)
ticks <- time.Now()
if got := waitPumpUpdate(t, started); got != "newest" {
t.Fatalf("coalesced update=%q want newest", got)
}
pump.Stop()
}
func TestCardUpdatePumpContinuesAfterUpdateError(t *testing.T) {
ticks := make(chan time.Time, 2)
calls := make(chan string, 2)
count := 0
pump := newCardUpdatePumpWithTicks(context.Background(), ticks, nil, func(_ context.Context, content string) error {
count++
calls <- content
if count == 1 {
return errors.New("token and content must not be logged")
}
return nil
})
defer pump.Stop()
pump.Offer("first")
ticks <- time.Now()
_ = waitPumpUpdate(t, calls)
pump.Offer("second")
ticks <- time.Now()
if got := waitPumpUpdate(t, calls); got != "second" {
t.Fatalf("second update=%q", got)
}
}
func TestCardUpdatePumpStopDropsPendingAndIsIdempotent(t *testing.T) {
ticks := make(chan time.Time, 1)
observed := make(chan string, 1)
pump := newCardUpdatePumpWithTicks(context.Background(), ticks, nil, func(_ context.Context, content string) error {
observed <- content
return nil
})
pump.Offer("stale")
pump.Stop()
pump.Stop()
pump.Offer("after-stop")
select {
case got := <-observed:
t.Fatalf("unexpected update after stop: %q", got)
default:
}
}