2017-04-19 03:02:20 +00:00
|
|
|
// Copyright 2017 The Gitea Authors. All rights reserved.
|
2022-11-27 18:20:29 +00:00
|
|
|
// SPDX-License-Identifier: MIT
|
2017-04-19 03:02:20 +00:00
|
|
|
|
|
|
|
package validation
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
|
2021-01-26 15:36:53 +00:00
|
|
|
"gitea.com/go-chi/binding"
|
2021-10-14 02:50:23 +00:00
|
|
|
chi "github.com/go-chi/chi/v5"
|
2017-04-19 03:02:20 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
testRoute = "/test"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
validationTestCase struct {
|
|
|
|
description string
|
|
|
|
data interface{}
|
|
|
|
expectedErrors binding.Errors
|
|
|
|
}
|
|
|
|
|
|
|
|
TestForm struct {
|
2021-06-25 14:28:55 +00:00
|
|
|
BranchName string `form:"BranchName" binding:"GitRefName"`
|
|
|
|
URL string `form:"ValidUrl" binding:"ValidUrl"`
|
|
|
|
GlobPattern string `form:"GlobPattern" binding:"GlobPattern"`
|
|
|
|
RegexPattern string `form:"RegexPattern" binding:"RegexPattern"`
|
2017-04-19 03:02:20 +00:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func performValidationTest(t *testing.T, testCase validationTestCase) {
|
|
|
|
httpRecorder := httptest.NewRecorder()
|
2021-01-26 15:36:53 +00:00
|
|
|
m := chi.NewRouter()
|
2017-04-19 03:02:20 +00:00
|
|
|
|
2021-01-26 15:36:53 +00:00
|
|
|
m.Post(testRoute, func(resp http.ResponseWriter, req *http.Request) {
|
|
|
|
actual := binding.Validate(req, testCase.data)
|
2019-08-12 02:17:25 +00:00
|
|
|
// see https://github.com/stretchr/testify/issues/435
|
|
|
|
if actual == nil {
|
|
|
|
actual = binding.Errors{}
|
|
|
|
}
|
|
|
|
|
|
|
|
assert.Equal(t, testCase.expectedErrors, actual)
|
2017-04-19 03:02:20 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
req, err := http.NewRequest("POST", testRoute, nil)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-01-26 15:36:53 +00:00
|
|
|
req.Header.Add("Content-Type", "x-www-form-urlencoded")
|
2017-04-19 03:02:20 +00:00
|
|
|
m.ServeHTTP(httpRecorder, req)
|
|
|
|
|
|
|
|
switch httpRecorder.Code {
|
|
|
|
case http.StatusNotFound:
|
|
|
|
panic("Routing is messed up in test fixture (got 404): check methods and paths")
|
|
|
|
case http.StatusInternalServerError:
|
|
|
|
panic("Something bad happened on '" + testCase.description + "'")
|
|
|
|
}
|
|
|
|
}
|