Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vorandrew/2b5c578919a5a32fd9785ba5148e4d88 to your computer and use it in GitHub Desktop.
Save vorandrew/2b5c578919a5a32fd9785ba5148e4d88 to your computer and use it in GitHub Desktop.
sample subscriber test
package pubsub
import (
"context"
"testing"
"time"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/pubsub/pstest"
"google.golang.org/api/option"
"google.golang.org/grpc"
)
func TestSubscriber(t *testing.T) {
t.Helper()
// テストケース作成
cases := map[string]struct {
projectID string
topicID string
subID string
msg string
expected bool
}{
"正常": {
projectID: "pstest-sample",
topicID: "sample-topic",
subID: "sample-subscription",
msg: "sample sample",
expected: false,
},
}
for k, c := range cases {
srv := pstest.NewServer()
conn, _ := grpc.Dial(srv.Addr, grpc.WithInsecure())
defer srv.Close()
defer conn.Close()
t.Run(k, func(t *testing.T) {
ctx := context.Background()
s, _ := NewSubscriber(ctx, c.projectID, option.WithGRPCConn(conn))
p, _ := NewPublisher(ctx, c.projectID, option.WithGRPCConn(conn))
// topicを事前に作成
topic, _ := p.client.CreateTopic(ctx, c.topicID)
// subscriptionを事前に作成
s.client.CreateSubscription(ctx, c.subID, pubsub.SubscriptionConfig{
Topic: topic,
})
// publish
p.Publish(ctx, c.topicID, c.msg)
// subscribeテスト
err := s.Receive(ctx, c.subID)
if (err != nil) != c.expected {
t.Errorf("TestSubscriber error. got: %v, expected: %v", err, c.expected)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment