Skip to content

Commit

Permalink
Fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelreiswildlife committed May 2, 2024
1 parent b3a459a commit 313b638
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 58 deletions.
21 changes: 11 additions & 10 deletions cmd/apns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,31 @@ package cmd

import (
"fmt"
"github.com/topfreegames/pusher/config"
"os"

. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"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()
Expand All @@ -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())
Expand All @@ -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())
Expand Down
2 changes: 1 addition & 1 deletion config/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ feedback:
topics: "com.games.test.feedbacks"
brokers: "localhost:9941"
cache:
requestTimeout: 10000
requestTimeout: 1000
cleaningInterval: 20
stats:
reporters:
Expand Down
83 changes: 46 additions & 37 deletions e2e/apns_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -19,67 +20,63 @@ 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"
}
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,
})
Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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,
})
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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 {
Expand Down
11 changes: 6 additions & 5 deletions extensions/apns_message_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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())
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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())
}()
})
})
Expand Down
8 changes: 4 additions & 4 deletions extensions/gcm_message_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion pusher/apns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit 313b638

Please sign in to comment.