Codebase list golang-github-mitchellh-reflectwalk / ebadd3f
New upstream version 1.0.1 Shengjing Zhu 3 years ago
3 changed file(s) with 71 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
0 module github.com/mitchellh/reflectwalk
229229 ew.Enter(MapValue)
230230 }
231231
232 if err := walk(kv, w); err != nil {
232 // get the map value again as it may have changed in the MapElem call
233 if err := walk(v.MapIndex(k), w); err != nil {
233234 return err
234235 }
235236
9494
9595 t.Keys[k.Interface().(string)] = true
9696 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))
97110 return nil
98111 }
99112
354367 }
355368 }
356369
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
357425 func TestWalk_Pointer(t *testing.T) {
358426 w := new(TestPointerWalker)
359427