Files
MailUI4Agents/server/internal/sse/manager_test.go

101 lines
2.4 KiB
Go
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.

package sse
import (
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestEventRingPushReplay(t *testing.T) {
ring := newEventRing(5)
// 推 3 条
for i := 1; i <= 3; i++ {
ring.push(StoredEvent{
ID: string(rune('0' + i)),
EventType: "test",
Data: []byte(`{"n":` + string(rune('0'+i)) + `}`),
Timestamp: time.Now(),
})
}
// 空 afterID → 首次连接,不回放(缓冲区未满)
rec := httptest.NewRecorder()
ring.replay("", rec, rec)
if rec.Body.Len() > 0 {
t.Error("首次连接不应回放事件,实际:", rec.Body.String())
}
// 有 afterID → 从下一条开始回放
rec2 := httptest.NewRecorder()
ring.replay("1", rec2, rec2)
body := rec2.Body.String()
if !strings.Contains(body, "id: 2") {
t.Error("afterID=1 应该回放 id:2实际:", body)
}
if !strings.Contains(body, "id: 3") {
t.Error("afterID=1 应该回放 id:3实际:", body)
}
if strings.Contains(body, "id: 1") {
t.Error("afterID=1 不应回放 id:1实际:", body)
}
// 不存在的 afterID → 从头回放全部
rec3 := httptest.NewRecorder()
ring.replay("999", rec3, rec3)
body3 := rec3.Body.String()
if !strings.Contains(body3, "id: 1") {
t.Error("不存在的 afterID 应从头回放,实际:", body3)
}
}
func TestEventRingOverflow(t *testing.T) {
ring := newEventRing(3)
// 推 5 条(超过容量 3最旧的 2 条被覆盖)
for i := 1; i <= 5; i++ {
ring.push(StoredEvent{
ID: string(rune('0' + i)),
EventType: "test",
Data: []byte(`{}`),
Timestamp: time.Now(),
})
}
if !ring.full {
t.Fatal("推了 5 条进容量 3 的缓冲区,应该已满")
}
// afterID=2 已被覆盖 → 找不到位置,从头回放全部
rec := httptest.NewRecorder()
ring.replay("2", rec, rec)
body := rec.Body.String()
if !strings.Contains(body, "id: 3") || !strings.Contains(body, "id: 5") {
t.Error("缓冲区溢出后应能回放可用范围,实际:", body)
}
}
func TestEventRingConcurrent(t *testing.T) {
ring := newEventRing(100)
done := make(chan bool, 10)
for i := 0; i < 10; i++ {
go func() {
for j := 0; j < 200; j++ {
ring.push(StoredEvent{
ID: "evt",
EventType: "test",
Data: []byte(`{}`),
Timestamp: time.Now(),
})
}
done <- true
}()
}
for i := 0; i < 10; i++ {
<-done
}
// 只验证不 panic不验证内容并发下顺序无意义
}