Skip to content

Commit

Permalink
middleware tests
Browse files Browse the repository at this point in the history
  • Loading branch information
marefr committed Oct 11, 2024
1 parent 1518be5 commit ca6c097
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
51 changes: 51 additions & 0 deletions backend/httpclient/error_source_middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package httpclient

import (
"errors"
"net"
"net/http"
"testing"

"github.com/grafana/grafana-plugin-sdk-go/experimental/status"
"github.com/stretchr/testify/require"
)

func TestErrorSourceMiddleware(t *testing.T) {
t.Run("With non-downstream HTTP error returned from http.RoundTripper should not be wrapped in a downstream error", func(t *testing.T) {
ctx := &testContext{}
someErr := errors.New("some error")
finalRoundTripper := ctx.createRoundTripperWithError(someErr)
mw := ErrorSourceMiddleware()
rt := mw.CreateMiddleware(Options{}, finalRoundTripper)
require.NotNil(t, rt)
middlewareName, ok := mw.(MiddlewareName)
require.True(t, ok)
require.Equal(t, ErrorSourceMiddlewareName, middlewareName.MiddlewareName())

req, err := http.NewRequest(http.MethodGet, "http://", nil)
require.NoError(t, err)
_, err = rt.RoundTrip(req)
require.Error(t, err)
require.False(t, status.IsDownstreamError(err))
require.ErrorIs(t, err, someErr)
})

t.Run("With downstream HTTP error returned from http.RoundTripper should be wrapped in a downstream error", func(t *testing.T) {
ctx := &testContext{}
someErr := &net.DNSError{IsNotFound: true}
finalRoundTripper := ctx.createRoundTripperWithError(someErr)
mw := ErrorSourceMiddleware()
rt := mw.CreateMiddleware(Options{}, finalRoundTripper)
require.NotNil(t, rt)
middlewareName, ok := mw.(MiddlewareName)
require.True(t, ok)
require.Equal(t, ErrorSourceMiddlewareName, middlewareName.MiddlewareName())

req, err := http.NewRequest(http.MethodGet, "http://", nil)
require.NoError(t, err)
_, err = rt.RoundTrip(req)
require.Error(t, err)
require.True(t, status.IsDownstreamError(err))
require.ErrorIs(t, err, someErr)
})
}
6 changes: 6 additions & 0 deletions backend/httpclient/http_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,12 @@ func (c *testContext) createRoundTripper(name string) http.RoundTripper {
})
}

func (c *testContext) createRoundTripperWithError(err error) http.RoundTripper {
return RoundTripperFunc(func(_ *http.Request) (*http.Response, error) {
return nil, err
})
}

func (c *testContext) createMiddleware(name string) Middleware {
return NamedMiddlewareFunc(name, func(_ Options, next http.RoundTripper) http.RoundTripper {
return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
Expand Down

0 comments on commit ca6c097

Please sign in to comment.