Skip to content

Commit

Permalink
test: refactor in context_test.go
Browse files Browse the repository at this point in the history
  • Loading branch information
AleksandrMatsko committed Nov 16, 2024
1 parent 64ca233 commit 86b6314
Showing 1 changed file with 110 additions and 12 deletions.
122 changes: 110 additions & 12 deletions api/middleware/context_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package middleware

import (
"context"
"fmt"
"github.com/moira-alert/moira/api"
"io"
"net/http"
"net/http/httptest"
"regexp"
"testing"

"github.com/moira-alert/moira/api"

. "github.com/smartystreets/goconvey/convey"
)

Expand All @@ -18,10 +20,16 @@ const expectedBadRequest = `{"status":"Invalid request","error":"invalid URL esc
func testRequestOk(
url string,
middlewareFunc func(next http.Handler) http.Handler,
contextVals map[ContextKey]interface{},
) {
responseWriter := httptest.NewRecorder()

testRequest := httptest.NewRequest(http.MethodGet, url, nil)
for contextKey, val := range contextVals {
ctx := context.WithValue(testRequest.Context(), contextKey, val)
testRequest = testRequest.WithContext(ctx)
}

handler := func(w http.ResponseWriter, r *http.Request) {}

wrappedHandler := middlewareFunc(http.HandlerFunc(handler))
Expand All @@ -36,12 +44,18 @@ func testRequestOk(
func testRequestFails(
url string,
middlewareFunc func(next http.Handler) http.Handler,
contextVals map[ContextKey]interface{},
failedRequestStr string,
failedRequestStatusCode int,
) {
responseWriter := httptest.NewRecorder()

testRequest := httptest.NewRequest(http.MethodGet, url, nil)
for contextKey, val := range contextVals {
ctx := context.WithValue(testRequest.Context(), contextKey, val)
testRequest = testRequest.WithContext(ctx)
}

handler := func(w http.ResponseWriter, r *http.Request) {}

wrappedHandler := middlewareFunc(http.HandlerFunc(handler))
Expand All @@ -56,9 +70,72 @@ func testRequestFails(
So(response.StatusCode, ShouldEqual, failedRequestStatusCode)
}

func TestAdminOnlyMiddleware(t *testing.T) {
Convey("Checking authorization", t, func() {
auth := api.Authorization{
Enabled: true,
AdminList: map[string]struct{}{
"admin": {},
},
AllowedContactTypes: map[string]struct{}{},
}

Convey("with enabled auth", func() {
Convey("admin access ok", func() {
testRequestOk(
"/test",
AdminOnlyMiddleware(),
map[ContextKey]interface{}{
authKey: &auth,
loginKey: "admin",
},
)
})

Convey("non admin access forbidden", func() {
testRequestFails(
"/test",
AdminOnlyMiddleware(),
map[ContextKey]interface{}{
authKey: &auth,
loginKey: "user",
},
"{\"status\":\"Forbidden\",\"error\":\"Only administrators can use this\"}\n",
http.StatusForbidden,
)
})
})

Convey("with auth disabled", func() {
auth.Enabled = false

Convey("admin access ok", func() {
testRequestOk(
"/test",
AdminOnlyMiddleware(),
map[ContextKey]interface{}{
authKey: &auth,
loginKey: "admin",
},
)
})

Convey("non admin access ok", func() {
testRequestOk(
"/test",
AdminOnlyMiddleware(),
map[ContextKey]interface{}{
authKey: &auth,
loginKey: "",
},
)
})
})
})
}

func TestPaginateMiddleware(t *testing.T) {
Convey("checking correctness of parameters", t, func() {
//responseWriter := httptest.NewRecorder()
defaultPage := int64(1)
defaultSize := int64(10)

Expand All @@ -68,14 +145,16 @@ func TestPaginateMiddleware(t *testing.T) {
for _, param := range parameters {
testRequestOk(
"/test?"+param,
Paginate(defaultPage, defaultSize))
Paginate(defaultPage, defaultSize),
nil)
}
})

Convey("with wrong url query parameters", func() {
testRequestFails(
"/test?p=0%&size=100",
Paginate(defaultPage, defaultSize),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -93,14 +172,16 @@ func TestPagerMiddleware(t *testing.T) {
for _, param := range parameters {
testRequestOk(
"/test?"+param,
Pager(defaultCreatePager, defaultPagerID))
Pager(defaultCreatePager, defaultPagerID),
nil)
}
})

Convey("with wrong url query parameters", func() {
testRequestFails(
"/test?pagerID=test%&createPager=true",
Pager(defaultCreatePager, defaultPagerID),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -114,13 +195,15 @@ func TestPopulateMiddleware(t *testing.T) {
Convey("with correct parameter", func() {
testRequestOk(
"/test?populated=true",
Populate(defaultPopulated))
Populate(defaultPopulated),
nil)
})

Convey("with wrong url query parameter", func() {
testRequestFails(
"/test?populated%=true",
Populate(defaultPopulated),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -138,14 +221,16 @@ func TestDateRangeMiddleware(t *testing.T) {
for _, param := range parameters {
testRequestOk(
"/test?"+param,
DateRange(defaultFrom, defaultTo))
DateRange(defaultFrom, defaultTo),
nil)
}
})

Convey("with wrong url query parameters", func() {
testRequestFails(
"/test?from=-2hours%&to=now",
DateRange(defaultFrom, defaultTo),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -159,13 +244,15 @@ func TestTargetNameMiddleware(t *testing.T) {
Convey("with correct parameter", func() {
testRequestOk(
"/test?target=test",
TargetName(defaultTargetName))
TargetName(defaultTargetName),
nil)
})

Convey("with wrong url query parameter", func() {
testRequestFails(
"/test?target%=test",
TargetName(defaultTargetName),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -179,13 +266,15 @@ func TestMetricContextMiddleware(t *testing.T) {
Convey("status ok with correct query paramete", func() {
testRequestOk(
"/test?metric=test%5C.metric.*",
MetricContext(defaultMetric))
MetricContext(defaultMetric),
nil)
})

Convey("status bad request with wrong url query parameter", func() {
testRequestFails(
"/test?metric%=test",
MetricContext(defaultMetric),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -197,13 +286,15 @@ func TestStatesContextMiddleware(t *testing.T) {
Convey("ok with correct states list", func() {
testRequestOk(
"/test?states=OK%2CERROR",
StatesContext())
StatesContext(),
nil)
})

Convey("bad request with bad states list", func() {
testRequestFails(
"/test?states=OK%2CERROR%2Cwarn",
StatesContext(),
nil,
"{\"status\":\"Invalid request\",\"error\":\"bad state in query parameter: warn\"}\n",
http.StatusBadRequest)
})
Expand All @@ -212,6 +303,7 @@ func TestStatesContextMiddleware(t *testing.T) {
testRequestFails(
"/test?states%=test",
StatesContext(),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -225,19 +317,22 @@ func TestSearchTextContext(t *testing.T) {
Convey("status ok with correct query parameter", func() {
testRequestOk(
"/test?searchText=test%5Ctext.*",
SearchTextContext(defaultSearchText))
SearchTextContext(defaultSearchText),
nil)
})

Convey("status ok with empty query parameter", func() {
testRequestOk(
"/test?searchText=",
SearchTextContext(defaultSearchText))
SearchTextContext(defaultSearchText),
nil)
})

Convey("status bad request with wrong url query parameter", func() {
testRequestFails(
"/test?searchText%=test",
SearchTextContext(defaultSearchText),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand All @@ -246,6 +341,7 @@ func TestSearchTextContext(t *testing.T) {
testRequestFails(
"/test?searchText=*",
SearchTextContext(defaultSearchText),
nil,
"{\"status\":\"Invalid request\",\"error\":\"failed to parse searchText template '*': error parsing regexp: missing argument to repetition operator: `*`\"}\n",
http.StatusBadRequest)
})
Expand All @@ -263,7 +359,8 @@ func TestSortOrderContext(t *testing.T) {
Convey(fmt.Sprintf("case %d: sord order '%s'", i+1, givenSortOrder), func() {
testRequestOk(
fmt.Sprintf("/test?sort=%s", givenSortOrder),
SortOrderContext(defaultSortOrder))
SortOrderContext(defaultSortOrder),
nil)
})
}
})
Expand All @@ -272,6 +369,7 @@ func TestSortOrderContext(t *testing.T) {
testRequestFails(
"/test?sort%=test",
SortOrderContext(defaultSortOrder),
nil,
expectedBadRequest,
http.StatusBadRequest)
})
Expand Down

0 comments on commit 86b6314

Please sign in to comment.