package apierror import ( "context" "errors" "testing" bslerror "edge-infra.dev/pkg/edge/api/apierror/bsl" "github.com/99designs/gqlgen/graphql" "github.com/stretchr/testify/assert" "github.com/vektah/gqlparser/v2/ast" ) func TestIsAPIError(t *testing.T) { err := bslerror.New("not found").SetStatusCode(404) ctx := context.Background() ctxPath := graphql.NewPathWithField("banner") ctx = graphql.WithPathContext(ctx, ctxPath) gerr := toAPIError(ctx, err) assert.NotNil(t, gerr) assert.Equal(t, ctxPath.Path(), gerr.Path) assert.Equal(t, err.Error(), gerr.Message) assert.Equal(t, err.Extensions(), gerr.Extensions[AdditionalKey]) } func TestIsNotFoundError(t *testing.T) { err := bslerror.New("not found").SetStatusCode(404) assert.True(t, IsNotFoundError(err)) } func TestIsForbiddenError(t *testing.T) { err := bslerror.New("forbidden").SetStatusCode(403) assert.True(t, IsForbiddenError(err)) } func TestAddAPIErrorToResponse(t *testing.T) { err := bslerror.New("not found").SetStatusCode(404) ctx := graphql.WithResponseContext(context.Background(), graphql.DefaultErrorPresenter, nil) root := &graphql.FieldContext{ Field: graphql.CollectedField{ Field: &ast.Field{ Alias: "banner", }, }, } ctx = graphql.WithFieldContext(ctx, root) assert.Nil(t, AddAPIErrorToResponse(ctx, err)) assert.Error(t, AddAPIErrorToResponse(ctx, errors.New("test"))) } func TestAddEmptyAPIErrorToResponse(t *testing.T) { err := bslerror.New("not found").SetStatusCode(404) ctx := graphql.WithResponseContext(context.Background(), graphql.DefaultErrorPresenter, nil) root := &graphql.FieldContext{ Field: graphql.CollectedField{ Field: &ast.Field{ Alias: "banner", }, }, } ctx = graphql.WithFieldContext(ctx, root) respError := AddEmptyAPIErrorToResponse(ctx, err) assert.NotNil(t, respError) assert.Empty(t, respError.Error()) newError := errors.New("test") respError = AddEmptyAPIErrorToResponse(ctx, newError) assert.Equal(t, newError, respError) }