github.com/gogf/gf/v2@v2.7.4/util/gconv/gconv_z_unit_converter_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gconv_test
     8  
     9  import (
    10  	"testing"
    11  
    12  	"github.com/gogf/gf/v2/test/gtest"
    13  	"github.com/gogf/gf/v2/util/gconv"
    14  )
    15  
    16  type converterStructInTest struct {
    17  	Name string
    18  }
    19  
    20  type converterStructOutTest struct {
    21  	Place string
    22  }
    23  
    24  func TestRegisterConverter(t *testing.T) {
    25  	gtest.C(t, func(t *gtest.T) {
    26  		err := gconv.RegisterConverter(
    27  			func(in converterStructInTest) (*converterStructOutTest, error) {
    28  				return &converterStructOutTest{
    29  					Place: in.Name,
    30  				}, nil
    31  			},
    32  		)
    33  		t.AssertNil(err)
    34  	})
    35  
    36  	// Test failure cases.
    37  	gtest.C(t, func(t *gtest.T) {
    38  		var err error
    39  		err = gconv.RegisterConverter(123)
    40  		t.AssertNE(err, nil)
    41  
    42  		err = gconv.RegisterConverter(func() {})
    43  		t.AssertNE(err, nil)
    44  
    45  		err = gconv.RegisterConverter(
    46  			func(in *converterStructInTest) (*converterStructOutTest, error) {
    47  				return nil, nil
    48  			},
    49  		)
    50  		t.AssertNE(err, nil)
    51  
    52  		err = gconv.RegisterConverter(
    53  			func(in converterStructInTest) (converterStructOutTest, error) {
    54  				return converterStructOutTest{}, nil
    55  			},
    56  		)
    57  		t.AssertNE(err, nil)
    58  
    59  		err = gconv.RegisterConverter(
    60  			func(in converterStructInTest) (*converterStructOutTest, error) {
    61  				return nil, nil
    62  			},
    63  		)
    64  		t.AssertNE(err, nil)
    65  	})
    66  
    67  	gtest.C(t, func(t *gtest.T) {
    68  		var (
    69  			converterStructIn  = converterStructInTest{"小行星带"}
    70  			converterStructOut converterStructOutTest
    71  		)
    72  		err := gconv.Scan(converterStructIn, &converterStructOut)
    73  		t.AssertNil(err)
    74  		t.Assert(converterStructOut.Place, converterStructIn.Name)
    75  	})
    76  }
    77  
    78  func TestConvertWithRefer(t *testing.T) {
    79  	gtest.C(t, func(t *gtest.T) {
    80  		t.AssertEQ(gconv.ConvertWithRefer("1", 100), 1)
    81  		t.AssertEQ(gconv.ConvertWithRefer("1.01", 1.111), 1.01)
    82  		t.AssertEQ(gconv.ConvertWithRefer("1.01", "1.111"), "1.01")
    83  		t.AssertEQ(gconv.ConvertWithRefer("1.01", false), true)
    84  		t.AssertNE(gconv.ConvertWithRefer("1.01", false), false)
    85  	})
    86  }