nesting_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package datautil
  10. import (
  11. "bytes"
  12. "encoding/gob"
  13. "fmt"
  14. "testing"
  15. )
  16. func TestNesting(t *testing.T) {
  17. // Create a nested piece of data which is serialized and deserialized
  18. var testData1 = map[string]interface{}{
  19. "level1": map[string]interface{}{
  20. "level2": map[string]interface{}{
  21. "atom": 42,
  22. },
  23. "atom2": "test5",
  24. },
  25. }
  26. var bb1 bytes.Buffer
  27. // Only register the generic map[string]interface{}
  28. gob.Register(map[string]interface{}{})
  29. if err := gob.NewEncoder(&bb1).Encode(testData1); err != nil {
  30. t.Error(err)
  31. return
  32. }
  33. var testOut map[string]interface{}
  34. if err := gob.NewDecoder(&bb1).Decode(&testOut); err != nil {
  35. t.Error(err)
  36. return
  37. }
  38. val, err := GetNestedValue(testOut, []string{"level1", "level2", "atom"})
  39. if val != 42 || err != nil {
  40. t.Error("Unexpected result:", val, err)
  41. return
  42. }
  43. val, err = GetNestedValue(testOut, []string{"level1", "level2"})
  44. if fmt.Sprint(val) != "map[atom:42]" || err != nil {
  45. t.Error("Unexpected result:", val, err)
  46. return
  47. }
  48. val, err = GetNestedValue(testOut, []string{"level1", "atom2"})
  49. if val != "test5" || err != nil {
  50. t.Error("Unexpected result:", val, err)
  51. return
  52. }
  53. val, err = GetNestedValue(testOut, []string{"level1", "atom3"})
  54. if val != nil || err != nil {
  55. t.Error("Unexpected result:", val, err)
  56. return
  57. }
  58. val, err = GetNestedValue(testOut, []string{"level1", "level2", "atom", "test"})
  59. if val != nil || err.Error() != "Unexpected data type int as value of atom" {
  60. t.Error("Unexpected result:", val, err)
  61. return
  62. }
  63. }