簡體   English   中英

如何在 GoLang 測試用例中發送 google.protobuf.Struct 數據?

[英]How to send google.protobuf.Struct data in a GoLang test case?

我正在使用 GRPC/proto-buffers 在 GoLang 中編寫我的第一個 API 端點。 我對 GoLang 比較陌生。 以下是我為測試用例編寫的文件

package my_package

import (
    "context"
    "testing"

    "github.com/stretchr/testify/require"

    "google.golang.org/protobuf/types/known/structpb"
    "github.com/MyTeam/myproject/cmd/eventstream/setup"
    v1handler "github.com/MyTeam/myproject/internal/handlers/myproject/v1"
    v1interface "github.com/MyTeam/myproject/proto/.gen/go/myteam/myproject/v1"
)

func TestEndpoint(t *testing.T) {
    conf := &setup.Config{}

    // Initialize our API handlers
    myhandler := v1handler.New(&v1handler.Config{})

    t.Run("Success", func(t *testing.T) {

        res, err := myhandler.Endpoint(context.Background(), &v1interface.EndpointRequest{
            Data: &structpb.Struct{},
        })
        require.Nil(t, err)

        // Assert we got what we want.
        require.Equal(t, "Ok", res.Text)
    })


}

這是EndpointRequest object 在上面包含的v1.go文件中定義的方式:

// An v1 interface Endpoint Request object.
message EndpointRequest {
  // data can be a complex object.
  google.protobuf.Struct data = 1;
}

這似乎有效。

但現在,我想做一些稍微不同的事情。 在我的測試用例中,我不想發送空data object,而是發送帶有鍵/值對A: "B", C: "D"的地圖/字典。 我該怎么做? 如果我將Data: &structpb.Struct{}替換為Data: &structpb.Struct{A: "B", C: "D"} ,我會收到編譯器錯誤:

invalid field name "A" in struct initializer
invalid field name "C" in struct initializer 

您初始化Data的方式意味着您期待以下內容:

type Struct struct {
    A string
    C string
}

但是, structpb.Struct定義如下:

type Struct struct {   
    // Unordered map of dynamically typed values.
    Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields,proto3" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
    // contains filtered or unexported fields
}

顯然那里有點不匹配。 您需要初始化結構的Fields map,並使用正確的方式設置Value字段。 與您顯示的代碼等效的是:

Data: &structpb.Struct{
    Fields: map[string]*structpb.Value{
        "A": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "B",
            },
        },
        "C": &structpb.Value{
            Kind: &structpb.Value_StringValue{
                StringValue: "D",
            },
        },
    },
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM