code.gitea.io/gitea@v1.19.3/modules/validation/binding_test.go (about)

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