Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "testing"
- "fmt"
- "reflect"
- "strings"
- )
- // Implementation Nested
- func Nested(position string, m map[string]interface{}) (interface{}, bool) {
- pos := strings.Split(position, ".")
- t := m
- for key, posKey := range pos {
- v, ok := t[posKey]
- if !ok {
- continue
- }
- if newValue, ok := v.(map[string]interface{}); ok {
- if key+1 == len(pos) {
- return v, true
- }
- t = newValue
- } else if newString, ok := v.(string); ok {
- return newString, true
- } else if newInt, ok := v.(int); ok {
- return newInt, true
- }
- }
- return nil, false
- }
- // Test for Nested function
- func TestNested(t *testing.T) {
- data := map[string]interface{}{
- "advert": map[string]interface{}{
- "id": "12",
- "title": "Lorem Ipsum",
- "status": map[string]interface{}{
- "code": "active",
- "url": "www.loremipsum.com",
- "ttl": 123123,
- },
- "contact": map[string]interface{}{
- "name": "daniel3",
- "phones": []string{
- "790123123",
- "790123546",
- },
- },
- },
- }
- tests := []struct {
- Parameter string
- ExpectedFirst interface{}
- ExpectedSecond bool
- Data map[string]interface{}
- }{
- {
- Parameter: "advert.id",
- ExpectedFirst: "12",
- ExpectedSecond: true,
- Data: data,
- },
- {
- Parameter: "advert.status.code",
- ExpectedFirst: "active",
- ExpectedSecond: true,
- Data: data,
- },
- {
- Parameter: "advert.status.ttl",
- ExpectedFirst: 123123,
- ExpectedSecond: true,
- Data: data,
- },
- {
- Parameter: "advert.contact",
- ExpectedFirst: map[string]interface{}{
- "name": "daniel3",
- "phones": []string{
- "790123123",
- "790123546",
- },
- },
- ExpectedSecond: true,
- Data: data,
- },
- {
- Parameter: "advert.bananas",
- ExpectedFirst: nil,
- ExpectedSecond: false,
- Data: data,
- },
- }
- for key, test := range tests {
- t.Run(fmt.Sprintf("Test #%d", key), func(t *testing.T) {
- actual, result := Nested(test.Parameter, test.Data)
- if !reflect.DeepEqual(test.ExpectedFirst, actual) || result != test.ExpectedSecond {
- t.Errorf("[%d] expected param1: %T(%v) and param2: %T(%v), but got param1: %T(%v) and param2: %T(%v)",
- key,
- test.ExpectedFirst, test.ExpectedFirst, // param1
- test.ExpectedSecond, test.ExpectedSecond, // param2
- actual, actual, // actual
- result, result, // result
- )
- }
- })
- }
- }
Add Comment
Please, Sign In to add comment