94 | 94 |
|
95 | 95 |
t.Keys[k.Interface().(string)] = true
|
96 | 96 |
t.Values[v.Interface().(string)] = true
|
|
97 |
return nil
|
|
98 |
}
|
|
99 |
|
|
100 |
type TestMapElemReplaceWalker struct {
|
|
101 |
ValueFn func(v reflect.Value) reflect.Value
|
|
102 |
}
|
|
103 |
|
|
104 |
func (t *TestMapElemReplaceWalker) Map(m reflect.Value) error {
|
|
105 |
return nil
|
|
106 |
}
|
|
107 |
|
|
108 |
func (t *TestMapElemReplaceWalker) MapElem(m, k, v reflect.Value) error {
|
|
109 |
m.SetMapIndex(k, t.ValueFn(v))
|
97 | 110 |
return nil
|
98 | 111 |
}
|
99 | 112 |
|
|
354 | 367 |
}
|
355 | 368 |
}
|
356 | 369 |
|
|
370 |
func TestWalk_Map_ReplaceValue(t *testing.T) {
|
|
371 |
w := &TestMapElemReplaceWalker{
|
|
372 |
ValueFn: func(v reflect.Value) reflect.Value {
|
|
373 |
if v.Type().Kind() == reflect.String {
|
|
374 |
return reflect.ValueOf("replaced")
|
|
375 |
}
|
|
376 |
|
|
377 |
if v.Type().Kind() == reflect.Interface {
|
|
378 |
if elem := v.Elem(); elem.Type() == reflect.TypeOf(map[string]interface{}{}) {
|
|
379 |
newMap := make(map[string]interface{})
|
|
380 |
for _, k := range elem.MapKeys() {
|
|
381 |
newMap[k.String()] = elem.MapIndex(k).Interface()
|
|
382 |
}
|
|
383 |
newMap["extra-replaced"] = "not-replaced"
|
|
384 |
return reflect.ValueOf(newMap)
|
|
385 |
} else if elem.Type().Kind() == reflect.String {
|
|
386 |
return reflect.ValueOf("replaced")
|
|
387 |
}
|
|
388 |
}
|
|
389 |
|
|
390 |
return v
|
|
391 |
},
|
|
392 |
}
|
|
393 |
|
|
394 |
type S struct {
|
|
395 |
Foo map[string]interface{}
|
|
396 |
}
|
|
397 |
|
|
398 |
data := &S{
|
|
399 |
Foo: map[string]interface{}{
|
|
400 |
"foo": map[string]interface{}{
|
|
401 |
"bar": map[string]string{"baz": "should-get-replaced"},
|
|
402 |
},
|
|
403 |
},
|
|
404 |
}
|
|
405 |
|
|
406 |
expected := &S{
|
|
407 |
Foo: map[string]interface{}{
|
|
408 |
"foo": map[string]interface{}{
|
|
409 |
"bar": map[string]string{"baz": "replaced"},
|
|
410 |
"extra-replaced": "replaced",
|
|
411 |
},
|
|
412 |
},
|
|
413 |
}
|
|
414 |
|
|
415 |
err := Walk(data, w)
|
|
416 |
if err != nil {
|
|
417 |
t.Fatalf("err: %v", err)
|
|
418 |
}
|
|
419 |
|
|
420 |
if !reflect.DeepEqual(data, expected) {
|
|
421 |
t.Fatalf("Values not equal: %#v", data)
|
|
422 |
}
|
|
423 |
}
|
|
424 |
|
357 | 425 |
func TestWalk_Pointer(t *testing.T) {
|
358 | 426 |
w := new(TestPointerWalker)
|
359 | 427 |
|