Skip to content

Commit

Permalink
Add test for mapKeys()
Browse files Browse the repository at this point in the history
Signed-off-by: Piotr Piotrowski <[email protected]>
  • Loading branch information
piotrpio committed Jan 14, 2024
1 parent 91b7873 commit 8888a3a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions collector/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ func (nc *NATSCollector) objectToMetrics(response map[string]interface{}, namesp

// mapKeys returns a map of all keys in a map, including nested maps.
// The keys from nested maps are prefixed with the parent key.
func mapKeys(input map[string]interface{}, prefix string) map[string]struct{} {
func mapKeys(input map[string]any, prefix string) map[string]struct{} {
keys := make(map[string]struct{})

for k, v := range input {
Expand All @@ -417,7 +417,7 @@ func mapKeys(input map[string]interface{}, prefix string) map[string]struct{} {
fullKey = prefix + "_" + k
}

if nestedMap, ok := v.(map[string]interface{}); ok {
if nestedMap, ok := v.(map[string]any); ok {
nestedKeys := mapKeys(nestedMap, fullKey)
for nestedKey := range nestedKeys {
keys[nestedKey] = struct{}{}
Expand Down
28 changes: 28 additions & 0 deletions collector/collector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package collector

import (
"fmt"
"maps"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -728,3 +729,30 @@ func TestReplicatorMetrics(t *testing.T) {
url := "http://127.0.0.1:9922"
verifyCollector(ReplicatorSystem, url, "varz", cases, t)
}

func TestMapKeys(t *testing.T) {
m := map[string]any{
"foo": "bar",
"baz": "quux",
"nested": map[string]any{
"foo": "bar",
"baz": "quux",
"nested": map[string]any{
"foo": "bar",
"baz": "quux",
},
},
}
expected := map[string]struct{}{
"foo": {},
"baz": {},
"nested_foo": {},
"nested_baz": {},
"nested_nested_foo": {},
"nested_nested_baz": {},
}
keys := mapKeys(m, "")
if !maps.Equal(keys, expected) {
t.Fatalf("expected %v, got %v", expected, keys)
}
}

0 comments on commit 8888a3a

Please sign in to comment.