如何在GoLang测试用例中发送google.protobuf.Struct数据?

mcdcgff0  于 2023-09-28  发布在  Go
关注(0)|答案(2)|浏览(137)

我正在使用GRPC/proto-buffers在GoLang中编写我的第一个API端点。我对果兰还是个新手。下面是我为我的测试用例编写的文件

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)
    })

}

下面是在上面包含的v1.go文件中定义EndpointRequest对象的方式:

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

这似乎工作。
但是现在,我想做一些稍微不同的事情。在我的测试用例中,我不是发送一个空的data对象,而是发送一个带有键/值对A: "B", C: "D"的map/dictionary。我该怎么做?如果我用Data: &structpb.Struct{A: "B", C: "D"}替换Data: &structpb.Struct{},我会得到编译器错误:

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

gcuhipw91#

初始化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
}

很明显这里有点不匹配。您需要初始化结构体的FieldsMap,并使用正确的方式设置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",
            },
        },
    },
}
zpqajqem

zpqajqem2#

使用structpb.NewStruct将map[string]interface{}转换为structpb.Struct

data := map[string]interface{}{
    "A": "B",
    "C": "D",
}

st, err := structpb.NewStruct(data)
if err != nil {
    // handle err
}

相关问题