-
Notifications
You must be signed in to change notification settings - Fork 8
/
testtranscoding.go
89 lines (72 loc) · 2.07 KB
/
testtranscoding.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"namespacelabs.dev/foundation/framework/testing"
"namespacelabs.dev/foundation/internal/testdata/service/proto"
)
func main() {
testing.Do(func(ctx context.Context, t testing.Test) error {
endpoint := t.MustEndpoint("namespacelabs.dev/foundation/std/networking/gateway/server", "grpc-http-transcoder")
if err := t.WaitForEndpoint(ctx, endpoint); err != nil {
return err
}
// Lets check if the grpc service is being transcoded to http.
// internal.testdata.service.proto.PostService is hosted in server/gogrpc.
if err := makeTest(endpoint.Address(), match[*proto.PostResponse]{
ServiceName: "internal.testdata.service.proto.PostService",
MethodName: "Post",
Request: &proto.PostRequest{Input: "xyz"},
Response: &proto.PostResponse{},
Match: func(pr *proto.PostResponse) error {
if pr.Id == "" {
return errors.New("expected id to be set")
}
if pr.Response != "hello there: xyz" {
return fmt.Errorf("unexpected response %q", pr.Response)
}
return nil
},
}); err != nil {
log.Fatal(err)
}
return nil
})
}
type match[V any] struct {
ServiceName string
MethodName string
Request interface{}
Response V
Match func(V) error
}
func makeTest[V any](address string, m match[V]) error {
serialized, err := json.Marshal(m.Request)
if err != nil {
return err
}
response, err := http.Post(fmt.Sprintf("http://%s/%s/%s", address, m.ServiceName, m.MethodName), "application/json", bytes.NewReader(serialized))
if err != nil {
return err
}
if response.StatusCode != 200 {
return fmt.Errorf("unexpected status code: %s", response.Status)
}
x, err := io.ReadAll(response.Body)
if err != nil {
return err
}
if err := json.Unmarshal(x, m.Response); err != nil {
return err
}
return m.Match(m.Response)
}