Skip to content

Commit

Permalink
add test case for cancelation
Browse files Browse the repository at this point in the history
Signed-off-by: Sandor Szücs <[email protected]>
  • Loading branch information
szuecs committed Jan 5, 2024
1 parent a298604 commit a12a7c3
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions io/log_stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ package io
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/zalando/skipper/filters/flowid"
)
Expand Down Expand Up @@ -135,4 +137,80 @@ func TestHttpBodyLogBody(t *testing.T) {
}
})

t.Run("logbody response with canceled request", func(t *testing.T) {
sent := strings.Repeat("b", 1024)
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b := make([]byte, 0, 1024)
buf := bytes.NewBuffer(b)
_, err := io.Copy(buf, r.Body)
if err != nil {
t.Fatalf("Failed to read body on backend receiver: %v", err)
}

if got := buf.String(); got != sent {
t.Fatalf("Failed to get request body in backend. want: %q, got: %q", sent, got)
}
w.WriteHeader(200)
w.(http.Flusher).Flush()
time.Sleep(100 * time.Millisecond)
w.Write([]byte("OK"))
}))
defer backend.Close()

lgbuf := &bytes.Buffer{}

var b mybuf
b.buf = bytes.NewBufferString(sent)

ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", backend.URL, b.buf)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Add(flowid.HeaderName, "qux")

rsp, err := backend.Client().Do(req)
if err != nil {
t.Fatalf("Failed to do request, expect no error, but go: %v", err)
}
if rsp.StatusCode != http.StatusOK {
t.Fatalf("Failed to get the expected status code 200, got: %d", rsp.StatusCode)
}

lg := func(format string, args ...interface{}) {
s := fmt.Sprintf(format, args...)
lgbuf.WriteString(s)
}
body := LogBody(
context.Background(),
func(chunk []byte) {
lg(
`logBody("response") %s: %s`,
req.Header.Get(flowid.HeaderName),
chunk)
},
rsp.Body,
)
defer body.Close()
rsp.Body = body

var buf bytes.Buffer
_, err = io.Copy(&buf, rsp.Body)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Failed to get expected error: %v", err)
}

rsp.Body.Close()
rspBody := buf.String()
if rspBody != "" {
t.Fatalf("Failed to get empty response body, got: %q", rspBody)
}

lgData := lgbuf.String()
if lgData != "" {
t.Fatalf("Failed to get empty log, got: %q", lgData)
}
})

}

0 comments on commit a12a7c3

Please sign in to comment.