How to use String method of grpc_any_testing Package

Best K6 code snippet using grpc_any_testing.String

client_test.go

Source:client_test.go Github

copy

Full Screen

...45}46type testcase struct {47 name string48 setup func(*httpmultibin.HTTPMultiBin)49 initString codeBlock // runs in the init context50 vuString codeBlock // runs in the vu context51}52func TestClient(t *testing.T) {53 t.Parallel()54 type testState struct {55 rt *goja.Runtime56 vuState *lib.State57 env *common.InitEnvironment58 httpBin *httpmultibin.HTTPMultiBin59 samples chan metrics.SampleContainer60 }61 setup := func(t *testing.T) testState {62 t.Helper()63 root, err := lib.NewGroup("", nil)64 require.NoError(t, err)65 tb := httpmultibin.NewHTTPMultiBin(t)66 samples := make(chan metrics.SampleContainer, 1000)67 state := &lib.State{68 Group: root,69 Dialer: tb.Dialer,70 TLSConfig: tb.TLSClientConfig,71 Samples: samples,72 Options: lib.Options{73 SystemTags: metrics.NewSystemTagSet(74 metrics.TagName,75 metrics.TagURL,76 ),77 UserAgent: null.StringFrom("k6-test"),78 },79 BuiltinMetrics: metrics.RegisterBuiltinMetrics(80 metrics.NewRegistry(),81 ),82 Tags: lib.NewTagMap(nil),83 }84 cwd, err := os.Getwd()85 require.NoError(t, err)86 fs := afero.NewOsFs()87 if isWindows {88 fs = fsext.NewTrimFilePathSeparatorFs(fs)89 }90 initEnv := &common.InitEnvironment{91 Logger: logrus.New(),92 CWD: &url.URL{Path: cwd},93 FileSystems: map[string]afero.Fs{94 "file": fs,95 },96 }97 rt := goja.New()98 rt.SetFieldNameMapper(common.FieldNameMapper{})99 return testState{100 rt: rt,101 httpBin: tb,102 vuState: state,103 env: initEnv,104 samples: samples,105 }106 }107 assertMetricEmitted := func(108 t *testing.T,109 metricName string,110 sampleContainers []metrics.SampleContainer,111 url string,112 ) {113 seenMetric := false114 for _, sampleContainer := range sampleContainers {115 for _, sample := range sampleContainer.GetSamples() {116 surl, ok := sample.Tags.Get("url")117 assert.True(t, ok)118 if surl == url {119 if sample.Metric.Name == metricName {120 seenMetric = true121 }122 }123 }124 }125 assert.True(t, seenMetric, "url %s didn't emit %s", url, metricName)126 }127 tests := []testcase{128 {129 name: "BadTLS",130 setup: func(tb *httpmultibin.HTTPMultiBin) {131 // changing the pointer's value132 // for affecting the lib.State133 // that uses the same pointer134 *tb.TLSClientConfig = tls.Config{135 MinVersion: tls.VersionTLS13,136 }137 },138 initString: codeBlock{139 code: `var client = new grpc.Client();`,140 },141 vuString: codeBlock{142 code: `client.connect("GRPCBIN_ADDR", {timeout: '1s'})`,143 err: "certificate signed by unknown authority",144 },145 },146 {147 name: "New",148 initString: codeBlock{149 code: `150 var client = new grpc.Client();151 if (!client) throw new Error("no client created")`,152 },153 },154 {155 name: "LoadNotFound",156 initString: codeBlock{157 code: `158 var client = new grpc.Client();159 client.load([], "./does_not_exist.proto");`,160 err: "no such file or directory",161 // (rogchap) this is a bit of a hack as windows reports a different system error than unix.162 windowsErr: "The system cannot find the file specified",163 },164 },165 {166 name: "Load",167 initString: codeBlock{168 code: `169 var client = new grpc.Client();170 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,171 val: []MethodInfo{{MethodInfo: grpc.MethodInfo{Name: "EmptyCall", IsClientStream: false, IsServerStream: false}, Package: "grpc.testing", Service: "TestService", FullMethod: "/grpc.testing.TestService/EmptyCall"}, {MethodInfo: grpc.MethodInfo{Name: "UnaryCall", IsClientStream: false, IsServerStream: false}, Package: "grpc.testing", Service: "TestService", FullMethod: "/grpc.testing.TestService/UnaryCall"}, {MethodInfo: grpc.MethodInfo{Name: "StreamingOutputCall", IsClientStream: false, IsServerStream: true}, Package: "grpc.testing", Service: "TestService", FullMethod: "/grpc.testing.TestService/StreamingOutputCall"}, {MethodInfo: grpc.MethodInfo{Name: "StreamingInputCall", IsClientStream: true, IsServerStream: false}, Package: "grpc.testing", Service: "TestService", FullMethod: "/grpc.testing.TestService/StreamingInputCall"}, {MethodInfo: grpc.MethodInfo{Name: "FullDuplexCall", IsClientStream: true, IsServerStream: true}, Package: "grpc.testing", Service: "TestService", FullMethod: "/grpc.testing.TestService/FullDuplexCall"}, {MethodInfo: grpc.MethodInfo{Name: "HalfDuplexCall", IsClientStream: true, IsServerStream: true}, Package: "grpc.testing", Service: "TestService", FullMethod: "/grpc.testing.TestService/HalfDuplexCall"}},172 },173 },174 {175 name: "ConnectInit",176 initString: codeBlock{177 code: `178 var client = new grpc.Client();179 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");180 client.connect();`,181 err: "connecting to a gRPC server in the init context is not supported",182 },183 },184 {185 name: "InvokeInit",186 initString: codeBlock{187 code: `188 var client = new grpc.Client();189 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");190 var err = client.invoke();191 throw new Error(err)`,192 err: "invoking RPC methods in the init context is not supported",193 },194 },195 {196 name: "NoConnect",197 initString: codeBlock{198 code: `199 var client = new grpc.Client();200 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");201 client.invoke("grpc.testing.TestService/EmptyCall", {})`,202 err: "invoking RPC methods in the init context is not supported",203 },204 },205 {206 name: "UnknownConnectParam",207 initString: codeBlock{code: `208 var client = new grpc.Client();209 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},210 vuString: codeBlock{211 code: `client.connect("GRPCBIN_ADDR", { name: "k6" });`,212 err: `unknown connect param: "name"`,213 },214 },215 {216 name: "ConnectInvalidTimeout",217 initString: codeBlock{218 code: `219 var client = new grpc.Client();220 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,221 },222 vuString: codeBlock{223 code: `client.connect("GRPCBIN_ADDR", { timeout: "k6" });`,224 err: "invalid duration",225 },226 },227 {228 name: "ConnectStringTimeout",229 initString: codeBlock{code: `230 var client = new grpc.Client();231 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},232 vuString: codeBlock{code: `client.connect("GRPCBIN_ADDR", { timeout: "1h3s" });`},233 },234 {235 name: "ConnectIntegerTimeout",236 initString: codeBlock{code: `237 var client = new grpc.Client();238 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},239 vuString: codeBlock{code: `client.connect("GRPCBIN_ADDR", { timeout: 3000 });`},240 },241 {242 name: "ConnectFloatTimeout",243 initString: codeBlock{code: `244 var client = new grpc.Client();245 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},246 vuString: codeBlock{code: `client.connect("GRPCBIN_ADDR", { timeout: 3456.3 });`},247 },248 {249 name: "Connect",250 initString: codeBlock{code: `251 var client = new grpc.Client();252 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},253 vuString: codeBlock{code: `client.connect("GRPCBIN_ADDR");`},254 },255 {256 name: "InvokeNotFound",257 initString: codeBlock{code: `258 var client = new grpc.Client();259 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},260 vuString: codeBlock{261 code: `262 client.connect("GRPCBIN_ADDR");263 client.invoke("foo/bar", {})`,264 err: `method "/foo/bar" not found in file descriptors`,265 },266 },267 {268 name: "InvokeInvalidParam",269 initString: codeBlock{code: `270 var client = new grpc.Client();271 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},272 vuString: codeBlock{273 code: `274 client.connect("GRPCBIN_ADDR");275 client.invoke("grpc.testing.TestService/EmptyCall", {}, { void: true })`,276 err: `unknown param: "void"`,277 },278 },279 {280 name: "InvokeInvalidTimeoutType",281 initString: codeBlock{code: `282 var client = new grpc.Client();283 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},284 vuString: codeBlock{285 code: `286 client.connect("GRPCBIN_ADDR");287 client.invoke("grpc.testing.TestService/EmptyCall", {}, { timeout: true })`,288 err: "invalid timeout value: unable to use type bool as a duration value",289 },290 },291 {292 name: "InvokeInvalidTimeout",293 initString: codeBlock{code: `294 var client = new grpc.Client();295 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},296 vuString: codeBlock{297 code: `298 client.connect("GRPCBIN_ADDR");299 client.invoke("grpc.testing.TestService/EmptyCall", {}, { timeout: "please" })`,300 err: "invalid duration",301 },302 },303 {304 name: "InvokeStringTimeout",305 initString: codeBlock{code: `306 var client = new grpc.Client();307 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},308 vuString: codeBlock{309 code: `310 client.connect("GRPCBIN_ADDR");311 client.invoke("grpc.testing.TestService/EmptyCall", {}, { timeout: "1h42m" })`,312 },313 },314 {315 name: "InvokeFloatTimeout",316 initString: codeBlock{code: `317 var client = new grpc.Client();318 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},319 vuString: codeBlock{320 code: `321 client.connect("GRPCBIN_ADDR");322 client.invoke("grpc.testing.TestService/EmptyCall", {}, { timeout: 400.50 })`,323 },324 },325 {326 name: "InvokeIntegerTimeout",327 initString: codeBlock{328 code: `329 var client = new grpc.Client();330 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,331 },332 vuString: codeBlock{333 code: `334 client.connect("GRPCBIN_ADDR");335 client.invoke("grpc.testing.TestService/EmptyCall", {}, { timeout: 2000 })`,336 },337 },338 {339 name: "Invoke",340 initString: codeBlock{code: `341 var client = new grpc.Client();342 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`},343 setup: func(tb *httpmultibin.HTTPMultiBin) {344 tb.GRPCStub.EmptyCallFunc = func(context.Context, *grpc_testing.Empty) (*grpc_testing.Empty, error) {345 return &grpc_testing.Empty{}, nil346 }347 },348 vuString: codeBlock{349 code: `350 client.connect("GRPCBIN_ADDR");351 var resp = client.invoke("grpc.testing.TestService/EmptyCall", {})352 if (resp.status !== grpc.StatusOK) {353 throw new Error("unexpected error: " + JSON.stringify(resp.error) + "or status: " + resp.status)354 }`,355 asserts: func(t *testing.T, rb *httpmultibin.HTTPMultiBin, samples chan metrics.SampleContainer, _ error) {356 samplesBuf := metrics.GetBufferedSamples(samples)357 assertMetricEmitted(t, metrics.GRPCReqDurationName, samplesBuf, rb.Replacer.Replace("GRPCBIN_ADDR/grpc.testing.TestService/EmptyCall"))358 },359 },360 },361 {362 name: "InvokeAnyProto",363 initString: codeBlock{code: `364 var client = new grpc.Client();365 client.load([], "../../../../lib/testutils/httpmultibin/grpc_any_testing/any_test.proto");`},366 setup: func(tb *httpmultibin.HTTPMultiBin) {367 tb.GRPCAnyStub.SumFunc = func(ctx context.Context, req *grpcanytesting.SumRequest) (*grpcanytesting.SumReply, error) {368 var sumRequestData grpcanytesting.SumRequestData369 if err := req.Data.UnmarshalTo(&sumRequestData); err != nil {370 return nil, err371 }372 sumReplyData := &grpcanytesting.SumReplyData{373 V: sumRequestData.A + sumRequestData.B,374 Err: "",375 }376 sumReply := &grpcanytesting.SumReply{377 Data: &any.Any{},378 }379 if err := sumReply.Data.MarshalFrom(sumReplyData); err != nil {380 return nil, err381 }382 return sumReply, nil383 }384 },385 vuString: codeBlock{386 code: `387 client.connect("GRPCBIN_ADDR");388 var resp = client.invoke("grpc.any.testing.AnyTestService/Sum", {389 data: {390 "@type": "type.googleapis.com/grpc.any.testing.SumRequestData",391 "a": 1,392 "b": 2,393 },394 })395 if (resp.status !== grpc.StatusOK) {396 throw new Error("unexpected error: " + JSON.stringify(resp.error) + "or status: " + resp.status)397 }398 if (resp.message.data.v !== "3") {399 throw new Error("unexpected resp message data")400 }`,401 asserts: func(t *testing.T, rb *httpmultibin.HTTPMultiBin, samples chan metrics.SampleContainer, _ error) {402 samplesBuf := metrics.GetBufferedSamples(samples)403 assertMetricEmitted(t, metrics.GRPCReqDurationName, samplesBuf, rb.Replacer.Replace("GRPCBIN_ADDR/grpc.any.testing.AnyTestService/Sum"))404 },405 },406 },407 {408 name: "RequestMessage",409 initString: codeBlock{410 code: `411 var client = new grpc.Client();412 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,413 },414 setup: func(tb *httpmultibin.HTTPMultiBin) {415 tb.GRPCStub.UnaryCallFunc = func(_ context.Context, req *grpc_testing.SimpleRequest) (*grpc_testing.SimpleResponse, error) {416 if req.Payload == nil || string(req.Payload.Body) != "负载测试" {417 return nil, status.Error(codes.InvalidArgument, "")418 }419 return &grpc_testing.SimpleResponse{}, nil420 }421 },422 vuString: codeBlock{code: `423 client.connect("GRPCBIN_ADDR");424 var resp = client.invoke("grpc.testing.TestService/UnaryCall", { payload: { body: "6LSf6L295rWL6K+V"} })425 if (resp.status !== grpc.StatusOK) {426 throw new Error("server did not receive the correct request message")427 }`},428 },429 {430 name: "RequestHeaders",431 initString: codeBlock{432 code: `433 var client = new grpc.Client();434 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,435 },436 setup: func(tb *httpmultibin.HTTPMultiBin) {437 tb.GRPCStub.EmptyCallFunc = func(ctx context.Context, _ *grpc_testing.Empty) (*grpc_testing.Empty, error) {438 md, ok := metadata.FromIncomingContext(ctx)439 if !ok || len(md["x-load-tester"]) == 0 || md["x-load-tester"][0] != "k6" {440 return nil, status.Error(codes.FailedPrecondition, "")441 }442 return &grpc_testing.Empty{}, nil443 }444 },445 vuString: codeBlock{code: `446 client.connect("GRPCBIN_ADDR");447 var resp = client.invoke("grpc.testing.TestService/EmptyCall", {}, { metadata: { "X-Load-Tester": "k6" } })448 if (resp.status !== grpc.StatusOK) {449 throw new Error("failed to send correct headers in the request")450 }451 `},452 },453 {454 name: "ResponseMessage",455 initString: codeBlock{456 code: `457 var client = new grpc.Client();458 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,459 },460 setup: func(tb *httpmultibin.HTTPMultiBin) {461 tb.GRPCStub.UnaryCallFunc = func(context.Context, *grpc_testing.SimpleRequest) (*grpc_testing.SimpleResponse, error) {462 return &grpc_testing.SimpleResponse{463 OauthScope: "水",464 }, nil465 }466 },467 vuString: codeBlock{468 code: `469 client.connect("GRPCBIN_ADDR");470 var resp = client.invoke("grpc.testing.TestService/UnaryCall", {})471 if (!resp.message || resp.message.username !== "" || resp.message.oauthScope !== "水") {472 throw new Error("unexpected response message: " + JSON.stringify(resp.message))473 }`,474 asserts: func(t *testing.T, rb *httpmultibin.HTTPMultiBin, samples chan metrics.SampleContainer, _ error) {475 samplesBuf := metrics.GetBufferedSamples(samples)476 assertMetricEmitted(t, metrics.GRPCReqDurationName, samplesBuf, rb.Replacer.Replace("GRPCBIN_ADDR/grpc.testing.TestService/UnaryCall"))477 },478 },479 },480 {481 name: "ResponseError",482 initString: codeBlock{483 code: `484 var client = new grpc.Client();485 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,486 },487 setup: func(tb *httpmultibin.HTTPMultiBin) {488 tb.GRPCStub.EmptyCallFunc = func(context.Context, *grpc_testing.Empty) (*grpc_testing.Empty, error) {489 return nil, status.Error(codes.DataLoss, "foobar")490 }491 },492 vuString: codeBlock{493 code: `494 client.connect("GRPCBIN_ADDR");495 var resp = client.invoke("grpc.testing.TestService/EmptyCall", {})496 if (resp.status !== grpc.StatusDataLoss) {497 throw new Error("unexpected error status: " + resp.status)498 }499 if (!resp.error || resp.error.message !== "foobar" || resp.error.code !== 15) {500 throw new Error("unexpected error object: " + JSON.stringify(resp.error.code))501 }`,502 asserts: func(t *testing.T, rb *httpmultibin.HTTPMultiBin, samples chan metrics.SampleContainer, _ error) {503 samplesBuf := metrics.GetBufferedSamples(samples)504 assertMetricEmitted(t, metrics.GRPCReqDurationName, samplesBuf, rb.Replacer.Replace("GRPCBIN_ADDR/grpc.testing.TestService/EmptyCall"))505 },506 },507 },508 {509 name: "ResponseHeaders",510 initString: codeBlock{511 code: `512 var client = new grpc.Client();513 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,514 },515 setup: func(tb *httpmultibin.HTTPMultiBin) {516 tb.GRPCStub.EmptyCallFunc = func(ctx context.Context, _ *grpc_testing.Empty) (*grpc_testing.Empty, error) {517 md := metadata.Pairs("foo", "bar")518 _ = grpc.SetHeader(ctx, md)519 return &grpc_testing.Empty{}, nil520 }521 },522 vuString: codeBlock{523 code: `524 client.connect("GRPCBIN_ADDR");525 var resp = client.invoke("grpc.testing.TestService/EmptyCall", {})526 if (resp.status !== grpc.StatusOK) {527 throw new Error("unexpected error status: " + resp.status)528 }529 if (!resp.headers || !resp.headers["foo"] || resp.headers["foo"][0] !== "bar") {530 throw new Error("unexpected headers object: " + JSON.stringify(resp.trailers))531 }`,532 asserts: func(t *testing.T, rb *httpmultibin.HTTPMultiBin, samples chan metrics.SampleContainer, _ error) {533 samplesBuf := metrics.GetBufferedSamples(samples)534 assertMetricEmitted(t, metrics.GRPCReqDurationName, samplesBuf, rb.Replacer.Replace("GRPCBIN_ADDR/grpc.testing.TestService/EmptyCall"))535 },536 },537 },538 {539 name: "ResponseTrailers",540 initString: codeBlock{541 code: `542 var client = new grpc.Client();543 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,544 },545 setup: func(tb *httpmultibin.HTTPMultiBin) {546 tb.GRPCStub.EmptyCallFunc = func(ctx context.Context, _ *grpc_testing.Empty) (*grpc_testing.Empty, error) {547 md := metadata.Pairs("foo", "bar")548 _ = grpc.SetTrailer(ctx, md)549 return &grpc_testing.Empty{}, nil550 }551 },552 vuString: codeBlock{553 code: `554 client.connect("GRPCBIN_ADDR");555 var resp = client.invoke("grpc.testing.TestService/EmptyCall", {})556 if (resp.status !== grpc.StatusOK) {557 throw new Error("unexpected error status: " + resp.status)558 }559 if (!resp.trailers || !resp.trailers["foo"] || resp.trailers["foo"][0] !== "bar") {560 throw new Error("unexpected trailers object: " + JSON.stringify(resp.trailers))561 }`,562 asserts: func(t *testing.T, rb *httpmultibin.HTTPMultiBin, samples chan metrics.SampleContainer, _ error) {563 samplesBuf := metrics.GetBufferedSamples(samples)564 assertMetricEmitted(t, metrics.GRPCReqDurationName, samplesBuf, rb.Replacer.Replace("GRPCBIN_ADDR/grpc.testing.TestService/EmptyCall"))565 },566 },567 },568 {569 name: "LoadNotInit",570 setup: func(tb *httpmultibin.HTTPMultiBin) {571 tb.GRPCStub.EmptyCallFunc = func(ctx context.Context, _ *grpc_testing.Empty) (*grpc_testing.Empty, error) {572 md := metadata.Pairs("foo", "bar")573 _ = grpc.SetTrailer(ctx, md)574 return &grpc_testing.Empty{}, nil575 }576 },577 initString: codeBlock{578 code: `579 var client = new grpc.Client();580 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,581 },582 vuString: codeBlock{583 code: `client.load()`,584 err: "load must be called in the init context",585 },586 },587 {588 name: "ReflectUnregistered",589 initString: codeBlock{590 code: `var client = new grpc.Client();`,591 },592 vuString: codeBlock{593 code: `client.connect("GRPCBIN_ADDR", {reflect: true})`,594 err: "rpc error: code = Unimplemented desc = unknown service grpc.reflection.v1alpha.ServerReflection",595 },596 },597 {598 name: "Reflect",599 setup: func(tb *httpmultibin.HTTPMultiBin) {600 reflection.Register(tb.ServerGRPC)601 },602 initString: codeBlock{603 code: `var client = new grpc.Client();`,604 },605 vuString: codeBlock{606 code: `client.connect("GRPCBIN_ADDR", {reflect: true})`,607 },608 },609 {610 name: "ReflectBadParam",611 setup: func(tb *httpmultibin.HTTPMultiBin) {612 reflection.Register(tb.ServerGRPC)613 },614 initString: codeBlock{615 code: `var client = new grpc.Client();`,616 },617 vuString: codeBlock{618 code: `client.connect("GRPCBIN_ADDR", {reflect: "true"})`,619 err: `invalid reflect value`,620 },621 },622 {623 name: "ReflectInvokeNoExist",624 setup: func(tb *httpmultibin.HTTPMultiBin) {625 reflection.Register(tb.ServerGRPC)626 tb.GRPCStub.EmptyCallFunc = func(ctx context.Context, _ *grpc_testing.Empty) (*grpc_testing.Empty, error) {627 return &grpc_testing.Empty{}, nil628 }629 },630 initString: codeBlock{631 code: `var client = new grpc.Client();`,632 },633 vuString: codeBlock{634 code: `635 client.connect("GRPCBIN_ADDR", {reflect: true})636 client.invoke("foo/bar", {})637 `,638 err: `method "/foo/bar" not found in file descriptors`,639 },640 },641 {642 name: "ReflectInvoke",643 setup: func(tb *httpmultibin.HTTPMultiBin) {644 reflection.Register(tb.ServerGRPC)645 tb.GRPCStub.EmptyCallFunc = func(ctx context.Context, _ *grpc_testing.Empty) (*grpc_testing.Empty, error) {646 return &grpc_testing.Empty{}, nil647 }648 },649 initString: codeBlock{650 code: `var client = new grpc.Client();`,651 },652 vuString: codeBlock{653 code: `654 client.connect("GRPCBIN_ADDR", {reflect: true})655 client.invoke("grpc.testing.TestService/EmptyCall", {})656 `,657 },658 },659 {660 name: "Close",661 initString: codeBlock{662 code: `663 var client = new grpc.Client();664 client.load([], "../../../../vendor/google.golang.org/grpc/test/grpc_testing/test.proto");`,665 },666 vuString: codeBlock{667 code: `668 client.close();669 client.invoke();`,670 err: "no gRPC connection",671 },672 },673 }674 assertResponse := func(t *testing.T, cb codeBlock, err error, val goja.Value, ts testState) {675 if isWindows && cb.windowsErr != "" && err != nil {676 err = errors.New(strings.ReplaceAll(err.Error(), cb.windowsErr, cb.err))677 }678 if cb.err == "" {679 assert.NoError(t, err)680 } else {681 require.Error(t, err)682 assert.Contains(t, err.Error(), cb.err)683 }684 if cb.val != nil {685 require.NotNil(t, val)686 assert.Equal(t, cb.val, val.Export())687 }688 if cb.asserts != nil {689 cb.asserts(t, ts.httpBin, ts.samples, err)690 }691 }692 for _, tt := range tests {693 tt := tt694 t.Run(tt.name, func(t *testing.T) {695 t.Parallel()696 ts := setup(t)697 ctx, cancel := context.WithCancel(context.Background())698 defer cancel()699 mvu := &modulestest.VU{700 RuntimeField: ts.rt,701 InitEnvField: ts.env,702 CtxField: ctx,703 }704 m, ok := New().NewModuleInstance(mvu).(*ModuleInstance)705 require.True(t, ok)706 require.NoError(t, ts.rt.Set("grpc", m.Exports().Named))707 // setup necessary environment if needed by a test708 if tt.setup != nil {709 tt.setup(ts.httpBin)710 }711 replace := func(code string) (goja.Value, error) {712 return ts.rt.RunString(ts.httpBin.Replacer.Replace(code))713 }714 val, err := replace(tt.initString.code)715 assertResponse(t, tt.initString, err, val, ts)716 mvu.StateField = ts.vuState717 val, err = replace(tt.vuString.code)718 assertResponse(t, tt.vuString, err, val, ts)719 })720 }721}722func TestDebugStat(t *testing.T) {723 t.Parallel()724 tests := [...]struct {725 name string726 stat grpcstats.RPCStats727 expected string728 }{729 {730 "OutHeader",731 &grpcstats.OutHeader{},732 "Out Header:",733 },734 {735 "OutTrailer",736 &grpcstats.OutTrailer{737 Trailer: metadata.MD{738 "x-trail": []string{"out"},739 },740 },741 "Out Trailer:",742 },743 {744 "OutPayload",745 &grpcstats.OutPayload{746 Payload: &grpc_testing.SimpleRequest{747 FillUsername: true,748 },749 },750 "fill_username:",751 },752 {753 "InHeader",754 &grpcstats.InHeader{755 Header: metadata.MD{756 "x-head": []string{"in"},757 },758 },759 "x-head: in",760 },761 {762 "InTrailer",763 &grpcstats.InTrailer{764 Trailer: metadata.MD{765 "x-trail": []string{"in"},766 },767 },768 "x-trail: in",769 },770 {771 "InPayload",772 &grpcstats.InPayload{773 Payload: &grpc_testing.SimpleResponse{774 Username: "k6-user",775 },776 },777 "username:",778 },779 }780 for _, tt := range tests {781 tt := tt782 t.Run(tt.name, func(t *testing.T) {783 t.Parallel()784 var b bytes.Buffer785 logger := logrus.New()786 logger.Out = &b787 grpcext.DebugStat(logger.WithField("source", "test"), tt.stat, "full")788 assert.Contains(t, b.String(), tt.expected)789 })790 }791}792func TestClientInvokeHeadersDeprecated(t *testing.T) {793 t.Parallel()794 logHook := &testutils.SimpleLogrusHook{795 HookedLevels: []logrus.Level{logrus.WarnLevel},796 }797 testLog := logrus.New()798 testLog.AddHook(logHook)799 testLog.SetOutput(ioutil.Discard)800 c := Client{801 vu: &modulestest.VU{802 StateField: &lib.State{...

Full Screen

Full Screen

httpmultibin.go

Source:httpmultibin.go Github

copy

Full Screen

...320 "HTTPBIN_IP_URL", httpSrv.URL,321 "HTTPBIN_DOMAIN", httpDomain,322 "HTTPBIN_URL", fmt.Sprintf("http://%s:%s", httpDomain, httpURL.Port()),323 "WSBIN_URL", fmt.Sprintf("ws://%s:%s", httpDomain, httpURL.Port()),324 "HTTPBIN_IP", httpIP.String(),325 "HTTPBIN_PORT", httpURL.Port(),326 "HTTPSBIN_IP_URL", httpsSrv.URL,327 "HTTPSBIN_DOMAIN", httpsDomain,328 "HTTPSBIN_URL", fmt.Sprintf("https://%s:%s", httpsDomain, httpsURL.Port()),329 "WSSBIN_URL", fmt.Sprintf("wss://%s:%s", httpsDomain, httpsURL.Port()),330 "HTTPSBIN_IP", httpsIP.String(),331 "HTTPSBIN_PORT", httpsURL.Port(),332 "HTTP2BIN_IP_URL", http2Srv.URL,333 "HTTP2BIN_DOMAIN", httpsDomain,334 "HTTP2BIN_URL", fmt.Sprintf("https://%s:%s", httpsDomain, http2URL.Port()),335 "HTTP2BIN_IP", http2IP.String(),336 "HTTP2BIN_PORT", http2URL.Port(),337 "GRPCBIN_ADDR", fmt.Sprintf("%s:%s", httpsDomain, http2URL.Port()),338 ),339 TLSClientConfig: tlsConfig,340 Dialer: dialer,341 HTTPTransport: transport,342 Context: ctx,343 }344 t.Cleanup(func() {345 grpcSrv.Stop()346 http2Srv.Close()347 httpsSrv.Close()348 httpSrv.Close()349 ctxCancel()...

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2type testServer struct {3}4func (s *testServer) UnaryCall(ctx context.Context, req *grpc_testing.SimpleRequest) (*grpc_testing.SimpleResponse, error) {5}6func (s *testServer) StreamingOutputCall(req *grpc_testing.StreamingOutputCallRequest, stream grpc_testing.TestService_StreamingOutputCallServer) error {7}8func (s *testServer) StreamingInputCall(stream grpc_testing.TestService_StreamingInputCallServer) error {9}10func (s *testServer) FullDuplexCall(stream grpc_testing.TestService_FullDuplexCallServer) error {11}12func (s *testServer) HalfDuplexCall(stream grpc_testing.TestService_HalfDuplexCallServer) error {13}14func (s *testServer) UnimplementedCall(ctx context.Context, req *grpc_testing.SimpleRequest) (*grpc_testing.SimpleResponse, error) {15 return nil, status.Errorf(codes.Unimplemented, "unimplemented")16}17func (s *testServer) UnimplementedStreamingCall(stream grpc_testing.TestService_UnimplementedStreamingCallServer) error {18 return status.Errorf(codes.Unimplemented, "unimplemented")19}20func (s *testServer) EmptyCall(ctx context.Context, in *grpc_testing.Empty) (*grpc_testing.Empty, error) {21}22func (s *testServer) Echo(ctx context.Context, req *grpc_testing.SimpleRequest) (*grpc_testing.SimpleResponse, error) {23 return &grpc_testing.SimpleResponse{Payload: &grpc_testing.Payload{Type: req

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())4 if err != nil {5 panic(err)6 }7 defer conn.Close()8 client := grpc_any_testing.NewAnyTestingClient(conn)9 ctx := context.Background()10 request := &grpc_any_testing.Request{11 Message: &any.Any{12 Value: []byte(`{"name": "John Doe"}`),13 },14 }15 response, err := client.String(ctx, request)16 if err != nil {17 s, ok := status.FromError(err)18 if ok && s.Code() == codes.InvalidArgument {19 fmt.Println(s.Message())20 fmt.Println(s.Details())21 } else {22 panic(err)23 }24 } else {25 fmt.Println(response)26 }27}28import (29func main() {30 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())31 if err != nil {32 panic(err)33 }34 defer conn.Close()35 client := grpc_any_testing.NewAnyTestingClient(conn)36 ctx := context.Background()37 request := &grpc_any_testing.Request{38 Message: &any.Any{39 Value: []byte(`{"name": "John Doe"}`),40 },41 }

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())4 if err != nil {5 log.Fatalf("did not connect: %v", err)6 }7 defer conn.Close()8 c := echo_any.NewEchoClient(conn)9 req := &echo.EchoRequest{10 }11 any, err := ptypes.MarshalAny(req)12 if err != nil {13 log.Fatalf("marshal error: %v", err)14 }15 resp, err := c.UnaryEcho(context.Background(), any)16 if err != nil {17 log.Fatalf("could not greet: %v", err)18 }19 fmt.Println(resp)20}21import (22func main() {23 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())24 if err != nil {25 log.Fatalf("did not connect: %v", err)26 }27 defer conn.Close()28 c := echo_any.NewEchoClient(conn)29 req := &echo.EchoRequest{30 }31 any, err := ptypes.MarshalAny(req)32 if err != nil {33 log.Fatalf("marshal error: %v", err)34 }35 resp, err := c.ServerStreamingEcho(context.Background(), any)36 if err != nil {37 log.Fatalf("could not greet: %v", err)38 }39 for {

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 any := any_testing.String("Hello")4 fmt.Println(any)5}6{type_url: "type.googleapis.com/google.protobuf.StringValue" value: "Hello"}

Full Screen

Full Screen

String

Using AI Code Generation

copy

Full Screen

1func main() {2 fmt.Println("Hello World")3 var m = grpc_any_testing.String("Testing")4 fmt.Println(m.String())5}6How to use the String() method in Golang

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful