Files
Atay-Makhzan/modules/validation/binding_test.go
T

64 lines
1.6 KiB
Go
Raw Normal View History

2017-04-19 06:02:20 +03:00
// Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2017-04-19 06:02:20 +03:00
package validation
import (
"net/http"
"net/http/httptest"
"testing"
2021-01-26 23:36:53 +08:00
"gitea.com/go-chi/binding"
2021-10-14 10:50:23 +08:00
chi "github.com/go-chi/chi/v5"
2017-04-19 06:02:20 +03:00
"github.com/stretchr/testify/assert"
)
const (
testRoute = "/test"
)
type (
validationTestCase struct {
description string
2023-07-04 20:36:08 +02:00
data any
2017-04-19 06:02:20 +03:00
expectedErrors binding.Errors
}
TestForm struct {
2021-06-25 16:28:55 +02:00
BranchName string `form:"BranchName" binding:"GitRefName"`
URL string `form:"ValidUrl" binding:"ValidUrl"`
2024-11-27 20:50:27 -06:00
URLs string `form:"ValidUrls" binding:"ValidUrlList"`
2021-06-25 16:28:55 +02:00
GlobPattern string `form:"GlobPattern" binding:"GlobPattern"`
RegexPattern string `form:"RegexPattern" binding:"RegexPattern"`
2017-04-19 06:02:20 +03:00
}
)
func performValidationTest(t *testing.T, testCase validationTestCase) {
httpRecorder := httptest.NewRecorder()
2021-01-26 23:36:53 +08:00
m := chi.NewRouter()
2017-04-19 06:02:20 +03:00
2021-01-26 23:36:53 +08:00
m.Post(testRoute, func(resp http.ResponseWriter, req *http.Request) {
actual := binding.Validate(req, testCase.data)
// see https://github.com/stretchr/testify/issues/435
if actual == nil {
actual = binding.Errors{}
}
assert.Equal(t, testCase.expectedErrors, actual)
2017-04-19 06:02:20 +03:00
})
2025-04-01 12:14:01 +02:00
req, err := http.NewRequest(http.MethodPost, testRoute, nil)
2017-04-19 06:02:20 +03:00
if err != nil {
panic(err)
}
2021-01-26 23:36:53 +08:00
req.Header.Add("Content-Type", "x-www-form-urlencoded")
2017-04-19 06:02:20 +03: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 + "'")
}
}