github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/jsoni/any_tests/jsoniter_any_bool_test.go (about)

     1  package any_tests
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"testing"
     7  
     8  	"github.com/bingoohuang/gg/pkg/jsoni"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  var boolConvertMap = map[string]bool{
    13  	"null":  false,
    14  	"true":  true,
    15  	"false": false,
    16  
    17  	`"true"`:  true,
    18  	`"false"`: true,
    19  
    20  	"123":   true,
    21  	`"123"`: true,
    22  	"0":     false,
    23  	`"0"`:   false,
    24  	"-1":    true,
    25  	`"-1"`:  true,
    26  
    27  	"1.1":       true,
    28  	"0.0":       false,
    29  	"-1.1":      true,
    30  	`""`:        false,
    31  	"[1,2]":     true,
    32  	"[]":        false,
    33  	"{}":        true,
    34  	`{"abc":1}`: true,
    35  }
    36  
    37  func Test_read_bool_as_any(t *testing.T) {
    38  	should := require.New(t)
    39  
    40  	var any jsoni.Any
    41  	for k, v := range boolConvertMap {
    42  		any = jsoni.Get([]byte(k))
    43  		if v {
    44  			should.True(any.ToBool(), fmt.Sprintf("origin val is %v", k))
    45  		} else {
    46  			should.False(any.ToBool(), fmt.Sprintf("origin val is %v", k))
    47  		}
    48  	}
    49  }
    50  
    51  func Test_write_bool_to_stream(t *testing.T) {
    52  	ctx := context.Background()
    53  	should := require.New(t)
    54  	any := jsoni.Get([]byte("true"))
    55  	stream := jsoni.NewStream(jsoni.ConfigDefault, nil, 32)
    56  	any.WriteTo(ctx, stream)
    57  	should.Equal("true", string(stream.Buffer()))
    58  	should.Equal(any.ValueType(), jsoni.BoolValue)
    59  
    60  	any = jsoni.Get([]byte("false"))
    61  	stream = jsoni.NewStream(jsoni.ConfigDefault, nil, 32)
    62  	any.WriteTo(ctx, stream)
    63  	should.Equal("false", string(stream.Buffer()))
    64  
    65  	should.Equal(any.ValueType(), jsoni.BoolValue)
    66  }