1// Copyright 2017 Vector Creations Ltd 2// Copyright 2017-2018 New Vector Ltd 3// Copyright 2019-2020 The Matrix.org Foundation C.I.C. 4// 5// Licensed under the Apache License, Version 2.0 (the "License"); 6// you may not use this file except in compliance with the License. 7// You may obtain a copy of the License at 8// 9// http://www.apache.org/licenses/LICENSE-2.0 10// 11// Unless required by applicable law or agreed to in writing, software 12// distributed under the License is distributed on an "AS IS" BASIS, 13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14// See the License for the specific language governing permissions and 15// limitations under the License. 16 17package cache 18 19import ( 20 "testing" 21 "time" 22 23 "github.com/matrix-org/dendrite/internal/test" 24) 25 26func TestEDUCache(t *testing.T) { 27 tCache := New() 28 if tCache == nil { 29 t.Fatal("New failed") 30 } 31 32 t.Run("AddTypingUser", func(t *testing.T) { 33 testAddTypingUser(t, tCache) 34 }) 35 36 t.Run("GetTypingUsers", func(t *testing.T) { 37 testGetTypingUsers(t, tCache) 38 }) 39 40 t.Run("RemoveUser", func(t *testing.T) { 41 testRemoveUser(t, tCache) 42 }) 43} 44 45func testAddTypingUser(t *testing.T, tCache *EDUCache) { // nolint: unparam 46 present := time.Now() 47 tests := []struct { 48 userID string 49 roomID string 50 expire *time.Time 51 }{ // Set four users typing state to room1 52 {"user1", "room1", nil}, 53 {"user2", "room1", nil}, 54 {"user3", "room1", nil}, 55 {"user4", "room1", nil}, 56 //typing state with past expireTime should not take effect or removed. 57 {"user1", "room2", &present}, 58 } 59 60 for _, tt := range tests { 61 tCache.AddTypingUser(tt.userID, tt.roomID, tt.expire) 62 } 63} 64 65func testGetTypingUsers(t *testing.T, tCache *EDUCache) { 66 tests := []struct { 67 roomID string 68 wantUsers []string 69 }{ 70 {"room1", []string{"user1", "user2", "user3", "user4"}}, 71 {"room2", []string{}}, 72 } 73 74 for _, tt := range tests { 75 gotUsers := tCache.GetTypingUsers(tt.roomID) 76 if !test.UnsortedStringSliceEqual(gotUsers, tt.wantUsers) { 77 t.Errorf("TypingCache.GetTypingUsers(%s) = %v, want %v", tt.roomID, gotUsers, tt.wantUsers) 78 } 79 } 80} 81 82func testRemoveUser(t *testing.T, tCache *EDUCache) { 83 tests := []struct { 84 roomID string 85 userIDs []string 86 }{ 87 {"room3", []string{"user1"}}, 88 {"room4", []string{"user1", "user2", "user3"}}, 89 } 90 91 for _, tt := range tests { 92 for _, userID := range tt.userIDs { 93 tCache.AddTypingUser(userID, tt.roomID, nil) 94 } 95 96 length := len(tt.userIDs) 97 tCache.RemoveUser(tt.userIDs[length-1], tt.roomID) 98 expLeftUsers := tt.userIDs[:length-1] 99 if leftUsers := tCache.GetTypingUsers(tt.roomID); !test.UnsortedStringSliceEqual(leftUsers, expLeftUsers) { 100 t.Errorf("Response after removal is unexpected. Want = %s, got = %s", leftUsers, expLeftUsers) 101 } 102 } 103} 104