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/")
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))
})
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
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,238 +22,245 @@ var (
token map[string]interface{}
)
func TestAccessToken(t *testing.T) {
Convey("Plugin with JWT token auth route", t, func() {
pluginRoute := &plugins.AppPluginRoute{
Path: "pathwithjwttoken1",
URL: "https://api.jwt.io/some/path",
Method: "GET",
JwtTokenAuth: &plugins.JwtTokenAuth{
Url: "https://login.server.com/{{.JsonData.tenantId}}/oauth2/token",
Scopes: []string{
"https://www.testapi.com/auth/monitoring.read",
"https://www.testapi.com/auth/cloudplatformprojects.readonly",
},
Params: map[string]string{
"token_uri": "{{.JsonData.tokenUri}}",
"client_email": "{{.JsonData.clientEmail}}",
"private_key": "{{.SecureJsonData.privateKey}}",
},
func TestAccessToken_pluginWithJWTTokenAuthRoute(t *testing.T) {
pluginRoute := &plugins.AppPluginRoute{
Path: "pathwithjwttoken1",
URL: "https://api.jwt.io/some/path",
Method: "GET",
JwtTokenAuth: &plugins.JwtTokenAuth{
Url: "https://login.server.com/{{.JsonData.tenantId}}/oauth2/token",
Scopes: []string{
"https://www.testapi.com/auth/monitoring.read",
"https://www.testapi.com/auth/cloudplatformprojects.readonly",
},
}
templateData := templateData{
JsonData: map[string]interface{}{
"clientEmail": "test@test.com",
"tokenUri": "login.url.com/token",
},
SecureJsonData: map[string]string{
"privateKey": "testkey",
Params: map[string]string{
"token_uri": "{{.JsonData.tokenUri}}",
"client_email": "{{.JsonData.clientEmail}}",
"private_key": "{{.SecureJsonData.privateKey}}",
},
}
},
}
ds := &models.DataSource{Id: 1, Version: 2}
templateData := templateData{
JsonData: map[string]interface{}{
"clientEmail": "test@test.com",
"tokenUri": "login.url.com/token",
},
SecureJsonData: map[string]string{
"privateKey": "testkey",
},
}
setUp := func(t *testing.T, fn func(*jwt.Config, context.Context) (*oauth2.Token, error)) {
origFn := getTokenSource
t.Cleanup(func() {
getTokenSource = origFn
})
getTokenSource = fn
}
Convey("should fetch token using jwt private key", func() {
getTokenSource = 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)
ds := &models.DataSource{Id: 1, Version: 2}
So(token, ShouldEqual, "abc")
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)
require.NoError(t, err)
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")
return &oauth2.Token{AccessToken: "abc"}, nil
}
provider := newAccessTokenProvider(ds, pluginRoute)
_, err := provider.getJwtAccessToken(context.Background(), templateData)
So(err, ShouldBeNil)
assert.Equal(t, "abc", 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
})
Convey("should use cached token on second call", func() {
getTokenSource = 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")
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")
provider := newAccessTokenProvider(ds, pluginRoute)
_, err := provider.getJwtAccessToken(context.Background(), templateData)
require.NoError(t, err)
})
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)
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)
require.NoError(t, err)
assert.Equal(t, "abc", token2)
})
}
Convey("Plugin with token auth route", t, func() {
apiHandler := http.NewServeMux()
server := httptest.NewServer(apiHandler)
defer server.Close()
pluginRoute := &plugins.AppPluginRoute{
Path: "pathwithtokenauth1",
URL: "",
Method: "GET",
TokenAuth: &plugins.JwtTokenAuth{
Url: server.URL + "/oauth/token",
Scopes: []string{
"https://www.testapi.com/auth/monitoring.read",
"https://www.testapi.com/auth/cloudplatformprojects.readonly",
},
Params: map[string]string{
"grant_type": "client_credentials",
"client_id": "{{.JsonData.client_id}}",
"client_secret": "{{.SecureJsonData.client_secret}}",
"audience": "{{.JsonData.audience}}",
"client_name": "datasource_plugin",
},
func TestAccessToken_pluginWithTokenAuthRoute(t *testing.T) {
apiHandler := http.NewServeMux()
server := httptest.NewServer(apiHandler)
defer server.Close()
pluginRoute := &plugins.AppPluginRoute{
Path: "pathwithtokenauth1",
URL: "",
Method: "GET",
TokenAuth: &plugins.JwtTokenAuth{
Url: server.URL + "/oauth/token",
Scopes: []string{
"https://www.testapi.com/auth/monitoring.read",
"https://www.testapi.com/auth/cloudplatformprojects.readonly",
},
Params: map[string]string{
"grant_type": "client_credentials",
"client_id": "{{.JsonData.client_id}}",
"client_secret": "{{.SecureJsonData.client_secret}}",
"audience": "{{.JsonData.audience}}",
"client_name": "datasource_plugin",
},
},
}
templateData := templateData{
JsonData: map[string]interface{}{
"client_id": "my_client_id",
"audience": "www.example.com",
},
SecureJsonData: map[string]string{
"client_secret": "my_secret",
},
}
var authCalls int
apiHandler.HandleFunc("/oauth/token", func(w http.ResponseWriter, req *http.Request) {
err := json.NewEncoder(w).Encode(token)
require.NoError(t, err)
authCalls++
})
t.Run("Should parse token, with different fields and types", func(t *testing.T) {
type tokenTestDescription struct {
desc string
expiresIn interface{}
expiresOn interface{}
expectedExpiresOn int64
}
templateData := templateData{
JsonData: map[string]interface{}{
"client_id": "my_client_id",
"audience": "www.example.com",
mockTimeNow(time.Now())
defer resetTimeNow()
provider := newAccessTokenProvider(&models.DataSource{}, pluginRoute)
testCases := []tokenTestDescription{
{
desc: "token with expires_in in string format",
expiresIn: "3600",
expiresOn: nil,
expectedExpiresOn: timeNow().Unix() + 3600,
},
{
desc: "token with expires_in in int format",
expiresIn: 3600,
expiresOn: nil,
expectedExpiresOn: timeNow().Unix() + 3600,
},
{
desc: "token with expires_on in string format",
expiresOn: strconv.FormatInt(timeNow().Add(86*time.Minute).Unix(), 10),
expiresIn: nil,
expectedExpiresOn: timeNow().Add(86 * time.Minute).Unix(),
},
SecureJsonData: map[string]string{
"client_secret": "my_secret",
{
desc: "token with expires_on in int format",
expiresOn: timeNow().Add(86 * time.Minute).Unix(),
expiresIn: nil,
expectedExpiresOn: timeNow().Add(86 * time.Minute).Unix(),
},
{
desc: "token with both expires_on and expires_in, should prioritize expiresOn",
expiresIn: 5200,
expiresOn: timeNow().Add(1 * time.Hour).Unix(),
expectedExpiresOn: timeNow().Add(1 * time.Hour).Unix(),
},
}
for _, testCase := range testCases {
t.Run(testCase.desc, func(t *testing.T) {
clearTokenCache()
// reset the httphandler counter
authCalls = 0
token = map[string]interface{}{
"access_token": "2YotnFZFEjr1zCsicMWpAA",
"token_type": "example",
"refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
}
if testCase.expiresIn != nil {
token["expires_in"] = testCase.expiresIn
}
if testCase.expiresOn != nil {
token["expires_on"] = testCase.expiresOn
}
accessToken, err := provider.getAccessToken(templateData)
require.NoError(t, err)
assert.Equal(t, token["access_token"], accessToken)
// getAccessToken should use internal cache
accessToken, err = provider.getAccessToken(templateData)
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()
assert.True(t, ok)
assert.Equal(t, testCase.expectedExpiresOn, v.ExpiresOn.Unix())
assert.Equal(t, token["access_token"], v.AccessToken)
})
}
})
var authCalls int
apiHandler.HandleFunc("/oauth/token", func(w http.ResponseWriter, req *http.Request) {
err := json.NewEncoder(w).Encode(token)
require.NoError(t, err)
authCalls++
})
t.Run("Should refetch token on expire", func(t *testing.T) {
clearTokenCache()
// reset the httphandler counter
authCalls = 0
Convey("Should parse token, with different fields and types", func() {
type tokenTestDescription struct {
desc string
expiresIn interface{}
expiresOn interface{}
expectedExpiresOn int64
}
mockTimeNow(time.Now())
defer resetTimeNow()
provider := newAccessTokenProvider(&models.DataSource{}, pluginRoute)
testCases := []tokenTestDescription{
{
desc: "token with expires_in in string format",
expiresIn: "3600",
expiresOn: nil,
expectedExpiresOn: timeNow().Unix() + 3600,
},
{
desc: "token with expires_in in int format",
expiresIn: 3600,
expiresOn: nil,
expectedExpiresOn: timeNow().Unix() + 3600,
},
{
desc: "token with expires_on in string format",
expiresOn: strconv.FormatInt(timeNow().Add(86*time.Minute).Unix(), 10),
expiresIn: nil,
expectedExpiresOn: timeNow().Add(86 * time.Minute).Unix(),
},
{
desc: "token with expires_on in int format",
expiresOn: timeNow().Add(86 * time.Minute).Unix(),
expiresIn: nil,
expectedExpiresOn: timeNow().Add(86 * time.Minute).Unix(),
},
{
desc: "token with both expires_on and expires_in, should prioritize expiresOn",
expiresIn: 5200,
expiresOn: timeNow().Add(1 * time.Hour).Unix(),
expectedExpiresOn: timeNow().Add(1 * time.Hour).Unix(),
},
}
for _, testCase := range testCases {
Convey(testCase.desc, func() {
clearTokenCache()
// reset the httphandler counter
authCalls = 0
token = map[string]interface{}{
"access_token": "2YotnFZFEjr1zCsicMWpAA",
"token_type": "example",
"refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
}
if testCase.expiresIn != nil {
token["expires_in"] = testCase.expiresIn
}
if testCase.expiresOn != nil {
token["expires_on"] = testCase.expiresOn
}
accessToken, err := provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
// getAccessToken should use internal cache
accessToken, err = provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
So(authCalls, ShouldEqual, 1)
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"])
})
}
})
mockTimeNow(time.Now())
defer resetTimeNow()
provider := newAccessTokenProvider(&models.DataSource{}, pluginRoute)
Convey("Should refetch token on expire", func() {
clearTokenCache()
// reset the httphandler counter
authCalls = 0
mockTimeNow(time.Now())
defer resetTimeNow()
provider := newAccessTokenProvider(&models.DataSource{}, pluginRoute)
token = map[string]interface{}{
"access_token": "2YotnFZFEjr1zCsicMWpAA",
"token_type": "3600",
"refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
}
accessToken, err := provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
mockTimeNow(timeNow().Add(3601 * time.Second))
accessToken, err = provider.getAccessToken(templateData)
So(err, ShouldBeNil)
So(accessToken, ShouldEqual, token["access_token"])
So(authCalls, ShouldEqual, 2)
})
token = map[string]interface{}{
"access_token": "2YotnFZFEjr1zCsicMWpAA",
"token_type": "3600",
"refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
}
accessToken, err := provider.getAccessToken(templateData)
require.NoError(t, err)
assert.Equal(t, token["access_token"], accessToken)
mockTimeNow(timeNow().Add(3601 * time.Second))
accessToken, err = provider.getAccessToken(templateData)
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")
})
// Get will return empty string even if header is not set
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, "")
})
// Get will return empty string even if header is not set
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, "")
})
// Get will return empty string even if header is not set
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,19 +3,18 @@ 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",
},
}
data := templateData{
SecureJsonData: map[string]string{
"Test": "0asd+asd",
},
}
interpolated, err := interpolateString("{{.SecureJsonData.Test}}", data)
So(err, ShouldBeNil)
So(interpolated, ShouldEqual, "0asd+asd")
})
interpolated, err := interpolateString("{{.SecureJsonData.Test}}", data)
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