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

Saq*_*Ali 4 go protocol-buffers grpc-go

我正在使用 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)
    })


}
Run Code Online (Sandbox Code Playgroud)

这是EndpointRequestv1.go上面包含的文件中定义对象的方式:

// An v1 interface Endpoint Request object.
message EndpointRequest {
  // data can be a complex object.
  google.protobuf.Struct data = 1;
}
Run Code Online (Sandbox Code Playgroud)

这似乎有效。

但是现在,我想做一些稍微不同的事情。在我的测试用例中data,我想发送一个带有键/值对的地图/字典,而不是发送一个空对象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 
Run Code Online (Sandbox Code Playgroud)

Mar*_*arc 5

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

type Struct struct {
    A string
    C string
}
Run Code Online (Sandbox Code Playgroud)

但是,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
}
Run Code Online (Sandbox Code Playgroud)

显然,那里有点不匹配。您需要初始化Fields结构体的映射并使用正确的方式设置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",
            },
        },
    },
}
Run Code Online (Sandbox Code Playgroud)