@@ -3,7 +3,7 @@ package mapaccess
33import (
44 "fmt"
55 "html/template"
6- "io/ioutil "
6+ "io"
77 "reflect"
88 "testing"
99)
@@ -69,6 +69,68 @@ func TestGet(t *testing.T) {
6969 }
7070}
7171
72+ func TestGetAs (t * testing.T ) {
73+ type args struct {
74+ key string
75+ data interface {}
76+ }
77+ tests := []struct {
78+ name string
79+ args args
80+ want string
81+ wantErr bool
82+ }{
83+ {"root" , args {"one" , data }, "two" , false },
84+ {"root array" , args {"array[0]" , data }, "value" , false },
85+ {"nested" , args {"nested.key" , data }, "three" , false },
86+ {"nested array" , args {"nested.array[0]" , data }, "four" , false },
87+
88+ {"spaces" , args {" one.two[0]" , data }, "" , true },
89+ {"spaces" , args {"o.test." , data }, "" , true },
90+ {"spaces" , args {"[0]" , data }, "" , true },
91+ }
92+ for _ , tt := range tests {
93+ t .Run (tt .name , func (t * testing.T ) {
94+ got , err := GetAs [string ](tt .args .data , tt .args .key )
95+ if (err != nil ) != tt .wantErr {
96+ t .Errorf ("Get() error = %v, wantErr %v" , err , tt .wantErr )
97+ return
98+ }
99+ if got != tt .want {
100+ t .Errorf ("Get() = %v, want %v" , got , tt .want )
101+ }
102+ })
103+ }
104+ }
105+
106+ func TestGetAsInt (t * testing.T ) {
107+ m := map [string ]interface {}{
108+ "one" : 1 ,
109+ "two" : 2.2 ,
110+ "three" : 0.3 ,
111+ }
112+
113+ if val , err := GetAs [int ](m , "one" ); err != nil {
114+ t .Errorf ("GetAs() error = %v" , err )
115+
116+ } else if val != 1 {
117+ t .Errorf ("GetAs() = %v, want %v" , val , 1 )
118+ }
119+
120+ if val , err := GetAs [float64 ](m , "two" ); err != nil {
121+ t .Errorf ("GetAs() error = %v" , err )
122+ } else if val != 2.2 {
123+ t .Errorf ("GetAs() = %v, want %v" , val , 2.2 )
124+ }
125+
126+ if val , err := GetAs [float64 ](m , "three" ); err != nil {
127+ t .Errorf ("GetAs() error = %v" , err )
128+ } else if val != 0.3 {
129+ t .Errorf ("GetAs() = %v, want %v" , val , 0.3 )
130+ }
131+
132+ }
133+
72134func benchmarkMapaccess (key string , b * testing.B ) {
73135 for n := 0 ; n < b .N ; n ++ {
74136 Get (data , key )
@@ -81,7 +143,7 @@ func benchmarkGoTemplate(key string, b *testing.B) {
81143 if err != nil {
82144 fmt .Println (err )
83145 }
84- t .Execute (ioutil .Discard , typed )
146+ t .Execute (io .Discard , typed )
85147 }
86148}
87149
0 commit comments