登录
首页 >  Golang >  Go问答

整合测试:在同一代码块中发送和接收与云 pubsub 模拟器的数据

来源:stackoverflow

时间:2024-02-08 21:18:22 295浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《整合测试:在同一代码块中发送和接收与云 pubsub 模拟器的数据》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我一直在尝试使用模拟器测试与 cloud pubsub 的交互。它将消息发布到主题,但接收者不会被触发。这是代码解决方法:

func testpubsubemulator(t *testing.t) {
ctx := context.background()
topic, sub, err := createtesttopicandsubscription(ctx, "project-id", "topic-id")
if err != nil {
    t.fatal(err)
}

cctx, cancelfunc := context.withcancel(ctx)
defer cancelfunc()

var messagerecieved int32

sub.receive(cctx, func(ctx context.context, m *pubsub.message) {
    t.log(m.data)
    atomic.addint32(&messagerecieved, 1)
    m.ack()
})

topic.publish(ctx, &pubsub.message{
    data: []byte("hello world"),
})

time.sleep(5 * time.second)

t.log(messagerecieved)
if messagerecieved != 1 {
    t.fatal("message was never sent")
}
}

这也是创建主题和订阅的代码:

func CreateTestTopicAndSubscription(ctx context.Context, projectID, topicID string) 
(*pubsub.Topic, *pubsub.Subscription, error) {
client, err := pubsub.NewClient(ctx, projectID)
if err != nil {
    return nil, nil, fmt.Errorf("pubsub.NewClient: %v", err)
}
defer client.Close()

topic, err := client.CreateTopic(ctx, topicID)
if err != nil {
    return nil, nil, fmt.Errorf("CreateTopic: %v", err)
}

// Create a new subscription to the created topic and ensure it never expires.
sub, err := client.CreateSubscription(ctx, topicID, pubsub.SubscriptionConfig{
    Topic:            topic,
    AckDeadline:      10 * time.Second,
    ExpirationPolicy: time.Duration(0),
})
if err != nil {
    return nil, nil, err
}

  return topic, sub, nil
}

目前正在尝试从其他程序发送消息以查看它是否被触发。


正确答案


很抱歉我没有尽早更新这个问题。我发现问题是由指向订阅的指针引起的。它没有监听消息。 我需要创建一个指向订阅的新指针来侦听更改。

这是概念

// create a new subscription to the created topic and ensure it never expires.
sub, err := client.createsubscription(ctx, topicid, pubsub.subscriptionconfig{
    topic:            topic,
    ackdeadline:      10 * time.second,
    expirationpolicy: time.duration(0),
})
if err != nil {
    return nil, nil, err
}
...
// this subscription won't work for some reason
sub.receive(cctx, func(ctx context.context, m *pubsub.message) {
   t.log(m.data)
   atomic.addint32(&messagerecieved, 1)
   m.ack()
})

相反,应该首先创建它,然后使用新指针进行监听。

client.CreateSubscription(ctx, subId, pubsub.SubscriptionConfig{Topic: topic})

// This subscription would be able to receive messages
sub := client.Subscription(subId)
sub.Receive(cctx, func(ctx context.Context, m *pubsub.Message) {
   t.Log(m.Data)
   atomic.AddInt32(&messageRecieved, 1)
   m.Ack()
})

本篇关于《整合测试:在同一代码块中发送和接收与云 pubsub 模拟器的数据》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>