Best K6 code snippet using grpc_any_testing.init
client_test.go
Source:client_test.go
...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 {...
init
Using AI Code Generation
1import (2var (3func main() {4 lis, err := net.Listen("tcp", ":"+Port)5 if err != nil {6 grpclog.Fatalf("failed to listen: %v", err)7 }8 if TLS {9 if creds, err := credentials.NewServerTLSFromFile("testdata/server1.pem", "testdata/server1.key"); err != nil {10 grpclog.Fatalf("Failed to generate credentials %v", err)11 } else {12 opts = []grpc.ServerOption{grpc.Creds(creds)}13 }14 }15 s := grpc.NewServer(opts...)16 grpc_testing.RegisterTestServiceServer(s, &grpc_any_testing{})17 reflection.Register(s)18 grpclog.Println("Server started")19 if err := s.Serve(lis); err != nil {20 grpclog.Fatalf("failed to serve: %v", err)21 }22}23func init() {24 grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stdout, os.Stdout, os.Stdout))25}26import (27var (
init
Using AI Code Generation
1func main() {2 grpc_any_testing.New()3}4func main() {5 grpc_any_testing.New()6}7func main() {8 grpc_any_testing.New()9}10func main() {11 grpc_any_testing.New()12}13func main() {14 grpc_any_testing.New()15}16func main() {17 grpc_any_testing.New()18}19func main() {20 grpc_any_testing.New()21}22func main() {23 grpc_any_testing.New()24}25func main() {26 grpc_any_testing.New()27}28func main() {29 grpc_any_testing.New()30}31func main() {32 grpc_any_testing.New()33}34func main() {35 grpc_any_testing.New()36}37func main() {38 grpc_any_testing.New()39}40func main() {41 grpc_any_testing.New()42}43func main() {44 grpc_any_testing.New()45}46func main() {47 grpc_any_testing.New()48}49func main() {50 grpc_any_testing.New()51}
init
Using AI Code Generation
1import (2func main() {3 if len(os.Args) > 1 {4 port, _ = strconv.Atoi(os.Args[1])5 }6 lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))7 if err != nil {8 log.Fatalf("failed to listen: %v", err)9 }10 s := grpc.NewServer()11 pb.RegisterAnyTestingServer(s, &server{})12 if err := s.Serve(lis); err != nil {13 log.Fatalf("failed to serve: %v", err)14 }15}16import (17func main() {18 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())19 if err != nil {20 log.Fatalf("did not connect: %v", err)21 }22 defer conn.Close()23 c := pb.NewAnyTestingClient(conn)24 ctx, cancel := context.WithTimeout(context.Background(), time.Second)25 defer cancel()26 r, err := c.TestAny(ctx, &pb.TestAnyRequest{})27 if err != nil {28 log.Fatalf("could not greet: %v", err)29 }30 log.Printf("Greeting: %s", r.GetAny())31}
init
Using AI Code Generation
1import (2func main() {3 conn, err := grpc.Dial("localhost:50052", grpc.WithInsecure())4 if err != nil {5 log.Fatalf("did not connect: %v", err)6 }7 defer conn.Close()8 c := echo.NewEchoClient(conn)9 anyMsg := &echo_any.EchoRequest{10 Value: &wrappers.Int32Value{Value: 123},11 }12 any, err := anypb.New(anyMsg)13 if err != nil {14 log.Fatalf("anypb.New(%v) failed with %v; want success", anyMsg, err)15 }16 ctx, cancel := context.WithTimeout(context.Background(), time.Second)17 defer cancel()18 r, err := c.Echo(ctx, &echo.EchoRequest{Message: any})19 if err != nil {20 log.Fatalf("c.Echo(_) = _, %v; want <nil>", err)21 }22 fmt.Printf("c.Echo(_) = %v23 any2 := &anypb.Any{}24 if err := proto.Unmarshal(r.Message.Value, any2); err != nil {25 log.Fatalf("proto.Unmarshal(%v) failed with %v; want success", r.Message.Value, err)26 }27 anyMsg2 := &echo_any.EchoRequest{}28 if err := anypb.UnmarshalTo(any2, anyMsg2, proto.UnmarshalOptions{}); err != nil {29 log.Fatalf("anypb.UnmarshalTo(%v) failed with %v; want success", any2, err)30 }31 fmt.Printf("anypb.UnmarshalTo(_) = %v32}
init
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello world!")4 grpc_any_testing.Testing()5}6import (7func main() {8 fmt.Println("Hello world!")9 grpc_any_testing.Testing()10}11import (12func main() {13 fmt.Println("Hello world!")14 grpc_any_testing.Testing()15}16import (17func main() {18 fmt.Println("Hello world!")19 grpc_any_testing.Testing()20}21import (22func main() {23 fmt.Println("Hello world!")24 grpc_any_testing.Testing()25}26import (27func main() {28 fmt.Println("Hello world!")29 grpc_any_testing.Testing()30}31import (32func main() {33 fmt.Println("Hello world!")34 grpc_any_testing.Testing()35}36import (37func main() {38 fmt.Println("Hello world!")39 grpc_any_testing.Testing()40}41import (42func main() {43 fmt.Println("Hello world!")44 grpc_any_testing.Testing()45}46import (47func main() {48 fmt.Println("Hello world!")
init
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 grpc_any_testing.Print()5}6import (7func main() {8 fmt.Println("Hello World")9 grpc_any_testing.Print()10}11import (12func main() {13 fmt.Println("Hello World")14 grpc_any_testing.Print()15}16require (
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!