@@ -18,6 +18,7 @@ package unstructured
18
18
19
19
import (
20
20
"io/ioutil"
21
+ "math"
21
22
"sync"
22
23
"testing"
23
24
@@ -225,3 +226,74 @@ func TestSetNestedMap(t *testing.T) {
225
226
assert .Len (t , obj ["x" ].(map [string ]interface {})["z" ], 1 )
226
227
assert .Equal (t , "bar" , obj ["x" ].(map [string ]interface {})["z" ].(map [string ]interface {})["b" ])
227
228
}
229
+
230
+ func TestNestedNumberAsFloat64 (t * testing.T ) {
231
+ for _ , tc := range []struct {
232
+ name string
233
+ obj map [string ]interface {}
234
+ path []string
235
+ wantFloat64 float64
236
+ wantBool bool
237
+ wantErrMessage string
238
+ }{
239
+ {
240
+ name : "not found" ,
241
+ obj : nil ,
242
+ path : []string {"missing" },
243
+ wantFloat64 : 0 ,
244
+ wantBool : false ,
245
+ wantErrMessage : "" ,
246
+ },
247
+ {
248
+ name : "found float64" ,
249
+ obj : map [string ]interface {}{"value" : float64 (42 )},
250
+ path : []string {"value" },
251
+ wantFloat64 : 42 ,
252
+ wantBool : true ,
253
+ wantErrMessage : "" ,
254
+ },
255
+ {
256
+ name : "found unexpected type bool" ,
257
+ obj : map [string ]interface {}{"value" : true },
258
+ path : []string {"value" },
259
+ wantFloat64 : 0 ,
260
+ wantBool : false ,
261
+ wantErrMessage : ".value accessor error: true is of the type bool, expected float64 or int64" ,
262
+ },
263
+ {
264
+ name : "found int64" ,
265
+ obj : map [string ]interface {}{"value" : int64 (42 )},
266
+ path : []string {"value" },
267
+ wantFloat64 : 42 ,
268
+ wantBool : true ,
269
+ wantErrMessage : "" ,
270
+ },
271
+ {
272
+ name : "found int64 not representable as float64" ,
273
+ obj : map [string ]interface {}{"value" : int64 (math .MaxInt64 )},
274
+ path : []string {"value" },
275
+ wantFloat64 : 0 ,
276
+ wantBool : false ,
277
+ wantErrMessage : ".value accessor error: int64 value 9223372036854775807 cannot be losslessly converted to float64" ,
278
+ },
279
+ } {
280
+ t .Run (tc .name , func (t * testing.T ) {
281
+ gotFloat64 , gotBool , gotErr := NestedNumberAsFloat64 (tc .obj , tc .path ... )
282
+ if gotFloat64 != tc .wantFloat64 {
283
+ t .Errorf ("got %v, wanted %v" , gotFloat64 , tc .wantFloat64 )
284
+ }
285
+ if gotBool != tc .wantBool {
286
+ t .Errorf ("got %t, wanted %t" , gotBool , tc .wantBool )
287
+ }
288
+ if tc .wantErrMessage != "" {
289
+ if gotErr == nil {
290
+ t .Errorf ("got nil error, wanted %s" , tc .wantErrMessage )
291
+ } else if gotErrMessage := gotErr .Error (); gotErrMessage != tc .wantErrMessage {
292
+ t .Errorf ("wanted error %q, got: %v" , gotErrMessage , tc .wantErrMessage )
293
+ }
294
+ } else if gotErr != nil {
295
+ t .Errorf ("wanted nil error, got %v" , gotErr )
296
+ }
297
+ })
298
+ }
299
+ }
0 commit comments