You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

binding_test.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. GlobPattern string `form:"GlobPattern" binding:"GlobPattern"`
  25. RegexPattern string `form:"RegexPattern" binding:"RegexPattern"`
  26. }
  27. )
  28. func performValidationTest(t *testing.T, testCase validationTestCase) {
  29. httpRecorder := httptest.NewRecorder()
  30. m := chi.NewRouter()
  31. m.Post(testRoute, func(resp http.ResponseWriter, req *http.Request) {
  32. actual := binding.Validate(req, testCase.data)
  33. // see https://github.com/stretchr/testify/issues/435
  34. if actual == nil {
  35. actual = binding.Errors{}
  36. }
  37. assert.Equal(t, testCase.expectedErrors, actual)
  38. })
  39. req, err := http.NewRequest("POST", testRoute, nil)
  40. if err != nil {
  41. panic(err)
  42. }
  43. req.Header.Add("Content-Type", "x-www-form-urlencoded")
  44. m.ServeHTTP(httpRecorder, req)
  45. switch httpRecorder.Code {
  46. case http.StatusNotFound:
  47. panic("Routing is messed up in test fixture (got 404): check methods and paths")
  48. case http.StatusInternalServerError:
  49. panic("Something bad happened on '" + testCase.description + "'")
  50. }
  51. }