gitea源码

binding_test.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package validation
  4. import (
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "gitea.com/go-chi/binding"
  9. chi "github.com/go-chi/chi/v5"
  10. "github.com/stretchr/testify/assert"
  11. )
  12. const (
  13. testRoute = "/test"
  14. )
  15. type (
  16. validationTestCase struct {
  17. description string
  18. data any
  19. expectedErrors binding.Errors
  20. }
  21. TestForm struct {
  22. BranchName string `form:"BranchName" binding:"GitRefName"`
  23. URL string `form:"ValidUrl" binding:"ValidUrl"`
  24. URLs string `form:"ValidUrls" binding:"ValidUrlList"`
  25. GlobPattern string `form:"GlobPattern" binding:"GlobPattern"`
  26. RegexPattern string `form:"RegexPattern" binding:"RegexPattern"`
  27. }
  28. )
  29. func performValidationTest(t *testing.T, testCase validationTestCase) {
  30. httpRecorder := httptest.NewRecorder()
  31. m := chi.NewRouter()
  32. m.Post(testRoute, func(resp http.ResponseWriter, req *http.Request) {
  33. actual := binding.Validate(req, testCase.data)
  34. // see https://github.com/stretchr/testify/issues/435
  35. if actual == nil {
  36. actual = binding.Errors{}
  37. }
  38. assert.Equal(t, testCase.expectedErrors, actual)
  39. })
  40. req, err := http.NewRequest(http.MethodPost, testRoute, nil)
  41. if err != nil {
  42. panic(err)
  43. }
  44. req.Header.Add("Content-Type", "x-www-form-urlencoded")
  45. m.ServeHTTP(httpRecorder, req)
  46. switch httpRecorder.Code {
  47. case http.StatusNotFound:
  48. panic("Routing is messed up in test fixture (got 404): check methods and paths")
  49. case http.StatusInternalServerError:
  50. panic("Something bad happened on '" + testCase.description + "'")
  51. }
  52. }