package api import ( "github.com/go-chi/chi/v5" "github.com/muety/wakapi/middlewares" "github.com/muety/wakapi/mocks" "github.com/muety/wakapi/models" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "io/ioutil" "net/http" "net/http/httptest" "regexp" "strings" "testing" "time" ) var ( user1 = models.User{ ID: "user1", ShareDataMaxDays: 30, ShareLanguages: true, } summary1 = models.Summary{ User: &user1, UserID: "user1", FromTime: models.CustomTime(time.Date(2023, 3, 14, 0, 0, 0, 0, time.Local)), ToTime: models.CustomTime(time.Date(2023, 3, 14, 23, 59, 59, 0, time.Local)), Languages: []*models.SummaryItem{ { Type: models.SummaryLanguage, Key: "go", Total: 12 * time.Minute / time.Second, }, }, } ) func TestBadgeHandler_Get(t *testing.T) { router := chi.NewRouter() apiRouter := chi.NewRouter() apiRouter.Use(middlewares.NewPrincipalMiddleware()) router.Mount("/api", apiRouter) userServiceMock := new(mocks.UserServiceMock) userServiceMock.On("GetUserById", "user1").Return(&user1, nil) summaryServiceMock := new(mocks.SummaryServiceMock) summaryServiceMock.On("Aliased", mock.AnythingOfType("time.Time"), mock.AnythingOfType("time.Time"), &user1, mock.Anything, mock.Anything).Return(&summary1, nil) badgeHandler := NewBadgeHandler(userServiceMock, summaryServiceMock) badgeHandler.RegisterRoutes(apiRouter) t.Run("when requesting badge", func(t *testing.T) { t.Run("should return badge", func(t *testing.T) { rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/api/badge/{user}/interval:week/language:go", nil) req = withUrlParam(req, "user", "user1") router.ServeHTTP(rec, req) res := rec.Result() defer res.Body.Close() assert.Equal(t, http.StatusOK, res.StatusCode) data, err := ioutil.ReadAll(res.Body) if err != nil { t.Errorf("unextected error. Error: %s", err) } assert.True(t, strings.HasPrefix(string(data), " 2 { key, val = groups[1], groups[2] } assert.Equal(t, tc.key, key) assert.Equal(t, tc.val, val) } }