Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(functions/metadata): Special-case marshaling #2669

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion functions/metadata/metadata.go
Expand Up @@ -87,7 +87,10 @@ func (r *Resource) MarshalJSON() ([]byte, error) {
}

// Otherwise, accept whatever the result of the normal marshal would be.
b, err := json.Marshal(r)
// Need to define a new type, otherwise it infinitely recurses and panics.
type resource Resource
roffjulie marked this conversation as resolved.
Show resolved Hide resolved
res := *r
b, err := json.Marshal(res)
if err != nil {
return nil, err
}
Expand Down
49 changes: 49 additions & 0 deletions functions/metadata/metadata_test.go
Expand Up @@ -120,3 +120,52 @@ func TestUnmarshalJSON(t *testing.T) {
}
}
}

func TestMarshalJSON(t *testing.T) {
ts, err := time.Parse("2006-01-02T15:04:05Z07:00", "2019-11-04T23:01:10.112Z")
if err != nil {
t.Fatalf("Error parsing time: %v.", err)
}
var tests = []struct {
name string
metadata Metadata
want []byte
}{
{
name: "MetadataWithResource",
metadata: Metadata{
EventID: "1234567",
Timestamp: ts,
EventType: "google.pubsub.topic.publish",
Resource: &Resource{
Service: "pubsub.googleapis.com",
Name: "mytopic",
Type: "type.googleapis.com/google.pubsub.v1.PubsubMessage",
},
},
want: []byte(`{"eventId":"1234567","timestamp":"2019-11-04T23:01:10.112Z","eventType":"google.pubsub.topic.publish","resource":{"service":"pubsub.googleapis.com","name":"mytopic","type":"type.googleapis.com/google.pubsub.v1.PubsubMessage"}}`),
},
{
name: "MetadataWithString",
metadata: Metadata{
EventID: "1234567",
Timestamp: ts,
EventType: "google.pubsub.topic.publish",
Resource: &Resource{
RawPath: "projects/myproject/mytopic",
},
},
want: []byte(`{"eventId":"1234567","timestamp":"2019-11-04T23:01:10.112Z","eventType":"google.pubsub.topic.publish","resource":"projects/myproject/mytopic"}`),
},
}

for _, tc := range tests {
b, err := json.Marshal(&tc.metadata)
roffjulie marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
t.Errorf("MarshalJSON(%s) error: %v", tc.name, err)
}
if !cmp.Equal(b, tc.want) {
t.Errorf("MarshalJSON(%s) error: got %v, want %v", tc.name, string(b), string(tc.want))
}
}
}