forked from sashabaranov/go-openai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_reader_test.go
65 lines (54 loc) · 1.94 KB
/
stream_reader_test.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package openai //nolint:testpackage // testing private field
import (
"bufio"
"bytes"
"errors"
"testing"
utils "github.com/sashabaranov/go-openai/internal"
"github.com/sashabaranov/go-openai/internal/test"
"github.com/sashabaranov/go-openai/internal/test/checks"
)
var errTestUnmarshalerFailed = errors.New("test unmarshaler failed")
type failingUnMarshaller struct{}
func (*failingUnMarshaller) Unmarshal(_ []byte, _ any) error {
return errTestUnmarshalerFailed
}
func TestStreamReaderReturnsUnmarshalerErrors(t *testing.T) {
stream := &streamReader[ChatCompletionStreamResponse]{
errAccumulator: utils.NewErrorAccumulator(),
unmarshaler: &failingUnMarshaller{},
}
respErr := stream.unmarshalError()
if respErr != nil {
t.Fatalf("Did not return nil with empty buffer: %v", respErr)
}
err := stream.errAccumulator.Write([]byte("{"))
if err != nil {
t.Fatalf("%+v", err)
}
respErr = stream.unmarshalError()
if respErr != nil {
t.Fatalf("Did not return nil when unmarshaler failed: %v", respErr)
}
}
func TestStreamReaderReturnsErrTooManyEmptyStreamMessages(t *testing.T) {
stream := &streamReader[ChatCompletionStreamResponse]{
emptyMessagesLimit: 3,
reader: bufio.NewReader(bytes.NewReader([]byte("\n\n\n\n"))),
errAccumulator: utils.NewErrorAccumulator(),
unmarshaler: &utils.JSONUnmarshaler{},
}
_, err := stream.Recv()
checks.ErrorIs(t, err, ErrTooManyEmptyStreamMessages, "Did not return error when recv failed", err.Error())
}
func TestStreamReaderReturnsErrTestErrorAccumulatorWriteFailed(t *testing.T) {
stream := &streamReader[ChatCompletionStreamResponse]{
reader: bufio.NewReader(bytes.NewReader([]byte("\n"))),
errAccumulator: &utils.DefaultErrorAccumulator{
Buffer: &test.FailingErrorBuffer{},
},
unmarshaler: &utils.JSONUnmarshaler{},
}
_, err := stream.Recv()
checks.ErrorIs(t, err, test.ErrTestErrorAccumulatorWriteFailed, "Did not return error when write failed", err.Error())
}