Commit 8c765e80 by Arve Knudsen Committed by GitHub

API: Rewrite tests from goconvey (#29091)

* API: Rewrite tests from goconvey

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>

* Fix test

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>

* Fix tests

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>
parent 2bf964c6
...@@ -6,36 +6,39 @@ import ( ...@@ -6,36 +6,39 @@ import (
"net/http" "net/http"
"testing" "testing"
. "github.com/smartystreets/goconvey/convey" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
func TestBasicAuthenticatedRequest(t *testing.T) { func TestBasicAuthenticatedRequest(t *testing.T) {
expectedUser := "prometheus" const expectedUser = "prometheus"
expectedPass := "password" const expectedPass = "password"
Convey("Given a valid set of basic auth credentials", t, func() { t.Run("Given a valid set of basic auth credentials", func(t *testing.T) {
httpReq, err := http.NewRequest("GET", "http://localhost:3000/metrics", nil) httpReq, err := http.NewRequest("GET", "http://localhost:3000/metrics", nil)
So(err, ShouldBeNil) require.NoError(t, err)
req := macaron.Request{ req := macaron.Request{
Request: httpReq, Request: httpReq,
} }
encodedCreds := encodeBasicAuthCredentials(expectedUser, expectedPass) encodedCreds := encodeBasicAuthCredentials(expectedUser, expectedPass)
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCreds)) req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCreds))
authenticated := BasicAuthenticatedRequest(req, expectedUser, expectedPass) authenticated := BasicAuthenticatedRequest(req, expectedUser, expectedPass)
So(authenticated, ShouldBeTrue)
assert.True(t, authenticated)
}) })
Convey("Given an invalid set of basic auth credentials", t, func() { t.Run("Given an invalid set of basic auth credentials", func(t *testing.T) {
httpReq, err := http.NewRequest("GET", "http://localhost:3000/metrics", nil) httpReq, err := http.NewRequest("GET", "http://localhost:3000/metrics", nil)
So(err, ShouldBeNil) require.NoError(t, err)
req := macaron.Request{ req := macaron.Request{
Request: httpReq, Request: httpReq,
} }
encodedCreds := encodeBasicAuthCredentials("invaliduser", "invalidpass") encodedCreds := encodeBasicAuthCredentials("invaliduser", "invalidpass")
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCreds)) req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCreds))
authenticated := BasicAuthenticatedRequest(req, expectedUser, expectedPass) authenticated := BasicAuthenticatedRequest(req, expectedUser, expectedPass)
So(authenticated, ShouldBeFalse)
assert.False(t, authenticated)
}) })
} }
......
...@@ -3,17 +3,32 @@ package api ...@@ -3,17 +3,32 @@ package api
import ( import (
"testing" "testing"
. "github.com/smartystreets/goconvey/convey" "github.com/stretchr/testify/assert"
) )
func TestDataProxy(t *testing.T) { func TestDataProxy(t *testing.T) {
Convey("Data proxy test", t, func() { testCases := []struct {
Convey("Should append trailing slash to proxy path if original path has a trailing slash", func() { desc string
So(ensureProxyPathTrailingSlash("/api/datasources/proxy/6/api/v1/query_range/", "api/v1/query_range/"), ShouldEqual, "api/v1/query_range/") origPath string
proxyPath string
exp string
}{
{
"Should append trailing slash to proxy path if original path has a trailing slash",
"/api/datasources/proxy/6/api/v1/query_range/",
"api/v1/query_range/",
"api/v1/query_range/",
},
{
"Should not append trailing slash to proxy path if original path doesn't have a trailing slash",
"/api/datasources/proxy/6/api/v1/query_range",
"api/v1/query_range",
"api/v1/query_range",
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
assert.Equal(t, tc.exp, ensureProxyPathTrailingSlash(tc.origPath, tc.proxyPath))
}) })
}
Convey("Should not append trailing slash to proxy path if original path doesn't have a trailing slash", func() {
So(ensureProxyPathTrailingSlash("/api/datasources/proxy/6/api/v1/query_range", "api/v1/query_range"), ShouldEqual, "api/v1/query_range")
})
})
} }
...@@ -184,6 +184,8 @@ func (provider *accessTokenProvider) getJwtAccessToken(ctx context.Context, data ...@@ -184,6 +184,8 @@ func (provider *accessTokenProvider) getJwtAccessToken(ctx context.Context, data
return token.AccessToken, nil return token.AccessToken, nil
} }
// getTokenSource gets a token source.
// Stubbable by tests.
var getTokenSource = func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) { var getTokenSource = func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
tokenSrc := conf.TokenSource(ctx) tokenSrc := conf.TokenSource(ctx)
token, err := tokenSrc.Token() token, err := tokenSrc.Token()
......
...@@ -9,11 +9,12 @@ import ( ...@@ -9,11 +9,12 @@ import (
"github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/util"
. "github.com/smartystreets/goconvey/convey" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestPluginProxy(t *testing.T) { func TestPluginProxy(t *testing.T) {
Convey("When getting proxy headers", t, func() { t.Run("When getting proxy headers", func(t *testing.T) {
route := &plugins.AppPluginRoute{ route := &plugins.AppPluginRoute{
Headers: []plugins.AppPluginRouteHeader{ Headers: []plugins.AppPluginRouteHeader{
{Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"}, {Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"},
...@@ -37,6 +38,7 @@ func TestPluginProxy(t *testing.T) { ...@@ -37,6 +38,7 @@ func TestPluginProxy(t *testing.T) {
}) })
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
t,
&models.ReqContext{ &models.ReqContext{
SignedInUser: &models.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
...@@ -46,13 +48,12 @@ func TestPluginProxy(t *testing.T) { ...@@ -46,13 +48,12 @@ func TestPluginProxy(t *testing.T) {
route, route,
) )
Convey("Should render header template", func() { assert.Equal(t, "my secret 123", req.Header.Get("x-header"))
So(req.Header.Get("x-header"), ShouldEqual, "my secret 123")
})
}) })
Convey("When SendUserHeader config is enabled", t, func() { t.Run("When SendUserHeader config is enabled", func(t *testing.T) {
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
t,
&models.ReqContext{ &models.ReqContext{
SignedInUser: &models.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
...@@ -62,14 +63,13 @@ func TestPluginProxy(t *testing.T) { ...@@ -62,14 +63,13 @@ func TestPluginProxy(t *testing.T) {
nil, nil,
) )
Convey("Should add header with username", func() { // Get will return empty string even if header is not set
// Get will return empty string even if header is not set assert.Equal(t, "test_user", req.Header.Get("X-Grafana-User"))
So(req.Header.Get("X-Grafana-User"), ShouldEqual, "test_user")
})
}) })
Convey("When SendUserHeader config is disabled", t, func() { t.Run("When SendUserHeader config is disabled", func(t *testing.T) {
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
t,
&models.ReqContext{ &models.ReqContext{
SignedInUser: &models.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
...@@ -78,14 +78,13 @@ func TestPluginProxy(t *testing.T) { ...@@ -78,14 +78,13 @@ func TestPluginProxy(t *testing.T) {
&setting.Cfg{SendUserHeader: false}, &setting.Cfg{SendUserHeader: false},
nil, nil,
) )
Convey("Should not add header with username", func() { // Get will return empty string even if header is not set
// Get will return empty string even if header is not set assert.Equal(t, "", req.Header.Get("X-Grafana-User"))
So(req.Header.Get("X-Grafana-User"), ShouldEqual, "")
})
}) })
Convey("When SendUserHeader config is enabled but user is anonymous", t, func() { t.Run("When SendUserHeader config is enabled but user is anonymous", func(t *testing.T) {
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
t,
&models.ReqContext{ &models.ReqContext{
SignedInUser: &models.SignedInUser{IsAnonymous: true}, SignedInUser: &models.SignedInUser{IsAnonymous: true},
}, },
...@@ -93,13 +92,11 @@ func TestPluginProxy(t *testing.T) { ...@@ -93,13 +92,11 @@ func TestPluginProxy(t *testing.T) {
nil, nil,
) )
Convey("Should not add header with username", func() { // Get will return empty string even if header is not set
// Get will return empty string even if header is not set assert.Equal(t, "", req.Header.Get("X-Grafana-User"))
So(req.Header.Get("X-Grafana-User"), ShouldEqual, "")
})
}) })
Convey("When getting templated url", t, func() { t.Run("When getting templated url", func(t *testing.T) {
route := &plugins.AppPluginRoute{ route := &plugins.AppPluginRoute{
URL: "{{.JsonData.dynamicUrl}}", URL: "{{.JsonData.dynamicUrl}}",
Method: "GET", Method: "GET",
...@@ -115,6 +112,7 @@ func TestPluginProxy(t *testing.T) { ...@@ -115,6 +112,7 @@ func TestPluginProxy(t *testing.T) {
}) })
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
t,
&models.ReqContext{ &models.ReqContext{
SignedInUser: &models.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
...@@ -123,15 +121,11 @@ func TestPluginProxy(t *testing.T) { ...@@ -123,15 +121,11 @@ func TestPluginProxy(t *testing.T) {
&setting.Cfg{SendUserHeader: true}, &setting.Cfg{SendUserHeader: true},
route, route,
) )
Convey("Should set req.URL to be interpolated value from jsonData", func() { assert.Equal(t, "https://dynamic.grafana.com", req.URL.String())
So(req.URL.String(), ShouldEqual, "https://dynamic.grafana.com") assert.Equal(t, "{{.JsonData.dynamicUrl}}", route.URL)
})
Convey("Route url should not be modified", func() {
So(route.URL, ShouldEqual, "{{.JsonData.dynamicUrl}}")
})
}) })
Convey("When getting complex templated url", t, func() { t.Run("When getting complex templated url", func(t *testing.T) {
route := &plugins.AppPluginRoute{ route := &plugins.AppPluginRoute{
URL: "{{if .JsonData.apiHost}}{{.JsonData.apiHost}}{{else}}https://example.com{{end}}", URL: "{{if .JsonData.apiHost}}{{.JsonData.apiHost}}{{else}}https://example.com{{end}}",
Method: "GET", Method: "GET",
...@@ -143,6 +137,7 @@ func TestPluginProxy(t *testing.T) { ...@@ -143,6 +137,7 @@ func TestPluginProxy(t *testing.T) {
}) })
req := getPluginProxiedRequest( req := getPluginProxiedRequest(
t,
&models.ReqContext{ &models.ReqContext{
SignedInUser: &models.SignedInUser{ SignedInUser: &models.SignedInUser{
Login: "test_user", Login: "test_user",
...@@ -151,14 +146,12 @@ func TestPluginProxy(t *testing.T) { ...@@ -151,14 +146,12 @@ func TestPluginProxy(t *testing.T) {
&setting.Cfg{SendUserHeader: true}, &setting.Cfg{SendUserHeader: true},
route, route,
) )
Convey("Should set req.URL to be interpolated default value", func() { assert.Equal(t, "https://example.com", req.URL.String())
So(req.URL.String(), ShouldEqual, "https://example.com")
})
}) })
} }
// getPluginProxiedRequest is a helper for easier setup of tests based on global config and ReqContext. // getPluginProxiedRequest is a helper for easier setup of tests based on global config and ReqContext.
func getPluginProxiedRequest(ctx *models.ReqContext, cfg *setting.Cfg, route *plugins.AppPluginRoute) *http.Request { func getPluginProxiedRequest(t *testing.T, ctx *models.ReqContext, cfg *setting.Cfg, route *plugins.AppPluginRoute) *http.Request {
// insert dummy route if none is specified // insert dummy route if none is specified
if route == nil { if route == nil {
route = &plugins.AppPluginRoute{ route = &plugins.AppPluginRoute{
...@@ -170,7 +163,7 @@ func getPluginProxiedRequest(ctx *models.ReqContext, cfg *setting.Cfg, route *pl ...@@ -170,7 +163,7 @@ func getPluginProxiedRequest(ctx *models.ReqContext, cfg *setting.Cfg, route *pl
proxy := NewApiPluginProxy(ctx, "", route, "", cfg) proxy := NewApiPluginProxy(ctx, "", route, "", cfg)
req, err := http.NewRequest(http.MethodGet, "/api/plugin-proxy/grafana-simple-app/api/v4/alerts", nil) req, err := http.NewRequest(http.MethodGet, "/api/plugin-proxy/grafana-simple-app/api/v4/alerts", nil)
So(err, ShouldBeNil) require.NoError(t, err)
proxy.Director(req) proxy.Director(req)
return req return req
} }
...@@ -3,19 +3,18 @@ package pluginproxy ...@@ -3,19 +3,18 @@ package pluginproxy
import ( import (
"testing" "testing"
. "github.com/smartystreets/goconvey/convey" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestInterpolateString(t *testing.T) { func TestInterpolateString(t *testing.T) {
Convey("When interpolating string", t, func() { data := templateData{
data := templateData{ SecureJsonData: map[string]string{
SecureJsonData: map[string]string{ "Test": "0asd+asd",
"Test": "0asd+asd", },
}, }
}
interpolated, err := interpolateString("{{.SecureJsonData.Test}}", data) interpolated, err := interpolateString("{{.SecureJsonData.Test}}", data)
So(err, ShouldBeNil) require.NoError(t, err)
So(interpolated, ShouldEqual, "0asd+asd") assert.Equal(t, "0asd+asd", interpolated)
})
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment