From eb1fed792905a08108fc2e8a4f8dc529448c7c57 Mon Sep 17 00:00:00 2001 From: Will Browne Date: Wed, 25 Jan 2023 11:45:52 +0100 Subject: [PATCH] Plugins: Add plugin resource tests (#62014) * remove plugin context from response * remove integration test indicator --- pkg/api/plugin_resource_test.go | 131 ++++++++++++++++++++ pkg/tsdb/testdatasource/resource_handler.go | 5 - 2 files changed, 131 insertions(+), 5 deletions(-) create mode 100644 pkg/api/plugin_resource_test.go diff --git a/pkg/api/plugin_resource_test.go b/pkg/api/plugin_resource_test.go new file mode 100644 index 00000000000..a7cf4e9bdfe --- /dev/null +++ b/pkg/api/plugin_resource_test.go @@ -0,0 +1,131 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "io" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/grafana/grafana-azure-sdk-go/azsettings" + "github.com/grafana/grafana-plugin-sdk-go/backend" + + "github.com/grafana/grafana/pkg/infra/db" + "github.com/grafana/grafana/pkg/infra/localcache" + "github.com/grafana/grafana/pkg/plugins" + "github.com/grafana/grafana/pkg/plugins/backendplugin/coreplugin" + "github.com/grafana/grafana/pkg/plugins/backendplugin/provider" + "github.com/grafana/grafana/pkg/plugins/config" + pluginClient "github.com/grafana/grafana/pkg/plugins/manager/client" + "github.com/grafana/grafana/pkg/plugins/manager/fakes" + "github.com/grafana/grafana/pkg/plugins/manager/loader" + "github.com/grafana/grafana/pkg/plugins/manager/registry" + "github.com/grafana/grafana/pkg/plugins/manager/signature" + "github.com/grafana/grafana/pkg/plugins/manager/store" + "github.com/grafana/grafana/pkg/plugins/plugincontext" + "github.com/grafana/grafana/pkg/services/accesscontrol" + datasources "github.com/grafana/grafana/pkg/services/datasources/fakes" + "github.com/grafana/grafana/pkg/services/featuremgmt" + "github.com/grafana/grafana/pkg/services/oauthtoken/oauthtokentest" + pluginSettings "github.com/grafana/grafana/pkg/services/pluginsettings/service" + "github.com/grafana/grafana/pkg/services/pluginsintegration" + "github.com/grafana/grafana/pkg/services/quota/quotatest" + "github.com/grafana/grafana/pkg/services/user" + "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/tsdb/cloudwatch" + "github.com/grafana/grafana/pkg/tsdb/testdatasource" + "github.com/grafana/grafana/pkg/web/webtest" +) + +func TestCallResource(t *testing.T) { + staticRootPath, err := filepath.Abs("../../public/") + require.NoError(t, err) + + cfg := setting.NewCfg() + cfg.StaticRootPath = staticRootPath + cfg.IsFeatureToggleEnabled = func(_ string) bool { + return false + } + cfg.Azure = &azsettings.AzureSettings{} + + coreRegistry := coreplugin.ProvideCoreRegistry(nil, &cloudwatch.CloudWatchService{}, nil, nil, nil, nil, + nil, nil, nil, nil, testdatasource.ProvideService(cfg, featuremgmt.WithFeatures()), nil, nil, nil, nil, nil, nil) + pCfg := config.ProvideConfig(setting.ProvideProvider(cfg), cfg) + reg := registry.ProvideService() + l := loader.ProvideService(pCfg, fakes.NewFakeLicensingService(), signature.NewUnsignedAuthorizer(pCfg), + reg, provider.ProvideService(coreRegistry), fakes.NewFakeRoleRegistry()) + ps, err := store.ProvideService(cfg, pCfg, reg, l) + require.NoError(t, err) + + pcp := plugincontext.ProvideService(localcache.ProvideService(), ps, &datasources.FakeCacheService{}, &datasources.FakeDataSourceService{}, pluginSettings.ProvideService(db.InitTestDB(t), nil)) + + srv := SetupAPITestServer(t, func(hs *HTTPServer) { + hs.Cfg = cfg + hs.PluginContextProvider = pcp + hs.QuotaService = quotatest.New(false, nil) + hs.pluginStore = ps + hs.pluginClient = pluginClient.ProvideService(reg, pCfg) + }) + + t.Run("Test successful response is received for valid request", func(t *testing.T) { + req := srv.NewPostRequest("/api/plugins/testdata/resources/test", strings.NewReader("{ \"test\": true }")) + webtest.RequestWithSignedInUser(req, &user.SignedInUser{UserID: 1, OrgID: 1, Permissions: map[int64]map[string][]string{ + 1: accesscontrol.GroupScopesByAction([]accesscontrol.Permission{ + {Action: plugins.ActionAppAccess, Scope: plugins.ScopeProvider.GetResourceAllScope()}, + }), + }}) + resp, err := srv.SendJSON(req) + require.NoError(t, err) + + b, err := io.ReadAll(resp.Body) + require.NoError(t, err) + + var body = make(map[string]interface{}) + err = json.Unmarshal(b, &body) + require.NoError(t, err) + + require.Equal(t, "Hello world from test datasource!", body["message"]) + require.NoError(t, resp.Body.Close()) + require.Equal(t, 200, resp.StatusCode) + }) + + pc, err := pluginClient.NewDecorator(&fakes.FakePluginClient{ + CallResourceHandlerFunc: backend.CallResourceHandlerFunc(func(ctx context.Context, + req *backend.CallResourceRequest, sender backend.CallResourceResponseSender) error { + return errors.New("something went wrong") + }), + }, pluginsintegration.CreateMiddlewares(cfg, &oauthtokentest.Service{})...) + require.NoError(t, err) + + srv = SetupAPITestServer(t, func(hs *HTTPServer) { + hs.Cfg = cfg + hs.PluginContextProvider = pcp + hs.QuotaService = quotatest.New(false, nil) + hs.pluginStore = ps + hs.pluginClient = pc + }) + + t.Run("Test error is properly propagated to API response", func(t *testing.T) { + req := srv.NewGetRequest("/api/plugins/testdata/resources/scenarios") + webtest.RequestWithSignedInUser(req, &user.SignedInUser{UserID: 1, OrgID: 1, Permissions: map[int64]map[string][]string{ + 1: accesscontrol.GroupScopesByAction([]accesscontrol.Permission{ + {Action: plugins.ActionAppAccess, Scope: plugins.ScopeProvider.GetResourceAllScope()}, + }), + }}) + resp, err := srv.SendJSON(req) + require.NoError(t, err) + + body := new(strings.Builder) + _, err = io.Copy(body, resp.Body) + require.NoError(t, err) + + expectedBody := `{ "error": "something went wrong", "message": "Failed to call resource", "traceID": "" }` + require.JSONEq(t, expectedBody, body.String()) + require.NoError(t, resp.Body.Close()) + require.Equal(t, 500, resp.StatusCode) + }) +} diff --git a/pkg/tsdb/testdatasource/resource_handler.go b/pkg/tsdb/testdatasource/resource_handler.go index 06615f22919..4d6eba4bd53 100644 --- a/pkg/tsdb/testdatasource/resource_handler.go +++ b/pkg/tsdb/testdatasource/resource_handler.go @@ -10,8 +10,6 @@ import ( "time" "github.com/grafana/grafana/pkg/infra/log" - - "github.com/grafana/grafana-plugin-sdk-go/backend/resource/httpadapter" ) func (s *Service) registerRoutes() *http.ServeMux { @@ -130,8 +128,6 @@ func createJSONHandler(logger log.Logger) http.Handler { } } - config := httpadapter.PluginConfigFromContext(req.Context()) - data := map[string]interface{}{ "message": "Hello world from test datasource!", "request": map[string]interface{}{ @@ -139,7 +135,6 @@ func createJSONHandler(logger log.Logger) http.Handler { "url": req.URL, "headers": req.Header, "body": reqData, - "config": config, }, } bytes, err := json.Marshal(&data)