github.com/searKing/golang/go@v1.2.117/database/sql/null_json_test.go (about)

     1  // Copyright 2020 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sql_test
     6  
     7  import (
     8  	"reflect"
     9  	"testing"
    10  
    11  	"github.com/searKing/golang/go/database/sql"
    12  )
    13  
    14  type people struct {
    15  	Name    string
    16  	Age     int
    17  	Friends []people
    18  }
    19  
    20  type NullJsonTest struct {
    21  	input  string
    22  	holder sql.NullJson
    23  	output sql.NullJson
    24  }
    25  
    26  var (
    27  	nullJsonTests = []NullJsonTest{
    28  		{
    29  			`[1,2,3]`,
    30  			sql.NullJson{
    31  				Data: &[]byte{},
    32  			},
    33  			sql.NullJson{Data: &[]byte{1, 2, 3},
    34  				Valid: true,
    35  			},
    36  		},
    37  		{
    38  			`{"Name":"Alice","Age":100,"Friends":[{"Name":"Bob","Age":50,"Friends":null}]}`,
    39  			sql.NullJson{
    40  				Data: &people{},
    41  			},
    42  			sql.NullJson{Data: &people{Name: "Alice",
    43  				Age: 100,
    44  				Friends: []people{{
    45  					Name:    "Bob",
    46  					Age:     50,
    47  					Friends: nil,
    48  				}}},
    49  				Valid: true,
    50  			},
    51  		},
    52  	}
    53  )
    54  
    55  func TestNullJson(t *testing.T) {
    56  
    57  	for n, test := range nullJsonTests {
    58  		err := test.holder.Scan(test.input)
    59  		if err != nil {
    60  			t.Errorf("#%d: Scan error:%v\n", n, err)
    61  			continue
    62  		}
    63  
    64  		if !reflect.DeepEqual(test.holder, test.output) {
    65  			t.Errorf("#%d: expected %+v got %+v", n, test.output, test.holder)
    66  		}
    67  	}
    68  }