...

Source file src/edge-infra.dev/pkg/edge/api/apierror/converter_test.go

Documentation: edge-infra.dev/pkg/edge/api/apierror

     1  package apierror
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"testing"
     7  
     8  	bslerror "edge-infra.dev/pkg/edge/api/apierror/bsl"
     9  
    10  	"github.com/99designs/gqlgen/graphql"
    11  	"github.com/stretchr/testify/assert"
    12  	"github.com/vektah/gqlparser/v2/ast"
    13  )
    14  
    15  func TestIsAPIError(t *testing.T) {
    16  	err := bslerror.New("not found").SetStatusCode(404)
    17  
    18  	ctx := context.Background()
    19  	ctxPath := graphql.NewPathWithField("banner")
    20  	ctx = graphql.WithPathContext(ctx, ctxPath)
    21  	gerr := toAPIError(ctx, err)
    22  	assert.NotNil(t, gerr)
    23  
    24  	assert.Equal(t, ctxPath.Path(), gerr.Path)
    25  	assert.Equal(t, err.Error(), gerr.Message)
    26  	assert.Equal(t, err.Extensions(), gerr.Extensions[AdditionalKey])
    27  }
    28  
    29  func TestIsNotFoundError(t *testing.T) {
    30  	err := bslerror.New("not found").SetStatusCode(404)
    31  	assert.True(t, IsNotFoundError(err))
    32  }
    33  
    34  func TestIsForbiddenError(t *testing.T) {
    35  	err := bslerror.New("forbidden").SetStatusCode(403)
    36  	assert.True(t, IsForbiddenError(err))
    37  }
    38  
    39  func TestAddAPIErrorToResponse(t *testing.T) {
    40  	err := bslerror.New("not found").SetStatusCode(404)
    41  	ctx := graphql.WithResponseContext(context.Background(), graphql.DefaultErrorPresenter, nil)
    42  	root := &graphql.FieldContext{
    43  		Field: graphql.CollectedField{
    44  			Field: &ast.Field{
    45  				Alias: "banner",
    46  			},
    47  		},
    48  	}
    49  	ctx = graphql.WithFieldContext(ctx, root)
    50  	assert.Nil(t, AddAPIErrorToResponse(ctx, err))
    51  
    52  	assert.Error(t, AddAPIErrorToResponse(ctx, errors.New("test")))
    53  }
    54  
    55  func TestAddEmptyAPIErrorToResponse(t *testing.T) {
    56  	err := bslerror.New("not found").SetStatusCode(404)
    57  	ctx := graphql.WithResponseContext(context.Background(), graphql.DefaultErrorPresenter, nil)
    58  	root := &graphql.FieldContext{
    59  		Field: graphql.CollectedField{
    60  			Field: &ast.Field{
    61  				Alias: "banner",
    62  			},
    63  		},
    64  	}
    65  	ctx = graphql.WithFieldContext(ctx, root)
    66  	respError := AddEmptyAPIErrorToResponse(ctx, err)
    67  	assert.NotNil(t, respError)
    68  	assert.Empty(t, respError.Error())
    69  
    70  	newError := errors.New("test")
    71  	respError = AddEmptyAPIErrorToResponse(ctx, newError)
    72  	assert.Equal(t, newError, respError)
    73  }
    74  

View as plain text