How to use Write method of testutils Package

Best K6 code snippet using testutils.Write

connection_test.go

Source:connection_test.go Github

copy

Full Screen

...87 stack := make([]byte, 4096)88 runtime.Stack(stack, false /* all */)89 h.t.Errorf("testHandler got error: %v stack:\n%s", err, stack)90}91func writeFlushStr(w ArgWriter, d string) error {92 if _, err := io.WriteString(w, d); err != nil {93 return err94 }95 return w.Flush()96}97func isTosPriority(c net.Conn, tosPriority tos.ToS) (bool, error) {98 var connTosPriority int99 var err error100 switch ip := c.RemoteAddr().(*net.TCPAddr).IP; {101 case ip.To16() != nil && ip.To4() == nil:102 connTosPriority, err = ipv6.NewConn(c).TrafficClass()103 case ip.To4() != nil:104 connTosPriority, err = ipv4.NewConn(c).TOS()105 }106 return connTosPriority == int(tosPriority), err107}108func TestRoundTrip(t *testing.T) {109 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {110 handler := newTestHandler(t)111 ts.Register(raw.Wrap(handler), "echo")112 ctx, cancel := NewContext(time.Second)113 defer cancel()114 call, err := ts.Server().BeginCall(ctx, ts.HostPort(), ts.ServiceName(), "echo", &CallOptions{Format: JSON})115 require.NoError(t, err)116 assert.NotEmpty(t, call.RemotePeer().HostPort)117 assert.Equal(t, ts.Server().PeerInfo(), call.LocalPeer(), "Unexpected local peer")118 require.NoError(t, NewArgWriter(call.Arg2Writer()).Write(testArg2))119 require.NoError(t, NewArgWriter(call.Arg3Writer()).Write(testArg3))120 var respArg2 []byte121 require.NoError(t, NewArgReader(call.Response().Arg2Reader()).Read(&respArg2))122 assert.Equal(t, testArg2, []byte(respArg2))123 var respArg3 []byte124 require.NoError(t, NewArgReader(call.Response().Arg3Reader()).Read(&respArg3))125 assert.Equal(t, testArg3, []byte(respArg3))126 assert.Equal(t, JSON, handler.format)127 assert.Equal(t, ts.ServiceName(), handler.caller)128 assert.Equal(t, JSON, call.Response().Format(), "response Format should match request Format")129 })130}131func TestDefaultFormat(t *testing.T) {132 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {133 handler := newTestHandler(t)134 ts.Register(raw.Wrap(handler), "echo")135 ctx, cancel := NewContext(time.Second)136 defer cancel()137 arg2, arg3, resp, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "echo", testArg2, testArg3)138 require.Nil(t, err)139 require.Equal(t, testArg2, arg2)140 require.Equal(t, testArg3, arg3)141 require.Equal(t, Raw, handler.format)142 assert.Equal(t, Raw, resp.Format(), "response Format should match request Format")143 })144}145func TestRemotePeer(t *testing.T) {146 wantVersion := PeerVersion{147 Language: "go",148 LanguageVersion: strings.TrimPrefix(runtime.Version(), "go"),149 TChannelVersion: VersionInfo,150 }151 tests := []struct {152 name string153 remote func(*testutils.TestServer) *Channel154 expectedFn func(*RuntimeState, *testutils.TestServer) PeerInfo155 }{156 {157 name: "ephemeral client",158 remote: func(ts *testutils.TestServer) *Channel { return ts.NewClient(nil) },159 expectedFn: func(state *RuntimeState, ts *testutils.TestServer) PeerInfo {160 return PeerInfo{161 HostPort: state.RootPeers[ts.HostPort()].OutboundConnections[0].LocalHostPort,162 IsEphemeral: true,163 ProcessName: state.LocalPeer.ProcessName,164 Version: wantVersion,165 }166 },167 },168 {169 name: "listening server",170 remote: func(ts *testutils.TestServer) *Channel { return ts.NewServer(nil) },171 expectedFn: func(state *RuntimeState, ts *testutils.TestServer) PeerInfo {172 return PeerInfo{173 HostPort: state.LocalPeer.HostPort,174 IsEphemeral: false,175 ProcessName: state.LocalPeer.ProcessName,176 Version: wantVersion,177 }178 },179 },180 }181 ctx, cancel := NewContext(time.Second)182 defer cancel()183 for _, tt := range tests {184 opts := testutils.NewOpts().SetServiceName("fake-service").NoRelay()185 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {186 remote := tt.remote(ts)187 defer remote.Close()188 gotPeer := make(chan PeerInfo, 1)189 ts.RegisterFunc("test", func(ctx context.Context, args *raw.Args) (*raw.Res, error) {190 gotPeer <- CurrentCall(ctx).RemotePeer()191 assert.Equal(t, ts.Server().PeerInfo(), CurrentCall(ctx).LocalPeer())192 return &raw.Res{}, nil193 })194 _, _, _, err := raw.Call(ctx, remote, ts.HostPort(), ts.Server().ServiceName(), "test", nil, nil)195 assert.NoError(t, err, "%v: Call failed", tt.name)196 expected := tt.expectedFn(remote.IntrospectState(nil), ts)197 assert.Equal(t, expected, <-gotPeer, "%v: RemotePeer mismatch", tt.name)198 })199 }200}201func TestReuseConnection(t *testing.T) {202 ctx, cancel := NewContext(time.Second)203 defer cancel()204 // Since we're specifically testing that connections between hosts are re-used,205 // we can't interpose a relay in this test.206 s1Opts := testutils.NewOpts().SetServiceName("s1").NoRelay()207 testutils.WithTestServer(t, s1Opts, func(ts *testutils.TestServer) {208 ch2 := ts.NewServer(&testutils.ChannelOpts{ServiceName: "s2"})209 hostPort2 := ch2.PeerInfo().HostPort210 defer ch2.Close()211 ts.Register(raw.Wrap(newTestHandler(t)), "echo")212 ch2.Register(raw.Wrap(newTestHandler(t)), "echo")213 outbound, err := ts.Server().BeginCall(ctx, hostPort2, "s2", "echo", nil)214 require.NoError(t, err)215 outboundConn, outboundNetConn := OutboundConnection(outbound)216 // Try to make another call at the same time, should reuse the same connection.217 outbound2, err := ts.Server().BeginCall(ctx, hostPort2, "s2", "echo", nil)218 require.NoError(t, err)219 outbound2Conn, _ := OutboundConnection(outbound)220 assert.Equal(t, outboundConn, outbound2Conn)221 // Wait for the connection to be marked as active in ch2.222 assert.True(t, testutils.WaitFor(time.Second, func() bool {223 return ch2.IntrospectState(nil).NumConnections > 0224 }), "ch2 does not have any active connections")225 // When ch2 tries to call the test server, it should reuse the existing226 // inbound connection the test server. Of course, this only works if the227 // test server -> ch2 call wasn't relayed.228 outbound3, err := ch2.BeginCall(ctx, ts.HostPort(), "s1", "echo", nil)229 require.NoError(t, err)230 _, outbound3NetConn := OutboundConnection(outbound3)231 assert.Equal(t, outboundNetConn.RemoteAddr(), outbound3NetConn.LocalAddr())232 assert.Equal(t, outboundNetConn.LocalAddr(), outbound3NetConn.RemoteAddr())233 // Ensure all calls can complete in parallel.234 var wg sync.WaitGroup235 for _, call := range []*OutboundCall{outbound, outbound2, outbound3} {236 wg.Add(1)237 go func(call *OutboundCall) {238 defer wg.Done()239 resp1, resp2, _, err := raw.WriteArgs(call, []byte("arg2"), []byte("arg3"))240 require.NoError(t, err)241 assert.Equal(t, resp1, []byte("arg2"), "result does match argument")242 assert.Equal(t, resp2, []byte("arg3"), "result does match argument")243 }(call)244 }245 wg.Wait()246 })247}248func TestPing(t *testing.T) {249 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {250 ctx, cancel := NewContext(time.Second)251 defer cancel()252 clientCh := ts.NewClient(nil)253 defer clientCh.Close()254 require.NoError(t, clientCh.Ping(ctx, ts.HostPort()))255 })256}257func TestBadRequest(t *testing.T) {258 // ch will log an error when it receives a request for an unknown handler.259 opts := testutils.NewOpts().AddLogFilter("Couldn't find handler.", 1)260 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {261 ctx, cancel := NewContext(time.Second)262 defer cancel()263 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "Noone", []byte("Headers"), []byte("Body"))264 require.NotNil(t, err)265 assert.Equal(t, ErrCodeBadRequest, GetSystemErrorCode(err))266 calls := relaytest.NewMockStats()267 calls.Add(ts.ServiceName(), ts.ServiceName(), "Noone").Failed("bad-request").End()268 ts.AssertRelayStats(calls)269 })270}271func TestNoTimeout(t *testing.T) {272 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {273 ts.Register(raw.Wrap(newTestHandler(t)), "Echo")274 ctx := context.Background()275 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), "svc", "Echo", []byte("Headers"), []byte("Body"))276 assert.Equal(t, ErrTimeoutRequired, err)277 ts.AssertRelayStats(relaytest.NewMockStats())278 })279}280func TestCancelled(t *testing.T) {281 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {282 ts.Register(raw.Wrap(newTestHandler(t)), "echo")283 ctx, cancel := NewContext(time.Second)284 // Make a call first to make sure we have a connection.285 // We want to test the BeginCall path.286 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "echo", []byte("Headers"), []byte("Body"))287 assert.NoError(t, err, "Call failed")288 // Now cancel the context.289 cancel()290 _, _, _, err = raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "echo", []byte("Headers"), []byte("Body"))291 assert.Equal(t, ErrRequestCancelled, err, "Unexpected error when making call with canceled context")292 })293}294func TestNoServiceNaming(t *testing.T) {295 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {296 ctx, cancel := NewContext(time.Second)297 defer cancel()298 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), "", "Echo", []byte("Headers"), []byte("Body"))299 assert.Equal(t, ErrNoServiceName, err)300 ts.AssertRelayStats(relaytest.NewMockStats())301 })302}303func TestServerBusy(t *testing.T) {304 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {305 ts.Register(ErrorHandlerFunc(func(ctx context.Context, call *InboundCall) error {306 if _, err := raw.ReadArgs(call); err != nil {307 return err308 }309 return ErrServerBusy310 }), "busy")311 ctx, cancel := NewContext(time.Second)312 defer cancel()313 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "busy", []byte("Arg2"), []byte("Arg3"))314 require.NotNil(t, err)315 assert.Equal(t, ErrCodeBusy, GetSystemErrorCode(err), "err: %v", err)316 calls := relaytest.NewMockStats()317 calls.Add(ts.ServiceName(), ts.ServiceName(), "busy").Failed("busy").End()318 ts.AssertRelayStats(calls)319 })320}321func TestUnexpectedHandlerError(t *testing.T) {322 opts := testutils.NewOpts().323 AddLogFilter("Unexpected handler error", 1)324 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {325 ts.Register(ErrorHandlerFunc(func(ctx context.Context, call *InboundCall) error {326 if _, err := raw.ReadArgs(call); err != nil {327 return err328 }329 return fmt.Errorf("nope")330 }), "nope")331 ctx, cancel := NewContext(time.Second)332 defer cancel()333 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "nope", []byte("Arg2"), []byte("Arg3"))334 require.NotNil(t, err)335 assert.Equal(t, ErrCodeUnexpected, GetSystemErrorCode(err), "err: %v", err)336 calls := relaytest.NewMockStats()337 calls.Add(ts.ServiceName(), ts.ServiceName(), "nope").Failed("unexpected-error").End()338 ts.AssertRelayStats(calls)339 })340}341type onErrorTestHandler struct {342 *testHandler343 onError func(ctx context.Context, err error)344}345func (h onErrorTestHandler) OnError(ctx context.Context, err error) {346 h.onError(ctx, err)347}348func TestTimeout(t *testing.T) {349 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {350 // onError may be called when the block call tries to write the call response.351 onError := func(ctx context.Context, err error) {352 assert.Equal(t, ErrTimeout, err, "onError err should be ErrTimeout")353 assert.Equal(t, context.DeadlineExceeded, ctx.Err(), "Context should timeout")354 }355 testHandler := onErrorTestHandler{newTestHandler(t), onError}356 ts.Register(raw.Wrap(testHandler), "block")357 ctx, cancel := NewContext(testutils.Timeout(15 * time.Millisecond))358 defer cancel()359 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "block", []byte("Arg2"), []byte("Arg3"))360 assert.Equal(t, ErrTimeout, err)361 // Verify the server-side receives an error from the context.362 select {363 case err := <-testHandler.blockErr:364 assert.Equal(t, context.DeadlineExceeded, err, "Server should have received timeout")365 case <-time.After(time.Second):366 t.Errorf("Server did not receive call, may need higher timeout")367 }368 calls := relaytest.NewMockStats()369 calls.Add(ts.ServiceName(), ts.ServiceName(), "block").Failed("timeout").End()370 ts.AssertRelayStats(calls)371 })372}373func TestLargeMethod(t *testing.T) {374 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {375 ctx, cancel := NewContext(time.Second)376 defer cancel()377 largeMethod := testutils.RandBytes(16*1024 + 1)378 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), string(largeMethod), nil, nil)379 assert.Equal(t, ErrMethodTooLarge, err)380 })381}382func TestLargeTimeout(t *testing.T) {383 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {384 ts.Register(raw.Wrap(newTestHandler(t)), "echo")385 ctx, cancel := NewContext(1000 * time.Second)386 defer cancel()387 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "echo", testArg2, testArg3)388 assert.NoError(t, err, "Call failed")389 calls := relaytest.NewMockStats()390 calls.Add(ts.ServiceName(), ts.ServiceName(), "echo").Succeeded().End()391 ts.AssertRelayStats(calls)392 })393}394func TestFragmentation(t *testing.T) {395 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {396 ts.Register(raw.Wrap(newTestHandler(t)), "echo")397 arg2 := make([]byte, MaxFramePayloadSize*2)398 for i := 0; i < len(arg2); i++ {399 arg2[i] = byte('a' + (i % 10))400 }401 arg3 := make([]byte, MaxFramePayloadSize*3)402 for i := 0; i < len(arg3); i++ {403 arg3[i] = byte('A' + (i % 10))404 }405 ctx, cancel := NewContext(time.Second)406 defer cancel()407 respArg2, respArg3, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "echo", arg2, arg3)408 require.NoError(t, err)409 assert.Equal(t, arg2, respArg2)410 assert.Equal(t, arg3, respArg3)411 calls := relaytest.NewMockStats()412 calls.Add(ts.ServiceName(), ts.ServiceName(), "echo").Succeeded().End()413 ts.AssertRelayStats(calls)414 })415}416func TestFragmentationSlowReader(t *testing.T) {417 // Inbound forward will timeout and cause a warning log.418 opts := testutils.NewOpts().419 AddLogFilter("Unable to forward frame", 1).420 AddLogFilter("Connection error", 1)421 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {422 startReading, handlerComplete := make(chan struct{}), make(chan struct{})423 handler := func(ctx context.Context, call *InboundCall) {424 <-startReading425 <-ctx.Done()426 _, err := raw.ReadArgs(call)427 assert.Error(t, err, "ReadArgs should fail since frames will be dropped due to slow reading")428 close(handlerComplete)429 }430 ts.Register(HandlerFunc(handler), "echo")431 arg2 := testutils.RandBytes(MaxFramePayloadSize * MexChannelBufferSize)432 arg3 := testutils.RandBytes(MaxFramePayloadSize * (MexChannelBufferSize + 1))433 ctx, cancel := NewContext(testutils.Timeout(30 * time.Millisecond))434 defer cancel()435 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "echo", arg2, arg3)436 assert.Error(t, err, "Call should timeout due to slow reader")437 close(startReading)438 select {439 case <-handlerComplete:440 case <-time.After(testutils.Timeout(70 * time.Millisecond)):441 t.Errorf("Handler not called, context timeout may be too low")442 }443 calls := relaytest.NewMockStats()444 calls.Add(ts.ServiceName(), ts.ServiceName(), "echo").Failed("timeout").End()445 ts.AssertRelayStats(calls)446 })447}448func TestWriteArg3AfterTimeout(t *testing.T) {449 // The channel reads and writes during timeouts, causing warning logs.450 opts := testutils.NewOpts().DisableLogVerification()451 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {452 timedOut := make(chan struct{})453 handler := func(ctx context.Context, call *InboundCall) {454 _, err := raw.ReadArgs(call)455 assert.NoError(t, err, "Read args failed")456 response := call.Response()457 assert.NoError(t, NewArgWriter(response.Arg2Writer()).Write(nil), "Write Arg2 failed")458 writer, err := response.Arg3Writer()459 assert.NoError(t, err, "Arg3Writer failed")460 for {461 if _, err := writer.Write(testutils.RandBytes(4)); err != nil {462 assert.Equal(t, err, ErrTimeout, "Handler should timeout")463 close(timedOut)464 return465 }466 runtime.Gosched()467 }468 }469 ts.Register(HandlerFunc(handler), "call")470 ctx, cancel := NewContext(testutils.Timeout(100 * time.Millisecond))471 defer cancel()472 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "call", nil, nil)473 assert.Equal(t, err, ErrTimeout, "Call should timeout")474 // Wait for the write to complete, make sure there are no errors.475 select {476 case <-time.After(testutils.Timeout(60 * time.Millisecond)):477 t.Errorf("Handler should have failed due to timeout")478 case <-timedOut:479 }480 calls := relaytest.NewMockStats()481 calls.Add(ts.ServiceName(), ts.ServiceName(), "call").Failed("timeout").Succeeded().End()482 ts.AssertRelayStats(calls)483 })484}485func TestWriteErrorAfterTimeout(t *testing.T) {486 // TODO: Make this test block at different points (e.g. before, during read/write).487 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {488 timedOut := make(chan struct{})489 done := make(chan struct{})490 handler := func(ctx context.Context, call *InboundCall) {491 <-ctx.Done()492 <-timedOut493 _, err := raw.ReadArgs(call)494 assert.Equal(t, ErrTimeout, err, "Read args should fail with timeout")495 response := call.Response()496 assert.Equal(t, ErrTimeout, response.SendSystemError(ErrServerBusy), "SendSystemError should fail")497 close(done)498 }499 ts.Register(HandlerFunc(handler), "call")500 ctx, cancel := NewContext(testutils.Timeout(30 * time.Millisecond))501 defer cancel()502 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "call", nil, testutils.RandBytes(100000))503 assert.Equal(t, err, ErrTimeout, "Call should timeout")504 close(timedOut)505 select {506 case <-done:507 case <-time.After(time.Second):508 t.Errorf("Handler not called, timeout may be too low")509 }510 calls := relaytest.NewMockStats()511 calls.Add(ts.ServiceName(), ts.ServiceName(), "call").Failed("timeout").End()512 ts.AssertRelayStats(calls)513 })514}515func TestWriteAfterConnectionError(t *testing.T) {516 ctx, cancel := NewContext(time.Second)517 defer cancel()518 // Closing network connections can lead to warnings in many places.519 // TODO: Relay is disabled due to https://github.com/uber/tchannel-go/issues/390520 // Enabling relay causes the test to be flaky.521 opts := testutils.NewOpts().DisableLogVerification().NoRelay()522 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {523 testutils.RegisterEcho(ts.Server(), nil)524 server := ts.Server()525 call, err := server.BeginCall(ctx, ts.HostPort(), server.ServiceName(), "echo", nil)526 require.NoError(t, err, "Call failed")527 w, err := call.Arg2Writer()528 require.NoError(t, err, "Arg2Writer failed")529 require.NoError(t, writeFlushStr(w, "initial"), "write initial failed")530 // Now close the underlying network connection, writes should fail.531 _, conn := OutboundConnection(call)532 conn.Close()533 // Writes should start failing pretty soon.534 var writeErr error535 for i := 0; i < 100; i++ {536 if writeErr = writeFlushStr(w, "f"); writeErr != nil {537 break538 }539 time.Sleep(time.Millisecond)540 }541 if assert.Error(t, writeErr, "Writes should fail after a connection is closed") {542 assert.Equal(t, ErrCodeNetwork, GetSystemErrorCode(writeErr), "write should fail due to network error")543 }544 })545}546func TestReadTimeout(t *testing.T) {547 // The error frame may fail to send since the connection closes before the handler sends it548 // or the handler connection may be closed as it sends when the other side closes the conn.549 opts := testutils.NewOpts().550 AddLogFilter("Couldn't send outbound error frame", 1).551 AddLogFilter("Connection error", 1, "site", "read frames").552 AddLogFilter("Connection error", 1, "site", "write frames").553 AddLogFilter("simpleHandler OnError", 1,554 "error", "failed to send error frame, connection state connectionClosed")555 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {556 sn := ts.ServiceName()557 calls := relaytest.NewMockStats()558 for i := 0; i < 10; i++ {559 ctx, cancel := NewContext(time.Second)560 handler := func(ctx context.Context, args *raw.Args) (*raw.Res, error) {561 defer cancel()562 return nil, ErrRequestCancelled563 }564 ts.RegisterFunc("call", handler)565 _, _, _, err := raw.Call(ctx, ts.Server(), ts.HostPort(), ts.ServiceName(), "call", nil, nil)566 assert.Equal(t, err, ErrRequestCancelled, "Call should fail due to cancel")567 calls.Add(sn, sn, "call").Failed("cancelled").End()568 }569 ts.AssertRelayStats(calls)570 })571}572func TestWriteTimeout(t *testing.T) {573 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {574 ch := ts.Server()575 ctx, cancel := NewContext(testutils.Timeout(15 * time.Millisecond))576 defer cancel()577 call, err := ch.BeginCall(ctx, ts.HostPort(), ch.ServiceName(), "call", nil)578 require.NoError(t, err, "Call failed")579 writer, err := call.Arg2Writer()580 require.NoError(t, err, "Arg2Writer failed")581 _, err = writer.Write([]byte{1})582 require.NoError(t, err, "Write initial bytes failed")583 <-ctx.Done()584 _, err = io.Copy(writer, testreader.Looper([]byte{1}))585 assert.Equal(t, ErrTimeout, err, "Write should fail with timeout")586 ts.AssertRelayStats(relaytest.NewMockStats())587 })588}589func TestGracefulClose(t *testing.T) {590 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {591 ch2 := ts.NewServer(nil)592 hp2 := ch2.PeerInfo().HostPort593 defer ch2.Close()594 ctx, cancel := NewContext(time.Second)595 defer cancel()596 assert.NoError(t, ts.Server().Ping(ctx, hp2), "Ping from ch1 -> ch2 failed")597 assert.NoError(t, ch2.Ping(ctx, ts.HostPort()), "Ping from ch2 -> ch1 failed")598 // No stats for pings.599 ts.AssertRelayStats(relaytest.NewMockStats())600 })601}602func TestNetDialTimeout(t *testing.T) {603 // timeoutHostPort uses a blackholed address (RFC 6890) with a port604 // reserved for documentation. This address should always cause a timeout.605 const timeoutHostPort = "192.18.0.254:44444"606 timeoutPeriod := testutils.Timeout(50 * time.Millisecond)607 client := testutils.NewClient(t, nil)608 defer client.Close()609 started := time.Now()610 ctx, cancel := NewContext(timeoutPeriod)611 defer cancel()612 err := client.Ping(ctx, timeoutHostPort)613 if !assert.Error(t, err, "Ping to blackhole address should fail") {614 return615 }616 if strings.Contains(err.Error(), "network is unreachable") {617 t.Skipf("Skipping test, as network interface may not be available")618 }619 d := time.Since(started)620 assert.Equal(t, ErrTimeout, err, "Ping expected to fail with timeout")621 assert.True(t, d >= timeoutPeriod, "Timeout should take more than %v, took %v", timeoutPeriod, d)622}623func TestConnectTimeout(t *testing.T) {624 opts := testutils.NewOpts().DisableLogVerification()625 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {626 // Set up a relay that will delay the initial init req.627 testComplete := make(chan struct{})628 relayFunc := func(outgoing bool, f *Frame) *Frame {629 select {630 case <-time.After(testutils.Timeout(200 * time.Millisecond)):631 return f632 case <-testComplete:633 // TODO: We should be able to forward the frame and have this test not fail.634 // Currently, it fails since the sequence of events is:635 // Server receives a TCP connection636 // Channel.Close() is called on the server637 // Server's TCP connection receives an init req638 // Since we don't currently track pending connections, the open TCP connection is not closed, and639 // we process the init req. This leaves an open connection at the end of the test.640 return nil641 }642 }643 relay, shutdown := testutils.FrameRelay(t, ts.HostPort(), relayFunc)644 defer shutdown()645 // Make a call with a long timeout, but short connect timeout.646 // We expect the call to fall almost immediately with ErrTimeout.647 ctx, cancel := NewContextBuilder(2 * time.Second).648 SetConnectTimeout(testutils.Timeout(100 * time.Millisecond)).649 Build()650 defer cancel()651 client := ts.NewClient(opts)652 err := client.Ping(ctx, relay)653 assert.Equal(t, ErrTimeout, err, "Ping should timeout due to timeout relay")654 // Note: we do not defer this, as we need to close(testComplete) before655 // we call shutdown since shutdown waits for the relay to close, which656 // is stuck waiting inside of our custom relay function.657 close(testComplete)658 })659}660func TestParallelConnectionAccepts(t *testing.T) {661 opts := testutils.NewOpts().AddLogFilter("Failed during connection handshake", 1)662 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {663 testutils.RegisterEcho(ts.Server(), nil)664 // Start a connection attempt that should timeout.665 conn, err := net.Dial("tcp", ts.HostPort())666 defer conn.Close()667 require.NoError(t, err, "Dial failed")668 // When we try to make a call using a new client, it will require a669 // new connection, and this verifies that the previous connection attempt670 // and handshake do not impact the call.671 client := ts.NewClient(nil)672 testutils.AssertEcho(t, client, ts.HostPort(), ts.ServiceName())673 })674}675func TestConnectionIDs(t *testing.T) {676 testutils.WithTestServer(t, nil, func(ts *testutils.TestServer) {677 var inbound, outbound []uint32678 relayFunc := func(outgoing bool, f *Frame) *Frame {679 if outgoing {680 outbound = append(outbound, f.Header.ID)681 } else {682 inbound = append(inbound, f.Header.ID)683 }684 return f685 }686 relay, shutdown := testutils.FrameRelay(t, ts.HostPort(), relayFunc)687 defer shutdown()688 ctx, cancel := NewContext(time.Second)689 defer cancel()690 s2 := ts.NewServer(nil)691 require.NoError(t, s2.Ping(ctx, relay), "Ping failed")692 assert.Equal(t, []uint32{1, 2}, outbound, "Unexpected outbound IDs")693 assert.Equal(t, []uint32{1, 2}, inbound, "Unexpected outbound IDs")694 // We want to reuse the same connection for the rest of the test which695 // only makes sense when the relay is not used.696 if ts.Relay() != nil {697 return698 }699 inbound = nil700 outbound = nil701 // We will reuse the inbound connection, but since the inbound connection702 // hasn't originated any outbound requests, we'll use id 1.703 require.NoError(t, ts.Server().Ping(ctx, s2.PeerInfo().HostPort), "Ping failed")704 assert.Equal(t, []uint32{1}, outbound, "Unexpected outbound IDs")705 assert.Equal(t, []uint32{1}, inbound, "Unexpected outbound IDs")706 })707}708func TestTosPriority(t *testing.T) {709 ctx, cancel := NewContext(time.Second)710 defer cancel()711 opts := testutils.NewOpts().SetServiceName("s1").SetTosPriority(tos.Lowdelay)712 testutils.WithTestServer(t, opts, func(ts *testutils.TestServer) {713 ts.Register(raw.Wrap(newTestHandler(t)), "echo")714 outbound, err := ts.Server().BeginCall(ctx, ts.HostPort(), "s1", "echo", nil)715 require.NoError(t, err, "BeginCall failed")716 _, outboundNetConn := OutboundConnection(outbound)717 connTosPriority, err := isTosPriority(outboundNetConn, tos.Lowdelay)718 require.NoError(t, err, "Checking TOS priority failed")719 assert.Equal(t, connTosPriority, true)720 _, _, _, err = raw.WriteArgs(outbound, []byte("arg2"), []byte("arg3"))721 require.NoError(t, err, "Failed to write to outbound conn")722 })723}724func TestPeerStatusChangeClientReduction(t *testing.T) {725 sopts := testutils.NewOpts().NoRelay()726 testutils.WithTestServer(t, sopts, func(ts *testutils.TestServer) {727 server := ts.Server()728 testutils.RegisterEcho(server, nil)729 changes := make(chan int, 2)730 copts := testutils.NewOpts().SetOnPeerStatusChanged(func(p *Peer) {731 i, o := p.NumConnections()732 assert.Equal(t, 0, i, "no inbound connections to client")733 changes <- o734 })...

Full Screen

Full Screen

config_test.go

Source:config_test.go Github

copy

Full Screen

...44func (s *ConfigSuite) TearDownTest(c *C) {45 node.SetInternalIPv4Router(nil)46 node.SetIPv4Loopback(nil)47}48type badWriter struct{}49func (b *badWriter) Write(p []byte) (int, error) {50 return 0, errors.New("bad write :(")51}52type writeFn func(io.Writer, datapath.ConfigWriter) error53func writeConfig(c *C, header string, write writeFn) {54 tests := []struct {55 description string56 output io.Writer57 expResult Checker58 }{59 {60 description: "successful write to an in-memory buffer",61 output: &bytes.Buffer{},62 expResult: IsNil,63 },64 {65 description: "write to a failing writer",66 output: &badWriter{},67 expResult: NotNil,68 },69 }70 for _, test := range tests {71 c.Logf(" Testing %s configuration: %s", header, test.description)72 cfg := &HeaderfileWriter{}73 c.Assert(write(test.output, cfg), test.expResult)74 }75}76func (s *ConfigSuite) TestWriteNodeConfig(c *C) {77 writeConfig(c, "node", func(w io.Writer, dp datapath.ConfigWriter) error {78 return dp.WriteNodeConfig(w, &dummyNodeCfg)79 })80}81func (s *ConfigSuite) TestWriteNetdevConfig(c *C) {82 writeConfig(c, "netdev", func(w io.Writer, dp datapath.ConfigWriter) error {83 return dp.WriteNetdevConfig(w, &dummyDevCfg)84 })85}86func (s *ConfigSuite) TestWriteEndpointConfig(c *C) {87 writeConfig(c, "endpoint", func(w io.Writer, dp datapath.ConfigWriter) error {88 return dp.WriteEndpointConfig(w, &dummyEPCfg)89 })90 // Create copy of config option so that it can be restored at the end of91 // this test. In the future, we'd like to parallelize running unit tests.92 // As it stands, this test would not be ready to parallelize until we93 // remove our dependency on globals (e.g. option.Config).94 oldEnableIPv6 := option.Config.EnableIPv695 defer func() {96 option.Config.EnableIPv6 = oldEnableIPv697 }()98 testRun := func(t *testutils.TestEndpoint) ([]byte, map[string]uint32, map[string]string) {99 cfg := &HeaderfileWriter{}100 varSub, stringSub := loader.ELFSubstitutions(t)101 var buf bytes.Buffer102 cfg.writeStaticData(&buf, t)103 return buf.Bytes(), varSub, stringSub104 }105 lxcIPs := []string{"LXC_IP_1", "LXC_IP_2", "LXC_IP_3", "LXC_IP_4"}106 tests := []struct {107 description string108 template testutils.TestEndpoint // Represents template bpf prog109 endpoint testutils.TestEndpoint // Represents normal endpoint bpf prog110 preTestRun func(t *testutils.TestEndpoint, e *testutils.TestEndpoint)111 templateExp bool112 endpointExp bool113 }{114 {115 description: "IPv6 is disabled, endpoint does not have an IPv6 addr",116 template: testutils.NewTestEndpoint(),117 endpoint: testutils.NewTestEndpoint(),118 preTestRun: func(t *testutils.TestEndpoint, e *testutils.TestEndpoint) {119 option.Config.EnableIPv6 = false120 t.IPv6 = ipv6DummyAddr // Template bpf prog always has dummy IPv6121 e.IPv6 = nil // This endpoint does not have an IPv6 addr122 },123 templateExp: true,124 endpointExp: false,125 },126 {127 description: "IPv6 is disabled, endpoint does have an IPv6 addr",128 template: testutils.NewTestEndpoint(),129 endpoint: testutils.NewTestEndpoint(),130 preTestRun: func(t *testutils.TestEndpoint, e *testutils.TestEndpoint) {131 option.Config.EnableIPv6 = false132 t.IPv6 = ipv6DummyAddr // Template bpf prog always has dummy IPv6133 e.IPv6 = ipv6DummyAddr // This endpoint does have an IPv6 addr134 },135 templateExp: true,136 endpointExp: true,137 },138 {139 description: "IPv6 is enabled",140 template: testutils.NewTestEndpoint(),141 endpoint: testutils.NewTestEndpoint(),142 preTestRun: func(t *testutils.TestEndpoint, e *testutils.TestEndpoint) {143 option.Config.EnableIPv6 = true144 t.IPv6 = ipv6DummyAddr145 e.IPv6 = ipv6DummyAddr146 },147 templateExp: true,148 endpointExp: true,149 },150 {151 description: "IPv6 is enabled, endpoint does not have IPv6 address",152 template: testutils.NewTestEndpoint(),153 endpoint: testutils.NewTestEndpoint(),154 preTestRun: func(t *testutils.TestEndpoint, e *testutils.TestEndpoint) {155 option.Config.EnableIPv6 = true156 t.IPv6 = ipv6DummyAddr157 e.IPv6 = nil158 },159 templateExp: true,160 endpointExp: false,161 },162 }163 for _, test := range tests {164 c.Logf("Testing %s", test.description)165 test.preTestRun(&test.template, &test.endpoint)166 b, vsub, _ := testRun(&test.template)167 c.Assert(bytes.Contains(b, []byte("DEFINE_IPV6")), Equals, test.templateExp)168 assertKeysInsideMap(c, vsub, lxcIPs, test.templateExp)169 b, vsub, _ = testRun(&test.endpoint)170 c.Assert(bytes.Contains(b, []byte("DEFINE_IPV6")), Equals, test.endpointExp)171 assertKeysInsideMap(c, vsub, lxcIPs, test.endpointExp)172 }173}174func (s *ConfigSuite) TestWriteStaticData(c *C) {175 cfg := &HeaderfileWriter{}176 ep := &dummyEPCfg177 varSub, stringSub := loader.ELFSubstitutions(ep)178 var buf bytes.Buffer179 cfg.writeStaticData(&buf, ep)180 b := buf.Bytes()181 for k := range varSub {182 for _, suffix := range []string{"_1", "_2", "_3", "_4"} {183 // Variables with these suffixes are implemented via184 // multiple 32-bit values. The header define doesn't185 // include these numbers though, so strip them.186 if strings.HasSuffix(k, suffix) {187 k = strings.TrimSuffix(k, suffix)188 break189 }...

Full Screen

Full Screen

packetcoder_test.go

Source:packetcoder_test.go Github

copy

Full Screen

...11 scheme.AddBitField("type", 8)12 scheme.AddStuffBits("fill", 4)13 scheme.AddBitField("crc", 8)14 packet.SetScheme(scheme)15 packet.WriteValue64("head", 5)16 packet.WriteValue64("type", 105)17 packet.WriteStuff("fill")18 packet.WriteValue64("crc", 99)19 buf := bytes.NewBuffer(nil)20 packet.EncodeTo(buf)21 testutils.ASSERT_EQ(t, len(buf.Bytes()), 3)22 testutils.ASSERT_U_EQ(t, uint(buf.Bytes()[0]), 86)23 testutils.ASSERT_U_EQ(t, uint(buf.Bytes()[1]), 144)24 testutils.ASSERT_U_EQ(t, uint(buf.Bytes()[2]), 99)25}26func TestPacketDecode(t *testing.T) {27 packet := new(Packet)28 scheme := NewBitScheme("test")29 scheme.AddBitField("head", 4)30 scheme.AddBitField("type", 8)31 scheme.AddStuffBits("fill", 4)32 scheme.AddBitField("crc", 8)33 packet.SetScheme(scheme)34 buf := bytes.NewBuffer([]byte{86, 144, 99, 86, 144, 140, 86, 144})35 // decode first packet36 _, err := packet.DecodeFrom(buf)37 value, _ := packet.ReadValue64("head")38 testutils.ASSERT_U64_EQ(t, value, 5)39 value, _ = packet.ReadValue64("type")40 testutils.ASSERT_U64_EQ(t, value, 105)41 value, _ = packet.ReadValue64("crc")42 testutils.ASSERT_U64_EQ(t, value, 99)43 // decode second packet44 _, err = packet.DecodeFrom(buf)45 value, _ = packet.ReadValue64("head")46 testutils.ASSERT_U64_EQ(t, value, 5)47 value, _ = packet.ReadValue64("type")48 testutils.ASSERT_U64_EQ(t, value, 105)49 value, _ = packet.ReadValue64("crc")50 testutils.ASSERT_U64_EQ(t, value, 140)51 //decode remainder and we should get error, because sizeInBits of packet more sizeInBits of buffer52 _, err = packet.DecodeFrom(buf)53 testutils.ASSERT_TRUE(t, err != nil)54}55func GetTestBitScheme() *BitScheme {56 scheme := NewBitScheme("testBits")57 scheme.AddBitField("head", 4)58 scheme.AddBitField("type", 8)59 scheme.AddByteField("data", 10)60 scheme.AddStuffBits("fill", 4)61 return scheme62}63func TestSchemeBitSize(t *testing.T) {64 scheme := GetTestBitScheme()65 var size uint66 size = scheme.BitSize()67 testutils.ASSERT_U_EQ(t, size, 96)68 scheme.AddBitField("crc", 8)69 size = scheme.BitSize()70 testutils.ASSERT_U_EQ(t, size, 104)71 size = 072 for _, field := range scheme.fields {73 size += field.bitSize()74 }75 testutils.ASSERT_U_EQ(t, size, scheme.BitSize())76}77func TestBitAndByteSize(t *testing.T) {78 scheme := GetTestBitScheme()79 var size uint80 size, _ = scheme.BitSizeOf("data")81 testutils.ASSERT_U_EQ(t, size, 80)82 size, _ = scheme.ByteSizeOf("data")83 testutils.ASSERT_U_EQ(t, size, 10)84}85func TestSchemeFieldsOffset(t *testing.T) {86 scheme := GetTestBitScheme()87 scheme.AddBitField("crc", 8)88 offset, _ := scheme.OffsetOf("type")89 testutils.ASSERT_U_EQ(t, offset, 4)90 offset, _ = scheme.OffsetOf("data")91 testutils.ASSERT_U_EQ(t, offset, 12)92 offset, _ = scheme.OffsetOf("crc")93 testutils.ASSERT_U_EQ(t, offset, 96)94}95func TestPacketFieldValue64(t *testing.T) {96 packet := NewPacket()97 scheme := NewBitScheme("test")98 scheme.AddBitField("head", 4)99 scheme.AddBitField("type", 8)100 scheme.AddStuffBits("fill", 4)101 scheme.AddBitField("bigEndian", 32)102 scheme.AddBitFieldLittleEndian("littleEndian", 32)103 scheme.AddBitField("crc", 8)104 packet.SetScheme(scheme)105 packet.WriteValue64("head", 5)106 packet.WriteValue64("type", 105)107 packet.WriteStuff("fill")108 packet.WriteValue64("bigEndian", 0x01234567)109 packet.WriteValue64("littleEndian", 0x01234567)110 packet.WriteValue64("crc", 99)111 //test big endian112 bytes := packet.GetData().Bytes()113 testutils.ASSERT_BYTE_EQ(t, bytes[2], 0x01)114 testutils.ASSERT_BYTE_EQ(t, bytes[3], 0x23)115 testutils.ASSERT_BYTE_EQ(t, bytes[4], 0x45)116 testutils.ASSERT_BYTE_EQ(t, bytes[5], 0x67)117 //test little endian118 testutils.ASSERT_BYTE_EQ(t, bytes[6], 0x67)119 testutils.ASSERT_BYTE_EQ(t, bytes[7], 0x45)120 testutils.ASSERT_BYTE_EQ(t, bytes[8], 0x23)121 testutils.ASSERT_BYTE_EQ(t, bytes[9], 0x01)122 value, _ := packet.ReadValue64("head")123 testutils.ASSERT_U64_EQ(t, value, 5)124 value, _ = packet.ReadValue64("type")125 testutils.ASSERT_U64_EQ(t, value, 105)126 value, _ = packet.ReadValue64("bigEndian")127 testutils.ASSERT_U64_EQ(t, value, 0x01234567)128 value, _ = packet.ReadValue64("littleEndian")129 testutils.ASSERT_U64_EQ(t, value, 0x01234567)130 value, _ = packet.ReadValue64("crc")131 testutils.ASSERT_U64_EQ(t, value, 99)132}133func TestPacketFieldBytesValue(t *testing.T) {134 packet := NewPacket()135 scheme := GetTestBitScheme()136 scheme.AddByteFieldLittleEndian("littleEndian", 5)137 scheme.AddBitField("crc", 8)138 packet.SetScheme(scheme)139 packet.WriteValue64("head", 0x05)140 packet.WriteValue64("type", 0x69)141 packet.WriteBytes("data", []byte{0x01, 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89, 0xAB})142 packet.WriteStuff("fill")143 packet.WriteBytes("littleEndian", []byte{0x56, 0x67, 0x78, 0x89, 0xAB})144 packet.WriteValue64("crc", 99)145 bytes := packet.GetData().Bytes()146 testutils.ASSERT_BYTE_EQ(t, bytes[0], 0x56)147 testutils.ASSERT_BYTE_EQ(t, bytes[1], 0x90)148 testutils.ASSERT_BYTE_EQ(t, bytes[2], 0x11)149 testutils.ASSERT_BYTE_EQ(t, bytes[3], 0x22)150 testutils.ASSERT_BYTE_EQ(t, bytes[10], 0x9A)151 testutils.ASSERT_BYTE_EQ(t, bytes[11], 0xB0)152 /*153 testutils.ASSERT_BYTE_EQ(t, bytes[12], 0x56)154 testutils.ASSERT_BYTE_EQ(t, bytes[13], 0x67)155 testutils.ASSERT_BYTE_EQ(t, bytes[14], 0x78)156 testutils.ASSERT_BYTE_EQ(t, bytes[15], 0x89)157 testutils.ASSERT_BYTE_EQ(t, bytes[16], 0xAB)158 testutils.ASSERT_BYTE_EQ(t, bytes[17], 99)*/...

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1func main() {2 testutils.Write("hello")3}4func main() {5 testutils.Read()6}7func main() {8 testutils.Read()9}10func main() {11 testutils.Write("hello")12}13import (14func TestWrite(t *testing.T) {15 testutils.Write("hello")16}17func TestRead(t *testing.T) {18 testutils.Read()19}20 /usr/local/go/src/testutils (from $GOROOT)21 /home/username/go/src/testutils (from $GOPATH)

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 t := testutils.Testutils{}5 t.Write()6}7import (8type Testutils struct {9}10func (t Testutils) Write() {

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func TestWrite(t *testing.T) {3 fmt.Println("Testing Write")4}5func Write() {6 fmt.Println("Write")7}8import (9func TestRead(t *testing.T) {10 fmt.Println("Testing Read")11}12func Read() {13 fmt.Println("Read")14}15import (16func main() {17 fmt.Println("Hello")18 testutils.Write()19 testutils.Read()20}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 testutils.Write()4 fmt.Println("Hello World")5}6import (7func main() {8 testutils.Write()9 fmt.Println("Hello World")10}11import (12func main() {13 testutils.Write()14 fmt.Println("Hello World")15}16import (17func main() {18 testutils.Write()19 fmt.Println("Hello World")20}21import (22func main() {23 testutils.Write()24 fmt.Println("Hello World")25}26import (27func main() {28 testutils.Write()29 fmt.Println("Hello World")30}31import (32func main() {33 testutils.Write()34 fmt.Println("Hello World")35}36import (37func main() {38 testutils.Write()39 fmt.Println("Hello World")40}41import (42func main() {43 testutils.Write()44 fmt.Println("Hello World")45}46import (

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 testutils.Write()5}6import (7func main() {8 fmt.Println("Hello World")9 testutils.Read()10}11websocket: close 1006 (abnormal closure): unexpected EOF12import (13func main() {14 fmt.Println("Hello World")15 ws, err := websocket.Dial(url, "", origin)16 if err != nil {17 fmt.Println(err)18 }19 fmt.Println("Connected to server")20 var msg = []byte("Hello from client")21 _, err = ws.Write(msg)22 if err != nil {23 fmt.Println(err)24 }25 fmt.Println("Message sent to server")26 time.Sleep(1000 * time.Millisecond)27}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 testutils.Write("1.go")4 fmt.Println("main")5}6import (7func Write(fileName string) {8 fmt.Println("Write")9 ioutil.WriteFile(fileName, []byte("package testutils10import (11func Write(fileName string) {12 fmt.Println(\"Write\")13}"), 0644)14}15 /usr/local/go/src/github.com/GoLangTest/testutils (from $GOROOT)16 /home/rohit/Documents/GoLang/src/github.com/GoLangTest/testutils (from $GOPATH)17 /usr/local/go/src/github.com/GoLangTest/testutils (from $GOROOT)18 /home/rohit/Documents/GoLang/src/github.com/GoLangTest/testutils (from $GOPATH)19 /usr/local/go/src/github.com/GoLangTest/testutils (from $GOROOT)20 /home/rohit/Documents/GoLang/src/github.com/GoLangTest/testutils (from $GOPATH)21I am new in GoLang. I am trying to create a package and use it in a separate file. I am getting the following error: 1.go:8:2: cannot find package "github.com/GoLangTest/testutils" in any of: /usr/local/go/src/github.com/GoLangTest/testutils (from $GOROOT) /

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 testutils.Write("Hello World")4 fmt.Println(testutils.Read())5}6import (7func main() {8 testutils.Write("Hello World")9 fmt.Println(testutils.Read())10}11import (12func main() {13 testutils.Write("Hello World")14 fmt.Println(testutils.Read())15}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1type TestUtils interface {2 Write([]byte) (int, error)3}4import (5func main() {6 tu = testutils.NewTestUtils()7 tu.Write([]byte("Hello World"))8}9import (10func main() {11 tu = testutils.NewTestUtils()12 tu.Write([]byte("Hello World"))13}

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "testutils"3func main() {4t.Write("Hello")5fmt.Println(t.Read())6}7import "fmt"8import "testutils"9func main() {10t.Write("Hello")11fmt.Println(t.Read())12}13/usr/local/go/src/pkg/testutils (from $GOROOT)14/home/username/go/src/testutils (from $GOPATH)

Full Screen

Full Screen

Write

Using AI Code Generation

copy

Full Screen

1Now, if you want to use this package in your project, you need to import it. You can do this by using the following command:2import "github.com/username/testutils"3To use the package, you need to import it in your code. You can do this by using the following command:4import "github.com/username/testutils"5import (6func main() {7 fmt.Println(testutils.Read())8}9Now, if you want to use this package in your project, you need to import it. You can do this by using the following command:10import "github.com/username/testutils"11import (12func main() {13 fmt.Println(testutils.Read())14}15Now, if you want to use this package in your project, you need to import it. You can do this by using the following command:16import "github.com/username/testutils"17import (18func main() {19 fmt.Println(testutils.Read())20}21Now, if you want to use this package in your project, you need to import it. You can do this by using the following command:22import "github.com/username/testutils"23import (24func main() {25 fmt.Println(testutils.Read())26}27Now, if you want to use this package in your project, you need to import it. You can do this by using the following command:28import "github.com/username/testutils"29import (30func main() {31 fmt.Println(testutils.Read())32}33Now, if you want to use this package in your project, you need to import it. You can do this by using the following command:34import "github.com/username/testutils"35import (

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.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful