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 (
"net/http"
"testing"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/macaron.v1"
)
func TestBasicAuthenticatedRequest(t *testing.T) {
expectedUser := "prometheus"
expectedPass := "password"
const expectedUser = "prometheus"
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)
So(err, ShouldBeNil)
require.NoError(t, err)
req := macaron.Request{
Request: httpReq,
}
encodedCreds := encodeBasicAuthCredentials(expectedUser, expectedPass)
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCreds))
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)
So(err, ShouldBeNil)
require.NoError(t, err)
req := macaron.Request{
Request: httpReq,
}
encodedCreds := encodeBasicAuthCredentials("invaliduser", "invalidpass")
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCreds))
authenticated := BasicAuthenticatedRequest(req, expectedUser, expectedPass)
So(authenticated, ShouldBeFalse)
assert.False(t, authenticated)
})
}
......
......@@ -3,17 +3,32 @@ package api
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
)
func TestDataProxy(t *testing.T) {
Convey("Data proxy test", t, func() {
Convey("Should append trailing slash to proxy path if original path has a trailing slash", func() {
So(ensureProxyPathTrailingSlash("/api/datasources/proxy/6/api/v1/query_range/", "api/v1/query_range/"), ShouldEqual, "api/v1/query_range/")
})
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")
})
testCases := []struct {
desc string
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))
})
}
}
......@@ -184,6 +184,8 @@ func (provider *accessTokenProvider) getJwtAccessToken(ctx context.Context, data
return token.AccessToken, nil
}
// getTokenSource gets a token source.
// Stubbable by tests.
var getTokenSource = func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
tokenSrc := conf.TokenSource(ctx)
token, err := tokenSrc.Token()
......
......@@ -9,11 +9,11 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
. "github.com/smartystreets/goconvey/convey"
"golang.org/x/oauth2"
"golang.org/x/oauth2/jwt"
)
......@@ -22,8 +22,7 @@ var (
token map[string]interface{}
)
func TestAccessToken(t *testing.T) {
Convey("Plugin with JWT token auth route", t, func() {
func TestAccessToken_pluginWithJWTTokenAuthRoute(t *testing.T) {
pluginRoute := &plugins.AppPluginRoute{
Path: "pathwithjwttoken1",
URL: "https://api.jwt.io/some/path",
......@@ -52,57 +51,66 @@ func TestAccessToken(t *testing.T) {
},
}
setUp := func(t *testing.T, fn func(*jwt.Config, context.Context) (*oauth2.Token, error)) {
origFn := getTokenSource
t.Cleanup(func() {
getTokenSource = origFn
})
getTokenSource = fn
}
ds := &models.DataSource{Id: 1, Version: 2}
Convey("should fetch token using jwt private key", func() {
getTokenSource = func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
t.Run("should fetch token using JWT private key", func(t *testing.T) {
setUp(t, func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "abc"}, nil
}
})
provider := newAccessTokenProvider(ds, pluginRoute)
token, err := provider.getJwtAccessToken(context.Background(), templateData)
So(err, ShouldBeNil)
require.NoError(t, err)
So(token, ShouldEqual, "abc")
assert.Equal(t, "abc", token)
})
Convey("should set jwt config values", func() {
getTokenSource = func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
So(conf.Email, ShouldEqual, "test@test.com")
So(conf.PrivateKey, ShouldResemble, []byte("testkey"))
So(len(conf.Scopes), ShouldEqual, 2)
So(conf.Scopes[0], ShouldEqual, "https://www.testapi.com/auth/monitoring.read")
So(conf.Scopes[1], ShouldEqual, "https://www.testapi.com/auth/cloudplatformprojects.readonly")
So(conf.TokenURL, ShouldEqual, "login.url.com/token")
t.Run("should set JWT config values", func(t *testing.T) {
setUp(t, func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
assert.Equal(t, "test@test.com", conf.Email)
assert.Equal(t, []byte("testkey"), conf.PrivateKey)
assert.Equal(t, 2, len(conf.Scopes))
assert.Equal(t, "https://www.testapi.com/auth/monitoring.read", conf.Scopes[0])
assert.Equal(t, "https://www.testapi.com/auth/cloudplatformprojects.readonly", conf.Scopes[1])
assert.Equal(t, "login.url.com/token", conf.TokenURL)
return &oauth2.Token{AccessToken: "abc"}, nil
}
})
provider := newAccessTokenProvider(ds, pluginRoute)
_, err := provider.getJwtAccessToken(context.Background(), templateData)
So(err, ShouldBeNil)
require.NoError(t, err)
})
Convey("should use cached token on second call", func() {
getTokenSource = func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
t.Run("should use cached token on second call", func(t *testing.T) {
setUp(t, func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
return &oauth2.Token{
AccessToken: "abc",
Expiry: time.Now().Add(1 * time.Minute)}, nil
}
})
provider := newAccessTokenProvider(ds, pluginRoute)
token1, err := provider.getJwtAccessToken(context.Background(), templateData)
So(err, ShouldBeNil)
So(token1, ShouldEqual, "abc")
require.NoError(t, err)
assert.Equal(t, "abc", token1)
getTokenSource = func(conf *jwt.Config, ctx context.Context) (*oauth2.Token, error) {
return &oauth2.Token{AccessToken: "error: cache not used"}, nil
}
token2, err := provider.getJwtAccessToken(context.Background(), templateData)
So(err, ShouldBeNil)
So(token2, ShouldEqual, "abc")
})
require.NoError(t, err)
assert.Equal(t, "abc", token2)
})
}
Convey("Plugin with token auth route", t, func() {
func TestAccessToken_pluginWithTokenAuthRoute(t *testing.T) {
apiHandler := http.NewServeMux()
server := httptest.NewServer(apiHandler)
defer server.Close()
......@@ -144,7 +152,7 @@ func TestAccessToken(t *testing.T) {
authCalls++
})
Convey("Should parse token, with different fields and types", func() {
t.Run("Should parse token, with different fields and types", func(t *testing.T) {
type tokenTestDescription struct {
desc string
expiresIn interface{}
......@@ -189,7 +197,7 @@ func TestAccessToken(t *testing.T) {
},
}
for _, testCase := range testCases {
Convey(testCase.desc, func() {
t.Run(testCase.desc, func(t *testing.T) {
clearTokenCache()
// reset the httphandler counter
authCalls = 0
......@@ -209,27 +217,27 @@ func TestAccessToken(t *testing.T) {
}
accessToken, err := provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
require.NoError(t, err)
assert.Equal(t, token["access_token"], accessToken)
// getAccessToken should use internal cache
accessToken, err = provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
So(authCalls, ShouldEqual, 1)
require.NoError(t, err)
assert.Equal(t, token["access_token"], accessToken)
assert.Equal(t, 1, authCalls)
tokenCache.Lock()
v, ok := tokenCache.cache[provider.getAccessTokenCacheKey()]
tokenCache.Unlock()
So(ok, ShouldBeTrue)
So(v.ExpiresOn.Unix(), ShouldEqual, testCase.expectedExpiresOn)
So(v.AccessToken, ShouldEqual, token["access_token"])
assert.True(t, ok)
assert.Equal(t, testCase.expectedExpiresOn, v.ExpiresOn.Unix())
assert.Equal(t, token["access_token"], v.AccessToken)
})
}
})
Convey("Should refetch token on expire", func() {
t.Run("Should refetch token on expire", func(t *testing.T) {
clearTokenCache()
// reset the httphandler counter
authCalls = 0
......@@ -244,16 +252,15 @@ func TestAccessToken(t *testing.T) {
"refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
}
accessToken, err := provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
require.NoError(t, err)
assert.Equal(t, token["access_token"], accessToken)
mockTimeNow(timeNow().Add(3601 * time.Second))
accessToken, err = provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
So(authCalls, ShouldEqual, 2)
})
require.NoError(t, err)
assert.Equal(t, token["access_token"], accessToken)
assert.Equal(t, 2, authCalls)
})
}
......
......@@ -9,11 +9,12 @@ import (
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/setting"
"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) {
Convey("When getting proxy headers", t, func() {
t.Run("When getting proxy headers", func(t *testing.T) {
route := &plugins.AppPluginRoute{
Headers: []plugins.AppPluginRouteHeader{
{Name: "x-header", Content: "my secret {{.SecureJsonData.key}}"},
......@@ -37,6 +38,7 @@ func TestPluginProxy(t *testing.T) {
})
req := getPluginProxiedRequest(
t,
&models.ReqContext{
SignedInUser: &models.SignedInUser{
Login: "test_user",
......@@ -46,13 +48,12 @@ func TestPluginProxy(t *testing.T) {
route,
)
Convey("Should render header template", func() {
So(req.Header.Get("x-header"), ShouldEqual, "my secret 123")
})
assert.Equal(t, "my secret 123", req.Header.Get("x-header"))
})
Convey("When SendUserHeader config is enabled", t, func() {
t.Run("When SendUserHeader config is enabled", func(t *testing.T) {
req := getPluginProxiedRequest(
t,
&models.ReqContext{
SignedInUser: &models.SignedInUser{
Login: "test_user",
......@@ -62,14 +63,13 @@ func TestPluginProxy(t *testing.T) {
nil,
)
Convey("Should add header with username", func() {
// Get will return empty string even if header is not set
So(req.Header.Get("X-Grafana-User"), ShouldEqual, "test_user")
})
assert.Equal(t, "test_user", req.Header.Get("X-Grafana-User"))
})
Convey("When SendUserHeader config is disabled", t, func() {
t.Run("When SendUserHeader config is disabled", func(t *testing.T) {
req := getPluginProxiedRequest(
t,
&models.ReqContext{
SignedInUser: &models.SignedInUser{
Login: "test_user",
......@@ -78,14 +78,13 @@ func TestPluginProxy(t *testing.T) {
&setting.Cfg{SendUserHeader: false},
nil,
)
Convey("Should not add header with username", func() {
// Get will return empty string even if header is not set
So(req.Header.Get("X-Grafana-User"), ShouldEqual, "")
})
assert.Equal(t, "", req.Header.Get("X-Grafana-User"))
})
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(
t,
&models.ReqContext{
SignedInUser: &models.SignedInUser{IsAnonymous: true},
},
......@@ -93,13 +92,11 @@ func TestPluginProxy(t *testing.T) {
nil,
)
Convey("Should not add header with username", func() {
// Get will return empty string even if header is not set
So(req.Header.Get("X-Grafana-User"), ShouldEqual, "")
})
assert.Equal(t, "", req.Header.Get("X-Grafana-User"))
})
Convey("When getting templated url", t, func() {
t.Run("When getting templated url", func(t *testing.T) {
route := &plugins.AppPluginRoute{
URL: "{{.JsonData.dynamicUrl}}",
Method: "GET",
......@@ -115,6 +112,7 @@ func TestPluginProxy(t *testing.T) {
})
req := getPluginProxiedRequest(
t,
&models.ReqContext{
SignedInUser: &models.SignedInUser{
Login: "test_user",
......@@ -123,15 +121,11 @@ func TestPluginProxy(t *testing.T) {
&setting.Cfg{SendUserHeader: true},
route,
)
Convey("Should set req.URL to be interpolated value from jsonData", func() {
So(req.URL.String(), ShouldEqual, "https://dynamic.grafana.com")
})
Convey("Route url should not be modified", func() {
So(route.URL, ShouldEqual, "{{.JsonData.dynamicUrl}}")
})
assert.Equal(t, "https://dynamic.grafana.com", req.URL.String())
assert.Equal(t, "{{.JsonData.dynamicUrl}}", route.URL)
})
Convey("When getting complex templated url", t, func() {
t.Run("When getting complex templated url", func(t *testing.T) {
route := &plugins.AppPluginRoute{
URL: "{{if .JsonData.apiHost}}{{.JsonData.apiHost}}{{else}}https://example.com{{end}}",
Method: "GET",
......@@ -143,6 +137,7 @@ func TestPluginProxy(t *testing.T) {
})
req := getPluginProxiedRequest(
t,
&models.ReqContext{
SignedInUser: &models.SignedInUser{
Login: "test_user",
......@@ -151,14 +146,12 @@ func TestPluginProxy(t *testing.T) {
&setting.Cfg{SendUserHeader: true},
route,
)
Convey("Should set req.URL to be interpolated default value", func() {
So(req.URL.String(), ShouldEqual, "https://example.com")
})
assert.Equal(t, "https://example.com", req.URL.String())
})
}
// 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
if route == nil {
route = &plugins.AppPluginRoute{
......@@ -170,7 +163,7 @@ func getPluginProxiedRequest(ctx *models.ReqContext, cfg *setting.Cfg, route *pl
proxy := NewApiPluginProxy(ctx, "", route, "", cfg)
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)
return req
}
......@@ -3,11 +3,11 @@ package pluginproxy
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestInterpolateString(t *testing.T) {
Convey("When interpolating string", t, func() {
data := templateData{
SecureJsonData: map[string]string{
"Test": "0asd+asd",
......@@ -15,7 +15,6 @@ func TestInterpolateString(t *testing.T) {
}
interpolated, err := interpolateString("{{.SecureJsonData.Test}}", data)
So(err, ShouldBeNil)
So(interpolated, ShouldEqual, "0asd+asd")
})
require.NoError(t, err)
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