github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/structwalk/walk_test.go (about)

     1  // Copyright 2024 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package structwalk
    16  
    17  import (
    18  	"reflect"
    19  	"testing"
    20  
    21  	"github.com/stretchr/testify/require"
    22  )
    23  
    24  func TestWalk(t *testing.T) {
    25  	type innerStruct struct {
    26  		Five *string `json:"five"`
    27  	}
    28  
    29  	type testStruct struct {
    30  		One   string       `json:"one"`
    31  		Two   int          `json:"two"`
    32  		Three bool         `json:"three"`
    33  		Four  *innerStruct `json:"four"`
    34  		Six   []string     `json:"six"`
    35  	}
    36  
    37  	expected := []struct {
    38  		name    string
    39  		typeStr string
    40  		depth   int
    41  		json    string
    42  	}{
    43  		{
    44  			name:    "One",
    45  			typeStr: "string",
    46  			depth:   0,
    47  			json:    "one",
    48  		},
    49  		{
    50  			name:    "Two",
    51  			typeStr: "int",
    52  			depth:   0,
    53  			json:    "two",
    54  		},
    55  		{
    56  			name:    "Three",
    57  			typeStr: "bool",
    58  			depth:   0,
    59  			json:    "three",
    60  		},
    61  		{
    62  			name:    "Four",
    63  			typeStr: "*structwalk.innerStruct",
    64  			depth:   0,
    65  			json:    "four",
    66  		},
    67  		{
    68  			name:    "Five",
    69  			typeStr: "*string",
    70  			depth:   1,
    71  			json:    "five",
    72  		},
    73  		{
    74  			name:    "Six",
    75  			typeStr: "[]string",
    76  			depth:   0,
    77  			json:    "six",
    78  		},
    79  	}
    80  
    81  	var n int
    82  	err := Walk(&testStruct{}, func(sf reflect.StructField, depth int) error {
    83  		require.Equal(t, expected[n].name, sf.Name)
    84  		require.Equal(t, expected[n].typeStr, sf.Type.String())
    85  		require.Equal(t, expected[n].depth, depth)
    86  		require.Equal(t, expected[n].json, sf.Tag.Get("json"))
    87  		n++
    88  		return nil
    89  	})
    90  
    91  	require.NoError(t, err)
    92  	require.Equal(t, len(expected), n)
    93  }