Replace AddHandler with AddHandlerCtx in tests (#42585)

pull/42604/head
idafurjes 4 years ago committed by GitHub
parent 2e3fd9d659
commit e6123bc3ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 14
      pkg/api/admin_users_test.go
  2. 17
      pkg/api/alerting_test.go
  3. 5
      pkg/api/annotations_test.go
  4. 2
      pkg/api/dashboard_permission_test.go
  5. 9
      pkg/api/dashboard_snapshot_test.go
  6. 42
      pkg/api/dashboard_test.go
  7. 19
      pkg/api/datasources_test.go
  8. 24
      pkg/api/ldap_debug_test.go
  9. 4
      pkg/api/login_test.go
  10. 2
      pkg/api/pluginproxy/ds_proxy_test.go
  11. 3
      pkg/api/team_members_test.go
  12. 5
      pkg/api/team_test.go
  13. 15
      pkg/api/user_test.go
  14. 8
      pkg/bus/bus_test.go
  15. 22
      pkg/infra/usagestats/service/usage_stats_test.go
  16. 6
      pkg/login/brute_force_login_protection_test.go
  17. 2
      pkg/login/grafana_login_test.go
  18. 7
      pkg/middleware/auth_test.go
  19. 8
      pkg/middleware/middleware_basic_auth_test.go
  20. 24
      pkg/middleware/middleware_test.go
  21. 4
      pkg/middleware/org_redirect_test.go
  22. 4
      pkg/middleware/quota_test.go
  23. 2
      pkg/services/alerting/alerting_usage_test.go
  24. 4
      pkg/services/alerting/engine_test.go
  25. 4
      pkg/services/alerting/extractor_test.go
  26. 4
      pkg/services/contexthandler/auth_proxy_test.go
  27. 3
      pkg/services/contexthandler/authproxy/authproxy_test.go
  28. 2
      pkg/services/dashboards/dashboard_service_test.go
  29. 10
      pkg/services/dashboards/folder_service_test.go
  30. 4
      pkg/services/guardian/guardian_test.go
  31. 4
      pkg/services/guardian/guardian_util_test.go
  32. 12
      pkg/services/login/loginservice/loginservice_test.go
  33. 4
      pkg/services/provisioning/dashboards/file_reader_test.go
  34. 2
      pkg/services/provisioning/dashboards/validator_test.go
  35. 20
      pkg/services/provisioning/datasources/config_reader_test.go
  36. 7
      pkg/services/provisioning/plugins/plugin_provisioner_test.go
  37. 7
      pkg/services/teamguardian/teams_test.go

@ -117,11 +117,11 @@ func TestAdminAPIEndpoint(t *testing.T) {
"/api/admin/users/42/enable", "/api/admin/users/:id/enable", func(sc *scenarioContext) { "/api/admin/users/42/enable", "/api/admin/users/:id/enable", func(sc *scenarioContext) {
var userID int64 var userID int64
isDisabled := false isDisabled := false
bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetAuthInfoQuery) error {
return models.ErrUserNotFound return models.ErrUserNotFound
}) })
bus.AddHandler("test", func(cmd *models.DisableUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DisableUserCommand) error {
userID = cmd.UserId userID = cmd.UserId
isDisabled = cmd.IsDisabled isDisabled = cmd.IsDisabled
return models.ErrUserNotFound return models.ErrUserNotFound
@ -143,11 +143,11 @@ func TestAdminAPIEndpoint(t *testing.T) {
"/api/admin/users/42/disable", "/api/admin/users/:id/disable", func(sc *scenarioContext) { "/api/admin/users/42/disable", "/api/admin/users/:id/disable", func(sc *scenarioContext) {
var userID int64 var userID int64
isDisabled := false isDisabled := false
bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetAuthInfoQuery) error {
return models.ErrUserNotFound return models.ErrUserNotFound
}) })
bus.AddHandler("test", func(cmd *models.DisableUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DisableUserCommand) error {
userID = cmd.UserId userID = cmd.UserId
isDisabled = cmd.IsDisabled isDisabled = cmd.IsDisabled
return models.ErrUserNotFound return models.ErrUserNotFound
@ -170,7 +170,7 @@ func TestAdminAPIEndpoint(t *testing.T) {
adminDisableUserScenario(t, "Should return Could not disable external user error", "disable", adminDisableUserScenario(t, "Should return Could not disable external user error", "disable",
"/api/admin/users/42/disable", "/api/admin/users/:id/disable", func(sc *scenarioContext) { "/api/admin/users/42/disable", "/api/admin/users/:id/disable", func(sc *scenarioContext) {
var userID int64 var userID int64
bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetAuthInfoQuery) error {
userID = cmd.UserId userID = cmd.UserId
return nil return nil
}) })
@ -188,7 +188,7 @@ func TestAdminAPIEndpoint(t *testing.T) {
adminDisableUserScenario(t, "Should return Could not enable external user error", "enable", adminDisableUserScenario(t, "Should return Could not enable external user error", "enable",
"/api/admin/users/42/enable", "/api/admin/users/:id/enable", func(sc *scenarioContext) { "/api/admin/users/42/enable", "/api/admin/users/:id/enable", func(sc *scenarioContext) {
var userID int64 var userID int64
bus.AddHandler("test", func(cmd *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetAuthInfoQuery) error {
userID = cmd.UserId userID = cmd.UserId
return nil return nil
}) })
@ -208,7 +208,7 @@ func TestAdminAPIEndpoint(t *testing.T) {
adminDeleteUserScenario(t, "Should return user not found error", "/api/admin/users/42", adminDeleteUserScenario(t, "Should return user not found error", "/api/admin/users/42",
"/api/admin/users/:id", func(sc *scenarioContext) { "/api/admin/users/:id", func(sc *scenarioContext) {
var userID int64 var userID int64
bus.AddHandler("test", func(cmd *models.DeleteUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DeleteUserCommand) error {
userID = cmd.UserId userID = cmd.UserId
return models.ErrUserNotFound return models.ErrUserNotFound
}) })

@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
@ -25,7 +26,7 @@ func TestAlertingAPIEndpoint(t *testing.T) {
editorRole := models.ROLE_EDITOR editorRole := models.ROLE_EDITOR
setUp := func(confs ...setUpConf) { setUp := func(confs ...setUpConf) {
bus.AddHandler("test", func(query *models.GetAlertByIdQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetAlertByIdQuery) error {
query.Result = singleAlert query.Result = singleAlert
return nil return nil
}) })
@ -36,12 +37,12 @@ func TestAlertingAPIEndpoint(t *testing.T) {
aclMockResp = c.aclMockResp aclMockResp = c.aclMockResp
} }
} }
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp query.Result = aclMockResp
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetTeamsByUserQuery) error {
query.Result = []*models.TeamDTO{} query.Result = []*models.TeamDTO{}
return nil return nil
}) })
@ -85,13 +86,13 @@ func TestAlertingAPIEndpoint(t *testing.T) {
setUp() setUp()
var searchQuery *search.Query var searchQuery *search.Query
bus.AddHandler("test", func(query *search.Query) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *search.Query) error {
searchQuery = query searchQuery = query
return nil return nil
}) })
var getAlertsQuery *models.GetAlertsQuery var getAlertsQuery *models.GetAlertsQuery
bus.AddHandler("test", func(query *models.GetAlertsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetAlertsQuery) error {
getAlertsQuery = query getAlertsQuery = query
return nil return nil
}) })
@ -109,7 +110,7 @@ func TestAlertingAPIEndpoint(t *testing.T) {
setUp() setUp()
var searchQuery *search.Query var searchQuery *search.Query
bus.AddHandler("test", func(query *search.Query) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *search.Query) error {
searchQuery = query searchQuery = query
query.Result = search.HitList{ query.Result = search.HitList{
&search.Hit{ID: 1}, &search.Hit{ID: 1},
@ -119,7 +120,7 @@ func TestAlertingAPIEndpoint(t *testing.T) {
}) })
var getAlertsQuery *models.GetAlertsQuery var getAlertsQuery *models.GetAlertsQuery
bus.AddHandler("test", func(query *models.GetAlertsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetAlertsQuery) error {
getAlertsQuery = query getAlertsQuery = query
return nil return nil
}) })
@ -152,7 +153,7 @@ func TestAlertingAPIEndpoint(t *testing.T) {
} }
func callPauseAlert(sc *scenarioContext) { func callPauseAlert(sc *scenarioContext) {
bus.AddHandler("test", func(cmd *models.PauseAlertCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.PauseAlertCommand) error {
return nil return nil
}) })

@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
@ -133,12 +134,12 @@ func TestAnnotationsAPIEndpoint(t *testing.T) {
} }
setUp := func() { setUp := func() {
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp query.Result = aclMockResp
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetTeamsByUserQuery) error {
query.Result = []*models.TeamDTO{} query.Result = []*models.TeamDTO{}
return nil return nil
}) })

