From 313b6387908422283e17fa8c073f82df1fc77d85 Mon Sep 17 00:00:00 2001 From: Miguel dos Reis Date: Thu, 2 May 2024 14:52:54 -0300 Subject: [PATCH] Fix tests --- cmd/apns_test.go | 21 ++++--- config/test.yaml | 2 +- e2e/apns_e2e_test.go | 83 ++++++++++++++----------- extensions/apns_message_handler_test.go | 11 ++-- extensions/gcm_message_handler_test.go | 8 +-- pusher/apns_test.go | 2 +- 6 files changed, 69 insertions(+), 58 deletions(-) diff --git a/cmd/apns_test.go b/cmd/apns_test.go index 694cf86..eaa760a 100644 --- a/cmd/apns_test.go +++ b/cmd/apns_test.go @@ -24,6 +24,7 @@ package cmd import ( "fmt" + "github.com/topfreegames/pusher/config" "os" . "github.com/onsi/ginkgo" @@ -31,23 +32,23 @@ import ( "github.com/sirupsen/logrus" "github.com/spf13/viper" "github.com/topfreegames/pusher/mocks" - "github.com/topfreegames/pusher/util" ) var _ = Describe("APNS", func() { - cfg := os.Getenv("CONFIG_FILE") - if cfg == "" { - cfg = "../config/test.yaml" + configFile := os.Getenv("CONFIG_FILE") + if configFile == "" { + configFile = "../config/test.yaml" } - var config *viper.Viper + var vConfig *viper.Viper + var cfg *config.Config var mockPushQueue *mocks.APNSPushQueueMock var mockDB *mocks.PGMock var mockStatsDClient *mocks.StatsDClientMock BeforeEach(func() { var err error - config, err = util.NewViperWithConfigFile(cfg) + cfg, vConfig, err = config.NewConfigAndViper(configFile) Expect(err).NotTo(HaveOccurred()) mockDB = mocks.NewPGMock(0, 1) mockPushQueue = mocks.NewAPNSPushQueueMock() @@ -56,7 +57,7 @@ var _ = Describe("APNS", func() { Describe("[Unit]", func() { It("Should return apnsPusher without errors", func() { - apnsPusher, err := startApns(false, false, false, config, mockStatsDClient, mockDB, mockPushQueue) + apnsPusher, err := startApns(false, false, false, vConfig, cfg, mockStatsDClient, mockDB, mockPushQueue) Expect(err).NotTo(HaveOccurred()) Expect(apnsPusher).NotTo(BeNil()) Expect(apnsPusher.ViperConfig).NotTo(BeNil()) @@ -66,21 +67,21 @@ var _ = Describe("APNS", func() { }) It("Should set log to json format", func() { - apnsPusher, err := startApns(false, true, false, config, mockStatsDClient, mockDB, mockPushQueue) + apnsPusher, err := startApns(false, true, false, vConfig, cfg, mockStatsDClient, mockDB, mockPushQueue) Expect(err).NotTo(HaveOccurred()) Expect(apnsPusher).NotTo(BeNil()) Expect(fmt.Sprintf("%T", apnsPusher.Logger.Formatter)).To(Equal(fmt.Sprintf("%T", &logrus.JSONFormatter{}))) }) It("Should set log to debug", func() { - apnsPusher, err := startApns(true, false, false, config, mockStatsDClient, mockDB, mockPushQueue) + apnsPusher, err := startApns(true, false, false, vConfig, cfg, mockStatsDClient, mockDB, mockPushQueue) Expect(err).NotTo(HaveOccurred()) Expect(apnsPusher).NotTo(BeNil()) Expect(apnsPusher.Logger.Level).To(Equal(logrus.DebugLevel)) }) It("Should set log to production", func() { - apnsPusher, err := startApns(false, false, true, config, mockStatsDClient, mockDB, mockPushQueue) + apnsPusher, err := startApns(false, false, true, vConfig, cfg, mockStatsDClient, mockDB, mockPushQueue) Expect(err).NotTo(HaveOccurred()) Expect(apnsPusher).NotTo(BeNil()) Expect(apnsPusher.IsProduction).To(BeTrue()) diff --git a/config/test.yaml b/config/test.yaml index e3785c9..fc1bbca 100644 --- a/config/test.yaml +++ b/config/test.yaml @@ -38,7 +38,7 @@ feedback: topics: "com.games.test.feedbacks" brokers: "localhost:9941" cache: - requestTimeout: 10000 + requestTimeout: 1000 cleaningInterval: 20 stats: reporters: diff --git a/e2e/apns_e2e_test.go b/e2e/apns_e2e_test.go index 3a979f3..542f7ff 100644 --- a/e2e/apns_e2e_test.go +++ b/e2e/apns_e2e_test.go @@ -7,6 +7,7 @@ import ( "github.com/google/uuid" "github.com/sideshow/apns2" "github.com/sirupsen/logrus" + "github.com/spf13/viper" "github.com/stretchr/testify/suite" "github.com/topfreegames/pusher/config" mocks "github.com/topfreegames/pusher/mocks/interfaces" @@ -19,26 +20,22 @@ import ( "time" ) -const wait = 15 * time.Second +const wait = 5 * time.Second const timeout = 1 * time.Minute const topicTemplate = "push-%s_apns-single" type ApnsE2ETestSuite struct { suite.Suite - statsdClientMock *mocks.MockStatsDClient - config *config.Config - listenerStatsdClientMock *mocks.MockStatsDClient - mockApnsClient *mocks.MockAPNSPushQueue - responsesChannel chan *structs.ResponseWithMetadata - stop context.CancelFunc + config *config.Config + vConfig *viper.Viper } func TestApnsE2eSuite(t *testing.T) { suite.Run(t, new(ApnsE2ETestSuite)) } -func (s *ApnsE2ETestSuite) SetupTest() { +func (s *ApnsE2ETestSuite) SetupSuite() { configFile := os.Getenv("CONFIG_FILE") if configFile == "" { configFile = "../config/test.yaml" @@ -46,40 +43,40 @@ func (s *ApnsE2ETestSuite) SetupTest() { c, v, err := config.NewConfigAndViper(configFile) s.Require().NoError(err) s.config = c + s.vConfig = v +} - appName := strings.Split(uuid.NewString(), "-")[0] - s.config.Apns.Apps = appName - v.Set("queue.topics", []string{fmt.Sprintf(topicTemplate, appName)}) - - s.responsesChannel = make(chan *structs.ResponseWithMetadata) +func (s *ApnsE2ETestSuite) setupApnsPusher() (*mocks.MockAPNSPushQueue, *mocks.MockStatsDClient, chan *structs.ResponseWithMetadata) { + responsesChannel := make(chan *structs.ResponseWithMetadata) ctrl := gomock.NewController(s.T()) - s.mockApnsClient = mocks.NewMockAPNSPushQueue(ctrl) - s.mockApnsClient.EXPECT().ResponseChannel().Return(s.responsesChannel) + mockApnsClient := mocks.NewMockAPNSPushQueue(ctrl) + mockApnsClient.EXPECT().ResponseChannel().Return(responsesChannel) + + statsdClientMock := mocks.NewMockStatsDClient(ctrl) - s.statsdClientMock = mocks.NewMockStatsDClient(ctrl) - s.listenerStatsdClientMock = mocks.NewMockStatsDClient(ctrl) logger := logrus.New() logger.Level = logrus.DebugLevel s.assureTopicsExist() time.Sleep(wait) - apnsPusher, err := pusher.NewAPNSPusher(false, v, c, logger, s.statsdClientMock, nil, s.mockApnsClient) + apnsPusher, err := pusher.NewAPNSPusher(false, s.vConfig, s.config, logger, statsdClientMock, nil, mockApnsClient) s.Require().NoError(err) ctx := context.Background() - ctx, s.stop = context.WithCancel(ctx) go apnsPusher.Start(ctx) time.Sleep(wait) -} -func (s *ApnsE2ETestSuite) TearDownTest() { - fmt.Println("Tearing down test") - s.stop() + return mockApnsClient, statsdClientMock, responsesChannel } func (s *ApnsE2ETestSuite) TestSimpleNotification() { + appName := strings.Split(uuid.NewString(), "-")[0] + s.config.Apns.Apps = appName + s.vConfig.Set("queue.topics", []string{fmt.Sprintf(topicTemplate, appName)}) + + mockApnsClient, statsdClientMock, responsesChannel := s.setupApnsPusher() producer, err := kafka.NewProducer(&kafka.ConfigMap{ "bootstrap.servers": s.config.Queue.Brokers, }) @@ -89,14 +86,14 @@ func (s *ApnsE2ETestSuite) TestSimpleNotification() { topic := "push-" + app + "_apns-single" token := "token" testDone := make(chan bool) - s.mockApnsClient.EXPECT(). + mockApnsClient.EXPECT(). Push(gomock.Any()). DoAndReturn(func(notification *apns2.Notification) error { s.Equal(token, notification.DeviceToken) s.Equal(s.config.Apns.Certs[app].Topic, notification.Topic) go func() { - s.responsesChannel <- &structs.ResponseWithMetadata{ + responsesChannel <- &structs.ResponseWithMetadata{ ApnsID: notification.ApnsID, Sent: true, StatusCode: 200, @@ -106,13 +103,13 @@ func (s *ApnsE2ETestSuite) TestSimpleNotification() { return nil }) - s.statsdClientMock.EXPECT(). + statsdClientMock.EXPECT(). Incr("sent", []string{fmt.Sprintf("platform:%s", "apns"), fmt.Sprintf("game:%s", app)}, float64(1)). DoAndReturn(func(string, []string, float64) error { return nil }) - s.statsdClientMock.EXPECT(). + statsdClientMock.EXPECT(). Incr("ack", []string{fmt.Sprintf("platform:%s", "apns"), fmt.Sprintf("game:%s", app)}, float64(1)). DoAndReturn(func(string, []string, float64) error { testDone <- true @@ -141,6 +138,12 @@ func (s *ApnsE2ETestSuite) TestSimpleNotification() { } func (s *ApnsE2ETestSuite) TestNotificationRetry() { + appName := strings.Split(uuid.NewString(), "-")[0] + s.config.Apns.Apps = appName + s.vConfig.Set("queue.topics", []string{fmt.Sprintf(topicTemplate, appName)}) + + mockApnsClient, statsdClientMock, responsesChannel := s.setupApnsPusher() + producer, err := kafka.NewProducer(&kafka.ConfigMap{ "bootstrap.servers": s.config.Queue.Brokers, }) @@ -151,14 +154,14 @@ func (s *ApnsE2ETestSuite) TestNotificationRetry() { token := "token" done := make(chan bool) - s.mockApnsClient.EXPECT(). + mockApnsClient.EXPECT(). Push(gomock.Any()). DoAndReturn(func(notification *apns2.Notification) error { s.Equal(token, notification.DeviceToken) s.Equal(s.config.Apns.Certs[app].Topic, notification.Topic) go func() { - s.responsesChannel <- &structs.ResponseWithMetadata{ + responsesChannel <- &structs.ResponseWithMetadata{ ApnsID: notification.ApnsID, Sent: true, StatusCode: 429, @@ -169,14 +172,14 @@ func (s *ApnsE2ETestSuite) TestNotificationRetry() { return nil }) - s.mockApnsClient.EXPECT(). + mockApnsClient.EXPECT(). Push(gomock.Any()). DoAndReturn(func(notification *apns2.Notification) error { s.Equal(token, notification.DeviceToken) s.Equal(s.config.Apns.Certs[app].Topic, notification.Topic) go func() { - s.responsesChannel <- &structs.ResponseWithMetadata{ + responsesChannel <- &structs.ResponseWithMetadata{ ApnsID: notification.ApnsID, Sent: true, StatusCode: 200, @@ -186,13 +189,13 @@ func (s *ApnsE2ETestSuite) TestNotificationRetry() { return nil }) - s.statsdClientMock.EXPECT(). + statsdClientMock.EXPECT(). Incr("sent", []string{fmt.Sprintf("platform:%s", "apns"), fmt.Sprintf("game:%s", app)}, float64(1)). DoAndReturn(func(string, []string, float64) error { return nil }) - s.statsdClientMock.EXPECT(). + statsdClientMock.EXPECT(). Incr("ack", []string{fmt.Sprintf("platform:%s", "apns"), fmt.Sprintf("game:%s", app)}, float64(1)). DoAndReturn(func(string, []string, float64) error { done <- true @@ -221,6 +224,12 @@ func (s *ApnsE2ETestSuite) TestNotificationRetry() { } func (s *ApnsE2ETestSuite) TestMultipleNotifications() { + appName := strings.Split(uuid.NewString(), "-")[0] + s.config.Apns.Apps = appName + s.vConfig.Set("queue.topics", []string{fmt.Sprintf(topicTemplate, appName)}) + + mockApnsClient, statsdClientMock, responsesChannel := s.setupApnsPusher() + notificationsToSend := 10 producer, err := kafka.NewProducer(&kafka.ConfigMap{ "bootstrap.servers": s.config.Queue.Brokers, @@ -233,13 +242,13 @@ func (s *ApnsE2ETestSuite) TestMultipleNotifications() { done := make(chan bool) for i := 0; i < notificationsToSend; i++ { - s.mockApnsClient.EXPECT(). + mockApnsClient.EXPECT(). Push(gomock.Any()). DoAndReturn(func(notification *apns2.Notification) error { s.Equal(s.config.Apns.Certs[app].Topic, notification.Topic) go func() { - s.responsesChannel <- &structs.ResponseWithMetadata{ + responsesChannel <- &structs.ResponseWithMetadata{ ApnsID: notification.ApnsID, Sent: true, StatusCode: 200, @@ -250,14 +259,14 @@ func (s *ApnsE2ETestSuite) TestMultipleNotifications() { }) } - s.statsdClientMock.EXPECT(). + statsdClientMock.EXPECT(). Incr("sent", []string{fmt.Sprintf("platform:%s", "apns"), fmt.Sprintf("game:%s", app)}, float64(1)). Times(notificationsToSend). DoAndReturn(func(string, []string, float64) error { return nil }) - s.statsdClientMock.EXPECT(). + statsdClientMock.EXPECT(). Incr("ack", []string{fmt.Sprintf("platform:%s", "apns"), fmt.Sprintf("game:%s", app)}, float64(1)). Times(notificationsToSend). DoAndReturn(func(string, []string, float64) error { diff --git a/extensions/apns_message_handler_test.go b/extensions/apns_message_handler_test.go index c44446d..8c2447e 100644 --- a/extensions/apns_message_handler_test.go +++ b/extensions/apns_message_handler_test.go @@ -511,7 +511,7 @@ var _ = FDescribe("APNS Message Handler", func() { Value: []byte(`{ "aps" : { "alert" : "Hello HTTP/2" } }`), }) Expect(func() { go handler.CleanMetadataCache() }).ShouldNot(Panic()) - time.Sleep(500 * time.Millisecond) + time.Sleep(2 * time.Duration(config.GetInt("feedback.cache.requestTimeout")) * time.Millisecond) handler.inFlightNotificationsMapLock.Lock() Expect(*handler.requestsHeap).To(BeEmpty()) Expect(handler.InFlightNotificationsMap).To(BeEmpty()) @@ -530,7 +530,8 @@ var _ = FDescribe("APNS Message Handler", func() { } handler.handleAPNSResponse(res) - time.Sleep(500 * time.Millisecond) + time.Sleep(2 * time.Duration(config.GetInt("feedback.cache.requestTimeout")) * time.Millisecond) + handler.inFlightNotificationsMapLock.Lock() Expect(*handler.requestsHeap).To(BeEmpty()) Expect(handler.InFlightNotificationsMap).To(BeEmpty()) @@ -563,7 +564,7 @@ var _ = FDescribe("APNS Message Handler", func() { Expect(func() { go sendRequests() }).ShouldNot(Panic()) time.Sleep(10 * time.Millisecond) Expect(func() { go handleResponses() }).ShouldNot(Panic()) - time.Sleep(500 * time.Millisecond) + time.Sleep(2 * time.Duration(config.GetInt("feedback.cache.requestTimeout")) * time.Millisecond) handler.inFlightNotificationsMapLock.Lock() Expect(*handler.requestsHeap).To(BeEmpty()) @@ -843,11 +844,11 @@ var _ = FDescribe("APNS Message Handler", func() { } go func() { err := handler.handleAPNSResponse(res) - Expect(err).To(HaveOccurred()) + Expect(err).NotTo(HaveOccurred()) }() go func() { err := handler.handleAPNSResponse(res2) - Expect(err).To(HaveOccurred()) + Expect(err).NotTo(HaveOccurred()) }() }) }) diff --git a/extensions/gcm_message_handler_test.go b/extensions/gcm_message_handler_test.go index 04016c6..0b3dada 100644 --- a/extensions/gcm_message_handler_test.go +++ b/extensions/gcm_message_handler_test.go @@ -517,7 +517,7 @@ func (s *GCMMessageHandlerTestSuite) TestCleanCache() { go handler.CleanMetadataCache() - time.Sleep(500 * time.Millisecond) + time.Sleep(2 * time.Duration(s.vConfig.GetInt("feedback.cache.requestTimeout")) * time.Millisecond) s.True(handler.requestsHeap.Empty()) handler.inflightMessagesMetadataLock.Lock() @@ -545,7 +545,7 @@ func (s *GCMMessageHandlerTestSuite) TestCleanCache() { err = handler.handleGCMResponse(res) s.Require().NoError(err) - time.Sleep(500 * time.Millisecond) + time.Sleep(2 * time.Duration(s.vConfig.GetInt("feedback.cache.requestTimeout")) * time.Millisecond) s.True(handler.requestsHeap.Empty()) handler.inflightMessagesMetadataLock.Lock() @@ -583,10 +583,10 @@ func (s *GCMMessageHandlerTestSuite) TestCleanCache() { go handler.CleanMetadataCache() go sendRequests() - time.Sleep(500 * time.Millisecond) + time.Sleep(2 * time.Duration(s.vConfig.GetInt("feedback.cache.requestTimeout")) * time.Millisecond) go handleResponses() - time.Sleep(500 * time.Millisecond) + time.Sleep(2 * time.Duration(s.vConfig.GetInt("feedback.cache.requestTimeout")) * time.Millisecond) s.True(handler.requestsHeap.Empty()) handler.inflightMessagesMetadataLock.Lock() diff --git a/pusher/apns_test.go b/pusher/apns_test.go index 7d7b4a5..e38944e 100644 --- a/pusher/apns_test.go +++ b/pusher/apns_test.go @@ -109,7 +109,7 @@ var _ = Describe("APNS Pusher", func() { }) It("should not ignore failed handlers", func() { - vConfig.Set("apns.apps", "game,invalidgame") + cfg.Apns.Apps = "game,invalidgame" vConfig.Set("apns.certs.invalidgame.authKeyPath", "../tls/authkey_invalid.p8") vConfig.Set("apns.certs.invalidgame.keyID", "oiejowijefiowejf") vConfig.Set("apns.certs.invalidgame.teamID", "aoijeoijfiowejfoij")