Files
lincodex/backend/internal/adapter/primary/http/v1/api_test.go
T

55 lines
2.0 KiB
Go

package v1
import (
"context"
"errors"
"log/slog"
"net/http"
"reflect"
"testing"
"lincodex/backend/internal/adapter/primary/http/problem"
)
// Once the contract defines a default error response, ogen adds NewError to
// api.Handler and api.UnimplementedHandler supplies one that returns a zero
// status code, which the generated encoder sends as HTTP 200. A handler error
// would then look like a success, so the composite must define its own NewError.
func TestHandlerNewErrorDoesNotReportSuccess(t *testing.T) {
newError := reflect.ValueOf(NewHandler(nil, problem.NewResponder(slog.New(slog.DiscardHandler)))).MethodByName("NewError")
if !newError.IsValid() {
t.Skip("the contract has no default error response, so the generated server has no NewError")
}
contextType := reflect.TypeFor[context.Context]()
errorType := reflect.TypeFor[error]()
signature := newError.Type()
if signature.NumIn() != 2 || signature.In(0) != contextType || signature.In(1) != errorType || signature.NumOut() != 1 {
t.Fatalf("NewError has signature %s, want func(context.Context, error) <error response>", signature)
}
results := newError.Call([]reflect.Value{
reflect.ValueOf(context.Background()),
reflect.ValueOf(errors.New("handler failure")),
})
if len(results) != 1 {
t.Fatalf("NewError() returned %d values, want 1", len(results))
}
response := results[0]
if response.Kind() == reflect.Pointer {
if response.IsNil() {
t.Fatal("NewError() returned nil")
}
response = response.Elem()
}
if response.Kind() != reflect.Struct {
t.Fatalf("NewError() result kind = %s, want struct", response.Kind())
}
statusCode := response.FieldByName("StatusCode")
if !statusCode.IsValid() || !statusCode.CanInt() {
t.Fatalf("NewError() result %s has no integer StatusCode field", response.Type())
}
if code := statusCode.Int(); code < http.StatusBadRequest {
t.Fatalf("v1.Handler must define NewError with an error status: NewError yields status %d; the promoted api.UnimplementedHandler.NewError yields 0, which ogen encodes as HTTP 200", code)
}
}