@ -26,7 +26,7 @@ func TestDashboardPermissionAPIEndpoint(t *testing.T) {
t.Run("Given dashboard not exists", func(t *testing.T) { t.Run("Given dashboard not exists", func(t *testing.T) {
setUp := func() { setUp := func() {
bus.AddHandler("test", func(query *models.GetDashboardQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardQuery) error {
return models.ErrDashboardNotFound return models.ErrDashboardNotFound
}) })
} }

@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -44,22 +45,22 @@ func TestDashboardSnapshotAPIEndpoint_singleSnapshot(t *testing.T) {
External: true, External: true,
} }
bus.AddHandler("test", func(query *models.GetDashboardSnapshotQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardSnapshotQuery) error {
query.Result = mockSnapshotResult query.Result = mockSnapshotResult
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.DeleteDashboardSnapshotCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DeleteDashboardSnapshotCommand) error {
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp query.Result = aclMockResp
return nil return nil
}) })
teamResp := []*models.TeamDTO{} teamResp := []*models.TeamDTO{}
bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetTeamsByUserQuery) error {
query.Result = teamResp query.Result = teamResp
return nil return nil
}) })

@ -108,7 +108,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
fakeDash.FolderId = 1 fakeDash.FolderId = 1
fakeDash.HasAcl = false fakeDash.HasAcl = false
bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardsBySlugQuery) error {
dashboards := []*models.Dashboard{fakeDash} dashboards := []*models.Dashboard{fakeDash}
query.Result = dashboards query.Result = dashboards
return nil return nil
@ -130,12 +130,12 @@ func TestDashboardAPIEndpoint(t *testing.T) {
{Role: &editorRole, Permission: models.PERMISSION_EDIT}, {Role: &editorRole, Permission: models.PERMISSION_EDIT},
} }
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp query.Result = aclMockResp
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetTeamsByUserQuery) error {
query.Result = []*models.TeamDTO{} query.Result = []*models.TeamDTO{}
return nil return nil
}) })
@ -262,7 +262,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
}) })
setting.ViewersCanEdit = false setting.ViewersCanEdit = false
bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardsBySlugQuery) error {
dashboards := []*models.Dashboard{fakeDash} dashboards := []*models.Dashboard{fakeDash}
query.Result = dashboards query.Result = dashboards
return nil return nil
@ -276,7 +276,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
}, },
} }
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = aclMockResp query.Result = aclMockResp
return nil return nil
}) })
@ -287,7 +287,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetTeamsByUserQuery) error {
query.Result = []*models.TeamDTO{} query.Result = []*models.TeamDTO{}
return nil return nil
}) })
@ -391,7 +391,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
setUpInner := func() *testState { setUpInner := func() *testState {
state := setUp() state := setUp()
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = mockResult query.Result = mockResult
return nil return nil
}) })
@ -443,7 +443,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
{OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_VIEW}, {OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_VIEW},
} }
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = mockResult query.Result = mockResult
return nil return nil
}) })
@ -487,7 +487,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
mockResult := []*models.DashboardAclInfoDTO{ mockResult := []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_ADMIN}, {OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_ADMIN},
} }
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = mockResult query.Result = mockResult
return nil return nil
}) })
@ -537,7 +537,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
mockResult := []*models.DashboardAclInfoDTO{ mockResult := []*models.DashboardAclInfoDTO{
{OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_VIEW}, {OrgId: 1, DashboardId: 2, UserId: 1, Permission: models.PERMISSION_VIEW},
} }
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = mockResult query.Result = mockResult
return nil return nil
}) })
@ -588,7 +588,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
dashTwo.FolderId = 3 dashTwo.FolderId = 3
dashTwo.HasAcl = false dashTwo.HasAcl = false
bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardsBySlugQuery) error {
dashboards := []*models.Dashboard{dashOne, dashTwo} dashboards := []*models.Dashboard{dashOne, dashTwo}
query.Result = dashboards query.Result = dashboards
return nil return nil
@ -778,12 +778,12 @@ func TestDashboardAPIEndpoint(t *testing.T) {
t.Run("Given two dashboards being compared", func(t *testing.T) { t.Run("Given two dashboards being compared", func(t *testing.T) {
setUp := func() { setUp := func() {
mockResult := []*models.DashboardAclInfoDTO{} mockResult := []*models.DashboardAclInfoDTO{}
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = mockResult query.Result = mockResult
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardVersionQuery) error {
query.Result = &models.DashboardVersion{ query.Result = &models.DashboardVersion{
Data: simplejson.NewFromAny(map[string]interface{}{ Data: simplejson.NewFromAny(map[string]interface{}{
"title": fmt.Sprintf("Dash%d", query.DashboardId), "title": fmt.Sprintf("Dash%d", query.DashboardId),
@ -841,7 +841,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardVersionQuery) error {
query.Result = &models.DashboardVersion{ query.Result = &models.DashboardVersion{
DashboardId: 2, DashboardId: 2,
Version: 1, Version: 1,
@ -889,7 +889,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardVersionQuery) error {
query.Result = &models.DashboardVersion{ query.Result = &models.DashboardVersion{
DashboardId: 2, DashboardId: 2,
Version: 1, Version: 1,
@ -928,7 +928,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
t.Run("Given provisioned dashboard", func(t *testing.T) { t.Run("Given provisioned dashboard", func(t *testing.T) {
setUp := func() { setUp := func() {
bus.AddHandler("test", func(query *models.GetDashboardsBySlugQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardsBySlugQuery) error {
query.Result = []*models.Dashboard{{}} query.Result = []*models.Dashboard{{}}
return nil return nil
}) })
@ -947,7 +947,7 @@ func TestDashboardAPIEndpoint(t *testing.T) {
return &models.DashboardProvisioning{ExternalId: "/tmp/grafana/dashboards/test/dashboard1.json"}, nil return &models.DashboardProvisioning{ExternalId: "/tmp/grafana/dashboards/test/dashboard1.json"}, nil
} }
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = []*models.DashboardAclInfoDTO{ query.Result = []*models.DashboardAclInfoDTO{
{OrgId: testOrgID, DashboardId: 1, UserId: testUserID, Permission: models.PERMISSION_EDIT}, {OrgId: testOrgID, DashboardId: 1, UserId: testUserID, Permission: models.PERMISSION_EDIT},
} }
@ -1049,7 +1049,7 @@ func callGetDashboard(sc *scenarioContext, hs *HTTPServer) {
} }
func callGetDashboardVersion(sc *scenarioContext) { func callGetDashboardVersion(sc *scenarioContext) {
bus.AddHandler("test", func(query *models.GetDashboardVersionQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardVersionQuery) error {
query.Result = &models.DashboardVersion{} query.Result = &models.DashboardVersion{}
return nil return nil
}) })
@ -1059,7 +1059,7 @@ func callGetDashboardVersion(sc *scenarioContext) {
} }
func callGetDashboardVersions(sc *scenarioContext) { func callGetDashboardVersions(sc *scenarioContext) {
bus.AddHandler("test", func(query *models.GetDashboardVersionsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardVersionsQuery) error {
query.Result = []*models.DashboardVersionDTO{} query.Result = []*models.DashboardVersionDTO{}
return nil return nil
}) })
@ -1069,7 +1069,7 @@ func callGetDashboardVersions(sc *scenarioContext) {
} }
func callDeleteDashboardBySlug(sc *scenarioContext, hs *HTTPServer) { func callDeleteDashboardBySlug(sc *scenarioContext, hs *HTTPServer) {
bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
return nil return nil
}) })
@ -1078,7 +1078,7 @@ func callDeleteDashboardBySlug(sc *scenarioContext, hs *HTTPServer) {
} }
func callDeleteDashboardByUID(sc *scenarioContext, hs *HTTPServer) { func callDeleteDashboardByUID(sc *scenarioContext, hs *HTTPServer) {
bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
return nil return nil
}) })

@ -2,6 +2,7 @@ package api
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@ -29,7 +30,7 @@ const (
func TestDataSourcesProxy_userLoggedIn(t *testing.T) { func TestDataSourcesProxy_userLoggedIn(t *testing.T) {
loggedInUserScenario(t, "When calling GET on", "/api/datasources/", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET on", "/api/datasources/", func(sc *scenarioContext) {
// Stubs the database query // Stubs the database query
bus.AddHandler("test", func(query *models.GetDataSourcesQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDataSourcesQuery) error {
assert.Equal(t, testOrgID, query.OrgId) assert.Equal(t, testOrgID, query.OrgId)
query.Result = []*models.DataSource{ query.Result = []*models.DataSource{
{Name: "mmm"}, {Name: "mmm"},
@ -102,7 +103,7 @@ func TestAddDataSource_URLWithoutProtocol(t *testing.T) {
const url = "localhost:5432" const url = "localhost:5432"
// Stub handler // Stub handler
bus.AddHandler("sql", func(cmd *models.AddDataSourceCommand) error { bus.AddHandlerCtx("sql", func(ctx context.Context, cmd *models.AddDataSourceCommand) error {
assert.Equal(t, name, cmd.Name) assert.Equal(t, name, cmd.Name)
assert.Equal(t, url, cmd.Url) assert.Equal(t, url, cmd.Url)
@ -156,7 +157,7 @@ func TestUpdateDataSource_URLWithoutProtocol(t *testing.T) {
const url = "localhost:5432" const url = "localhost:5432"
// Stub handler // Stub handler
bus.AddHandler("sql", func(cmd *models.AddDataSourceCommand) error { bus.AddHandlerCtx("sql", func(ctx context.Context, cmd *models.AddDataSourceCommand) error {
assert.Equal(t, name, cmd.Name) assert.Equal(t, name, cmd.Name)
assert.Equal(t, url, cmd.Url) assert.Equal(t, url, cmd.Url)
@ -191,26 +192,26 @@ func TestAPI_Datasources_AccessControl(t *testing.T) {
Type: "postgresql", Type: "postgresql",
Access: "Proxy", Access: "Proxy",
} }
getDatasourceStub := func(query *models.GetDataSourceQuery) error { getDatasourceStub := func(ctx context.Context, query *models.GetDataSourceQuery) error {
result := testDatasource result := testDatasource
result.Id = query.Id result.Id = query.Id
result.OrgId = query.OrgId result.OrgId = query.OrgId
query.Result = &result query.Result = &result
return nil return nil
} }
getDatasourcesStub := func(cmd *models.GetDataSourcesQuery) error { getDatasourcesStub := func(ctx context.Context, cmd *models.GetDataSourcesQuery) error {
cmd.Result = []*models.DataSource{} cmd.Result = []*models.DataSource{}
return nil return nil
} }
addDatasourceStub := func(cmd *models.AddDataSourceCommand) error { addDatasourceStub := func(ctx context.Context, cmd *models.AddDataSourceCommand) error {
cmd.Result = &testDatasource cmd.Result = &testDatasource
return nil return nil
} }
updateDatasourceStub := func(cmd *models.UpdateDataSourceCommand) error { updateDatasourceStub := func(ctx context.Context, cmd *models.UpdateDataSourceCommand) error {
cmd.Result = &testDatasource cmd.Result = &testDatasource
return nil return nil
} }
deleteDatasourceStub := func(cmd *models.DeleteDataSourceCommand) error { deleteDatasourceStub := func(ctx context.Context, cmd *models.DeleteDataSourceCommand) error {
cmd.DeletedDatasourcesCount = 1 cmd.DeletedDatasourcesCount = 1
return nil return nil
} }
@ -477,7 +478,7 @@ func TestAPI_Datasources_AccessControl(t *testing.T) {
t.Run(test.desc, func(t *testing.T) { t.Run(test.desc, func(t *testing.T) {
t.Cleanup(bus.ClearBusHandlers) t.Cleanup(bus.ClearBusHandlers)
for i, handler := range test.busStubs { for i, handler := range test.busStubs {
bus.AddHandler(fmt.Sprintf("test_handler_%v", i), handler) bus.AddHandlerCtx(fmt.Sprintf("test_handler_%v", i), handler)
} }
cfg := setting.NewCfg() cfg := setting.NewCfg()

@ -132,7 +132,7 @@ func TestGetUserFromLDAPAPIEndpoint_OrgNotfound(t *testing.T) {
{Id: 1, Name: "Main Org."}, {Id: 1, Name: "Main Org."},
} }
bus.AddHandler("test", func(query *models.SearchOrgsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchOrgsQuery) error {
query.Result = mockOrgSearchResult query.Result = mockOrgSearchResult
return nil return nil
}) })
@ -194,7 +194,7 @@ func TestGetUserFromLDAPAPIEndpoint(t *testing.T) {
{Id: 1, Name: "Main Org."}, {Id: 1, Name: "Main Org."},
} }
bus.AddHandler("test", func(query *models.SearchOrgsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchOrgsQuery) error {
query.Result = mockOrgSearchResult query.Result = mockOrgSearchResult
return nil return nil
}) })
@ -269,12 +269,12 @@ func TestGetUserFromLDAPAPIEndpoint_WithTeamHandler(t *testing.T) {
{Id: 1, Name: "Main Org."}, {Id: 1, Name: "Main Org."},
} }
bus.AddHandler("test", func(query *models.SearchOrgsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchOrgsQuery) error {
query.Result = mockOrgSearchResult query.Result = mockOrgSearchResult
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.GetTeamsForLDAPGroupCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetTeamsForLDAPGroupCommand) error {
cmd.Result = []models.TeamOrgGroupDTO{} cmd.Result = []models.TeamOrgGroupDTO{}
return nil return nil
}) })
@ -430,7 +430,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_Success(t *testing.T) {
Login: "ldap-daniel", Login: "ldap-daniel",
} }
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
require.Equal(t, "ldap-daniel", cmd.ExternalUser.Login) require.Equal(t, "ldap-daniel", cmd.ExternalUser.Login)
return nil return nil
}) })
@ -442,7 +442,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_Success(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(q *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, q *models.GetAuthInfoQuery) error {
require.Equal(t, q.UserId, int64(34)) require.Equal(t, q.UserId, int64(34))
require.Equal(t, q.AuthModule, models.AuthModuleLDAP) require.Equal(t, q.AuthModule, models.AuthModuleLDAP)
@ -510,7 +510,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenGrafanaAdmin(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(q *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, q *models.GetAuthInfoQuery) error {
require.Equal(t, q.UserId, int64(34)) require.Equal(t, q.UserId, int64(34))
require.Equal(t, q.AuthModule, models.AuthModuleLDAP) require.Equal(t, q.AuthModule, models.AuthModuleLDAP)
@ -542,7 +542,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenUserNotInLDAP(t *testing.T) {
userSearchResult = nil userSearchResult = nil
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
require.Equal(t, "ldap-daniel", cmd.ExternalUser.Login) require.Equal(t, "ldap-daniel", cmd.ExternalUser.Login)
return nil return nil
}) })
@ -554,14 +554,14 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenUserNotInLDAP(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(q *models.GetExternalUserInfoByLoginQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, q *models.GetExternalUserInfoByLoginQuery) error {
assert.Equal(t, "ldap-daniel", q.LoginOrEmail) assert.Equal(t, "ldap-daniel", q.LoginOrEmail)
q.Result = &models.ExternalUserInfo{IsDisabled: true, UserId: 34} q.Result = &models.ExternalUserInfo{IsDisabled: true, UserId: 34}
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.DisableUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DisableUserCommand) error {
assert.Equal(t, 34, cmd.UserId) assert.Equal(t, 34, cmd.UserId)
return nil return nil
}) })
@ -693,11 +693,11 @@ func TestLDAP_AccessControl(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(q *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, q *models.GetAuthInfoQuery) error {
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
return nil return nil
}) })

@ -348,7 +348,7 @@ func TestLoginPostRedirect(t *testing.T) {
return hs.LoginPost(c) return hs.LoginPost(c)
}) })
bus.AddHandler("grafana-auth", func(query *models.LoginUserQuery) error { bus.AddHandlerCtx("grafana-auth", func(ctx context.Context, query *models.LoginUserQuery) error {
query.User = &models.User{ query.User = &models.User{
Id: 42, Id: 42,
Email: "", Email: "",
@ -685,7 +685,7 @@ func TestLoginPostRunLokingHook(t *testing.T) {
for _, c := range testCases { for _, c := range testCases {
t.Run(c.desc, func(t *testing.T) { t.Run(c.desc, func(t *testing.T) {
bus.AddHandler("grafana-auth", func(query *models.LoginUserQuery) error { bus.AddHandlerCtx("grafana-auth", func(ctx context.Context, query *models.LoginUserQuery) error {
query.User = c.authUser query.User = c.authUser
query.AuthModule = c.authModule query.AuthModule = c.authModule
return c.authErr return c.authErr

@ -460,7 +460,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) {
}) })
t.Run("When proxying a datasource that has OAuth token pass-through enabled", func(t *testing.T) { t.Run("When proxying a datasource that has OAuth token pass-through enabled", func(t *testing.T) {
bus.AddHandler("test", func(query *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetAuthInfoQuery) error {
query.Result = &models.UserAuth{ query.Result = &models.UserAuth{
Id: 1, Id: 1,
UserId: 1, UserId: 1,

@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"encoding/json" "encoding/json"
"net/http" "net/http"
"testing" "testing"
@ -14,7 +15,7 @@ import (
) )
func setUpGetTeamMembersHandler() { func setUpGetTeamMembersHandler() {
bus.AddHandler("test", func(query *models.GetTeamMembersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetTeamMembersQuery) error {
query.Result = []*models.TeamMemberDTO{ query.Result = []*models.TeamMemberDTO{
{Email: "testUser@grafana.com", Login: testUserLogin}, {Email: "testUser@grafana.com", Login: testUserLogin},
{Email: "user1@grafana.com", Login: "user1"}, {Email: "user1@grafana.com", Login: "user1"},

@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"testing" "testing"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
@ -45,7 +46,7 @@ func TestTeamAPIEndpoint(t *testing.T) {
loggedInUserScenario(t, "When calling GET on", "/api/teams/search", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET on", "/api/teams/search", func(sc *scenarioContext) {
var sentLimit int var sentLimit int
var sendPage int var sendPage int
bus.AddHandler("test", func(query *models.SearchTeamsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchTeamsQuery) error {
query.Result = mockResult query.Result = mockResult
sentLimit = query.Limit sentLimit = query.Limit
@ -70,7 +71,7 @@ func TestTeamAPIEndpoint(t *testing.T) {
loggedInUserScenario(t, "When calling GET on", "/api/teams/search", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET on", "/api/teams/search", func(sc *scenarioContext) {
var sentLimit int var sentLimit int
var sendPage int var sendPage int
bus.AddHandler("test", func(query *models.SearchTeamsQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchTeamsQuery) error {
query.Result = mockResult query.Result = mockResult
sentLimit = query.Limit sentLimit = query.Limit

@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"testing" "testing"
@ -29,7 +30,7 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
loggedInUserScenario(t, "When calling GET on", "api/users/:id", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET on", "api/users/:id", func(sc *scenarioContext) {
fakeNow := time.Date(2019, 2, 11, 17, 30, 40, 0, time.UTC) fakeNow := time.Date(2019, 2, 11, 17, 30, 40, 0, time.UTC)
bus.AddHandler("test", func(query *models.GetUserProfileQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetUserProfileQuery) error {
query.Result = models.UserProfileDTO{ query.Result = models.UserProfileDTO{
Id: int64(1), Id: int64(1),
Email: "daniel@grafana.com", Email: "daniel@grafana.com",
@ -45,7 +46,7 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetAuthInfoQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetAuthInfoQuery) error {
query.Result = &models.UserAuth{ query.Result = &models.UserAuth{
AuthModule: models.AuthModuleLDAP, AuthModule: models.AuthModuleLDAP,
} }
@ -82,7 +83,7 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
loggedInUserScenario(t, "When calling GET on", "/api/users/lookup", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET on", "/api/users/lookup", func(sc *scenarioContext) {
fakeNow := time.Date(2019, 2, 11, 17, 30, 40, 0, time.UTC) fakeNow := time.Date(2019, 2, 11, 17, 30, 40, 0, time.UTC)
bus.AddHandler("test", func(query *models.GetUserByLoginQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetUserByLoginQuery) error {
require.Equal(t, "danlee", query.LoginOrEmail) require.Equal(t, "danlee", query.LoginOrEmail)
query.Result = &models.User{ query.Result = &models.User{
@ -129,7 +130,7 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
loggedInUserScenario(t, "When calling GET on", "/api/users", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET on", "/api/users", func(sc *scenarioContext) {
var sentLimit int var sentLimit int
var sendPage int var sendPage int
bus.AddHandler("test", func(query *models.SearchUsersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchUsersQuery) error {
query.Result = mockResult query.Result = mockResult
sentLimit = query.Limit sentLimit = query.Limit
@ -153,7 +154,7 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
loggedInUserScenario(t, "When calling GET with page and limit querystring parameters on", "/api/users", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET with page and limit querystring parameters on", "/api/users", func(sc *scenarioContext) {
var sentLimit int var sentLimit int
var sendPage int var sendPage int
bus.AddHandler("test", func(query *models.SearchUsersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchUsersQuery) error {
query.Result = mockResult query.Result = mockResult
sentLimit = query.Limit sentLimit = query.Limit
@ -173,7 +174,7 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
loggedInUserScenario(t, "When calling GET on", "/api/users/search", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET on", "/api/users/search", func(sc *scenarioContext) {
var sentLimit int var sentLimit int
var sendPage int var sendPage int
bus.AddHandler("test", func(query *models.SearchUsersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchUsersQuery) error {
query.Result = mockResult query.Result = mockResult
sentLimit = query.Limit sentLimit = query.Limit
@ -199,7 +200,7 @@ func TestUserAPIEndpoint_userLoggedIn(t *testing.T) {
loggedInUserScenario(t, "When calling GET with page and perpage querystring parameters on", "/api/users/search", func(sc *scenarioContext) { loggedInUserScenario(t, "When calling GET with page and perpage querystring parameters on", "/api/users/search", func(sc *scenarioContext) {
var sentLimit int var sentLimit int
var sendPage int var sendPage int
bus.AddHandler("test", func(query *models.SearchUsersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SearchUsersQuery) error {
query.Result = mockResult query.Result = mockResult
sentLimit = query.Limit sentLimit = query.Limit

@ -18,7 +18,7 @@ func TestDispatch(t *testing.T) {
var invoked bool var invoked bool
bus.AddHandler(func(query *testQuery) error { bus.AddHandlerCtx(func(ctx context.Context, query *testQuery) error {
invoked = true invoked = true
return nil return nil
}) })
@ -74,7 +74,7 @@ func TestDispatchCtx_NoContextHandler(t *testing.T) {
var invoked bool var invoked bool
bus.AddHandler(func(query *testQuery) error { bus.AddHandlerCtx(func(ctx context.Context, query *testQuery) error {
invoked = true invoked = true
return nil return nil
}) })
@ -98,7 +98,7 @@ func TestQuery(t *testing.T) {
want := "hello from handler" want := "hello from handler"
bus.AddHandler(func(q *testQuery) error { bus.AddHandlerCtx(func(ctx context.Context, q *testQuery) error {
q.Resp = want q.Resp = want
return nil return nil
}) })
@ -114,7 +114,7 @@ func TestQuery(t *testing.T) {
func TestQuery_HandlerReturnsError(t *testing.T) { func TestQuery_HandlerReturnsError(t *testing.T) {
bus := New() bus := New()
bus.AddHandler(func(query *testQuery) error { bus.AddHandlerCtx(func(ctx context.Context, query *testQuery) error {
return errors.New("handler error") return errors.New("handler error")
}) })

@ -41,7 +41,7 @@ func TestMetrics(t *testing.T) {
setupSomeDataSourcePlugins(t, uss) setupSomeDataSourcePlugins(t, uss)
var getSystemStatsQuery *models.GetSystemStatsQuery var getSystemStatsQuery *models.GetSystemStatsQuery
uss.Bus.AddHandler(func(query *models.GetSystemStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error {
query.Result = &models.SystemStats{ query.Result = &models.SystemStats{
Dashboards: 1, Dashboards: 1,
Datasources: 2, Datasources: 2,
@ -85,7 +85,7 @@ func TestMetrics(t *testing.T) {
}) })
var getDataSourceStatsQuery *models.GetDataSourceStatsQuery var getDataSourceStatsQuery *models.GetDataSourceStatsQuery
uss.Bus.AddHandler(func(query *models.GetDataSourceStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error {
query.Result = []*models.DataSourceStats{ query.Result = []*models.DataSourceStats{
{ {
Type: models.DS_ES, Type: models.DS_ES,
@ -109,7 +109,7 @@ func TestMetrics(t *testing.T) {
}) })
var getESDatasSourcesQuery *models.GetDataSourcesByTypeQuery var getESDatasSourcesQuery *models.GetDataSourcesByTypeQuery
uss.Bus.AddHandler(func(query *models.GetDataSourcesByTypeQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error {
query.Result = []*models.DataSource{ query.Result = []*models.DataSource{
{ {
JsonData: simplejson.NewFromAny(map[string]interface{}{ JsonData: simplejson.NewFromAny(map[string]interface{}{
@ -132,7 +132,7 @@ func TestMetrics(t *testing.T) {
}) })
var getDataSourceAccessStatsQuery *models.GetDataSourceAccessStatsQuery var getDataSourceAccessStatsQuery *models.GetDataSourceAccessStatsQuery
uss.Bus.AddHandler(func(query *models.GetDataSourceAccessStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error {
query.Result = []*models.DataSourceAccessStats{ query.Result = []*models.DataSourceAccessStats{
{ {
Type: models.DS_ES, Type: models.DS_ES,
@ -180,7 +180,7 @@ func TestMetrics(t *testing.T) {
}) })
var getAlertNotifierUsageStatsQuery *models.GetAlertNotifierUsageStatsQuery var getAlertNotifierUsageStatsQuery *models.GetAlertNotifierUsageStatsQuery
uss.Bus.AddHandler(func(query *models.GetAlertNotifierUsageStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error {
query.Result = []*models.NotifierUsageStats{ query.Result = []*models.NotifierUsageStats{
{ {
Type: "slack", Type: "slack",
@ -401,7 +401,7 @@ func TestMetrics(t *testing.T) {
uss.Cfg.MetricsEndpointEnabled = true uss.Cfg.MetricsEndpointEnabled = true
uss.Cfg.MetricsEndpointDisableTotalStats = false uss.Cfg.MetricsEndpointDisableTotalStats = false
getSystemStatsWasCalled := false getSystemStatsWasCalled := false
uss.Bus.AddHandler(func(query *models.GetSystemStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error {
query.Result = &models.SystemStats{} query.Result = &models.SystemStats{}
getSystemStatsWasCalled = true getSystemStatsWasCalled = true
return nil return nil
@ -462,27 +462,27 @@ func TestMetrics(t *testing.T) {
uss := createService(t, setting.Cfg{}) uss := createService(t, setting.Cfg{})
metricName := "stats.test_metric.count" metricName := "stats.test_metric.count"
uss.Bus.AddHandler(func(query *models.GetSystemStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetSystemStatsQuery) error {
query.Result = &models.SystemStats{} query.Result = &models.SystemStats{}
return nil return nil
}) })
uss.Bus.AddHandler(func(query *models.GetDataSourceStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceStatsQuery) error {
query.Result = []*models.DataSourceStats{} query.Result = []*models.DataSourceStats{}
return nil return nil
}) })
uss.Bus.AddHandler(func(query *models.GetDataSourcesByTypeQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourcesByTypeQuery) error {
query.Result = []*models.DataSource{} query.Result = []*models.DataSource{}
return nil return nil
}) })
uss.Bus.AddHandler(func(query *models.GetDataSourceAccessStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetDataSourceAccessStatsQuery) error {
query.Result = []*models.DataSourceAccessStats{} query.Result = []*models.DataSourceAccessStats{}
return nil return nil
}) })
uss.Bus.AddHandler(func(query *models.GetAlertNotifierUsageStatsQuery) error { uss.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAlertNotifierUsageStatsQuery) error {
query.Result = []*models.NotifierUsageStats{} query.Result = []*models.NotifierUsageStats{}
return nil return nil
}) })

@ -73,7 +73,7 @@ func TestSaveInvalidLoginAttempt(t *testing.T) {
t.Cleanup(func() { bus.ClearBusHandlers() }) t.Cleanup(func() { bus.ClearBusHandlers() })
createLoginAttemptCmd := &models.CreateLoginAttemptCommand{} createLoginAttemptCmd := &models.CreateLoginAttemptCommand{}
bus.AddHandler("test", func(cmd *models.CreateLoginAttemptCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.CreateLoginAttemptCommand) error {
createLoginAttemptCmd = cmd createLoginAttemptCmd = cmd
return nil return nil
}) })
@ -95,7 +95,7 @@ func TestSaveInvalidLoginAttempt(t *testing.T) {
t.Cleanup(func() { bus.ClearBusHandlers() }) t.Cleanup(func() { bus.ClearBusHandlers() })
var createLoginAttemptCmd *models.CreateLoginAttemptCommand var createLoginAttemptCmd *models.CreateLoginAttemptCommand
bus.AddHandler("test", func(cmd *models.CreateLoginAttemptCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.CreateLoginAttemptCommand) error {
createLoginAttemptCmd = cmd createLoginAttemptCmd = cmd
return nil return nil
}) })
@ -128,7 +128,7 @@ func cfgWithBruteForceLoginProtectionEnabled(t *testing.T) *setting.Cfg {
func withLoginAttempts(t *testing.T, loginAttempts int64) { func withLoginAttempts(t *testing.T, loginAttempts int64) {
t.Helper() t.Helper()
bus.AddHandler("test", func(query *models.GetUserLoginAttemptCountQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetUserLoginAttemptCountQuery) error {
query.Result = loginAttempts query.Result = loginAttempts
return nil return nil
}) })

@ -95,7 +95,7 @@ func mockPasswordValidation(valid bool, sc *grafanaLoginScenarioContext) {
} }
func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *models.User) { func (sc *grafanaLoginScenarioContext) getUserByLoginQueryReturns(user *models.User) {
bus.AddHandler("test", func(query *models.GetUserByLoginQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetUserByLoginQuery) error {
if user == nil { if user == nil {
return models.ErrUserNotFound return models.ErrUserNotFound
} }

@ -1,6 +1,7 @@
package middleware package middleware
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
@ -40,7 +41,7 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "ReqSignIn true and NoAnonynmous true", func( middlewareScenario(t, "ReqSignIn true and NoAnonynmous true", func(
t *testing.T, sc *scenarioContext) { t *testing.T, sc *scenarioContext) {
bus.AddHandler("test", func(query *models.GetOrgByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetOrgByNameQuery) error {
query.Result = &models.Org{Id: orgID, Name: "test"} query.Result = &models.Org{Id: orgID, Name: "test"}
return nil return nil
}) })
@ -53,7 +54,7 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "ReqSignIn true and request with forceLogin in query string", func( middlewareScenario(t, "ReqSignIn true and request with forceLogin in query string", func(
t *testing.T, sc *scenarioContext) { t *testing.T, sc *scenarioContext) {
bus.AddHandler("test", func(query *models.GetOrgByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetOrgByNameQuery) error {
query.Result = &models.Org{Id: orgID, Name: "test"} query.Result = &models.Org{Id: orgID, Name: "test"}
return nil return nil
}) })
@ -82,7 +83,7 @@ func TestMiddlewareAuth(t *testing.T) {
middlewareScenario(t, "ReqSignIn true and request with different org provided in query string", func( middlewareScenario(t, "ReqSignIn true and request with different org provided in query string", func(
t *testing.T, sc *scenarioContext) { t *testing.T, sc *scenarioContext) {
bus.AddHandler("test", func(query *models.GetOrgByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetOrgByNameQuery) error {
query.Result = &models.Org{Id: orgID, Name: "test"} query.Result = &models.Org{Id: orgID, Name: "test"}
return nil return nil
}) })

@ -28,7 +28,7 @@ func TestMiddlewareBasicAuth(t *testing.T) {
keyhash, err := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd") keyhash, err := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
require.NoError(t, err) require.NoError(t, err)
bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetApiKeyByNameQuery) error {
query.Result = &models.ApiKey{OrgId: orgID, Role: models.ROLE_EDITOR, Key: keyhash} query.Result = &models.ApiKey{OrgId: orgID, Role: models.ROLE_EDITOR, Key: keyhash}
return nil return nil
}) })
@ -47,7 +47,7 @@ func TestMiddlewareBasicAuth(t *testing.T) {
const salt = "Salt" const salt = "Salt"
const orgID int64 = 2 const orgID int64 = 2
bus.AddHandler("grafana-auth", func(query *models.LoginUserQuery) error { bus.AddHandlerCtx("grafana-auth", func(ctx context.Context, query *models.LoginUserQuery) error {
t.Log("Handling LoginUserQuery") t.Log("Handling LoginUserQuery")
encoded, err := util.EncodePassword(password, salt) encoded, err := util.EncodePassword(password, salt)
if err != nil { if err != nil {
@ -80,7 +80,7 @@ func TestMiddlewareBasicAuth(t *testing.T) {
login.Init() login.Init()
bus.AddHandler("user-query", func(query *models.GetUserByLoginQuery) error { bus.AddHandlerCtx("user-query", func(ctx context.Context, query *models.GetUserByLoginQuery) error {
encoded, err := util.EncodePassword(password, salt) encoded, err := util.EncodePassword(password, salt)
if err != nil { if err != nil {
return err return err
@ -119,7 +119,7 @@ func TestMiddlewareBasicAuth(t *testing.T) {
}, configure) }, configure)
middlewareScenario(t, "Should return error if user & password do not match", func(t *testing.T, sc *scenarioContext) { middlewareScenario(t, "Should return error if user & password do not match", func(t *testing.T, sc *scenarioContext) {
bus.AddHandler("user-query", func(loginUserQuery *models.GetUserByLoginQuery) error { bus.AddHandlerCtx("user-query", func(ctx context.Context, loginUserQuery *models.GetUserByLoginQuery) error {
return nil return nil
}) })

@ -149,7 +149,7 @@ func TestMiddlewareContext(t *testing.T) {
keyhash, err := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd") keyhash, err := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
require.NoError(t, err) require.NoError(t, err)
bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetApiKeyByNameQuery) error {
query.Result = &models.ApiKey{OrgId: orgID, Role: models.ROLE_EDITOR, Key: keyhash} query.Result = &models.ApiKey{OrgId: orgID, Role: models.ROLE_EDITOR, Key: keyhash}
return nil return nil
}) })
@ -166,7 +166,7 @@ func TestMiddlewareContext(t *testing.T) {
middlewareScenario(t, "Valid API key, but does not match DB hash", func(t *testing.T, sc *scenarioContext) { middlewareScenario(t, "Valid API key, but does not match DB hash", func(t *testing.T, sc *scenarioContext) {
const keyhash = "Something_not_matching" const keyhash = "Something_not_matching"
bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetApiKeyByNameQuery) error {
query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash} query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash}
return nil return nil
}) })
@ -183,7 +183,7 @@ func TestMiddlewareContext(t *testing.T) {
keyhash, err := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd") keyhash, err := util.EncodePassword("v5nAwpMafFP6znaS4urhdWDLS5511M42", "asd")
require.NoError(t, err) require.NoError(t, err)
bus.AddHandler("test", func(query *models.GetApiKeyByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetApiKeyByNameQuery) error {
// api key expired one second before // api key expired one second before
expires := sc.contextHandler.GetTime().Add(-1 * time.Second).Unix() expires := sc.contextHandler.GetTime().Add(-1 * time.Second).Unix()
query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash, query.Result = &models.ApiKey{OrgId: 12, Role: models.ROLE_EDITOR, Key: keyhash,
@ -389,7 +389,7 @@ func TestMiddlewareContext(t *testing.T) {
middlewareScenario(t, "Should respect auto signup option", func(t *testing.T, sc *scenarioContext) { middlewareScenario(t, "Should respect auto signup option", func(t *testing.T, sc *scenarioContext) {
var actualAuthProxyAutoSignUp *bool = nil var actualAuthProxyAutoSignUp *bool = nil
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
actualAuthProxyAutoSignUp = &cmd.SignupAllowed actualAuthProxyAutoSignUp = &cmd.SignupAllowed
return login.ErrInvalidCredentials return login.ErrInvalidCredentials
}) })
@ -416,7 +416,7 @@ func TestMiddlewareContext(t *testing.T) {
return models.ErrUserNotFound return models.ErrUserNotFound
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
return nil return nil
}) })
@ -444,7 +444,7 @@ func TestMiddlewareContext(t *testing.T) {
return models.ErrUserNotFound return models.ErrUserNotFound
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
storedRoleInfo = cmd.ExternalUser.OrgRoles storedRoleInfo = cmd.ExternalUser.OrgRoles
return nil return nil
@ -475,7 +475,7 @@ func TestMiddlewareContext(t *testing.T) {
return models.ErrUserNotFound return models.ErrUserNotFound
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
storedRoleInfo = cmd.ExternalUser.OrgRoles storedRoleInfo = cmd.ExternalUser.OrgRoles
return nil return nil
@ -508,7 +508,7 @@ func TestMiddlewareContext(t *testing.T) {
return models.ErrUserNotFound return models.ErrUserNotFound
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
return nil return nil
}) })
@ -560,7 +560,7 @@ func TestMiddlewareContext(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
return nil return nil
}) })
@ -583,7 +583,7 @@ func TestMiddlewareContext(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
return nil return nil
}) })
@ -608,7 +608,7 @@ func TestMiddlewareContext(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
return nil return nil
}) })
@ -627,7 +627,7 @@ func TestMiddlewareContext(t *testing.T) {
}) })
middlewareScenario(t, "Should return 407 status code if LDAP says no", func(t *testing.T, sc *scenarioContext) { middlewareScenario(t, "Should return 407 status code if LDAP says no", func(t *testing.T, sc *scenarioContext) {
bus.AddHandler("LDAP", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("LDAP", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
return errors.New("Do not add user") return errors.New("Do not add user")
}) })

@ -13,7 +13,7 @@ import (
func TestOrgRedirectMiddleware(t *testing.T) { func TestOrgRedirectMiddleware(t *testing.T) {
middlewareScenario(t, "when setting a correct org for the user", func(t *testing.T, sc *scenarioContext) { middlewareScenario(t, "when setting a correct org for the user", func(t *testing.T, sc *scenarioContext) {
sc.withTokenSessionCookie("token") sc.withTokenSessionCookie("token")
bus.AddHandler("test", func(query *models.SetUsingOrgCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SetUsingOrgCommand) error {
return nil return nil
}) })
@ -37,7 +37,7 @@ func TestOrgRedirectMiddleware(t *testing.T) {
middlewareScenario(t, "when setting an invalid org for user", func(t *testing.T, sc *scenarioContext) { middlewareScenario(t, "when setting an invalid org for user", func(t *testing.T, sc *scenarioContext) {
sc.withTokenSessionCookie("token") sc.withTokenSessionCookie("token")
bus.AddHandler("test", func(query *models.SetUsingOrgCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.SetUsingOrgCommand) error {
return fmt.Errorf("") return fmt.Errorf("")
}) })

@ -110,7 +110,7 @@ func TestMiddlewareQuota(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("userQuota", func(query *models.GetUserQuotaByTargetQuery) error { bus.AddHandlerCtx("userQuota", func(_ context.Context, query *models.GetUserQuotaByTargetQuery) error {
query.Result = &models.UserQuotaDTO{ query.Result = &models.UserQuotaDTO{
Target: query.Target, Target: query.Target,
Limit: query.Default, Limit: query.Default,
@ -119,7 +119,7 @@ func TestMiddlewareQuota(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("orgQuota", func(query *models.GetOrgQuotaByTargetQuery) error { bus.AddHandlerCtx("orgQuota", func(_ context.Context, query *models.GetOrgQuotaByTargetQuery) error {
query.Result = &models.OrgQuotaDTO{ query.Result = &models.OrgQuotaDTO{
Target: query.Target, Target: query.Target,
Limit: query.Default, Limit: query.Default,

@ -18,7 +18,7 @@ func TestAlertingUsageStats(t *testing.T) {
Bus: bus.New(), Bus: bus.New(),
} }
ae.Bus.AddHandler(func(query *models.GetAllAlertsQuery) error { ae.Bus.AddHandlerCtx(func(ctx context.Context, query *models.GetAllAlertsQuery) error {
var createFake = func(file string) *simplejson.Json { var createFake = func(file string) *simplejson.Json {
// Ignore gosec warning G304 since it's a test // Ignore gosec warning G304 since it's a test
// nolint:gosec // nolint:gosec

@ -53,7 +53,7 @@ func TestEngineProcessJob(t *testing.T) {
job := &Job{running: true, Rule: &Rule{}} job := &Job{running: true, Rule: &Rule{}}
t.Run("Should register usage metrics func", func(t *testing.T) { t.Run("Should register usage metrics func", func(t *testing.T) {
bus.AddHandler(func(q *models.GetAllAlertsQuery) error { bus.AddHandlerCtx(func(ctx context.Context, q *models.GetAllAlertsQuery) error {
settings, err := simplejson.NewJson([]byte(`{"conditions": [{"query": { "datasourceId": 1}}]}`)) settings, err := simplejson.NewJson([]byte(`{"conditions": [{"query": { "datasourceId": 1}}]}`))
if err != nil { if err != nil {
return err return err
@ -62,7 +62,7 @@ func TestEngineProcessJob(t *testing.T) {
return nil return nil
}) })
bus.AddHandler(func(q *models.GetDataSourceQuery) error { bus.AddHandlerCtx(func(ctx context.Context, q *models.GetDataSourceQuery) error {
q.Result = &models.DataSource{Id: 1, Type: models.DS_PROMETHEUS} q.Result = &models.DataSource{Id: 1, Type: models.DS_PROMETHEUS}
return nil return nil
}) })

@ -24,12 +24,12 @@ func TestAlertRuleExtraction(t *testing.T) {
influxDBDs := &models.DataSource{Id: 16, OrgId: 1, Name: "InfluxDB", Uid: "InfluxDB-uid"} influxDBDs := &models.DataSource{Id: 16, OrgId: 1, Name: "InfluxDB", Uid: "InfluxDB-uid"}
prom := &models.DataSource{Id: 17, OrgId: 1, Name: "Prometheus", Uid: "Prometheus-uid"} prom := &models.DataSource{Id: 17, OrgId: 1, Name: "Prometheus", Uid: "Prometheus-uid"}
bus.AddHandler("test", func(query *models.GetDefaultDataSourceQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDefaultDataSourceQuery) error {
query.Result = defaultDs query.Result = defaultDs
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetDataSourceQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDataSourceQuery) error {
if query.Name == defaultDs.Name || query.Uid == defaultDs.Uid { if query.Name == defaultDs.Name || query.Uid == defaultDs.Uid {
query.Result = defaultDs query.Result = defaultDs
} }

@ -32,7 +32,7 @@ func TestInitContextWithAuthProxy_CachedInvalidUserID(t *testing.T) {
// XXX: These handlers have to be injected AFTER calling getContextHandler, since the latter // XXX: These handlers have to be injected AFTER calling getContextHandler, since the latter
// creates a SQLStore which installs its own handlers. // creates a SQLStore which installs its own handlers.
upsertHandler := func(cmd *models.UpsertUserCommand) error { upsertHandler := func(ctx context.Context, cmd *models.UpsertUserCommand) error {
require.Equal(t, name, cmd.ExternalUser.Login) require.Equal(t, name, cmd.ExternalUser.Login)
cmd.Result = &models.User{Id: userID} cmd.Result = &models.User{Id: userID}
return nil return nil
@ -49,7 +49,7 @@ func TestInitContextWithAuthProxy_CachedInvalidUserID(t *testing.T) {
} }
return nil return nil
} }
bus.AddHandler("", upsertHandler) bus.AddHandlerCtx("", upsertHandler)
bus.AddHandlerCtx("", getUserHandler) bus.AddHandlerCtx("", getUserHandler)
t.Cleanup(func() { t.Cleanup(func() {
bus.ClearBusHandlers() bus.ClearBusHandlers()

@ -1,6 +1,7 @@
package authproxy package authproxy
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"net/http" "net/http"
@ -130,7 +131,7 @@ func TestMiddlewareContext_ldap(t *testing.T) {
t.Run("Logs in via LDAP", func(t *testing.T) { t.Run("Logs in via LDAP", func(t *testing.T) {
const id int64 = 42 const id int64 = 42
bus.AddHandler("test", func(cmd *models.UpsertUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpsertUserCommand) error {
cmd.Result = &models.User{ cmd.Result = &models.User{
Id: id, Id: id,
} }

@ -283,7 +283,7 @@ func setupDeleteHandlers(t *testing.T, fakeStore *fakeDashboardStore, provisione
} }
result := &Result{} result := &Result{}
bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
require.Equal(t, cmd.Id, int64(1)) require.Equal(t, cmd.Id, int64(1))
require.Equal(t, cmd.OrgId, int64(1)) require.Equal(t, cmd.OrgId, int64(1))
result.deleteWasCalled = true result.deleteWasCalled = true

@ -25,7 +25,7 @@ func TestFolderService(t *testing.T) {
origNewGuardian := guardian.New origNewGuardian := guardian.New
guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{}) guardian.MockDashboardGuardian(&guardian.FakeDashboardGuardian{})
bus.AddHandler("test", func(query *models.GetDashboardQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardQuery) error {
query.Result = models.NewDashboardFolder("Folder") query.Result = models.NewDashboardFolder("Folder")
return nil return nil
}) })
@ -85,7 +85,7 @@ func TestFolderService(t *testing.T) {
dash := models.NewDashboardFolder("Folder") dash := models.NewDashboardFolder("Folder")
dash.Id = 1 dash.Id = 1
bus.AddHandler("test", func(query *models.GetDashboardQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardQuery) error {
query.Result = dash query.Result = dash
return nil return nil
}) })
@ -99,12 +99,12 @@ func TestFolderService(t *testing.T) {
return nil return nil
} }
bus.AddHandler("test", func(cmd *models.SaveDashboardCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.SaveDashboardCommand) error {
cmd.Result = dash cmd.Result = dash
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.DeleteDashboardCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.DeleteDashboardCommand) error {
return nil return nil
}) })
@ -139,7 +139,7 @@ func TestFolderService(t *testing.T) {
dashFolder.Id = 1 dashFolder.Id = 1
dashFolder.Uid = "uid-abc" dashFolder.Uid = "uid-abc"
bus.AddHandler("test", func(query *models.GetDashboardQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardQuery) error {
query.Result = dashFolder query.Result = dashFolder
return nil return nil
}) })

@ -684,7 +684,7 @@ func TestGuardianGetHiddenACL(t *testing.T) {
t.Run("Get hidden ACL tests", func(t *testing.T) { t.Run("Get hidden ACL tests", func(t *testing.T) {
bus.ClearBusHandlers() bus.ClearBusHandlers()
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = []*models.DashboardAclInfoDTO{ query.Result = []*models.DashboardAclInfoDTO{
{Inherited: false, UserId: 1, UserLogin: "user1", Permission: models.PERMISSION_EDIT}, {Inherited: false, UserId: 1, UserLogin: "user1", Permission: models.PERMISSION_EDIT},
{Inherited: false, UserId: 2, UserLogin: "user2", Permission: models.PERMISSION_ADMIN}, {Inherited: false, UserId: 2, UserLogin: "user2", Permission: models.PERMISSION_ADMIN},
@ -732,7 +732,7 @@ func TestGuardianGetAclWithoutDuplicates(t *testing.T) {
t.Run("Get hidden ACL tests", func(t *testing.T) { t.Run("Get hidden ACL tests", func(t *testing.T) {
t.Cleanup(bus.ClearBusHandlers) t.Cleanup(bus.ClearBusHandlers)
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
query.Result = []*models.DashboardAclInfoDTO{ query.Result = []*models.DashboardAclInfoDTO{
{Inherited: true, UserId: 3, UserLogin: "user3", Permission: models.PERMISSION_EDIT}, {Inherited: true, UserId: 3, UserLogin: "user3", Permission: models.PERMISSION_EDIT},
{Inherited: false, UserId: 3, UserLogin: "user3", Permission: models.PERMISSION_VIEW}, {Inherited: false, UserId: 3, UserLogin: "user3", Permission: models.PERMISSION_VIEW},

@ -75,7 +75,7 @@ func permissionScenario(desc string, dashboardID int64, sc *scenarioContext,
sc.t.Run(desc, func(t *testing.T) { sc.t.Run(desc, func(t *testing.T) {
bus.ClearBusHandlers() bus.ClearBusHandlers()
bus.AddHandler("test", func(query *models.GetDashboardAclInfoListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetDashboardAclInfoListQuery) error {
if query.OrgID != sc.givenUser.OrgId { if query.OrgID != sc.givenUser.OrgId {
sc.reportFailure("Invalid organization id for GetDashboardAclInfoListQuery", sc.givenUser.OrgId, query.OrgID) sc.reportFailure("Invalid organization id for GetDashboardAclInfoListQuery", sc.givenUser.OrgId, query.OrgID)
} }
@ -95,7 +95,7 @@ func permissionScenario(desc string, dashboardID int64, sc *scenarioContext,
} }
} }
bus.AddHandler("test", func(query *models.GetTeamsByUserQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetTeamsByUserQuery) error {
if query.OrgId != sc.givenUser.OrgId { if query.OrgId != sc.givenUser.OrgId {
sc.reportFailure("Invalid organization id for GetTeamsByUserQuery", sc.givenUser.OrgId, query.OrgId) sc.reportFailure("Invalid organization id for GetTeamsByUserQuery", sc.givenUser.OrgId, query.OrgId)
} }

@ -20,20 +20,20 @@ func Test_syncOrgRoles_doesNotBreakWhenTryingToRemoveLastOrgAdmin(t *testing.T)
bus.ClearBusHandlers() bus.ClearBusHandlers()
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
bus.AddHandler("test", func(q *models.GetUserOrgListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, q *models.GetUserOrgListQuery) error {
q.Result = createUserOrgDTO() q.Result = createUserOrgDTO()
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.RemoveOrgUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.RemoveOrgUserCommand) error {
testData := remResp[0] testData := remResp[0]
remResp = remResp[1:] remResp = remResp[1:]
require.Equal(t, testData.orgId, cmd.OrgId) require.Equal(t, testData.orgId, cmd.OrgId)
return testData.response return testData.response
}) })
bus.AddHandler("test", func(cmd *models.SetUsingOrgCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.SetUsingOrgCommand) error {
return nil return nil
}) })
@ -55,20 +55,20 @@ func Test_syncOrgRoles_whenTryingToRemoveLastOrgLogsError(t *testing.T) {
bus.ClearBusHandlers() bus.ClearBusHandlers()
defer bus.ClearBusHandlers() defer bus.ClearBusHandlers()
bus.AddHandler("test", func(q *models.GetUserOrgListQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, q *models.GetUserOrgListQuery) error {
q.Result = createUserOrgDTO() q.Result = createUserOrgDTO()
return nil return nil
}) })
bus.AddHandler("test", func(cmd *models.RemoveOrgUserCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.RemoveOrgUserCommand) error {
testData := remResp[0] testData := remResp[0]
remResp = remResp[1:] remResp = remResp[1:]
require.Equal(t, testData.orgId, cmd.OrgId) require.Equal(t, testData.orgId, cmd.OrgId)
return testData.response return testData.response
}) })
bus.AddHandler("test", func(cmd *models.SetUsingOrgCommand) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.SetUsingOrgCommand) error {
return nil return nil
}) })

@ -106,7 +106,7 @@ func TestDashboardFileReader(t *testing.T) {
setup := func() { setup := func() {
bus.ClearBusHandlers() bus.ClearBusHandlers()
fakeService = mockDashboardProvisioningService() fakeService = mockDashboardProvisioningService()
bus.AddHandler("test", mockGetDashboardQuery) bus.AddHandlerCtx("test", mockGetDashboardQuery)
cfg = &config{ cfg = &config{
Name: "Default", Name: "Default",
Type: "file", Type: "file",
@ -637,7 +637,7 @@ func (s *fakeDashboardProvisioningService) GetProvisionedDashboardDataByDashboar
return nil, nil return nil, nil
} }
func mockGetDashboardQuery(cmd *models.GetDashboardQuery) error { func mockGetDashboardQuery(ctx context.Context, cmd *models.GetDashboardQuery) error {
for _, d := range fakeService.getDashboard { for _, d := range fakeService.getDashboard {
if d.Slug == cmd.Slug { if d.Slug == cmd.Slug {
cmd.Result = d cmd.Result = d

@ -20,7 +20,7 @@ func TestDuplicatesValidator(t *testing.T) {
bus.ClearBusHandlers() bus.ClearBusHandlers()
fakeService = mockDashboardProvisioningService() fakeService = mockDashboardProvisioningService()
bus.AddHandler("test", mockGetDashboardQuery) bus.AddHandlerCtx("test", mockGetDashboardQuery)
cfg := &config{ cfg := &config{
Name: "Default", Name: "Default",
Type: "file", Type: "file",

@ -32,11 +32,11 @@ func TestDatasourceAsConfig(t *testing.T) {
setup := func() { setup := func() {
fakeRepo = &fakeRepository{} fakeRepo = &fakeRepository{}
bus.ClearBusHandlers() bus.ClearBusHandlers()
bus.AddHandler("test", mockDelete) bus.AddHandlerCtx("test", mockDelete)
bus.AddHandler("test", mockInsert) bus.AddHandlerCtx("test", mockInsert)
bus.AddHandler("test", mockUpdate) bus.AddHandlerCtx("test", mockUpdate)
bus.AddHandler("test", mockGet) bus.AddHandlerCtx("test", mockGet)
bus.AddHandler("test", mockGetOrg) bus.AddHandlerCtx("test", mockGetOrg)
} }
t.Run("apply default values when missing", func(t *testing.T) { t.Run("apply default values when missing", func(t *testing.T) {
@ -280,22 +280,22 @@ type fakeRepository struct {
loadAll []*models.DataSource loadAll []*models.DataSource
} }
func mockDelete(cmd *models.DeleteDataSourceCommand) error { func mockDelete(ctx context.Context, cmd *models.DeleteDataSourceCommand) error {
fakeRepo.deleted = append(fakeRepo.deleted, cmd) fakeRepo.deleted = append(fakeRepo.deleted, cmd)
return nil return nil
} }
func mockUpdate(cmd *models.UpdateDataSourceCommand) error { func mockUpdate(ctx context.Context, cmd *models.UpdateDataSourceCommand) error {
fakeRepo.updated = append(fakeRepo.updated, cmd) fakeRepo.updated = append(fakeRepo.updated, cmd)
return nil return nil
} }
func mockInsert(cmd *models.AddDataSourceCommand) error { func mockInsert(ctx context.Context, cmd *models.AddDataSourceCommand) error {
fakeRepo.inserted = append(fakeRepo.inserted, cmd) fakeRepo.inserted = append(fakeRepo.inserted, cmd)
return nil return nil
} }
func mockGet(cmd *models.GetDataSourceQuery) error { func mockGet(ctx context.Context, cmd *models.GetDataSourceQuery) error {
for _, v := range fakeRepo.loadAll { for _, v := range fakeRepo.loadAll {
if cmd.Name == v.Name && cmd.OrgId == v.OrgId { if cmd.Name == v.Name && cmd.OrgId == v.OrgId {
cmd.Result = v cmd.Result = v
@ -306,6 +306,6 @@ func mockGet(cmd *models.GetDataSourceQuery) error {
return models.ErrDataSourceNotFound return models.ErrDataSourceNotFound
} }
func mockGetOrg(_ *models.GetOrgByIdQuery) error { func mockGetOrg(ctx context.Context, _ *models.GetOrgByIdQuery) error {
return nil return nil
} }

@ -1,6 +1,7 @@
package plugins package plugins
import ( import (
"context"
"errors" "errors"
"testing" "testing"
@ -20,7 +21,7 @@ func TestPluginProvisioner(t *testing.T) {
}) })
t.Run("Should apply configurations", func(t *testing.T) { t.Run("Should apply configurations", func(t *testing.T) {
bus.AddHandler("test", func(query *models.GetOrgByNameQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetOrgByNameQuery) error {
if query.Name == "Org 4" { if query.Name == "Org 4" {
query.Result = &models.Org{Id: 4} query.Result = &models.Org{Id: 4}
} }
@ -28,7 +29,7 @@ func TestPluginProvisioner(t *testing.T) {
return nil return nil
}) })
bus.AddHandler("test", func(query *models.GetPluginSettingByIdQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, query *models.GetPluginSettingByIdQuery) error {
if query.PluginId == "test-plugin" && query.OrgId == 2 { if query.PluginId == "test-plugin" && query.OrgId == 2 {
query.Result = &models.PluginSetting{ query.Result = &models.PluginSetting{
PluginVersion: "2.0.1", PluginVersion: "2.0.1",
@ -41,7 +42,7 @@ func TestPluginProvisioner(t *testing.T) {
sentCommands := []*models.UpdatePluginSettingCmd{} sentCommands := []*models.UpdatePluginSettingCmd{}
bus.AddHandler("test", func(cmd *models.UpdatePluginSettingCmd) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.UpdatePluginSettingCmd) error {
sentCommands = append(sentCommands, cmd) sentCommands = append(sentCommands, cmd)
return nil return nil
}) })

@ -1,6 +1,7 @@
package teamguardian package teamguardian
import ( import (
"context"
"testing" "testing"
"github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/bus"
@ -30,7 +31,7 @@ func TestUpdateTeam(t *testing.T) {
t.Run("Given an editor and a team he isn't a member of", func(t *testing.T) { t.Run("Given an editor and a team he isn't a member of", func(t *testing.T) {
t.Run("Should not be able to update the team", func(t *testing.T) { t.Run("Should not be able to update the team", func(t *testing.T) {
bus.AddHandler("test", func(cmd *models.GetTeamMembersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetTeamMembersQuery) error {
cmd.Result = []*models.TeamMemberDTO{} cmd.Result = []*models.TeamMemberDTO{}
return nil return nil
}) })
@ -42,7 +43,7 @@ func TestUpdateTeam(t *testing.T) {
t.Run("Given an editor and a team he is an admin in", func(t *testing.T) { t.Run("Given an editor and a team he is an admin in", func(t *testing.T) {
t.Run("Should be able to update the team", func(t *testing.T) { t.Run("Should be able to update the team", func(t *testing.T) {
bus.AddHandler("test", func(cmd *models.GetTeamMembersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetTeamMembersQuery) error {
cmd.Result = []*models.TeamMemberDTO{{ cmd.Result = []*models.TeamMemberDTO{{
OrgId: testTeam.OrgId, OrgId: testTeam.OrgId,
TeamId: testTeam.Id, TeamId: testTeam.Id,
@ -64,7 +65,7 @@ func TestUpdateTeam(t *testing.T) {
} }
t.Run("Shouldn't be able to update the team", func(t *testing.T) { t.Run("Shouldn't be able to update the team", func(t *testing.T) {
bus.AddHandler("test", func(cmd *models.GetTeamMembersQuery) error { bus.AddHandlerCtx("test", func(ctx context.Context, cmd *models.GetTeamMembersQuery) error {
cmd.Result = []*models.TeamMemberDTO{{ cmd.Result = []*models.TeamMemberDTO{{
OrgId: testTeamOtherOrg.OrgId, OrgId: testTeamOtherOrg.OrgId,
TeamId: testTeamOtherOrg.Id, TeamId: testTeamOtherOrg.Id,

Loading…
Cancel
Save