code.gitea.io/gitea@v1.21.7/tests/integration/eventsource_test.go (about) 1 // Copyright 2020 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package integration 5 6 import ( 7 "fmt" 8 "net/http" 9 "testing" 10 "time" 11 12 activities_model "code.gitea.io/gitea/models/activities" 13 auth_model "code.gitea.io/gitea/models/auth" 14 "code.gitea.io/gitea/models/db" 15 repo_model "code.gitea.io/gitea/models/repo" 16 "code.gitea.io/gitea/models/unittest" 17 user_model "code.gitea.io/gitea/models/user" 18 "code.gitea.io/gitea/modules/eventsource" 19 api "code.gitea.io/gitea/modules/structs" 20 "code.gitea.io/gitea/tests" 21 22 "github.com/stretchr/testify/assert" 23 ) 24 25 func TestEventSourceManagerRun(t *testing.T) { 26 defer tests.PrepareTestEnv(t)() 27 manager := eventsource.GetManager() 28 29 eventChan := manager.Register(2) 30 defer func() { 31 manager.Unregister(2, eventChan) 32 // ensure the eventChan is closed 33 for { 34 _, ok := <-eventChan 35 if !ok { 36 break 37 } 38 } 39 }() 40 expectNotificationCountEvent := func(count int64) func() bool { 41 return func() bool { 42 select { 43 case event, ok := <-eventChan: 44 if !ok { 45 return false 46 } 47 data, ok := event.Data.(activities_model.UserIDCount) 48 if !ok { 49 return false 50 } 51 return event.Name == "notification-count" && data.Count == count 52 default: 53 return false 54 } 55 } 56 } 57 58 user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) 59 repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) 60 thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) 61 assert.NoError(t, thread5.LoadAttributes(db.DefaultContext)) 62 session := loginUser(t, user2.Name) 63 token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification, auth_model.AccessTokenScopeWriteRepository) 64 65 var apiNL []api.NotificationThread 66 67 // -- mark notifications as read -- 68 req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?status-types=unread&token=%s", token)) 69 resp := session.MakeRequest(t, req, http.StatusOK) 70 71 DecodeJSON(t, resp, &apiNL) 72 assert.Len(t, apiNL, 2) 73 74 lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... 75 req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) 76 session.MakeRequest(t, req, http.StatusResetContent) 77 78 req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?token=%s&status-types=unread", token)) 79 resp = session.MakeRequest(t, req, http.StatusOK) 80 DecodeJSON(t, resp, &apiNL) 81 assert.Len(t, apiNL, 1) 82 83 assert.Eventually(t, expectNotificationCountEvent(1), 30*time.Second, 1*time.Second) 84 }