forked from sashabaranov/go-openai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_accumulator_test.go
94 lines (75 loc) · 2.27 KB
/
error_accumulator_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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package openai //nolint:testpackage // testing private field
import (
"bytes"
"context"
"errors"
"testing"
"github.com/sashabaranov/go-openai/internal/test"
"github.com/sashabaranov/go-openai/internal/test/checks"
)
var (
errTestUnmarshalerFailed = errors.New("test unmarshaler failed")
errTestErrorAccumulatorWriteFailed = errors.New("test error accumulator failed")
)
type (
failingUnMarshaller struct{}
failingErrorBuffer struct{}
)
func (b *failingErrorBuffer) Write(_ []byte) (n int, err error) {
return 0, errTestErrorAccumulatorWriteFailed
}
func (b *failingErrorBuffer) Len() int {
return 0
}
func (b *failingErrorBuffer) Bytes() []byte {
return []byte{}
}
func (*failingUnMarshaller) unmarshal(_ []byte, _ any) error {
return errTestUnmarshalerFailed
}
func TestErrorAccumulatorReturnsUnmarshalerErrors(t *testing.T) {
accumulator := &defaultErrorAccumulator{
buffer: &bytes.Buffer{},
unmarshaler: &failingUnMarshaller{},
}
respErr := accumulator.unmarshalError()
if respErr != nil {
t.Fatalf("Did not return nil with empty buffer: %v", respErr)
}
err := accumulator.write([]byte("{"))
if err != nil {
t.Fatalf("%+v", err)
}
respErr = accumulator.unmarshalError()
if respErr != nil {
t.Fatalf("Did not return nil when unmarshaler failed: %v", respErr)
}
}
func TestErrorByteWriteErrors(t *testing.T) {
accumulator := &defaultErrorAccumulator{
buffer: &failingErrorBuffer{},
unmarshaler: &jsonUnmarshaler{},
}
err := accumulator.write([]byte("{"))
if !errors.Is(err, errTestErrorAccumulatorWriteFailed) {
t.Fatalf("Did not return error when write failed: %v", err)
}
}
func TestErrorAccumulatorWriteErrors(t *testing.T) {
var err error
ts := test.NewTestServer().OpenAITestServer()
ts.Start()
defer ts.Close()
config := DefaultConfig(test.GetTestToken())
config.BaseURL = ts.URL + "/v1"
client := NewClientWithConfig(config)
ctx := context.Background()
stream, err := client.CreateChatCompletionStream(ctx, ChatCompletionRequest{})
checks.NoError(t, err)
stream.errAccumulator = &defaultErrorAccumulator{
buffer: &failingErrorBuffer{},
unmarshaler: &jsonUnmarshaler{},
}
_, err = stream.Recv()
checks.ErrorIs(t, err, errTestErrorAccumulatorWriteFailed, "Did not return error when write failed", err.Error())
}