9 Commits

Author SHA1 Message Date
Josh Humphries
06a970022e darwin/386... 🤦 2021-01-05 12:42:15 -05:00
Josh Humphries
db90ec1160 go 1.15 no longer supports darwin/386; ignore any IDE config folder 2021-01-05 12:39:34 -05:00
Mikhail Katychev
9da71fbe53 when -format-error option is used, format service reflection errors, too (#188) 2020-09-30 13:24:46 -04:00
Guilherme Salazar
9846afccbc feat: add support for user-agent header (#182) 2020-09-04 11:31:28 -04:00
Joshua Humphries
ba5f667e13 fix latest CI breakages by forking code from grpc-go's interop/testing
Also moves testing package to internal/testing
2020-08-31 14:44:59 -04:00
Joshua Humphries
54ffdcacda fix typo 2020-08-24 13:58:09 -04:00
Joshua Humphries
ceef817807 make use of -plaintext flag more clear in examples 2020-08-24 13:56:57 -04:00
Sergei Vorobev
e544b9e66f Print size of the message in very verbose mode (#181)
Adds -vv flag for "very verbose".
Includes estimated message size when enabled. The size is an estimate because it is the canonical size for the proto message, but not necessarily its actual on-the-wire size.
2020-08-14 11:02:42 -04:00
Joshua Humphries
41a6ac0479 no more support for go 1.11 without modules (#180) 2020-07-31 12:26:31 -04:00
56 changed files with 1369 additions and 163 deletions

1
.gitignore vendored
View File

@@ -1,2 +1,3 @@
dist/ dist/
.idea/
VERSION VERSION

View File

@@ -8,6 +8,9 @@ builds:
goarch: goarch:
- amd64 - amd64
- 386 - 386
ignore:
- goos: darwin
goarch: 386
ldflags: ldflags:
- -s -w -X main.version=v{{.Version}} - -s -w -X main.version=v{{.Version}}

View File

@@ -3,8 +3,6 @@ sudo: false
matrix: matrix:
include: include:
- go: 1.11.x
env: GO111MODULE=off
- go: 1.11.x - go: 1.11.x
env: GO111MODULE=on env: GO111MODULE=on
- go: 1.12.x - go: 1.12.x

View File

@@ -35,9 +35,9 @@ See also the [`grpcurl` talk at GopherCon 2018](https://www.youtube.com/watch?v=
operate bi-directional streaming methods interactively by running `grpcurl` from an operate bi-directional streaming methods interactively by running `grpcurl` from an
interactive terminal and using stdin as the request body! interactive terminal and using stdin as the request body!
`grpcurl` supports both plain-text and TLS servers and has numerous options for TLS `grpcurl` supports both secure/TLS servers _and_ plain-text servers (i.e. no TLS) and has
configuration. It also supports mutual TLS, where the client is required to present a numerous options for TLS configuration. It also supports mutual TLS, where the client is
client certificate. required to present a client certificate.
As mentioned above, `grpcurl` works seamlessly if the server supports the reflection As mentioned above, `grpcurl` works seamlessly if the server supports the reflection
service. If not, you can supply the `.proto` source files or you can supply protoset service. If not, you can supply the `.proto` source files or you can supply protoset
@@ -91,6 +91,9 @@ that requires no client certs and supports server reflection is the simplest thi
do with `grpcurl`. This minimal invocation sends an empty request body: do with `grpcurl`. This minimal invocation sends an empty request body:
```shell ```shell
grpcurl grpc.server.com:443 my.custom.server.Service/Method grpcurl grpc.server.com:443 my.custom.server.Service/Method
# no TLS
grpcurl -plaintext grpc.server.com:80 my.custom.server.Service/Method
``` ```
To send a non-empty request, use the `-d` argument. Note that all arguments must come To send a non-empty request, use the `-d` argument. Note that all arguments must come

View File

@@ -37,7 +37,9 @@ import (
// the response status codes emitted use an offest of 64 // the response status codes emitted use an offest of 64
const statusCodeOffset = 64 const statusCodeOffset = 64
var version = "dev build <no version set>" const no_version = "dev build <no version set>"
var version = no_version
var ( var (
exit = os.Exit exit = os.Exit
@@ -85,6 +87,10 @@ var (
is used, this will also be used as the server name when verifying the is used, this will also be used as the server name when verifying the
server's certificate. It defaults to the address that is provided in the server's certificate. It defaults to the address that is provided in the
positional arguments.`)) positional arguments.`))
userAgent = flags.String("user-agent", "", prettify(`
If set, the specified value will be added to the User-Agent header set
by the grpc-go library.
`))
data = flags.String("d", "", prettify(` data = flags.String("d", "", prettify(`
Data for request contents. If the value is '@' then the request contents Data for request contents. If the value is '@' then the request contents
are read from stdin. For calls that accept a stream of requests, the are read from stdin. For calls that accept a stream of requests, the
@@ -135,6 +141,8 @@ var (
When describing messages, show a template of input data.`)) When describing messages, show a template of input data.`))
verbose = flags.Bool("v", false, prettify(` verbose = flags.Bool("v", false, prettify(`
Enable verbose output.`)) Enable verbose output.`))
veryVerbose = flags.Bool("vv", false, prettify(`
Enable very verbose output.`))
serverName = flags.String("servername", "", prettify(` serverName = flags.String("servername", "", prettify(`
Override server name when validating TLS certificate. This flag is Override server name when validating TLS certificate. This flag is
ignored if -plaintext or -insecure is used. ignored if -plaintext or -insecure is used.
@@ -316,6 +324,14 @@ func main() {
invoke = true invoke = true
} }
verbosityLevel := 0
if *verbose {
verbosityLevel = 1
}
if *veryVerbose {
verbosityLevel = 2
}
var symbol string var symbol string
if invoke { if invoke {
if len(args) == 0 { if len(args) == 0 {
@@ -416,6 +432,16 @@ func main() {
} else if *authority != "" { } else if *authority != "" {
opts = append(opts, grpc.WithAuthority(*authority)) opts = append(opts, grpc.WithAuthority(*authority))
} }
grpcurlUA := "grpcurl/" + version
if version == no_version {
grpcurlUA = "grpcurl/dev-build (no version set)"
}
if *userAgent != "" {
grpcurlUA = *userAgent + " " + grpcurlUA
}
opts = append(opts, grpc.WithUserAgent(grpcurlUA))
network := "tcp" network := "tcp"
if isUnixSocket != nil && isUnixSocket() { if isUnixSocket != nil && isUnixSocket() {
network = "unix" network = "unix"
@@ -651,7 +677,7 @@ func main() {
// if not verbose output, then also include record delimiters // if not verbose output, then also include record delimiters
// between each message, so output could potentially be piped // between each message, so output could potentially be piped
// to another grpcurl process // to another grpcurl process
includeSeparators := !*verbose includeSeparators := verbosityLevel == 0
options := grpcurl.FormatOptions{ options := grpcurl.FormatOptions{
EmitJSONDefaultFields: *emitDefaults, EmitJSONDefaultFields: *emitDefaults,
IncludeTextSeparator: includeSeparators, IncludeTextSeparator: includeSeparators,
@@ -661,11 +687,19 @@ func main() {
if err != nil { if err != nil {
fail(err, "Failed to construct request parser and formatter for %q", *format) fail(err, "Failed to construct request parser and formatter for %q", *format)
} }
h := grpcurl.NewDefaultEventHandler(os.Stdout, descSource, formatter, *verbose) h := &grpcurl.DefaultEventHandler{
Out: os.Stdout,
Formatter: formatter,
VerbosityLevel: verbosityLevel,
}
err = grpcurl.InvokeRPC(ctx, descSource, cc, symbol, append(addlHeaders, rpcHeaders...), h, rf.Next) err = grpcurl.InvokeRPC(ctx, descSource, cc, symbol, append(addlHeaders, rpcHeaders...), h, rf.Next)
if err != nil { if err != nil {
fail(err, "Error invoking method %q", symbol) if errStatus, ok := status.FromError(err); ok && *formatError {
h.Status = errStatus
} else {
fail(err, "Error invoking method %q", symbol)
}
} }
reqSuffix := "" reqSuffix := ""
respSuffix := "" respSuffix := ""
@@ -676,7 +710,7 @@ func main() {
if h.NumResponses != 1 { if h.NumResponses != 1 {
respSuffix = "s" respSuffix = "s"
} }
if *verbose { if verbosityLevel > 0 {
fmt.Printf("Sent %d request%s and received %d response%s\n", reqCount, reqSuffix, h.NumResponses, respSuffix) fmt.Printf("Sent %d request%s and received %d response%s\n", reqCount, reqSuffix, h.NumResponses, respSuffix)
} }
if h.Status.Code() != codes.OK { if h.Status.Code() != codes.OK {

View File

@@ -10,11 +10,11 @@ import (
) )
func TestWriteProtoset(t *testing.T) { func TestWriteProtoset(t *testing.T) {
exampleProtoset, err := loadProtoset("./testing/example.protoset") exampleProtoset, err := loadProtoset("./internal/testing/example.protoset")
if err != nil { if err != nil {
t.Fatalf("failed to load example.protoset: %v", err) t.Fatalf("failed to load example.protoset: %v", err)
} }
testProtoset, err := loadProtoset("./testing/test.protoset") testProtoset, err := loadProtoset("./internal/testing/test.protoset")
if err != nil { if err != nil {
t.Fatalf("failed to load test.protoset: %v", err) t.Fatalf("failed to load test.protoset: %v", err)
} }
@@ -29,8 +29,8 @@ func TestWriteProtoset(t *testing.T) {
} }
checkWriteProtoset(t, descSrc, exampleProtoset, "TestService") checkWriteProtoset(t, descSrc, exampleProtoset, "TestService")
checkWriteProtoset(t, descSrc, testProtoset, "grpc.testing.TestService") checkWriteProtoset(t, descSrc, testProtoset, "testing.TestService")
checkWriteProtoset(t, descSrc, mergedProtoset, "TestService", "grpc.testing.TestService") checkWriteProtoset(t, descSrc, mergedProtoset, "TestService", "testing.TestService")
} }
func loadProtoset(path string) (*descriptor.FileDescriptorSet, error) { func loadProtoset(path string) (*descriptor.FileDescriptorSet, error) {

View File

@@ -409,10 +409,12 @@ func RequestParserAndFormatterFor(format Format, descSource DescriptorSource, em
// safe for use with InvokeRPC as long as NumResponses and Status are not read // safe for use with InvokeRPC as long as NumResponses and Status are not read
// until the call to InvokeRPC completes. // until the call to InvokeRPC completes.
type DefaultEventHandler struct { type DefaultEventHandler struct {
out io.Writer Out io.Writer
descSource DescriptorSource Formatter Formatter
formatter func(proto.Message) (string, error) // 0 = default
verbose bool // 1 = verbose
// 2 = very verbose
VerbosityLevel int
// NumResponses is the number of responses that have been received. // NumResponses is the number of responses that have been received.
NumResponses int NumResponses int
@@ -424,54 +426,65 @@ type DefaultEventHandler struct {
// NewDefaultEventHandler returns an InvocationEventHandler that logs events to // NewDefaultEventHandler returns an InvocationEventHandler that logs events to
// the given output. If verbose is true, all events are logged. Otherwise, only // the given output. If verbose is true, all events are logged. Otherwise, only
// response messages are logged. // response messages are logged.
//
// Deprecated: NewDefaultEventHandler exists for compatability.
// It doesn't allow fine control over the `VerbosityLevel`
// and provides only 0 and 1 options (which corresponds to the `verbose` argument).
// Use DefaultEventHandler{} initializer directly.
func NewDefaultEventHandler(out io.Writer, descSource DescriptorSource, formatter Formatter, verbose bool) *DefaultEventHandler { func NewDefaultEventHandler(out io.Writer, descSource DescriptorSource, formatter Formatter, verbose bool) *DefaultEventHandler {
verbosityLevel := 0
if verbose {
verbosityLevel = 1
}
return &DefaultEventHandler{ return &DefaultEventHandler{
out: out, Out: out,
descSource: descSource, Formatter: formatter,
formatter: formatter, VerbosityLevel: verbosityLevel,
verbose: verbose,
} }
} }
var _ InvocationEventHandler = (*DefaultEventHandler)(nil) var _ InvocationEventHandler = (*DefaultEventHandler)(nil)
func (h *DefaultEventHandler) OnResolveMethod(md *desc.MethodDescriptor) { func (h *DefaultEventHandler) OnResolveMethod(md *desc.MethodDescriptor) {
if h.verbose { if h.VerbosityLevel > 0 {
txt, err := GetDescriptorText(md, h.descSource) txt, err := GetDescriptorText(md, nil)
if err == nil { if err == nil {
fmt.Fprintf(h.out, "\nResolved method descriptor:\n%s\n", txt) fmt.Fprintf(h.Out, "\nResolved method descriptor:\n%s\n", txt)
} }
} }
} }
func (h *DefaultEventHandler) OnSendHeaders(md metadata.MD) { func (h *DefaultEventHandler) OnSendHeaders(md metadata.MD) {
if h.verbose { if h.VerbosityLevel > 0 {
fmt.Fprintf(h.out, "\nRequest metadata to send:\n%s\n", MetadataToString(md)) fmt.Fprintf(h.Out, "\nRequest metadata to send:\n%s\n", MetadataToString(md))
} }
} }
func (h *DefaultEventHandler) OnReceiveHeaders(md metadata.MD) { func (h *DefaultEventHandler) OnReceiveHeaders(md metadata.MD) {
if h.verbose { if h.VerbosityLevel > 0 {
fmt.Fprintf(h.out, "\nResponse headers received:\n%s\n", MetadataToString(md)) fmt.Fprintf(h.Out, "\nResponse headers received:\n%s\n", MetadataToString(md))
} }
} }
func (h *DefaultEventHandler) OnReceiveResponse(resp proto.Message) { func (h *DefaultEventHandler) OnReceiveResponse(resp proto.Message) {
h.NumResponses++ h.NumResponses++
if h.verbose { if h.VerbosityLevel > 1 {
fmt.Fprint(h.out, "\nResponse contents:\n") fmt.Fprintf(h.Out, "\nEstimated response size: %d bytes\n", proto.Size(resp))
} }
if respStr, err := h.formatter(resp); err != nil { if h.VerbosityLevel > 0 {
fmt.Fprintf(h.out, "Failed to format response message %d: %v\n", h.NumResponses, err) fmt.Fprint(h.Out, "\nResponse contents:\n")
}
if respStr, err := h.Formatter(resp); err != nil {
fmt.Fprintf(h.Out, "Failed to format response message %d: %v\n", h.NumResponses, err)
} else { } else {
fmt.Fprintln(h.out, respStr) fmt.Fprintln(h.Out, respStr)
} }
} }
func (h *DefaultEventHandler) OnReceiveTrailers(stat *status.Status, md metadata.MD) { func (h *DefaultEventHandler) OnReceiveTrailers(stat *status.Status, md metadata.MD) {
h.Status = stat h.Status = stat
if h.verbose { if h.VerbosityLevel > 0 {
fmt.Fprintf(h.out, "\nResponse trailers received:\n%s\n", MetadataToString(md)) fmt.Fprintf(h.Out, "\nResponse trailers received:\n%s\n", MetadataToString(md))
} }
} }

View File

@@ -15,7 +15,7 @@ import (
) )
func TestRequestParser(t *testing.T) { func TestRequestParser(t *testing.T) {
source, err := DescriptorSourceFromProtoSets("testing/example.protoset") source, err := DescriptorSourceFromProtoSets("internal/testing/example.protoset")
if err != nil { if err != nil {
t.Fatalf("failed to create descriptor source: %v", err) t.Fatalf("failed to create descriptor source: %v", err)
} }
@@ -97,7 +97,7 @@ func TestRequestParser(t *testing.T) {
// Handler prints response data (and headers/trailers in verbose mode). // Handler prints response data (and headers/trailers in verbose mode).
// This verifies that we get the right output in both JSON and proto text modes. // This verifies that we get the right output in both JSON and proto text modes.
func TestHandler(t *testing.T) { func TestHandler(t *testing.T) {
source, err := DescriptorSourceFromProtoSets("testing/example.protoset") source, err := DescriptorSourceFromProtoSets("internal/testing/example.protoset")
if err != nil { if err != nil {
t.Fatalf("failed to create descriptor source: %v", err) t.Fatalf("failed to create descriptor source: %v", err)
} }
@@ -120,12 +120,14 @@ func TestHandler(t *testing.T) {
for _, format := range []Format{FormatJSON, FormatText} { for _, format := range []Format{FormatJSON, FormatText} {
for _, numMessages := range []int{1, 3} { for _, numMessages := range []int{1, 3} {
for _, verbose := range []bool{true, false} { for verbosityLevel := 0; verbosityLevel <= 2; verbosityLevel++ {
name := fmt.Sprintf("%s, %d message(s)", format, numMessages) name := fmt.Sprintf("%s, %d message(s)", format, numMessages)
if verbose { if verbosityLevel > 0 {
name += ", verbose" name += fmt.Sprintf(", verbosityLevel=%d", verbosityLevel)
} }
verbose := verbosityLevel > 0
_, formatter, err := RequestParserAndFormatter(format, source, nil, FormatOptions{IncludeTextSeparator: !verbose}) _, formatter, err := RequestParserAndFormatter(format, source, nil, FormatOptions{IncludeTextSeparator: !verbose})
if err != nil { if err != nil {
t.Errorf("Failed to create parser and formatter: %v", err) t.Errorf("Failed to create parser and formatter: %v", err)
@@ -133,7 +135,11 @@ func TestHandler(t *testing.T) {
} }
var buf bytes.Buffer var buf bytes.Buffer
h := NewDefaultEventHandler(&buf, source, formatter, verbose) h := &DefaultEventHandler{
Out: &buf,
Formatter: formatter,
VerbosityLevel: verbosityLevel,
}
h.OnResolveMethod(md) h.OnResolveMethod(md)
h.OnSendHeaders(reqHeaders) h.OnSendHeaders(reqHeaders)
@@ -148,6 +154,9 @@ func TestHandler(t *testing.T) {
expectedOutput += verbosePrefix expectedOutput += verbosePrefix
} }
for i := 0; i < numMessages; i++ { for i := 0; i < numMessages; i++ {
if verbosityLevel > 1 {
expectedOutput += verboseResponseSize
}
if verbose { if verbose {
expectedOutput += verboseResponseHeader expectedOutput += verboseResponseHeader
} }
@@ -226,6 +235,9 @@ Response trailers received:
a: 1 a: 1
b: 2 b: 2
c: 3 c: 3
`
verboseResponseSize = `
Estimated response size: 100 bytes
` `
verboseResponseHeader = ` verboseResponseHeader = `
Response contents: Response contents:

2
go.sum
View File

@@ -365,6 +365,7 @@ golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHl
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs=
golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b h1:Wh+f8QHJXR411sJR8/vRBTZ7YapZaRvUcLFFJhusH0k=
golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
@@ -444,6 +445,7 @@ golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200331124033-c3d80250170d h1:nc5K6ox/4lTFbMVSL9WRR81ixkcwXThoiF6yf+R9scA=
golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=

View File

@@ -18,15 +18,14 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/interop/grpc_testing"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection" "google.golang.org/grpc/reflection"
reflectpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha" reflectpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
. "github.com/fullstorydev/grpcurl" . "github.com/fullstorydev/grpcurl"
grpcurl_testing "github.com/fullstorydev/grpcurl/testing" grpcurl_testing "github.com/fullstorydev/grpcurl/internal/testing"
jsonpbtest "github.com/fullstorydev/grpcurl/testing/jsonpb_test_proto" jsonpbtest "github.com/fullstorydev/grpcurl/internal/testing/jsonpb_test_proto"
) )
var ( var (
@@ -52,18 +51,18 @@ type descSourceCase struct {
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
var err error var err error
sourceProtoset, err = DescriptorSourceFromProtoSets("testing/test.protoset") sourceProtoset, err = DescriptorSourceFromProtoSets("internal/testing/test.protoset")
if err != nil { if err != nil {
panic(err) panic(err)
} }
sourceProtoFiles, err = DescriptorSourceFromProtoFiles(nil, "testing/test.proto") sourceProtoFiles, err = DescriptorSourceFromProtoFiles([]string{"internal/testing"}, "test.proto")
if err != nil { if err != nil {
panic(err) panic(err)
} }
// Create a server that includes the reflection service // Create a server that includes the reflection service
svrReflect := grpc.NewServer() svrReflect := grpc.NewServer()
grpc_testing.RegisterTestServiceServer(svrReflect, grpcurl_testing.TestServer{}) grpcurl_testing.RegisterTestServiceServer(svrReflect, grpcurl_testing.TestServer{})
reflection.Register(svrReflect) reflection.Register(svrReflect)
var portReflect int var portReflect int
if l, err := net.Listen("tcp", "127.0.0.1:0"); err != nil { if l, err := net.Listen("tcp", "127.0.0.1:0"); err != nil {
@@ -89,7 +88,7 @@ func TestMain(m *testing.M) {
// Also create a server that does *not* include the reflection service // Also create a server that does *not* include the reflection service
svrProtoset := grpc.NewServer() svrProtoset := grpc.NewServer()
grpc_testing.RegisterTestServiceServer(svrProtoset, grpcurl_testing.TestServer{}) grpcurl_testing.RegisterTestServiceServer(svrProtoset, grpcurl_testing.TestServer{})
var portProtoset int var portProtoset int
if l, err := net.Listen("tcp", "127.0.0.1:0"); err != nil { if l, err := net.Listen("tcp", "127.0.0.1:0"); err != nil {
panic(err) panic(err)
@@ -141,7 +140,7 @@ func TestServerDoesNotSupportReflection(t *testing.T) {
} }
func TestProtosetWithImports(t *testing.T) { func TestProtosetWithImports(t *testing.T) {
sourceProtoset, err := DescriptorSourceFromProtoSets("testing/example.protoset") sourceProtoset, err := DescriptorSourceFromProtoSets("internal/testing/example.protoset")
if err != nil { if err != nil {
t.Fatalf("failed to load protoset: %v", err) t.Fatalf("failed to load protoset: %v", err)
} }
@@ -178,11 +177,11 @@ func doTestListServices(t *testing.T, source DescriptorSource, includeReflection
var expected []string var expected []string
if includeReflection { if includeReflection {
// when using server reflection, we see the TestService as well as the ServerReflection service // when using server reflection, we see the TestService as well as the ServerReflection service
expected = []string{"grpc.reflection.v1alpha.ServerReflection", "grpc.testing.TestService"} expected = []string{"grpc.reflection.v1alpha.ServerReflection", "testing.TestService"}
} else { } else {
// without reflection, we see all services defined in the same test.proto file, which is the // without reflection, we see all services defined in the same test.proto file, which is the
// TestService as well as UnimplementedService // TestService as well as UnimplementedService
expected = []string{"grpc.testing.TestService", "grpc.testing.UnimplementedService"} expected = []string{"testing.TestService", "testing.UnimplementedService"}
} }
if !reflect.DeepEqual(expected, names) { if !reflect.DeepEqual(expected, names) {
t.Errorf("ListServices returned wrong results: wanted %v, got %v", expected, names) t.Errorf("ListServices returned wrong results: wanted %v, got %v", expected, names)
@@ -198,17 +197,17 @@ func TestListMethods(t *testing.T) {
} }
func doTestListMethods(t *testing.T, source DescriptorSource, includeReflection bool) { func doTestListMethods(t *testing.T, source DescriptorSource, includeReflection bool) {
names, err := ListMethods(source, "grpc.testing.TestService") names, err := ListMethods(source, "testing.TestService")
if err != nil { if err != nil {
t.Fatalf("failed to list methods for TestService: %v", err) t.Fatalf("failed to list methods for TestService: %v", err)
} }
expected := []string{ expected := []string{
"grpc.testing.TestService.EmptyCall", "testing.TestService.EmptyCall",
"grpc.testing.TestService.FullDuplexCall", "testing.TestService.FullDuplexCall",
"grpc.testing.TestService.HalfDuplexCall", "testing.TestService.HalfDuplexCall",
"grpc.testing.TestService.StreamingInputCall", "testing.TestService.StreamingInputCall",
"grpc.testing.TestService.StreamingOutputCall", "testing.TestService.StreamingOutputCall",
"grpc.testing.TestService.UnaryCall", "testing.TestService.UnaryCall",
} }
if !reflect.DeepEqual(expected, names) { if !reflect.DeepEqual(expected, names) {
t.Errorf("ListMethods returned wrong results: wanted %v, got %v", expected, names) t.Errorf("ListMethods returned wrong results: wanted %v, got %v", expected, names)
@@ -224,11 +223,11 @@ func doTestListMethods(t *testing.T, source DescriptorSource, includeReflection
} else { } else {
// without reflection, we see all services defined in the same test.proto file, which is the // without reflection, we see all services defined in the same test.proto file, which is the
// TestService as well as UnimplementedService // TestService as well as UnimplementedService
names, err = ListMethods(source, "grpc.testing.UnimplementedService") names, err = ListMethods(source, "testing.UnimplementedService")
if err != nil { if err != nil {
t.Fatalf("failed to list methods for ServerReflection: %v", err) t.Fatalf("failed to list methods for ServerReflection: %v", err)
} }
expected = []string{"grpc.testing.UnimplementedService.UnimplementedCall"} expected = []string{"testing.UnimplementedService.UnimplementedCall"}
} }
if !reflect.DeepEqual(expected, names) { if !reflect.DeepEqual(expected, names) {
t.Errorf("ListMethods returned wrong results: wanted %v, got %v", expected, names) t.Errorf("ListMethods returned wrong results: wanted %v, got %v", expected, names)
@@ -242,13 +241,13 @@ func doTestListMethods(t *testing.T, source DescriptorSource, includeReflection
} }
func TestGetAllFiles(t *testing.T) { func TestGetAllFiles(t *testing.T) {
expectedFiles := []string{"testing/test.proto"} expectedFiles := []string{"test.proto"}
// server reflection picks up filename from linked in Go package, // server reflection picks up filename from linked in Go package,
// which indicates "grpc_testing/test.proto", not our local copy. // which indicates "grpc_testing/test.proto", not our local copy.
expectedFilesWithReflection := [][]string{ expectedFilesWithReflection := [][]string{
{"grpc_reflection_v1alpha/reflection.proto", "grpc_testing/test.proto"}, {"grpc_reflection_v1alpha/reflection.proto", "test.proto"},
// depending on the version of grpc, the filenames could be prefixed with "interop/" and "reflection/" // depending on the version of grpc, the filenames could be prefixed with "interop/" and "reflection/"
{"interop/grpc_testing/test.proto", "reflection/grpc_reflection_v1alpha/reflection.proto"}, {"reflection/grpc_reflection_v1alpha/reflection.proto", "test.proto"},
} }
for _, ds := range descSources { for _, ds := range descSources {
@@ -279,11 +278,11 @@ func TestGetAllFiles(t *testing.T) {
} }
// try cases with more complicated set of files // try cases with more complicated set of files
otherSourceProtoset, err := DescriptorSourceFromProtoSets("testing/test.protoset", "testing/example.protoset") otherSourceProtoset, err := DescriptorSourceFromProtoSets("internal/testing/test.protoset", "internal/testing/example.protoset")
if err != nil { if err != nil {
t.Fatal(err.Error()) t.Fatal(err.Error())
} }
otherSourceProtoFiles, err := DescriptorSourceFromProtoFiles(nil, "testing/test.proto", "testing/example.proto") otherSourceProtoFiles, err := DescriptorSourceFromProtoFiles([]string{"internal/testing"}, "test.proto", "example.proto")
if err != nil { if err != nil {
t.Fatal(err.Error()) t.Fatal(err.Error())
} }
@@ -292,13 +291,13 @@ func TestGetAllFiles(t *testing.T) {
{"proto[b]", otherSourceProtoFiles, false}, {"proto[b]", otherSourceProtoFiles, false},
} }
expectedFiles = []string{ expectedFiles = []string{
"example.proto",
"example2.proto",
"google/protobuf/any.proto", "google/protobuf/any.proto",
"google/protobuf/descriptor.proto", "google/protobuf/descriptor.proto",
"google/protobuf/empty.proto", "google/protobuf/empty.proto",
"google/protobuf/timestamp.proto", "google/protobuf/timestamp.proto",
"testing/example.proto", "test.proto",
"testing/example2.proto",
"testing/test.proto",
} }
for _, ds := range otherDescSources { for _, ds := range otherDescSources {
t.Run(ds.name, func(t *testing.T) { t.Run(ds.name, func(t *testing.T) {
@@ -403,7 +402,7 @@ func TestDescribe(t *testing.T) {
} }
func doTestDescribe(t *testing.T, source DescriptorSource) { func doTestDescribe(t *testing.T, source DescriptorSource) {
sym := "grpc.testing.TestService.EmptyCall" sym := "testing.TestService.EmptyCall"
dsc, err := source.FindSymbol(sym) dsc, err := source.FindSymbol(sym)
if err != nil { if err != nil {
t.Fatalf("failed to get descriptor for %q: %v", sym, err) t.Fatalf("failed to get descriptor for %q: %v", sym, err)
@@ -414,14 +413,14 @@ func doTestDescribe(t *testing.T, source DescriptorSource) {
txt := proto.MarshalTextString(dsc.AsProto()) txt := proto.MarshalTextString(dsc.AsProto())
expected := expected :=
`name: "EmptyCall" `name: "EmptyCall"
input_type: ".grpc.testing.Empty" input_type: ".testing.Empty"
output_type: ".grpc.testing.Empty" output_type: ".testing.Empty"
` `
if expected != txt { if expected != txt {
t.Errorf("descriptor mismatch: expected %s, got %s", expected, txt) t.Errorf("descriptor mismatch: expected %s, got %s", expected, txt)
} }
sym = "grpc.testing.StreamingOutputCallResponse" sym = "testing.StreamingOutputCallResponse"
dsc, err = source.FindSymbol(sym) dsc, err = source.FindSymbol(sym)
if err != nil { if err != nil {
t.Fatalf("failed to get descriptor for %q: %v", sym, err) t.Fatalf("failed to get descriptor for %q: %v", sym, err)
@@ -437,7 +436,7 @@ field: <
number: 1 number: 1
label: LABEL_OPTIONAL label: LABEL_OPTIONAL
type: TYPE_MESSAGE type: TYPE_MESSAGE
type_name: ".grpc.testing.Payload" type_name: ".testing.Payload"
json_name: "payload" json_name: "payload"
> >
` `
@@ -493,12 +492,12 @@ func TestUnary(t *testing.T) {
func doTestUnary(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) { func doTestUnary(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) {
// Success // Success
h := &handler{reqMessages: []string{payload1}} h := &handler{reqMessages: []string{payload1}}
err := InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/UnaryCall", makeHeaders(codes.OK), h, h.getRequestData) err := InvokeRpc(context.Background(), source, cc, "testing.TestService/UnaryCall", makeHeaders(codes.OK), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
if h.check(t, "grpc.testing.TestService.UnaryCall", codes.OK, 1, 1) { if h.check(t, "testing.TestService.UnaryCall", codes.OK, 1, 1) {
if h.respMessages[0] != payload1 { if h.respMessages[0] != payload1 {
t.Errorf("unexpected response from RPC: expecting %s; got %s", payload1, h.respMessages[0]) t.Errorf("unexpected response from RPC: expecting %s; got %s", payload1, h.respMessages[0])
} }
@@ -506,12 +505,12 @@ func doTestUnary(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) {
// Failure // Failure
h = &handler{reqMessages: []string{payload1}} h = &handler{reqMessages: []string{payload1}}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/UnaryCall", makeHeaders(codes.NotFound), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/UnaryCall", makeHeaders(codes.NotFound), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.UnaryCall", codes.NotFound, 1, 0) h.check(t, "testing.TestService.UnaryCall", codes.NotFound, 1, 0)
} }
func TestClientStream(t *testing.T) { func TestClientStream(t *testing.T) {
@@ -525,12 +524,12 @@ func TestClientStream(t *testing.T) {
func doTestClientStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) { func doTestClientStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) {
// Success // Success
h := &handler{reqMessages: []string{payload1, payload2, payload3}} h := &handler{reqMessages: []string{payload1, payload2, payload3}}
err := InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/StreamingInputCall", makeHeaders(codes.OK), h, h.getRequestData) err := InvokeRpc(context.Background(), source, cc, "testing.TestService/StreamingInputCall", makeHeaders(codes.OK), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
if h.check(t, "grpc.testing.TestService.StreamingInputCall", codes.OK, 3, 1) { if h.check(t, "testing.TestService.StreamingInputCall", codes.OK, 3, 1) {
expected := expected :=
`{ `{
"aggregatedPayloadSize": 61 "aggregatedPayloadSize": 61
@@ -542,21 +541,21 @@ func doTestClientStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSour
// Fail fast (server rejects as soon as possible) // Fail fast (server rejects as soon as possible)
h = &handler{reqMessages: []string{payload1, payload2, payload3}} h = &handler{reqMessages: []string{payload1, payload2, payload3}}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/StreamingInputCall", makeHeaders(codes.InvalidArgument), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/StreamingInputCall", makeHeaders(codes.InvalidArgument), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.StreamingInputCall", codes.InvalidArgument, -3, 0) h.check(t, "testing.TestService.StreamingInputCall", codes.InvalidArgument, -3, 0)
// Fail late (server waits until stream is complete to reject) // Fail late (server waits until stream is complete to reject)
h = &handler{reqMessages: []string{payload1, payload2, payload3}} h = &handler{reqMessages: []string{payload1, payload2, payload3}}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/StreamingInputCall", makeHeaders(codes.Internal, true), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/StreamingInputCall", makeHeaders(codes.Internal, true), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.StreamingInputCall", codes.Internal, 3, 0) h.check(t, "testing.TestService.StreamingInputCall", codes.Internal, 3, 0)
} }
func TestServerStream(t *testing.T) { func TestServerStream(t *testing.T) {
@@ -568,9 +567,9 @@ func TestServerStream(t *testing.T) {
} }
func doTestServerStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) { func doTestServerStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) {
req := &grpc_testing.StreamingOutputCallRequest{ req := &grpcurl_testing.StreamingOutputCallRequest{
ResponseType: grpc_testing.PayloadType_COMPRESSABLE, ResponseType: grpcurl_testing.PayloadType_COMPRESSABLE,
ResponseParameters: []*grpc_testing.ResponseParameters{ ResponseParameters: []*grpcurl_testing.ResponseParameters{
{Size: 10}, {Size: 20}, {Size: 30}, {Size: 40}, {Size: 50}, {Size: 10}, {Size: 20}, {Size: 30}, {Size: 40}, {Size: 50},
}, },
} }
@@ -581,19 +580,19 @@ func doTestServerStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSour
// Success // Success
h := &handler{reqMessages: []string{payload}} h := &handler{reqMessages: []string{payload}}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/StreamingOutputCall", makeHeaders(codes.OK), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/StreamingOutputCall", makeHeaders(codes.OK), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
if h.check(t, "grpc.testing.TestService.StreamingOutputCall", codes.OK, 1, 5) { if h.check(t, "testing.TestService.StreamingOutputCall", codes.OK, 1, 5) {
resp := &grpc_testing.StreamingOutputCallResponse{} resp := &grpcurl_testing.StreamingOutputCallResponse{}
for i, msg := range h.respMessages { for i, msg := range h.respMessages {
if err := jsonpb.UnmarshalString(msg, resp); err != nil { if err := jsonpb.UnmarshalString(msg, resp); err != nil {
t.Errorf("failed to parse response %d: %v", i+1, err) t.Errorf("failed to parse response %d: %v", i+1, err)
} }
if resp.Payload.GetType() != grpc_testing.PayloadType_COMPRESSABLE { if resp.Payload.GetType() != grpcurl_testing.PayloadType_COMPRESSABLE {
t.Errorf("response %d has wrong payload type; expecting %v, got %v", i, grpc_testing.PayloadType_COMPRESSABLE, resp.Payload.Type) t.Errorf("response %d has wrong payload type; expecting %v, got %v", i, grpcurl_testing.PayloadType_COMPRESSABLE, resp.Payload.Type)
} }
if len(resp.Payload.Body) != (i+1)*10 { if len(resp.Payload.Body) != (i+1)*10 {
t.Errorf("response %d has wrong payload size; expecting %d, got %d", i, (i+1)*10, len(resp.Payload.Body)) t.Errorf("response %d has wrong payload size; expecting %d, got %d", i, (i+1)*10, len(resp.Payload.Body))
@@ -604,21 +603,21 @@ func doTestServerStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSour
// Fail fast (server rejects as soon as possible) // Fail fast (server rejects as soon as possible)
h = &handler{reqMessages: []string{payload}} h = &handler{reqMessages: []string{payload}}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/StreamingOutputCall", makeHeaders(codes.Aborted), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/StreamingOutputCall", makeHeaders(codes.Aborted), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.StreamingOutputCall", codes.Aborted, 1, 0) h.check(t, "testing.TestService.StreamingOutputCall", codes.Aborted, 1, 0)
// Fail late (server waits until stream is complete to reject) // Fail late (server waits until stream is complete to reject)
h = &handler{reqMessages: []string{payload}} h = &handler{reqMessages: []string{payload}}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/StreamingOutputCall", makeHeaders(codes.AlreadyExists, true), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/StreamingOutputCall", makeHeaders(codes.AlreadyExists, true), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.StreamingOutputCall", codes.AlreadyExists, 1, 5) h.check(t, "testing.TestService.StreamingOutputCall", codes.AlreadyExists, 1, 5)
} }
func TestHalfDuplexStream(t *testing.T) { func TestHalfDuplexStream(t *testing.T) {
@@ -634,12 +633,12 @@ func doTestHalfDuplexStream(t *testing.T, cc *grpc.ClientConn, source Descriptor
// Success // Success
h := &handler{reqMessages: reqs} h := &handler{reqMessages: reqs}
err := InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/HalfDuplexCall", makeHeaders(codes.OK), h, h.getRequestData) err := InvokeRpc(context.Background(), source, cc, "testing.TestService/HalfDuplexCall", makeHeaders(codes.OK), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
if h.check(t, "grpc.testing.TestService.HalfDuplexCall", codes.OK, 3, 3) { if h.check(t, "testing.TestService.HalfDuplexCall", codes.OK, 3, 3) {
for i, resp := range h.respMessages { for i, resp := range h.respMessages {
if resp != reqs[i] { if resp != reqs[i] {
t.Errorf("unexpected response %d from RPC:\nexpecting %q\ngot %q", i, reqs[i], resp) t.Errorf("unexpected response %d from RPC:\nexpecting %q\ngot %q", i, reqs[i], resp)
@@ -649,21 +648,21 @@ func doTestHalfDuplexStream(t *testing.T, cc *grpc.ClientConn, source Descriptor
// Fail fast (server rejects as soon as possible) // Fail fast (server rejects as soon as possible)
h = &handler{reqMessages: reqs} h = &handler{reqMessages: reqs}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/HalfDuplexCall", makeHeaders(codes.Canceled), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/HalfDuplexCall", makeHeaders(codes.Canceled), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.HalfDuplexCall", codes.Canceled, -3, 0) h.check(t, "testing.TestService.HalfDuplexCall", codes.Canceled, -3, 0)
// Fail late (server waits until stream is complete to reject) // Fail late (server waits until stream is complete to reject)
h = &handler{reqMessages: reqs} h = &handler{reqMessages: reqs}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/HalfDuplexCall", makeHeaders(codes.DataLoss, true), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/HalfDuplexCall", makeHeaders(codes.DataLoss, true), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.HalfDuplexCall", codes.DataLoss, 3, 3) h.check(t, "testing.TestService.HalfDuplexCall", codes.DataLoss, 3, 3)
} }
func TestFullDuplexStream(t *testing.T) { func TestFullDuplexStream(t *testing.T) {
@@ -676,11 +675,11 @@ func TestFullDuplexStream(t *testing.T) {
func doTestFullDuplexStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) { func doTestFullDuplexStream(t *testing.T, cc *grpc.ClientConn, source DescriptorSource) {
reqs := make([]string, 3) reqs := make([]string, 3)
req := &grpc_testing.StreamingOutputCallRequest{ req := &grpcurl_testing.StreamingOutputCallRequest{
ResponseType: grpc_testing.PayloadType_RANDOM, ResponseType: grpcurl_testing.PayloadType_RANDOM,
} }
for i := range reqs { for i := range reqs {
req.ResponseParameters = append(req.ResponseParameters, &grpc_testing.ResponseParameters{Size: int32((i + 1) * 10)}) req.ResponseParameters = append(req.ResponseParameters, &grpcurl_testing.ResponseParameters{Size: int32((i + 1) * 10)})
payload, err := (&jsonpb.Marshaler{}).MarshalToString(req) payload, err := (&jsonpb.Marshaler{}).MarshalToString(req)
if err != nil { if err != nil {
t.Fatalf("failed to construct request %d: %v", i, err) t.Fatalf("failed to construct request %d: %v", i, err)
@@ -690,13 +689,13 @@ func doTestFullDuplexStream(t *testing.T, cc *grpc.ClientConn, source Descriptor
// Success // Success
h := &handler{reqMessages: reqs} h := &handler{reqMessages: reqs}
err := InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/FullDuplexCall", makeHeaders(codes.OK), h, h.getRequestData) err := InvokeRpc(context.Background(), source, cc, "testing.TestService/FullDuplexCall", makeHeaders(codes.OK), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
if h.check(t, "grpc.testing.TestService.FullDuplexCall", codes.OK, 3, 6) { if h.check(t, "testing.TestService.FullDuplexCall", codes.OK, 3, 6) {
resp := &grpc_testing.StreamingOutputCallResponse{} resp := &grpcurl_testing.StreamingOutputCallResponse{}
i := 0 i := 0
for j := 1; j < 3; j++ { for j := 1; j < 3; j++ {
// three requests // three requests
@@ -706,8 +705,8 @@ func doTestFullDuplexStream(t *testing.T, cc *grpc.ClientConn, source Descriptor
if err := jsonpb.UnmarshalString(msg, resp); err != nil { if err := jsonpb.UnmarshalString(msg, resp); err != nil {
t.Errorf("failed to parse response %d: %v", i+1, err) t.Errorf("failed to parse response %d: %v", i+1, err)
} }
if resp.Payload.GetType() != grpc_testing.PayloadType_RANDOM { if resp.Payload.GetType() != grpcurl_testing.PayloadType_RANDOM {
t.Errorf("response %d has wrong payload type; expecting %v, got %v", i, grpc_testing.PayloadType_RANDOM, resp.Payload.Type) t.Errorf("response %d has wrong payload type; expecting %v, got %v", i, grpcurl_testing.PayloadType_RANDOM, resp.Payload.Type)
} }
if len(resp.Payload.Body) != (k+1)*10 { if len(resp.Payload.Body) != (k+1)*10 {
t.Errorf("response %d has wrong payload size; expecting %d, got %d", i, (k+1)*10, len(resp.Payload.Body)) t.Errorf("response %d has wrong payload size; expecting %d, got %d", i, (k+1)*10, len(resp.Payload.Body))
@@ -721,21 +720,21 @@ func doTestFullDuplexStream(t *testing.T, cc *grpc.ClientConn, source Descriptor
// Fail fast (server rejects as soon as possible) // Fail fast (server rejects as soon as possible)
h = &handler{reqMessages: reqs} h = &handler{reqMessages: reqs}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/FullDuplexCall", makeHeaders(codes.PermissionDenied), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/FullDuplexCall", makeHeaders(codes.PermissionDenied), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.FullDuplexCall", codes.PermissionDenied, -3, 0) h.check(t, "testing.TestService.FullDuplexCall", codes.PermissionDenied, -3, 0)
// Fail late (server waits until stream is complete to reject) // Fail late (server waits until stream is complete to reject)
h = &handler{reqMessages: reqs} h = &handler{reqMessages: reqs}
err = InvokeRpc(context.Background(), source, cc, "grpc.testing.TestService/FullDuplexCall", makeHeaders(codes.ResourceExhausted, true), h, h.getRequestData) err = InvokeRpc(context.Background(), source, cc, "testing.TestService/FullDuplexCall", makeHeaders(codes.ResourceExhausted, true), h, h.getRequestData)
if err != nil { if err != nil {
t.Fatalf("unexpected error during RPC: %v", err) t.Fatalf("unexpected error during RPC: %v", err)
} }
h.check(t, "grpc.testing.TestService.FullDuplexCall", codes.ResourceExhausted, 3, 6) h.check(t, "testing.TestService.FullDuplexCall", codes.ResourceExhausted, 3, 6)
} }
type handler struct { type handler struct {

View File

@@ -13,13 +13,12 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog" "google.golang.org/grpc/grpclog"
"google.golang.org/grpc/interop/grpc_testing"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"google.golang.org/grpc/reflection" "google.golang.org/grpc/reflection"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"github.com/fullstorydev/grpcurl" "github.com/fullstorydev/grpcurl"
grpcurl_testing "github.com/fullstorydev/grpcurl/testing" grpcurl_testing "github.com/fullstorydev/grpcurl/internal/testing"
) )
var ( var (
@@ -96,7 +95,7 @@ func main() {
svr := grpc.NewServer(opts...) svr := grpc.NewServer(opts...)
grpc_testing.RegisterTestServiceServer(svr, grpcurl_testing.TestServer{}) grpcurl_testing.RegisterTestServiceServer(svr, grpcurl_testing.TestServer{})
if !*noreflect { if !*noreflect {
reflection.Register(svr) reflection.Register(svr)
} }

View File

@@ -3,7 +3,7 @@ syntax = "proto3";
import "google/protobuf/descriptor.proto"; import "google/protobuf/descriptor.proto";
import "google/protobuf/empty.proto"; import "google/protobuf/empty.proto";
import "google/protobuf/timestamp.proto"; import "google/protobuf/timestamp.proto";
import "testing/example2.proto"; import "example2.proto";
message TestRequest { message TestRequest {
repeated string file_names = 1; repeated string file_names = 1;

1132
internal/testing/test.pb.go Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,7 @@
// of unary/streaming requests/responses. // of unary/streaming requests/responses.
syntax = "proto3"; syntax = "proto3";
package grpc.testing; package testing;
message Empty {} message Empty {}
@@ -172,5 +172,5 @@ service TestService {
// that case. // that case.
service UnimplementedService { service UnimplementedService {
// A call that no server should implement // A call that no server should implement
rpc UnimplementedCall(grpc.testing.Empty) returns (grpc.testing.Empty); rpc UnimplementedCall(Empty) returns (Empty);
} }

Binary file not shown.

View File

@@ -1,5 +1,9 @@
package testing package testing
//go:generate protoc --go_out=plugins=grpc:./ test.proto
//go:generate protoc --descriptor_set_out=./test.protoset test.proto
//go:generate protoc --descriptor_set_out=./example.protoset --include_imports example.proto
import ( import (
"io" "io"
"strconv" "strconv"
@@ -8,7 +12,6 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/interop/grpc_testing"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
@@ -19,7 +22,7 @@ import (
type TestServer struct{} type TestServer struct{}
// EmptyCall accepts one empty request and issues one empty response. // EmptyCall accepts one empty request and issues one empty response.
func (TestServer) EmptyCall(ctx context.Context, req *grpc_testing.Empty) (*grpc_testing.Empty, error) { func (TestServer) EmptyCall(ctx context.Context, req *Empty) (*Empty, error) {
headers, trailers, failEarly, failLate := processMetadata(ctx) headers, trailers, failEarly, failLate := processMetadata(ctx)
grpc.SetHeader(ctx, headers) grpc.SetHeader(ctx, headers)
grpc.SetTrailer(ctx, trailers) grpc.SetTrailer(ctx, trailers)
@@ -35,7 +38,7 @@ func (TestServer) EmptyCall(ctx context.Context, req *grpc_testing.Empty) (*grpc
// UnaryCall accepts one request and issues one response. The response includes // UnaryCall accepts one request and issues one response. The response includes
// the client's payload as-is. // the client's payload as-is.
func (TestServer) UnaryCall(ctx context.Context, req *grpc_testing.SimpleRequest) (*grpc_testing.SimpleResponse, error) { func (TestServer) UnaryCall(ctx context.Context, req *SimpleRequest) (*SimpleResponse, error) {
headers, trailers, failEarly, failLate := processMetadata(ctx) headers, trailers, failEarly, failLate := processMetadata(ctx)
grpc.SetHeader(ctx, headers) grpc.SetHeader(ctx, headers)
grpc.SetTrailer(ctx, trailers) grpc.SetTrailer(ctx, trailers)
@@ -46,7 +49,7 @@ func (TestServer) UnaryCall(ctx context.Context, req *grpc_testing.SimpleRequest
return nil, status.Error(failLate, "fail") return nil, status.Error(failLate, "fail")
} }
return &grpc_testing.SimpleResponse{ return &SimpleResponse{
Payload: req.Payload, Payload: req.Payload,
}, nil }, nil
} }
@@ -54,7 +57,7 @@ func (TestServer) UnaryCall(ctx context.Context, req *grpc_testing.SimpleRequest
// StreamingOutputCall accepts one request and issues a sequence of responses // StreamingOutputCall accepts one request and issues a sequence of responses
// (streamed download). The server returns the payload with client desired type // (streamed download). The server returns the payload with client desired type
// and sizes as specified in the request's ResponseParameters. // and sizes as specified in the request's ResponseParameters.
func (TestServer) StreamingOutputCall(req *grpc_testing.StreamingOutputCallRequest, str grpc_testing.TestService_StreamingOutputCallServer) error { func (TestServer) StreamingOutputCall(req *StreamingOutputCallRequest, str TestService_StreamingOutputCallServer) error {
headers, trailers, failEarly, failLate := processMetadata(str.Context()) headers, trailers, failEarly, failLate := processMetadata(str.Context())
str.SetHeader(headers) str.SetHeader(headers)
str.SetTrailer(trailers) str.SetTrailer(trailers)
@@ -62,7 +65,7 @@ func (TestServer) StreamingOutputCall(req *grpc_testing.StreamingOutputCallReque
return status.Error(failEarly, "fail") return status.Error(failEarly, "fail")
} }
rsp := &grpc_testing.StreamingOutputCallResponse{Payload: &grpc_testing.Payload{}} rsp := &StreamingOutputCallResponse{Payload: &Payload{}}
for _, param := range req.ResponseParameters { for _, param := range req.ResponseParameters {
if str.Context().Err() != nil { if str.Context().Err() != nil {
return str.Context().Err() return str.Context().Err()
@@ -92,7 +95,7 @@ func (TestServer) StreamingOutputCall(req *grpc_testing.StreamingOutputCallReque
// StreamingInputCall accepts a sequence of requests and issues one response // StreamingInputCall accepts a sequence of requests and issues one response
// (streamed upload). The server returns the aggregated size of client payloads // (streamed upload). The server returns the aggregated size of client payloads
// as the result. // as the result.
func (TestServer) StreamingInputCall(str grpc_testing.TestService_StreamingInputCallServer) error { func (TestServer) StreamingInputCall(str TestService_StreamingInputCallServer) error {
headers, trailers, failEarly, failLate := processMetadata(str.Context()) headers, trailers, failEarly, failLate := processMetadata(str.Context())
str.SetHeader(headers) str.SetHeader(headers)
str.SetTrailer(trailers) str.SetTrailer(trailers)
@@ -114,7 +117,7 @@ func (TestServer) StreamingInputCall(str grpc_testing.TestService_StreamingInput
sz += len(req.Payload.Body) sz += len(req.Payload.Body)
} }
} }
if err := str.SendAndClose(&grpc_testing.StreamingInputCallResponse{AggregatedPayloadSize: int32(sz)}); err != nil { if err := str.SendAndClose(&StreamingInputCallResponse{AggregatedPayloadSize: int32(sz)}); err != nil {
return err return err
} }
@@ -127,7 +130,7 @@ func (TestServer) StreamingInputCall(str grpc_testing.TestService_StreamingInput
// FullDuplexCall accepts a sequence of requests with each request served by the // FullDuplexCall accepts a sequence of requests with each request served by the
// server immediately. As one request could lead to multiple responses, this // server immediately. As one request could lead to multiple responses, this
// interface demonstrates the idea of full duplexing. // interface demonstrates the idea of full duplexing.
func (TestServer) FullDuplexCall(str grpc_testing.TestService_FullDuplexCallServer) error { func (TestServer) FullDuplexCall(str TestService_FullDuplexCallServer) error {
headers, trailers, failEarly, failLate := processMetadata(str.Context()) headers, trailers, failEarly, failLate := processMetadata(str.Context())
str.SetHeader(headers) str.SetHeader(headers)
str.SetTrailer(trailers) str.SetTrailer(trailers)
@@ -135,7 +138,7 @@ func (TestServer) FullDuplexCall(str grpc_testing.TestService_FullDuplexCallServ
return status.Error(failEarly, "fail") return status.Error(failEarly, "fail")
} }
rsp := &grpc_testing.StreamingOutputCallResponse{Payload: &grpc_testing.Payload{}} rsp := &StreamingOutputCallResponse{Payload: &Payload{}}
for { for {
if str.Context().Err() != nil { if str.Context().Err() != nil {
return str.Context().Err() return str.Context().Err()
@@ -170,7 +173,7 @@ func (TestServer) FullDuplexCall(str grpc_testing.TestService_FullDuplexCallServ
// responses. The server buffers all the client requests and then serves them // responses. The server buffers all the client requests and then serves them
// in order. A stream of responses is returned to the client once the client // in order. A stream of responses is returned to the client once the client
// half-closes the stream. // half-closes the stream.
func (TestServer) HalfDuplexCall(str grpc_testing.TestService_HalfDuplexCallServer) error { func (TestServer) HalfDuplexCall(str TestService_HalfDuplexCallServer) error {
headers, trailers, failEarly, failLate := processMetadata(str.Context()) headers, trailers, failEarly, failLate := processMetadata(str.Context())
str.SetHeader(headers) str.SetHeader(headers)
str.SetTrailer(trailers) str.SetTrailer(trailers)
@@ -178,7 +181,7 @@ func (TestServer) HalfDuplexCall(str grpc_testing.TestService_HalfDuplexCallServ
return status.Error(failEarly, "fail") return status.Error(failEarly, "fail")
} }
var reqs []*grpc_testing.StreamingOutputCallRequest var reqs []*StreamingOutputCallRequest
for { for {
if str.Context().Err() != nil { if str.Context().Err() != nil {
return str.Context().Err() return str.Context().Err()
@@ -192,7 +195,7 @@ func (TestServer) HalfDuplexCall(str grpc_testing.TestService_HalfDuplexCallServ
reqs = append(reqs, req) reqs = append(reqs, req)
} }
} }
rsp := &grpc_testing.StreamingOutputCallResponse{} rsp := &StreamingOutputCallResponse{}
for _, req := range reqs { for _, req := range reqs {
rsp.Payload = req.Payload rsp.Payload = req.Payload
if err := str.Send(rsp); err != nil { if err := str.Send(rsp); err != nil {
@@ -251,4 +254,4 @@ func toCode(vals []string) codes.Code {
return codes.Code(i) return codes.Code(i)
} }
var _ grpc_testing.TestServiceServer = TestServer{} var _ TestServiceServer = TestServer{}

View File

@@ -93,9 +93,17 @@ func InvokeRPC(ctx context.Context, source DescriptorSource, ch grpcdynamic.Chan
if svc == "" || mth == "" { if svc == "" || mth == "" {
return fmt.Errorf("given method name %q is not in expected format: 'service/method' or 'service.method'", methodName) return fmt.Errorf("given method name %q is not in expected format: 'service/method' or 'service.method'", methodName)
} }
dsc, err := source.FindSymbol(svc) dsc, err := source.FindSymbol(svc)
if err != nil { if err != nil {
if isNotFoundError(err) { // return a gRPC status error if hasStatus is true
errStatus, hasStatus := status.FromError(err)
switch {
case hasStatus && isNotFoundError(err):
return status.Errorf(errStatus.Code(), "target server does not expose service %q: %s", svc, errStatus.Message())
case hasStatus:
return status.Errorf(errStatus.Code(), "failed to query for service descriptor %q: %s", svc, errStatus.Message())
case isNotFoundError(err):
return fmt.Errorf("target server does not expose service %q", svc) return fmt.Errorf("target server does not expose service %q", svc)
} }
return fmt.Errorf("failed to query for service descriptor %q: %v", svc, err) return fmt.Errorf("failed to query for service descriptor %q: %v", svc, err)

Binary file not shown.

View File

@@ -10,10 +10,9 @@ import (
"golang.org/x/net/context" "golang.org/x/net/context"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials"
"google.golang.org/grpc/interop/grpc_testing"
. "github.com/fullstorydev/grpcurl" . "github.com/fullstorydev/grpcurl"
grpcurl_testing "github.com/fullstorydev/grpcurl/testing" grpcurl_testing "github.com/fullstorydev/grpcurl/internal/testing"
) )
func TestPlainText(t *testing.T) { func TestPlainText(t *testing.T) {
@@ -27,11 +26,11 @@ func TestPlainText(t *testing.T) {
} }
func TestBasicTLS(t *testing.T) { func TestBasicTLS(t *testing.T) {
serverCreds, err := ServerTransportCredentials("", "testing/tls/server.crt", "testing/tls/server.key", false) serverCreds, err := ServerTransportCredentials("", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "", "") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "", "")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -46,7 +45,7 @@ func TestBasicTLS(t *testing.T) {
} }
func TestInsecureClientTLS(t *testing.T) { func TestInsecureClientTLS(t *testing.T) {
serverCreds, err := ServerTransportCredentials("", "testing/tls/server.crt", "testing/tls/server.key", false) serverCreds, err := ServerTransportCredentials("", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -65,11 +64,11 @@ func TestInsecureClientTLS(t *testing.T) {
} }
func TestClientCertTLS(t *testing.T) { func TestClientCertTLS(t *testing.T) {
serverCreds, err := ServerTransportCredentials("testing/tls/ca.crt", "testing/tls/server.crt", "testing/tls/server.key", false) serverCreds, err := ServerTransportCredentials("internal/testing/tls/ca.crt", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "testing/tls/client.crt", "testing/tls/client.key") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "internal/testing/tls/client.crt", "internal/testing/tls/client.key")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -84,11 +83,11 @@ func TestClientCertTLS(t *testing.T) {
} }
func TestRequireClientCertTLS(t *testing.T) { func TestRequireClientCertTLS(t *testing.T) {
serverCreds, err := ServerTransportCredentials("testing/tls/ca.crt", "testing/tls/server.crt", "testing/tls/server.key", true) serverCreds, err := ServerTransportCredentials("internal/testing/tls/ca.crt", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", true)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "testing/tls/client.crt", "testing/tls/client.key") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "internal/testing/tls/client.crt", "internal/testing/tls/client.key")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -103,7 +102,7 @@ func TestRequireClientCertTLS(t *testing.T) {
} }
func TestBrokenTLS_ClientPlainText(t *testing.T) { func TestBrokenTLS_ClientPlainText(t *testing.T) {
serverCreds, err := ServerTransportCredentials("", "testing/tls/server.crt", "testing/tls/server.key", false) serverCreds, err := ServerTransportCredentials("", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -148,8 +147,8 @@ func TestBrokenTLS_ClientPlainText(t *testing.T) {
// but request fails because server closes connection upon seeing request // but request fails because server closes connection upon seeing request
// bytes that are not a TLS handshake // bytes that are not a TLS handshake
cl := grpc_testing.NewTestServiceClient(e.cc) cl := grpcurl_testing.NewTestServiceClient(e.cc)
_, err = cl.UnaryCall(context.Background(), &grpc_testing.SimpleRequest{}) _, err = cl.UnaryCall(context.Background(), &grpcurl_testing.SimpleRequest{})
if err == nil { if err == nil {
t.Fatal("expecting failure") t.Fatal("expecting failure")
} }
@@ -164,7 +163,7 @@ func TestBrokenTLS_ClientPlainText(t *testing.T) {
} }
func TestBrokenTLS_ServerPlainText(t *testing.T) { func TestBrokenTLS_ServerPlainText(t *testing.T) {
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "", "") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "", "")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -180,11 +179,11 @@ func TestBrokenTLS_ServerPlainText(t *testing.T) {
} }
func TestBrokenTLS_ServerUsesWrongCert(t *testing.T) { func TestBrokenTLS_ServerUsesWrongCert(t *testing.T) {
serverCreds, err := ServerTransportCredentials("", "testing/tls/other.crt", "testing/tls/other.key", false) serverCreds, err := ServerTransportCredentials("", "internal/testing/tls/other.crt", "internal/testing/tls/other.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "", "") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "", "")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -200,11 +199,11 @@ func TestBrokenTLS_ServerUsesWrongCert(t *testing.T) {
} }
func TestBrokenTLS_ClientHasExpiredCert(t *testing.T) { func TestBrokenTLS_ClientHasExpiredCert(t *testing.T) {
serverCreds, err := ServerTransportCredentials("testing/tls/ca.crt", "testing/tls/server.crt", "testing/tls/server.key", false) serverCreds, err := ServerTransportCredentials("internal/testing/tls/ca.crt", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "testing/tls/expired.crt", "testing/tls/expired.key") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "internal/testing/tls/expired.crt", "internal/testing/tls/expired.key")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -220,11 +219,11 @@ func TestBrokenTLS_ClientHasExpiredCert(t *testing.T) {
} }
func TestBrokenTLS_ServerHasExpiredCert(t *testing.T) { func TestBrokenTLS_ServerHasExpiredCert(t *testing.T) {
serverCreds, err := ServerTransportCredentials("", "testing/tls/expired.crt", "testing/tls/expired.key", false) serverCreds, err := ServerTransportCredentials("", "internal/testing/tls/expired.crt", "internal/testing/tls/expired.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "", "") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "", "")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -240,11 +239,11 @@ func TestBrokenTLS_ServerHasExpiredCert(t *testing.T) {
} }
func TestBrokenTLS_ClientNotTrusted(t *testing.T) { func TestBrokenTLS_ClientNotTrusted(t *testing.T) {
serverCreds, err := ServerTransportCredentials("testing/tls/ca.crt", "testing/tls/server.crt", "testing/tls/server.key", true) serverCreds, err := ServerTransportCredentials("internal/testing/tls/ca.crt", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", true)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "testing/tls/wrong-client.crt", "testing/tls/wrong-client.key") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "internal/testing/tls/wrong-client.crt", "internal/testing/tls/wrong-client.key")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -260,11 +259,11 @@ func TestBrokenTLS_ClientNotTrusted(t *testing.T) {
} }
func TestBrokenTLS_ServerNotTrusted(t *testing.T) { func TestBrokenTLS_ServerNotTrusted(t *testing.T) {
serverCreds, err := ServerTransportCredentials("", "testing/tls/server.crt", "testing/tls/server.key", false) serverCreds, err := ServerTransportCredentials("", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", false)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "", "testing/tls/client.crt", "testing/tls/client.key") clientCreds, err := ClientTransportCredentials(false, "", "internal/testing/tls/client.crt", "internal/testing/tls/client.key")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -280,11 +279,11 @@ func TestBrokenTLS_ServerNotTrusted(t *testing.T) {
} }
func TestBrokenTLS_RequireClientCertButNonePresented(t *testing.T) { func TestBrokenTLS_RequireClientCertButNonePresented(t *testing.T) {
serverCreds, err := ServerTransportCredentials("testing/tls/ca.crt", "testing/tls/server.crt", "testing/tls/server.key", true) serverCreds, err := ServerTransportCredentials("internal/testing/tls/ca.crt", "internal/testing/tls/server.crt", "internal/testing/tls/server.key", true)
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
clientCreds, err := ClientTransportCredentials(false, "testing/tls/ca.crt", "", "") clientCreds, err := ClientTransportCredentials(false, "internal/testing/tls/ca.crt", "", "")
if err != nil { if err != nil {
t.Fatalf("failed to create server creds: %v", err) t.Fatalf("failed to create server creds: %v", err)
} }
@@ -300,10 +299,10 @@ func TestBrokenTLS_RequireClientCertButNonePresented(t *testing.T) {
} }
func simpleTest(t *testing.T, cc *grpc.ClientConn) { func simpleTest(t *testing.T, cc *grpc.ClientConn) {
cl := grpc_testing.NewTestServiceClient(cc) cl := grpcurl_testing.NewTestServiceClient(cc)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel() defer cancel()
_, err := cl.UnaryCall(ctx, &grpc_testing.SimpleRequest{}, grpc.WaitForReady(true)) _, err := cl.UnaryCall(ctx, &grpcurl_testing.SimpleRequest{}, grpc.WaitForReady(true))
if err != nil { if err != nil {
t.Errorf("simple RPC failed: %v", err) t.Errorf("simple RPC failed: %v", err)
} }
@@ -323,7 +322,7 @@ func createTestServerAndClient(serverCreds, clientCreds credentials.TransportCre
svrOpts = []grpc.ServerOption{grpc.Creds(serverCreds)} svrOpts = []grpc.ServerOption{grpc.Creds(serverCreds)}
} }
svr := grpc.NewServer(svrOpts...) svr := grpc.NewServer(svrOpts...)
grpc_testing.RegisterTestServiceServer(svr, grpcurl_testing.TestServer{}) grpcurl_testing.RegisterTestServiceServer(svr, grpcurl_testing.TestServer{})
l, err := net.Listen("tcp", "127.0.0.1:0") l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil { if err != nil {
return e, err return e, err