<commit_before>package api

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/grafana/grafana/pkg/models"
	"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
	"github.com/grafana/grafana/pkg/services/publicdashboards"
	publicdashboardsService "github.com/grafana/grafana/pkg/services/publicdashboards/service"
	"github.com/grafana/grafana/pkg/setting"
	"github.com/grafana/grafana/pkg/web"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
)

func TestRequiresValidAccessToken(t *testing.T) {
	t.Run("Returns 404 when access token is empty", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(false, nil))

		require.Equal(t, http.StatusNotFound, resp.Code)
	})

	t.Run("Returns 200 when public dashboard with access token exists", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/myAccessToken", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(true, nil))

		require.Equal(t, http.StatusOK, resp.Code)
	})

	t.Run("Returns 400 when public dashboard with access token does not exist", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/myAccessToken", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(false, nil))

		require.Equal(t, http.StatusBadRequest, resp.Code)
	})

	t.Run("Returns 500 when public dashboard service gives an error", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/myAccessToken", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(false, fmt.Errorf("error not found")))

		require.Equal(t, http.StatusInternalServerError, resp.Code)
	})
}

func mockAccessTokenExistsResponse(returnArguments ...interface{}) *publicdashboardsService.PublicDashboardServiceImpl {
	fakeStore := &publicdashboards.FakePublicDashboardStore{}
	fakeStore.On("AccessTokenExists", mock.Anything, mock.Anything).Return(returnArguments[0], returnArguments[1])
	return publicdashboardsService.ProvideService(setting.NewCfg(), fakeStore)
}

func runMiddleware(request *http.Request, pubdashService *publicdashboardsService.PublicDashboardServiceImpl) *httptest.ResponseRecorder {
	recorder := httptest.NewRecorder()
	m := web.New()
	initCtx := &models.ReqContext{}
	m.Use(func(c *web.Context) {
		initCtx.Context = c
		c.Req = c.Req.WithContext(ctxkey.Set(c.Req.Context(), initCtx))
	})
	m.Get("/api/public/ma/events/:accessToken", RequiresValidAccessToken(pubdashService))
	m.ServeHTTP(recorder, request)

	return recorder
}
<commit_msg>Fix middleware tests for public dashboards (#53557)<commit_after>package api

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/grafana/grafana/pkg/models"
	"github.com/grafana/grafana/pkg/services/contexthandler/ctxkey"
	"github.com/grafana/grafana/pkg/services/publicdashboards"
	publicdashboardsService "github.com/grafana/grafana/pkg/services/publicdashboards/service"
	"github.com/grafana/grafana/pkg/setting"
	"github.com/grafana/grafana/pkg/web"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
)

func TestRequiresValidAccessToken(t *testing.T) {
	t.Run("Returns 404 when access token is empty", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(false, nil))

		require.Equal(t, http.StatusNotFound, resp.Code)
	})

	t.Run("Returns 200 when public dashboard with access token exists", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/myAccessToken", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(true, nil))

		require.Equal(t, http.StatusOK, resp.Code)
	})

	t.Run("Returns 400 when public dashboard with access token does not exist", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/myAccessToken", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(false, nil))

		require.Equal(t, http.StatusBadRequest, resp.Code)
	})

	t.Run("Returns 500 when public dashboard service gives an error", func(t *testing.T) {
		request, err := http.NewRequest("GET", "/api/public/ma/events/myAccessToken", nil)
		require.NoError(t, err)

		resp := runMiddleware(request, mockAccessTokenExistsResponse(false, fmt.Errorf("error not found")))

		require.Equal(t, http.StatusInternalServerError, resp.Code)
	})
}

func mockAccessTokenExistsResponse(returnArguments ...interface{}) *publicdashboardsService.PublicDashboardServiceImpl {
	fakeStore := &publicdashboards.FakePublicDashboardStore{}
	fakeStore.On("AccessTokenExists", mock.Anything, mock.Anything).Return(returnArguments[0], returnArguments[1])
	return publicdashboardsService.ProvideService(setting.NewCfg(), fakeStore)
}

func runMiddleware(request *http.Request, pubdashService *publicdashboardsService.PublicDashboardServiceImpl) *httptest.ResponseRecorder {
	recorder := httptest.NewRecorder()
	m := web.New()
	initCtx := &models.ReqContext{}
	m.Use(func(c *web.Context) {
		initCtx.Context = c
		c.Req = c.Req.WithContext(ctxkey.Set(c.Req.Context(), initCtx))
	})
	m.Get("/api/public/ma/events/:accessToken", RequiresValidAccessToken(pubdashService), mockValidRequestHandler)
	m.ServeHTTP(recorder, request)

	return recorder
}

func mockValidRequestHandler(c *models.ReqContext) {
	resp := make(map[string]interface{})
	resp["message"] = "Valid request"
	c.JSON(http.StatusOK, resp)
}

{'fraction_non_alphanumeric': 0.14025342822426662, 'fraction_numerical': 0.005728172192327721, 'mean_word_length': 5.884109916367981, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7054277', 'n_tokens_mistral': 1997, 'n_tokens_neox': 1921, 'n_words': 335}