github.com/anthropics/anthropic-sdk-go@v1.70.1/packages/jsonl/jsonl_test.go (about) 1 package jsonl 2 3 import ( 4 "bufio" 5 "errors" 6 "io" 7 "net/http" 8 "strings" 9 "testing" 10 ) 11 12 // Close must not panic when the stream was constructed with an error and has no reader. 13 func TestCloseNilPanic(t *testing.T) { 14 stream := NewStream[map[string]any](nil, io.ErrUnexpectedEOF) 15 defer func() { 16 if r := recover(); r != nil { 17 t.Fatalf("Close panicked: %v", r) 18 } 19 }() 20 if err := stream.Close(); err != nil { 21 t.Fatalf("Close returned unexpected error: %v", err) 22 } 23 } 24 25 // A JSONL line larger than the default 64 KiB scanner buffer must yield one record. 26 func TestLargeLine(t *testing.T) { 27 big := strings.Repeat("x", bufio.MaxScanTokenSize+10) 28 body := `{"custom_id":"a","payload":"` + big + `"}` + "\n" 29 res := &http.Response{Body: io.NopCloser(strings.NewReader(body))} 30 31 stream := NewStream[map[string]any](res, nil) 32 n := 0 33 for stream.Next() { 34 n++ 35 } 36 if n != 1 { 37 t.Fatalf("expected 1 record, got %d", n) 38 } 39 if err := stream.Err(); err != nil { 40 t.Fatalf("Err() = %v, want nil", err) 41 } 42 } 43 44 // A read error from the body must surface via Err rather than look like clean EOF. 45 func TestScannerErrorSurfaced(t *testing.T) { 46 res := &http.Response{Body: io.NopCloser(&errReader{fail: io.ErrClosedPipe})} 47 stream := NewStream[map[string]any](res, nil) 48 for stream.Next() { 49 } 50 if err := stream.Err(); !errors.Is(err, io.ErrClosedPipe) { 51 t.Fatalf("Err() = %v, want error matching io.ErrClosedPipe", err) 52 } 53 } 54 55 type errReader struct{ fail error } 56 57 func (r *errReader) Read(p []byte) (int, error) { return 0, r.fail }