generics/maps_test.go

163 lines
2.4 KiB
Go
Raw Normal View History

2023-11-03 21:18:22 +01:00
package generics
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestMapPairs(t *testing.T) {
tests := map[string]struct {
src map[string]int
dst []Pair[string, int]
}{
"nil map": {
src: nil,
2024-05-21 22:39:52 +02:00
dst: Pairs[string, int]{},
2023-11-03 21:18:22 +01:00
},
"empty map": {
src: map[string]int{},
2024-05-21 22:39:52 +02:00
dst: Pairs[string, int]{},
2023-11-03 21:18:22 +01:00
},
"filled map": {
src: map[string]int{
"foo": 1,
"bar": 2,
"baz": 3,
},
2024-05-21 22:39:52 +02:00
dst: Pairs[string, int]{
2023-11-03 21:18:22 +01:00
{
Key: "foo",
Value: 1,
},
{
Key: "bar",
Value: 2,
},
{
Key: "baz",
Value: 3,
},
},
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
dst := MapPairs(tc.src)
require.ElementsMatch(t, tc.dst, dst)
})
}
}
func TestMapKeys(t *testing.T) {
tests := map[string]struct {
src map[string]int
dst []string
}{
"nil map": {
src: nil,
dst: []string{},
},
"empty map": {
src: map[string]int{},
dst: []string{},
},
"filled map": {
src: map[string]int{
"foo": 1,
"bar": 2,
"baz": 3,
},
dst: []string{
"foo",
"bar",
"baz",
},
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
dst := MapKeys(tc.src)
require.ElementsMatch(t, tc.dst, dst)
})
}
}
func TestMapValues(t *testing.T) {
tests := map[string]struct {
src map[string]int
dst []int
}{
"nil map": {
src: nil,
dst: []int{},
},
"empty map": {
src: map[string]int{},
dst: []int{},
},
"filled map": {
src: map[string]int{
"foo": 1,
"bar": 2,
"baz": 3,
},
dst: []int{1, 2, 3},
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
dst := MapValues(tc.src)
require.ElementsMatch(t, tc.dst, dst)
})
}
}
func TestInvertMap(t *testing.T) {
tests := map[string]struct {
src map[string]int
dst map[int]string
}{
"nil map": {
src: nil,
dst: nil,
},
"empty map": {
src: map[string]int{},
dst: map[int]string{},
},
"filled map": {
src: map[string]int{
"foo": 1,
"bar": 2,
"baz": 3,
},
dst: map[int]string{
1: "foo",
2: "bar",
3: "baz",
},
},
}
for name, tc := range tests {
name, tc := name, tc
t.Run(name, func(t *testing.T) {
dst := InvertMap(tc.src)
if tc.dst == nil {
require.Nil(t, dst)
return
}
require.NotNil(t, dst)
require.EqualValues(t, tc.dst, dst)
})
}
}