Guest User

Untitled

a guest
Dec 14th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "testing"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. )
  9.  
  10. // Implementation Nested
  11. func Nested(position string, m map[string]interface{}) (interface{}, bool) {
  12. pos := strings.Split(position, ".")
  13.  
  14. t := m
  15. for key, posKey := range pos {
  16. v, ok := t[posKey]
  17. if !ok {
  18. continue
  19. }
  20.  
  21. if newValue, ok := v.(map[string]interface{}); ok {
  22. if key+1 == len(pos) {
  23. return v, true
  24. }
  25.  
  26. t = newValue
  27. } else if newString, ok := v.(string); ok {
  28. return newString, true
  29. } else if newInt, ok := v.(int); ok {
  30. return newInt, true
  31. }
  32. }
  33.  
  34. return nil, false
  35. }
  36.  
  37. // Test for Nested function
  38. func TestNested(t *testing.T) {
  39. data := map[string]interface{}{
  40. "advert": map[string]interface{}{
  41. "id": "12",
  42. "title": "Lorem Ipsum",
  43. "status": map[string]interface{}{
  44. "code": "active",
  45. "url": "www.loremipsum.com",
  46. "ttl": 123123,
  47. },
  48. "contact": map[string]interface{}{
  49. "name": "daniel3",
  50. "phones": []string{
  51. "790123123",
  52. "790123546",
  53. },
  54. },
  55. },
  56. }
  57.  
  58. tests := []struct {
  59. Parameter string
  60. ExpectedFirst interface{}
  61. ExpectedSecond bool
  62. Data map[string]interface{}
  63. }{
  64. {
  65. Parameter: "advert.id",
  66. ExpectedFirst: "12",
  67. ExpectedSecond: true,
  68. Data: data,
  69. },
  70. {
  71. Parameter: "advert.status.code",
  72. ExpectedFirst: "active",
  73. ExpectedSecond: true,
  74. Data: data,
  75. },
  76. {
  77. Parameter: "advert.status.ttl",
  78. ExpectedFirst: 123123,
  79. ExpectedSecond: true,
  80. Data: data,
  81. },
  82. {
  83. Parameter: "advert.contact",
  84. ExpectedFirst: map[string]interface{}{
  85. "name": "daniel3",
  86. "phones": []string{
  87. "790123123",
  88. "790123546",
  89. },
  90. },
  91. ExpectedSecond: true,
  92. Data: data,
  93. },
  94. {
  95. Parameter: "advert.bananas",
  96. ExpectedFirst: nil,
  97. ExpectedSecond: false,
  98. Data: data,
  99. },
  100. }
  101.  
  102. for key, test := range tests {
  103. t.Run(fmt.Sprintf("Test #%d", key), func(t *testing.T) {
  104. actual, result := Nested(test.Parameter, test.Data)
  105. if !reflect.DeepEqual(test.ExpectedFirst, actual) || result != test.ExpectedSecond {
  106. t.Errorf("[%d] expected param1: %T(%v) and param2: %T(%v), but got param1: %T(%v) and param2: %T(%v)",
  107. key,
  108. test.ExpectedFirst, test.ExpectedFirst, // param1
  109. test.ExpectedSecond, test.ExpectedSecond, // param2
  110. actual, actual, // actual
  111. result, result, // result
  112. )
  113. }
  114. })
  115. }
  116. }
Add Comment
Please, Sign In to add comment