github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/validation/binding_test.go (about)

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