github.com/greenpau/go-authcrunch@v1.1.4/pkg/util/data/map_traversal_test.go (about)

     1  // Copyright 2022 Paul Greenberg greenpau@outlook.com
     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 data
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  	"github.com/greenpau/go-authcrunch/internal/tests"
    21  	"testing"
    22  )
    23  
    24  func TestGetValueFromMapByPath(t *testing.T) {
    25  	var testcases = []struct {
    26  		name string
    27  		path string
    28  		data string
    29  		want interface{}
    30  	}{
    31  		{
    32  			name: "extract nested list",
    33  			path: "userinfo|custom_groups",
    34  			data: testSample1,
    35  			want: []interface{}{
    36  				"authp/admin",
    37  				"authp/user",
    38  			},
    39  		},
    40  		{
    41  			name: "extract nested string",
    42  			path: "userinfo|name",
    43  			data: testSample1,
    44  			want: "John Smith",
    45  		},
    46  		{
    47  			name: "extract sub",
    48  			path: "sub",
    49  			data: testSample1,
    50  			want: "jsmith",
    51  		},
    52  		{
    53  			name: "test invalid path",
    54  			path: "userinfo|foo|bar",
    55  			data: testSample1,
    56  			want: "",
    57  		},
    58  		{
    59  			name: "test invalid path",
    60  			path: "foo|bar|baz",
    61  			data: testSample1,
    62  			want: "",
    63  		},
    64  	}
    65  	for _, tc := range testcases {
    66  		t.Run(tc.name, func(t *testing.T) {
    67  			msgs := []string{fmt.Sprintf("test name: %s", tc.name)}
    68  			data := make(map[string]interface{})
    69  			json.Unmarshal([]byte(tc.data), &data)
    70  			got := GetValueFromMapByPath(tc.path, data)
    71  			tests.EvalObjectsWithLog(t, "GetValueFromMapByPath", tc.want, got, msgs)
    72  		})
    73  	}
    74  }
    75  
    76  var testSample1 = `{
    77    "userinfo": {
    78      "custom_groups": [
    79        "authp/admin",
    80        "authp/user"
    81      ],
    82      "name": "John Smith",
    83      "zoneinfo": "America/Los_Angeles",
    84  	"foo": ["bar"]
    85    },
    86    "sub": "jsmith"
    87  }
    88  `