File size: 1,103 Bytes
8d3471e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package stream

import (
	"context"
	"strings"
	"testing"

	"ds2api/internal/sse"
)

func TestConsumeSSEPrefersContextCancellationOverReadyParsedLines(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	cancel()

	var finalized bool
	var contextDone bool
	var parsedCalled bool

	ConsumeSSE(ConsumeConfig{
		Context:           ctx,
		Body:              strings.NewReader("data: {\"p\":\"response/content\",\"v\":\"hello\"}\n\ndata: [DONE]\n"),
		ThinkingEnabled:   false,
		InitialType:       "text",
		KeepAliveInterval: 0,
	}, ConsumeHooks{
		OnParsed: func(_ sse.LineResult) ParsedDecision {
			parsedCalled = true
			return ParsedDecision{}
		},
		OnFinalize: func(_ StopReason, _ error) {
			finalized = true
		},
		OnContextDone: func() {
			contextDone = true
		},
	})

	if !contextDone {
		t.Fatal("expected OnContextDone to run for an already-cancelled context")
	}
	if finalized {
		t.Fatal("expected OnFinalize not to run after context cancellation wins")
	}
	if parsedCalled {
		t.Fatal("expected parsed lines not to be processed after context cancellation wins")
	}
}