github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/genutil/mapz/multimap_test.go (about) 1 package mapz 2 3 import ( 4 "sort" 5 "testing" 6 7 "github.com/stretchr/testify/require" 8 ) 9 10 func TestMultimapOperations(t *testing.T) { 11 mm := NewMultiMap[string, int]() 12 require.Equal(t, 0, mm.Len()) 13 require.True(t, mm.IsEmpty()) 14 15 // Add some values to the map. 16 mm.Add("odd", 1) 17 mm.Add("odd", 3) 18 mm.Add("odd", 5) 19 20 require.Equal(t, 1, mm.Len()) 21 require.False(t, mm.IsEmpty()) 22 23 require.True(t, mm.Has("odd")) 24 found, ok := mm.Get("odd") 25 require.True(t, ok) 26 require.Equal(t, []int{1, 3, 5}, found) 27 28 require.False(t, mm.Has("even")) 29 found, ok = mm.Get("even") 30 require.False(t, ok) 31 require.Equal(t, []int{}, found) 32 33 require.Equal(t, []string{"odd"}, mm.Keys()) 34 35 // Add some more values. 36 mm.Add("even", 2) 37 mm.Add("even", 4) 38 39 require.Equal(t, 2, mm.Len()) 40 require.False(t, mm.IsEmpty()) 41 42 require.True(t, mm.Has("even")) 43 found, ok = mm.Get("even") 44 require.True(t, ok) 45 require.Equal(t, []int{2, 4}, found) 46 47 foundKeys := mm.Keys() 48 sort.Strings(foundKeys) 49 50 require.Equal(t, []string{"even", "odd"}, foundKeys) 51 52 // Remove a key. 53 mm.RemoveKey("odd") 54 55 require.Equal(t, 1, mm.Len()) 56 require.False(t, mm.IsEmpty()) 57 58 foundKeys = mm.Keys() 59 sort.Strings(foundKeys) 60 require.Equal(t, []string{"even"}, foundKeys) 61 62 require.False(t, mm.Has("odd")) 63 found, ok = mm.Get("odd") 64 require.False(t, ok) 65 require.Equal(t, []int{}, found) 66 67 // Remove an unknown key. 68 mm.RemoveKey("unknown") 69 require.Equal(t, 1, mm.Len()) 70 require.False(t, mm.IsEmpty()) 71 72 // Remove the last key. 73 mm.RemoveKey("even") 74 require.Equal(t, 0, mm.Len()) 75 require.True(t, mm.IsEmpty()) 76 } 77 78 func TestMultimapReadOnly(t *testing.T) { 79 mm := NewMultiMap[string, int]() 80 require.Equal(t, 0, mm.Len()) 81 require.True(t, mm.IsEmpty()) 82 83 // Add some values to the map. 84 mm.Add("odd", 1) 85 mm.Add("odd", 3) 86 mm.Add("odd", 5) 87 88 // Make a read-only copy. 89 ro := mm.AsReadOnly() 90 91 // Add some values to the original map. 92 mm.Add("even", 2) 93 mm.Add("zero", 0) 94 95 // Make sure the read-only map was not modified. 96 require.Equal(t, 3, mm.Len()) 97 require.Equal(t, 1, ro.Len()) 98 99 require.True(t, mm.Has("even")) 100 require.False(t, ro.Has("even")) 101 }