github.com/cloudwego/hertz@v0.9.3/pkg/app/server/binding/validator_test.go (about)

     1  /*
     2   * Copyright 2023 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package binding
    18  
    19  import (
    20  	"testing"
    21  )
    22  
    23  func Test_ValidateStruct(t *testing.T) {
    24  	type User struct {
    25  		Age int `vd:"$>=0&&$<=130"`
    26  	}
    27  
    28  	user := &User{
    29  		Age: 135,
    30  	}
    31  	err := DefaultValidator().ValidateStruct(user)
    32  	if err == nil {
    33  		t.Fatalf("expected an error, but got nil")
    34  	}
    35  }
    36  
    37  func Test_ValidateTag(t *testing.T) {
    38  	type User struct {
    39  		Age int `query:"age" vt:"$>=0&&$<=130"`
    40  	}
    41  
    42  	user := &User{
    43  		Age: 135,
    44  	}
    45  	validateConfig := NewValidateConfig()
    46  	validateConfig.ValidateTag = "vt"
    47  	vd := NewValidator(validateConfig)
    48  	err := vd.ValidateStruct(user)
    49  	if err == nil {
    50  		t.Fatalf("expected an error, but got nil")
    51  	}
    52  
    53  	bindConfig := NewBindConfig()
    54  	bindConfig.Validator = vd
    55  	binder := NewDefaultBinder(bindConfig)
    56  	user = &User{}
    57  	req := newMockRequest().
    58  		SetRequestURI("http://foobar.com?age=135").
    59  		SetHeaders("h", "header")
    60  	err = binder.BindAndValidate(req.Req, user, nil)
    61  	if err == nil {
    62  		t.Fatalf("expected an error, but got nil")
    63  	}
    64  }