Files

674 lines
23 KiB
Go

package httperror_test
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/cockroachdb/errors"
"github.com/effective-security/porto/xhttp/correlation"
"github.com/effective-security/porto/xhttp/httperror"
"github.com/effective-security/xdb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
anypb "google.golang.org/protobuf/types/known/anypb"
)
func TestErrorCorrelation(t *testing.T) {
ctx := correlation.WithID(context.Background())
cid := correlation.ID(ctx)
assert.NotEmpty(t, cid)
ne2 := httperror.NewFromCtx(ctx, http.StatusBadRequest, httperror.CodeInvalidJSON, "some error")
assert.Equal(t, fmt.Sprintf("request %s: invalid_json: some error", cid), ne2.Error())
assert.Equal(t, cid, httperror.CorrelationID(ne2))
rs := ne2.GRPCStatus()
assert.Equal(t, "rpc error: code = InvalidArgument desc = some error", rs.String())
}
func TestErrorCode_JSON(t *testing.T) {
v := map[string]string{"foo": httperror.CodeInvalidJSON}
b, err := json.Marshal(&v)
require.NoError(t, err, "Unable to marshal to json")
exp := `{"foo":"invalid_json"}`
assert.Equal(t, exp, string(b), "Unexpected JSON serializtion of ErrorCode")
}
func TestError_Error(t *testing.T) {
// compile error if Error doesn't impl error
var _ error = &httperror.Error{}
e := httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "Bob")
assert.Equal(t, "invalid_json: Bob", e.Error())
ctx := correlation.WithID(context.Background())
cid := correlation.ID(ctx)
assert.NotEmpty(t, cid)
e.WithContext(ctx)
assert.Equal(t, fmt.Sprintf("request %s: invalid_json: Bob", cid), e.Error())
e = e.WithCause(errors.New("some other error"))
assert.EqualError(t, e, fmt.Sprintf("request %s: invalid_json: Bob", cid))
}
func TestError_Unwrap(t *testing.T) {
e := httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "Bob")
assert.Equal(t, "invalid_json: Bob", e.Error())
assert.Nil(t, e.Unwrap())
e = e.WithCause(errors.New("some other error"))
assert.EqualError(t, e.Unwrap(), "some other error")
e = e.WithCause(errors.WithMessage(errors.New("some other error"), "wrapped"))
assert.EqualError(t, e.Unwrap(), "some other error")
}
func TestError_Nil(t *testing.T) {
var e *httperror.Error
assert.Nil(t, e)
assert.Equal(t, "nil", e.Error())
}
func TestError_ManyErrorIsError(t *testing.T) {
oerr := errors.New("original")
err := httperror.NewMany(http.StatusTooManyRequests, httperror.CodeRateLimitExceeded, "There were 42 errors!").
WithCause(oerr)
var _ error = err // won't compile if ManyError doesn't impl error
assert.Equal(t, "rate_limit_exceeded: There were 42 errors!", err.Error())
err.RequestID = "123"
assert.Equal(t, "request 123: rate_limit_exceeded: There were 42 errors!", err.Error())
assert.Equal(t, err.RequestID, err.CorrelationID())
assert.Equal(t, codes.ResourceExhausted, err.GRPCStatus().Code())
}
func TestError_ManyError(t *testing.T) {
var many *httperror.ManyError
assert.Nil(t, many)
assert.Equal(t, "nil", many.Error())
many = many.Add("testing", errors.Errorf("from nil"))
require.NotNil(t, many)
assert.NotNil(t, many.Errors)
assert.Equal(t, "unexpected: from nil", many.Error())
many.Code = ""
assert.NotNil(t, many.Errors)
assert.Equal(t, "unexpected: from nil", many.Error())
}
func TestError_AddErrorToManyError(t *testing.T) {
me := httperror.NewMany(http.StatusBadRequest, httperror.CodeRateLimitExceeded, "There were 42 errors!")
_ = me.Add("one", errors.Errorf("test error 1"))
assert.Equal(t, 1, len(me.Errors))
_ = me.Add("two", httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "test error 2"))
assert.Equal(t, 2, len(me.Errors))
assert.True(t, me.HasErrors(), "many error contains two errors")
assert.Contains(t, me.Errors, "one")
assert.Contains(t, me.Errors, "two")
}
func TestError_AddErrorToNilManyError(t *testing.T) {
var me httperror.ManyError
_ = me.Add("one", errors.Errorf("test error 1"))
assert.Equal(t, 1, len(me.Errors))
me.Add("two", httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "test error 2"))
assert.Equal(t, 2, len(me.Errors))
assert.True(t, me.HasErrors(), "many error contains two errors")
assert.Contains(t, me.Errors, "one")
assert.Contains(t, me.Errors, "two")
}
func TestError_WriteHTTPResponse(t *testing.T) {
single := httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "test error 2")
single.RequestID = "123"
many := httperror.NewMany(http.StatusBadRequest, httperror.CodeRateLimitExceeded, "There were 2 errors!")
_ = many.Add("one", errors.Errorf("test error 1"))
_ = many.Add("two", httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "test error 2"))
many.RequestID = "123"
many.Add("one", errors.Errorf("test error 1"))
many.Add("two", httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "test error 2"))
assert.EqualError(t, many.Cause(), "test error 1")
manyNil := &httperror.ManyError{HTTPStatus: http.StatusBadRequest}
_ = manyNil.Add("one", errors.Errorf("test error 1"))
_ = manyNil.Add("two", httperror.New(http.StatusBadRequest, httperror.CodeInvalidJSON, "test error 2"))
cases := []struct {
name string
err error
urlPath string
expected string
}{
{
name: "single_raw_json",
err: single,
urlPath: "/",
expected: `{"code":"invalid_json","request_id":"123","message":"test error 2"}`,
},
{
name: "single_pretty_json",
err: single,
urlPath: "/?pp",
expected: `{
"code": "invalid_json",
"message": "test error 2",
"request_id": "123"
}`,
},
{
name: "many_pretty_json",
err: many,
urlPath: "/?pp",
expected: `{
"code": "rate_limit_exceeded",
"errors": {
"one": {
"code": "unexpected",
"message": "test error 1"
},
"two": {
"code": "invalid_json",
"message": "test error 2"
}
},
"message": "There were 2 errors!",
"request_id": "123"
}`,
},
{
name: "manynil_pretty_json",
err: manyNil,
urlPath: "/?pp",
expected: `{
"errors": {
"one": {
"code": "unexpected",
"message": "test error 1"
},
"two": {
"code": "invalid_json",
"message": "test error 2"
}
}
}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
w := httptest.NewRecorder()
r, err := http.NewRequest(http.MethodGet, tc.urlPath, nil)
require.NoError(t, err)
switch tc.err.(type) {
case *httperror.ManyError:
tc.err.(*httperror.ManyError).WriteHTTPResponse(w, r)
default:
tc.err.(*httperror.Error).WriteHTTPResponse(w, r)
}
assert.Equal(t, tc.expected, w.Body.String())
})
}
}
func TestError_IsInvalidRequestError(t *testing.T) {
assert.True(t, httperror.IsInvalidRequestError(errors.Errorf("invalid ID")))
assert.True(t, httperror.IsInvalidRequestError(errors.Errorf("Invalid ID")))
assert.True(t, httperror.IsInvalidRequestError(errors.Errorf("bad request")))
assert.True(t, httperror.IsInvalidRequestError(errors.Errorf("400: invalid")))
}
func TestError_IsNotFound(t *testing.T) {
assert.True(t, httperror.IsNotFound(errors.Errorf("not found")))
assert.True(t, httperror.IsNotFound(errors.Errorf("Not Found")))
assert.True(t, httperror.IsNotFound(errors.Errorf("404: not found")))
assert.True(t, httperror.IsNotFound(errors.Wrap(sql.ErrNoRows, "failed")))
assert.True(t, httperror.IsNotFound(errors.Wrap(errors.New("sql: no rows in result set"), "failed")))
assert.True(t, httperror.IsNotFound(errors.Wrap(&xdb.ErrorNotFound{}, "failed")))
}
func TestError_IsTimeout(t *testing.T) {
assert.True(t, httperror.IsTimeout(errors.Errorf("context deadline exceeded")))
assert.True(t, httperror.IsTimeout(errors.Errorf("request timeout")))
assert.True(t, httperror.IsTimeout(errors.Errorf("Request Timeout")))
assert.True(t, httperror.IsTimeout(errors.Wrap(context.DeadlineExceeded, "failed")))
assert.True(t, httperror.IsTimeout(errors.Wrap(context.Canceled, "failed")))
}
func TestError_NewFromPb(t *testing.T) {
err := httperror.InvalidParam("test")
assert.Equal(t, err.Error(), httperror.NewFromPb(err).Error())
assert.Equal(t, codes.InvalidArgument, httperror.GRPCCode(err))
assert.Equal(t, "test", httperror.GRPCMessage(err))
err2 := errors.Errorf("test")
assert.Equal(t, "unexpected: test", httperror.NewFromPb(err2).Error())
assert.Equal(t, codes.Internal, httperror.GRPCCode(err2))
assert.Equal(t, "test", httperror.GRPCMessage(err2))
assert.Equal(t, "unavailable: request timed out", httperror.NewFromPb(ErrGRPCTimeout).Error())
}
func TestError_Status(t *testing.T) {
assert.Equal(t, http.StatusOK, httperror.Status(nil))
err1 := httperror.Status(httperror.NotFound("test"))
assert.Equal(t, http.StatusNotFound, err1)
err2 := httperror.Status(status.New(codes.NotFound, "test").Err())
assert.Equal(t, http.StatusNotFound, err2)
assert.Equal(t, http.StatusInternalServerError, httperror.Status(errors.New("test")))
}
func TestError_Is(t *testing.T) {
err1 := httperror.NotFound("test")
err2 := status.New(codes.NotFound, "test").Err()
err3 := httperror.NotFound("test").WithCause(err2)
assert.False(t, err1.Is(err2))
assert.True(t, err1.Is(err3))
assert.EqualError(t, err3.Cause(), "rpc error: code = NotFound desc = test")
}
func TestError_WrapMsg(t *testing.T) {
tcases := []struct {
err error
expected string
}{
{err: errors.New("not found"), expected: "not_found: other message"},
{err: errors.Errorf("invalid ID"), expected: "invalid_request: other message"},
{err: errors.Errorf("bad request"), expected: "invalid_request: other message"},
{err: errors.Errorf("400: invalid"), expected: "invalid_request: other message"},
{err: errors.Errorf("context deadline exceeded"), expected: "timeout: other message"},
{err: errors.Errorf("request timeout"), expected: "timeout: other message"},
{err: errors.Wrap(context.DeadlineExceeded, "failed"), expected: "timeout: other message"},
{err: errors.Wrap(context.Canceled, "failed"), expected: "timeout: other message"},
}
for _, tc := range tcases {
assert.Equal(t, tc.expected, httperror.Wrap(tc.err, "other message").Error())
}
}
func TestError_Wrap(t *testing.T) {
werr1 := httperror.Wrap(errors.New("no rows in result set"), "wrapped")
assert.EqualError(t, werr1, "not_found: wrapped")
werr1s := httperror.Wrap(errors.New("no rows in result set"))
assert.EqualError(t, werr1s, "not_found: no rows in result set")
err := status.New(codes.NotFound, "no rows in result set").Err()
werr2 := httperror.Wrap(err, "wrapped")
assert.EqualError(t, werr2, "not_found: wrapped")
werr2s := httperror.Wrap(err)
assert.EqualError(t, werr2s, "not_found: no rows in result set")
werr3 := httperror.Wrap(werr2, "wrapped2")
assert.EqualError(t, werr3, "not_found: wrapped2")
assert.EqualError(t, werr3.Unwrap(), "rpc error: code = NotFound desc = no rows in result set")
werr3s := httperror.Wrap(werr2s)
assert.EqualError(t, werr3s, "not_found: no rows in result set")
many := httperror.NewMany(werr1.HTTPStatus, werr1.Code, "%s", werr1.Message).WithCause(errors.New("many cause"))
many.Add("werr1", werr1)
assert.EqualError(t, many, "not_found: wrapped")
werr4 := httperror.Wrap(many, "wrappedMany")
assert.EqualError(t, werr4, "not_found: wrappedMany")
assert.EqualError(t, werr4.Unwrap(), many.Error())
ctx := correlation.WithID(context.Background())
cid := correlation.ID(ctx)
assert.NotEmpty(t, cid)
werr4 = httperror.WrapWithCtx(ctx, werr3, "wrapped%d", 3)
assert.EqualError(t, werr4, fmt.Sprintf("request %s: not_found: wrapped3", cid))
assert.EqualError(t, werr4.Unwrap(), "rpc error: code = NotFound desc = no rows in result set")
werr4s := httperror.WrapWithCtx(ctx, werr3)
assert.EqualError(t, werr4s, fmt.Sprintf("request %s: not_found: wrapped2", cid))
werr5 := httperror.WrapWithCtx(ctx, nil, "wrapped nil")
assert.EqualError(t, werr5, fmt.Sprintf("request %s: unexpected: wrapped nil", cid))
assert.Nil(t, werr5.Unwrap())
werr6 := httperror.WrapWithCtx(ctx, werr5, "wrapped 5")
assert.EqualError(t, werr6, fmt.Sprintf("request %s: unexpected: wrapped 5", cid))
assert.EqualError(t, werr6.Unwrap(), werr5.Error())
werr6s := httperror.WrapWithCtx(ctx, werr5)
assert.EqualError(t, werr6s, fmt.Sprintf("request %s: unexpected: wrapped nil", cid))
}
func TestGRPCError(t *testing.T) {
e1 := status.New(codes.PermissionDenied, "permission denied").Err()
e2 := ErrGRPCPermissionDenied
e3 := ErrGRPCTimeout
require.Equal(t, e1.Error(), e2.Error())
assert.NotEqual(t, e1.Error(), e3.Error())
_, ok := status.FromError(e1)
assert.True(t, ok)
ne := httperror.NewGrpcFromCtx(context.Background(), codes.Unavailable, "some error")
ev4, ok := status.FromError(ne)
assert.True(t, ok)
assert.Equal(t, codes.Unavailable, ev4.Code())
rs := ne.GRPCStatus()
assert.Equal(t, "rpc error: code = Unavailable desc = some error", rs.String())
rse := rs.Err()
assert.Equal(t, codes.Unavailable, httperror.GRPCCode(rse))
assert.Equal(t, "some error", httperror.GRPCMessage(rse))
ctx := correlation.WithID(context.Background())
cid := correlation.ID(ctx)
assert.NotEmpty(t, cid)
ne2 := httperror.NewGrpcFromCtx(ctx, codes.Unavailable, "some error")
assert.Equal(t, fmt.Sprintf("request %s: unavailable: some error", cid), ne2.Error())
assert.Equal(t, cid, httperror.CorrelationID(ne2))
rs = ne2.GRPCStatus()
assert.Equal(t, "rpc error: code = Unavailable desc = some error", rs.String())
ne = httperror.NewGrpc(codes.Unavailable, "some error")
ev4, ok = status.FromError(ne)
assert.True(t, ok)
assert.Equal(t, codes.Unavailable, ev4.Code())
}
func TestIsNotFoundError(t *testing.T) {
assert.True(t, xdb.IsNotFoundError(sql.ErrNoRows))
assert.True(t, xdb.IsNotFoundError(errors.WithMessage(errors.New("sql: no rows in result set"), "failed")))
assert.False(t, xdb.IsNotFoundError(nil))
assert.False(t, httperror.IsInvalidModel(nil))
}
// grpc error
var (
ErrGRPCTimeout = status.New(codes.Unavailable, "request timed out").Err()
ErrGRPCPermissionDenied = status.New(codes.PermissionDenied, "permission denied").Err()
ErrGRPCInvalidArgument = status.New(codes.InvalidArgument, "invalid argument").Err()
)
// overWire returns a copy of m decoded from its protobuf encoding, as a gRPC
// peer receives a status.
func overWire[T proto.Message](t *testing.T, m T) T {
t.Helper()
b, err := proto.Marshal(m)
require.NoError(t, err)
out := m.ProtoReflect().New().Interface().(T)
require.NoError(t, proto.Unmarshal(b, out))
return out
}
func TestError_GRPCRoundTrip(t *testing.T) {
t.Parallel()
ctx := correlation.WithID(context.Background())
cid := correlation.ID(ctx)
inconsistent, err := status.New(codes.InvalidArgument, "big").WithDetails(&anypb.Any{
TypeUrl: "@httperror.code",
Value: []byte(httperror.CodeRequestTooLarge),
})
require.NoError(t, err)
for _, tc := range []struct {
name string
err error
rpc codes.Code
httpStatus int
code string
requestID string
}{
{
name: "request too large",
err: httperror.RequestTooLarge("big").WithContext(ctx),
rpc: codes.ResourceExhausted,
httpStatus: http.StatusRequestEntityTooLarge,
code: httperror.CodeRequestTooLarge,
requestID: cid,
},
{
name: "many request too large",
err: httperror.NewMany(http.StatusRequestEntityTooLarge, httperror.CodeRequestTooLarge, "big"),
rpc: codes.ResourceExhausted,
httpStatus: http.StatusRequestEntityTooLarge,
code: httperror.CodeRequestTooLarge,
},
{
name: "rate limit keeps 429",
err: httperror.RateLimitExceeded("slow down"),
rpc: codes.ResourceExhausted,
httpStatus: http.StatusTooManyRequests,
code: "too_many_requests",
},
{
name: "grpc message size keeps 429",
err: status.Error(codes.ResourceExhausted, "grpc: received message larger than max"),
rpc: codes.ResourceExhausted,
httpStatus: http.StatusTooManyRequests,
code: "too_many_requests",
},
{
name: "invalid param",
err: httperror.InvalidParam("id"),
rpc: codes.InvalidArgument,
httpStatus: http.StatusBadRequest,
code: "bad_request",
},
{
name: "detail inconsistent with code is ignored",
err: inconsistent.Err(),
rpc: codes.InvalidArgument,
httpStatus: http.StatusBadRequest,
code: "bad_request",
},
{
name: "unauthorized keeps 401",
err: httperror.Unauthorized("who are you"),
rpc: codes.Unauthenticated,
httpStatus: http.StatusUnauthorized,
code: "unauthorized",
},
{
name: "forbidden keeps 403",
err: httperror.Forbidden("not for you"),
rpc: codes.PermissionDenied,
httpStatus: http.StatusForbidden,
code: "forbidden",
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
received := status.ErrorProto(overWire(t, status.Convert(tc.err).Proto()))
e := httperror.NewFromPb(received)
assert.Equal(t, tc.rpc, e.RPCStatus)
assert.Equal(t, tc.httpStatus, e.HTTPStatus)
assert.Equal(t, tc.code, e.Code)
assert.Equal(t, tc.requestID, e.RequestID)
assert.Equal(t, tc.httpStatus, httperror.Status(received))
wrapped := httperror.Wrap(received, "proxied")
assert.Equal(t, tc.httpStatus, wrapped.HTTPStatus)
assert.Equal(t, tc.code, wrapped.Code)
})
}
}
func TestError_GRPCStatusWithoutRPCCode(t *testing.T) {
t.Parallel()
// A custom code has no gRPC mapping (OK), which cannot carry details.
e := httperror.New(http.StatusTeapot, "custom", "brew")
e.RequestID = "123"
st := e.GRPCStatus()
require.NotNil(t, st)
assert.Equal(t, codes.OK, st.Code())
assert.Empty(t, st.Details())
}
func TestError_WriteHTTPResponse_SharedValue(t *testing.T) {
t.Parallel()
shared := httperror.NotReady("not yet")
sharedMany := httperror.NewMany(http.StatusBadRequest, httperror.CodeInvalidRequest, "many")
sharedMany.Add("one", httperror.InvalidParam("one"))
write := func(ctx context.Context, e interface {
WriteHTTPResponse(http.ResponseWriter, *http.Request)
}) string {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
e.WriteHTTPResponse(w, r)
return w.Body.String()
}
ctx1 := correlation.WithID(context.Background())
ctx2 := correlation.WithID(context.Background())
cid1 := correlation.ID(ctx1)
cid2 := correlation.ID(ctx2)
require.NotEqual(t, cid1, cid2)
assert.Equal(t, fmt.Sprintf(`{"code":"not_ready","request_id":"%s","message":"not yet"}`, cid1), write(ctx1, shared))
assert.Equal(t, fmt.Sprintf(`{"code":"not_ready","request_id":"%s","message":"not yet"}`, cid2), write(ctx2, shared))
assert.Equal(t, `{"code":"not_ready","message":"not yet"}`, write(context.Background(), shared))
assert.Empty(t, shared.RequestID, "WriteHTTPResponse must not modify the shared error")
expMany := `{"code":"invalid_request","request_id":"%s","message":"many","errors":{"one":{"code":"invalid_parameter","message":"one"}}}`
assert.Equal(t, fmt.Sprintf(expMany, cid1), write(ctx1, sharedMany))
assert.Equal(t, fmt.Sprintf(expMany, cid2), write(ctx2, sharedMany))
assert.Empty(t, sharedMany.RequestID, "WriteHTTPResponse must not modify the shared error")
// An explicit RequestID wins over the request's correlation ID.
own := httperror.NotReady("not yet")
own.RequestID = "own"
assert.Equal(t, `{"code":"not_ready","request_id":"own","message":"not yet"}`, write(ctx1, own))
}
func TestError_WriteHTTPResponse_Concurrent(t *testing.T) {
t.Parallel()
shared := httperror.NotReady("not yet")
sharedMany := httperror.NewMany(http.StatusBadRequest, httperror.CodeInvalidRequest, "many")
const writers = 16
var wg sync.WaitGroup
for i := range writers {
wg.Add(1)
go func() {
defer wg.Done()
ctx := correlation.WithID(context.Background())
cid := correlation.ID(ctx)
r := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
w := httptest.NewRecorder()
shared.WriteHTTPResponse(w, r)
assert.Equal(t, fmt.Sprintf(`{"code":"not_ready","request_id":"%s","message":"not yet"}`, cid), w.Body.String())
// Add races with the encoder unless WriteHTTPResponse holds the lock.
sharedMany.Add(fmt.Sprintf("key%d", i), httperror.InvalidParam("one"))
w = httptest.NewRecorder()
sharedMany.WriteHTTPResponse(w, r)
assert.Contains(t, w.Body.String(), fmt.Sprintf(`"request_id":"%s"`, cid))
}()
}
wg.Wait()
assert.Empty(t, shared.RequestID)
assert.Empty(t, sharedMany.RequestID)
assert.Len(t, sharedMany.Errors, writers)
}
func TestError_WrapMsg_Format(t *testing.T) {
t.Parallel()
base := errors.New("base")
assert.Equal(t, "unexpected: base", httperror.Wrap(base).Error())
assert.Equal(t, "unexpected: item 7 failed", httperror.Wrap(base, "item %d failed", 7).Error())
assert.Equal(t, "unexpected: 7", httperror.Wrap(base, 7).Error())
// A non-string first value is not a format: nothing panics, the values are joined.
assert.Equal(t, "unexpected: 7 8", httperror.Wrap(base, 7, 8).Error())
assert.Equal(t, "7 8", httperror.Wrap(httperror.InvalidParam("id"), 7, 8).Message)
}
// blockingWriter is a ResponseWriter whose first Write blocks until release
// is closed, simulating a slow client.
type blockingWriter struct {
httptest.ResponseRecorder
release <-chan struct{}
blocked chan struct{}
once sync.Once
}
func (w *blockingWriter) Write(p []byte) (int, error) {
w.once.Do(func() {
close(w.blocked)
<-w.release
})
return w.ResponseRecorder.Write(p)
}
func TestError_ManyErrorWriteDoesNotHoldLock(t *testing.T) {
t.Parallel()
const wait = 5 * time.Second
shared := httperror.NewMany(http.StatusBadRequest, httperror.CodeInvalidRequest, "many")
shared.Add("one", httperror.InvalidParam("one"))
release := make(chan struct{})
slow := &blockingWriter{
ResponseRecorder: *httptest.NewRecorder(),
release: release,
blocked: make(chan struct{}),
}
r := httptest.NewRequest(http.MethodGet, "/", nil)
slowDone := make(chan struct{})
go func() {
defer close(slowDone)
shared.WriteHTTPResponse(slow, r)
}()
select {
case <-slow.blocked:
case <-time.After(wait):
t.Fatal("the slow response never started writing")
}
// While the slow client stalls, other users of the shared error proceed.
addDone := make(chan struct{})
go func() {
defer close(addDone)
shared.Add("two", httperror.InvalidParam("two"))
}()
select {
case <-addDone:
case <-time.After(wait):
t.Fatal("Add blocked behind a slow response write")
}
fast := httptest.NewRecorder()
fastDone := make(chan struct{})
go func() {
defer close(fastDone)
shared.WriteHTTPResponse(fast, r)
}()
select {
case <-fastDone:
case <-time.After(wait):
t.Fatal("a second response blocked behind a slow response write")
}
// the compact encoder writes map keys in iteration order, so compare
// the JSON structurally
assert.JSONEq(t, `{"code":"invalid_request","message":"many","errors":{"one":{"code":"invalid_parameter","message":"one"},"two":{"code":"invalid_parameter","message":"two"}}}`, fast.Body.String())
close(release)
select {
case <-slowDone:
case <-time.After(wait):
t.Fatal("the slow response never finished")
}
// The slow response was snapshotted before "two" was added.
assert.JSONEq(t, `{"code":"invalid_request","message":"many","errors":{"one":{"code":"invalid_parameter","message":"one"}}}`, slow.Body.String())
}