| 1 | package testutil |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "testing" |
| 7 | |
| 8 | "reasonix/internal/provider" |
| 9 | ) |
| 10 | |
| 11 | func TestMockProviderStreamHonorsCanceledContext(t *testing.T) { |
| 12 | ctx, cancel := context.WithCancel(context.Background()) |
| 13 | cancel() |
| 14 | |
| 15 | mp := NewMock("mock", Turn{Text: "hello"}) |
| 16 | ch, err := mp.Stream(ctx, provider.Request{}) |
| 17 | if !errors.Is(err, context.Canceled) { |
| 18 | t.Fatalf("Stream error = %v, want context.Canceled", err) |
| 19 | } |
| 20 | if ch != nil { |
| 21 | t.Fatal("Stream returned a channel for canceled context") |
| 22 | } |
| 23 | if got := mp.CallCount(); got != 0 { |
| 24 | t.Fatalf("CallCount = %d, want 0", got) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | func TestMockProviderStreamStopsOnContextCancellation(t *testing.T) { |
| 29 | ctx, cancel := context.WithCancel(context.Background()) |
| 30 | mp := NewMock("mock", Turn{ |
| 31 | Text: "first", |
| 32 | ToolCalls: []provider.ToolCall{ |
| 33 | {ID: "call-1", Name: "noop", Arguments: `{}`}, |
| 34 | }, |
| 35 | }) |
| 36 | |
| 37 | ch, err := mp.Stream(ctx, provider.Request{}) |
| 38 | if err != nil { |
| 39 | t.Fatalf("Stream: %v", err) |
| 40 | } |
| 41 | if got := (<-ch).Text; got != "first" { |
| 42 | t.Fatalf("first chunk text = %q, want first", got) |
| 43 | } |
| 44 | cancel() |
| 45 | chunk, ok := <-ch |
| 46 | if !ok { |
| 47 | t.Fatal("stream closed without returning cancellation error") |
| 48 | } |
| 49 | if chunk.Type != provider.ChunkError || !errors.Is(chunk.Err, context.Canceled) { |
| 50 | t.Fatalf("chunk after cancellation = %#v, want context.Canceled error", chunk) |
| 51 | } |
| 52 | if _, ok := <-ch; ok { |
| 53 | t.Fatal("stream stayed open after cancellation error") |
| 54 | } |
| 55 | } |
| 56 |