Best Gauge code snippet using event.Test
http_test.go
Source:http_test.go
...53 // state stores []byte which is used to test creating and loading54 // snapshots55 state atomic.Value56}57func newTestService(ctx *adapters.ServiceContext) (node.Service, error) {58 svc := &testService{59 id: ctx.Config.ID,60 peers: make(map[enode.ID]*testPeer),61 }62 svc.state.Store(ctx.Snapshot)63 return svc, nil64}65type testPeer struct {66 testReady chan struct{}67 dumReady chan struct{}68}69func (t *testService) peer(id enode.ID) *testPeer {70 t.peersMtx.Lock()71 defer t.peersMtx.Unlock()72 if peer, ok := t.peers[id]; ok {73 return peer74 }75 peer := &testPeer{76 testReady: make(chan struct{}),77 dumReady: make(chan struct{}),78 }79 t.peers[id] = peer80 return peer81}82func (t *testService) Protocols() []p2p.Protocol {83 return []p2p.Protocol{84 {85 Name: "test",86 Version: 1,87 Length: 3,88 Run: t.RunTest,89 },90 {91 Name: "dum",92 Version: 1,93 Length: 1,94 Run: t.RunDum,95 },96 {97 Name: "prb",98 Version: 1,99 Length: 1,100 Run: t.RunPrb,101 },102 }103}104func (t *testService) APIs() []rpc.API {105 return []rpc.API{{106 Namespace: "test",107 Version: "1.0",108 Service: &TestAPI{109 state: &t.state,110 peerCount: &t.peerCount,111 },112 }}113}114func (t *testService) Start(server *p2p.Server) error {115 return nil116}117func (t *testService) Stop() error {118 return nil119}120// handshake performs a peer handshake by sending and expecting an empty121// message with the given code122func (t *testService) handshake(rw p2p.MsgReadWriter, code uint64) error {123 errc := make(chan error, 2)124 go func() { errc <- p2p.Send(rw, code, struct{}{}) }()125 go func() { errc <- p2p.ExpectMsg(rw, code, struct{}{}) }()126 for i := 0; i < 2; i++ {127 if err := <-errc; err != nil {128 return err129 }130 }131 return nil132}133func (t *testService) RunTest(p *p2p.Peer, rw p2p.MsgReadWriter) error {134 peer := t.peer(p.ID())135 // perform three handshakes with three different message codes,136 // used to test message sending and filtering137 if err := t.handshake(rw, 2); err != nil {138 return err139 }140 if err := t.handshake(rw, 1); err != nil {141 return err142 }143 if err := t.handshake(rw, 0); err != nil {144 return err145 }146 // close the testReady channel so that other protocols can run147 close(peer.testReady)148 // track the peer149 atomic.AddInt64(&t.peerCount, 1)150 defer atomic.AddInt64(&t.peerCount, -1)151 // block until the peer is dropped152 for {153 _, err := rw.ReadMsg()154 if err != nil {155 return err156 }157 }158}159func (t *testService) RunDum(p *p2p.Peer, rw p2p.MsgReadWriter) error {160 peer := t.peer(p.ID())161 // wait for the test protocol to perform its handshake162 <-peer.testReady163 // perform a handshake164 if err := t.handshake(rw, 0); err != nil {165 return err166 }167 // close the dumReady channel so that other protocols can run168 close(peer.dumReady)169 // block until the peer is dropped170 for {171 _, err := rw.ReadMsg()172 if err != nil {173 return err174 }175 }176}177func (t *testService) RunPrb(p *p2p.Peer, rw p2p.MsgReadWriter) error {178 peer := t.peer(p.ID())179 // wait for the dum protocol to perform its handshake180 <-peer.dumReady181 // perform a handshake182 if err := t.handshake(rw, 0); err != nil {183 return err184 }185 // block until the peer is dropped186 for {187 _, err := rw.ReadMsg()188 if err != nil {189 return err190 }191 }192}193func (t *testService) Snapshot() ([]byte, error) {194 return t.state.Load().([]byte), nil195}196// TestAPI provides a test API to:197// * get the peer count198// * get and set an arbitrary state byte slice199// * get and increment a counter200// * subscribe to counter increment events201type TestAPI struct {202 state *atomic.Value203 peerCount *int64204 counter int64205 feed event.Feed206}207func (t *TestAPI) PeerCount() int64 {208 return atomic.LoadInt64(t.peerCount)209}210func (t *TestAPI) Get() int64 {211 return atomic.LoadInt64(&t.counter)212}213func (t *TestAPI) Add(delta int64) {214 atomic.AddInt64(&t.counter, delta)215 t.feed.Send(delta)216}217func (t *TestAPI) GetState() []byte {218 return t.state.Load().([]byte)219}220func (t *TestAPI) SetState(state []byte) {221 t.state.Store(state)222}223func (t *TestAPI) Events(ctx context.Context) (*rpc.Subscription, error) {224 notifier, supported := rpc.NotifierFromContext(ctx)225 if !supported {226 return nil, rpc.ErrNotificationsUnsupported227 }228 rpcSub := notifier.CreateSubscription()229 go func() {230 events := make(chan int64)231 sub := t.feed.Subscribe(events)232 defer sub.Unsubscribe()233 for {234 select {235 case event := <-events:236 notifier.Notify(rpcSub.ID, event)237 case <-sub.Err():238 return239 case <-rpcSub.Err():240 return241 case <-notifier.Closed():242 return243 }244 }245 }()246 return rpcSub, nil247}248var testServices = adapters.Services{249 "test": newTestService,250}251func testHTTPServer(t *testing.T) (*Network, *httptest.Server) {252 t.Helper()253 adapter := adapters.NewSimAdapter(testServices)254 network := NewNetwork(adapter, &NetworkConfig{255 DefaultService: "test",256 })257 return network, httptest.NewServer(NewServer(network))258}259// TestHTTPNetwork tests interacting with a simulation network using the HTTP260// API261func TestHTTPNetwork(t *testing.T) {262 // start the server263 network, s := testHTTPServer(t)264 defer s.Close()265 // subscribe to events so we can check them later266 client := NewClient(s.URL)267 events := make(chan *Event, 100)268 var opts SubscribeOpts269 sub, err := client.SubscribeNetwork(events, opts)270 if err != nil {271 t.Fatalf("error subscribing to network events: %s", err)272 }273 defer sub.Unsubscribe()274 // check we can retrieve details about the network275 gotNetwork, err := client.GetNetwork()276 if err != nil {277 t.Fatalf("error getting network: %s", err)278 }279 if gotNetwork.ID != network.ID {280 t.Fatalf("expected network to have ID %q, got %q", network.ID, gotNetwork.ID)281 }282 // start a simulation network283 nodeIDs := startTestNetwork(t, client)284 // check we got all the events285 x := &expectEvents{t, events, sub}286 x.expect(287 x.nodeEvent(nodeIDs[0], false),288 x.nodeEvent(nodeIDs[1], false),289 x.nodeEvent(nodeIDs[0], true),290 x.nodeEvent(nodeIDs[1], true),291 x.connEvent(nodeIDs[0], nodeIDs[1], false),292 x.connEvent(nodeIDs[0], nodeIDs[1], true),293 )294 // reconnect the stream and check we get the current nodes and conns295 events = make(chan *Event, 100)296 opts.Current = true297 sub, err = client.SubscribeNetwork(events, opts)298 if err != nil {299 t.Fatalf("error subscribing to network events: %s", err)300 }301 defer sub.Unsubscribe()302 x = &expectEvents{t, events, sub}303 x.expect(304 x.nodeEvent(nodeIDs[0], true),305 x.nodeEvent(nodeIDs[1], true),306 x.connEvent(nodeIDs[0], nodeIDs[1], true),307 )308}309func startTestNetwork(t *testing.T, client *Client) []string {310 // create two nodes311 nodeCount := 2312 nodeIDs := make([]string, nodeCount)313 for i := 0; i < nodeCount; i++ {314 config := adapters.RandomNodeConfig()315 node, err := client.CreateNode(config)316 if err != nil {317 t.Fatalf("error creating node: %s", err)318 }319 nodeIDs[i] = node.ID320 }321 // check both nodes exist322 nodes, err := client.GetNodes()323 if err != nil {324 t.Fatalf("error getting nodes: %s", err)325 }326 if len(nodes) != nodeCount {327 t.Fatalf("expected %d nodes, got %d", nodeCount, len(nodes))328 }329 for i, nodeID := range nodeIDs {330 if nodes[i].ID != nodeID {331 t.Fatalf("expected node %d to have ID %q, got %q", i, nodeID, nodes[i].ID)332 }333 node, err := client.GetNode(nodeID)334 if err != nil {335 t.Fatalf("error getting node %d: %s", i, err)336 }337 if node.ID != nodeID {338 t.Fatalf("expected node %d to have ID %q, got %q", i, nodeID, node.ID)339 }340 }341 // start both nodes342 for _, nodeID := range nodeIDs {343 if err := client.StartNode(nodeID); err != nil {344 t.Fatalf("error starting node %q: %s", nodeID, err)345 }346 }347 // connect the nodes348 for i := 0; i < nodeCount-1; i++ {349 peerId := i + 1350 if i == nodeCount-1 {351 peerId = 0352 }353 if err := client.ConnectNode(nodeIDs[i], nodeIDs[peerId]); err != nil {354 t.Fatalf("error connecting nodes: %s", err)355 }356 }357 return nodeIDs358}359type expectEvents struct {360 *testing.T361 events chan *Event362 sub event.Subscription363}364func (t *expectEvents) nodeEvent(id string, up bool) *Event {365 node := Node{366 Config: &adapters.NodeConfig{367 ID: enode.HexID(id),368 },369 up: up,370 }371 return &Event{372 Type: EventTypeNode,373 Node: &node,374 }375}376func (t *expectEvents) connEvent(one, other string, up bool) *Event {377 return &Event{378 Type: EventTypeConn,379 Conn: &Conn{380 One: enode.HexID(one),381 Other: enode.HexID(other),382 Up: up,383 },384 }385}386func (t *expectEvents) expectMsgs(expected map[MsgFilter]int) {387 actual := make(map[MsgFilter]int)388 timeout := time.After(10 * time.Second)389loop:390 for {391 select {392 case event := <-t.events:393 t.Logf("received %s event: %s", event.Type, event)394 if event.Type != EventTypeMsg || event.Msg.Received {395 continue loop396 }397 if event.Msg == nil {398 t.Fatal("expected event.Msg to be set")399 }400 filter := MsgFilter{401 Proto: event.Msg.Protocol,402 Code: int64(event.Msg.Code),403 }404 actual[filter]++405 if actual[filter] > expected[filter] {406 t.Fatalf("received too many msgs for filter: %v", filter)407 }408 if reflect.DeepEqual(actual, expected) {409 return410 }411 case err := <-t.sub.Err():412 t.Fatalf("network stream closed unexpectedly: %s", err)413 case <-timeout:414 t.Fatal("timed out waiting for expected events")415 }416 }417}418func (t *expectEvents) expect(events ...*Event) {419 t.Helper()420 timeout := time.After(10 * time.Second)421 i := 0422 for {423 select {424 case event := <-t.events:425 t.Logf("received %s event: %s", event.Type, event)426 expected := events[i]427 if event.Type != expected.Type {428 t.Fatalf("expected event %d to have type %q, got %q", i, expected.Type, event.Type)429 }430 switch expected.Type {431 case EventTypeNode:432 if event.Node == nil {433 t.Fatal("expected event.Node to be set")434 }435 if event.Node.ID() != expected.Node.ID() {436 t.Fatalf("expected node event %d to have id %q, got %q", i, expected.Node.ID().TerminalString(), event.Node.ID().TerminalString())437 }438 if event.Node.Up() != expected.Node.Up() {439 t.Fatalf("expected node event %d to have up=%t, got up=%t", i, expected.Node.Up(), event.Node.Up())440 }441 case EventTypeConn:442 if event.Conn == nil {443 t.Fatal("expected event.Conn to be set")444 }445 if event.Conn.One != expected.Conn.One {446 t.Fatalf("expected conn event %d to have one=%q, got one=%q", i, expected.Conn.One.TerminalString(), event.Conn.One.TerminalString())447 }448 if event.Conn.Other != expected.Conn.Other {449 t.Fatalf("expected conn event %d to have other=%q, got other=%q", i, expected.Conn.Other.TerminalString(), event.Conn.Other.TerminalString())450 }451 if event.Conn.Up != expected.Conn.Up {452 t.Fatalf("expected conn event %d to have up=%t, got up=%t", i, expected.Conn.Up, event.Conn.Up)453 }454 }455 i++456 if i == len(events) {457 return458 }459 case err := <-t.sub.Err():460 t.Fatalf("network stream closed unexpectedly: %s", err)461 case <-timeout:462 t.Fatal("timed out waiting for expected events")463 }464 }465}466// TestHTTPNodeRPC tests calling RPC methods on nodes via the HTTP API467func TestHTTPNodeRPC(t *testing.T) {468 // start the server469 _, s := testHTTPServer(t)470 defer s.Close()471 // start a node in the network472 client := NewClient(s.URL)473 config := adapters.RandomNodeConfig()474 node, err := client.CreateNode(config)475 if err != nil {476 t.Fatalf("error creating node: %s", err)477 }478 if err := client.StartNode(node.ID); err != nil {479 t.Fatalf("error starting node: %s", err)480 }481 // create two RPC clients482 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)483 defer cancel()484 rpcClient1, err := client.RPCClient(ctx, node.ID)485 if err != nil {486 t.Fatalf("error getting node RPC client: %s", err)487 }488 rpcClient2, err := client.RPCClient(ctx, node.ID)489 if err != nil {490 t.Fatalf("error getting node RPC client: %s", err)491 }492 // subscribe to events using client 1493 events := make(chan int64, 1)494 sub, err := rpcClient1.Subscribe(ctx, "test", events, "events")495 if err != nil {496 t.Fatalf("error subscribing to events: %s", err)497 }498 defer sub.Unsubscribe()499 // call some RPC methods using client 2500 if err := rpcClient2.CallContext(ctx, nil, "test_add", 10); err != nil {501 t.Fatalf("error calling RPC method: %s", err)502 }503 var result int64504 if err := rpcClient2.CallContext(ctx, &result, "test_get"); err != nil {505 t.Fatalf("error calling RPC method: %s", err)506 }507 if result != 10 {508 t.Fatalf("expected result to be 10, got %d", result)509 }510 // check we got an event from client 1511 select {512 case event := <-events:513 if event != 10 {514 t.Fatalf("expected event to be 10, got %d", event)515 }516 case <-ctx.Done():517 t.Fatal(ctx.Err())518 }519}520// TestHTTPSnapshot tests creating and loading network snapshots521func TestHTTPSnapshot(t *testing.T) {522 // start the server523 network, s := testHTTPServer(t)524 defer s.Close()525 var eventsDone = make(chan struct{})526 count := 1527 eventsDoneChan := make(chan *Event)528 eventSub := network.Events().Subscribe(eventsDoneChan)529 go func() {530 defer eventSub.Unsubscribe()531 for event := range eventsDoneChan {532 if event.Type == EventTypeConn && !event.Control {533 count--534 if count == 0 {535 eventsDone <- struct{}{}536 return537 }538 }539 }540 }()541 // create a two-node network542 client := NewClient(s.URL)543 nodeCount := 2544 nodes := make([]*p2p.NodeInfo, nodeCount)545 for i := 0; i < nodeCount; i++ {546 config := adapters.RandomNodeConfig()547 node, err := client.CreateNode(config)548 if err != nil {549 t.Fatalf("error creating node: %s", err)550 }551 if err := client.StartNode(node.ID); err != nil {552 t.Fatalf("error starting node: %s", err)553 }554 nodes[i] = node555 }556 if err := client.ConnectNode(nodes[0].ID, nodes[1].ID); err != nil {557 t.Fatalf("error connecting nodes: %s", err)558 }559 // store some state in the test services560 states := make([]string, nodeCount)561 for i, node := range nodes {562 rpc, err := client.RPCClient(context.Background(), node.ID)563 if err != nil {564 t.Fatalf("error getting RPC client: %s", err)565 }566 defer rpc.Close()567 state := fmt.Sprintf("%x", rand.Int())568 if err := rpc.Call(nil, "test_setState", []byte(state)); err != nil {569 t.Fatalf("error setting service state: %s", err)570 }571 states[i] = state572 }573 <-eventsDone574 // create a snapshot575 snap, err := client.CreateSnapshot()576 if err != nil {577 t.Fatalf("error creating snapshot: %s", err)578 }579 for i, state := range states {580 gotState := snap.Nodes[i].Snapshots["test"]581 if string(gotState) != state {582 t.Fatalf("expected snapshot state %q, got %q", state, gotState)583 }584 }585 // create another network586 network2, s := testHTTPServer(t)587 defer s.Close()588 client = NewClient(s.URL)589 count = 1590 eventSub = network2.Events().Subscribe(eventsDoneChan)591 go func() {592 defer eventSub.Unsubscribe()593 for event := range eventsDoneChan {594 if event.Type == EventTypeConn && !event.Control {595 count--596 if count == 0 {597 eventsDone <- struct{}{}598 return599 }600 }601 }602 }()603 // subscribe to events so we can check them later604 events := make(chan *Event, 100)605 var opts SubscribeOpts606 sub, err := client.SubscribeNetwork(events, opts)607 if err != nil {608 t.Fatalf("error subscribing to network events: %s", err)609 }610 defer sub.Unsubscribe()611 // load the snapshot612 if err := client.LoadSnapshot(snap); err != nil {613 t.Fatalf("error loading snapshot: %s", err)614 }615 <-eventsDone616 // check the nodes and connection exists617 net, err := client.GetNetwork()618 if err != nil {619 t.Fatalf("error getting network: %s", err)620 }621 if len(net.Nodes) != nodeCount {622 t.Fatalf("expected network to have %d nodes, got %d", nodeCount, len(net.Nodes))623 }624 for i, node := range nodes {625 id := net.Nodes[i].ID().String()626 if id != node.ID {627 t.Fatalf("expected node %d to have ID %s, got %s", i, node.ID, id)628 }629 }630 if len(net.Conns) != 1 {631 t.Fatalf("expected network to have 1 connection, got %d", len(net.Conns))632 }633 conn := net.Conns[0]634 if conn.One.String() != nodes[0].ID {635 t.Fatalf("expected connection to have one=%q, got one=%q", nodes[0].ID, conn.One)636 }637 if conn.Other.String() != nodes[1].ID {638 t.Fatalf("expected connection to have other=%q, got other=%q", nodes[1].ID, conn.Other)639 }640 if !conn.Up {641 t.Fatal("should be up")642 }643 // check the node states were restored644 for i, node := range nodes {645 rpc, err := client.RPCClient(context.Background(), node.ID)646 if err != nil {647 t.Fatalf("error getting RPC client: %s", err)648 }649 defer rpc.Close()650 var state []byte651 if err := rpc.Call(&state, "test_getState"); err != nil {652 t.Fatalf("error getting service state: %s", err)653 }654 if string(state) != states[i] {655 t.Fatalf("expected snapshot state %q, got %q", states[i], state)656 }657 }658 // check we got all the events659 x := &expectEvents{t, events, sub}660 x.expect(661 x.nodeEvent(nodes[0].ID, false),662 x.nodeEvent(nodes[0].ID, true),663 x.nodeEvent(nodes[1].ID, false),664 x.nodeEvent(nodes[1].ID, true),665 x.connEvent(nodes[0].ID, nodes[1].ID, false),666 x.connEvent(nodes[0].ID, nodes[1].ID, true),667 )668}669// TestMsgFilterPassMultiple tests streaming message events using a filter670// with multiple protocols671func TestMsgFilterPassMultiple(t *testing.T) {672 // start the server673 _, s := testHTTPServer(t)674 defer s.Close()675 // subscribe to events with a message filter676 client := NewClient(s.URL)677 events := make(chan *Event, 10)678 opts := SubscribeOpts{679 Filter: "prb:0-test:0",680 }681 sub, err := client.SubscribeNetwork(events, opts)682 if err != nil {683 t.Fatalf("error subscribing to network events: %s", err)684 }685 defer sub.Unsubscribe()686 // start a simulation network687 startTestNetwork(t, client)688 // check we got the expected events689 x := &expectEvents{t, events, sub}690 x.expectMsgs(map[MsgFilter]int{691 {"test", 0}: 2,692 {"prb", 0}: 2,693 })694}695// TestMsgFilterPassWildcard tests streaming message events using a filter696// with a code wildcard697func TestMsgFilterPassWildcard(t *testing.T) {698 // start the server699 _, s := testHTTPServer(t)700 defer s.Close()701 // subscribe to events with a message filter702 client := NewClient(s.URL)703 events := make(chan *Event, 10)704 opts := SubscribeOpts{705 Filter: "prb:0,2-test:*",706 }707 sub, err := client.SubscribeNetwork(events, opts)708 if err != nil {709 t.Fatalf("error subscribing to network events: %s", err)710 }711 defer sub.Unsubscribe()712 // start a simulation network713 startTestNetwork(t, client)714 // check we got the expected events715 x := &expectEvents{t, events, sub}716 x.expectMsgs(map[MsgFilter]int{717 {"test", 2}: 2,718 {"test", 1}: 2,719 {"test", 0}: 2,720 {"prb", 0}: 2,721 })722}723// TestMsgFilterPassSingle tests streaming message events using a filter724// with a single protocol and code725func TestMsgFilterPassSingle(t *testing.T) {726 // start the server727 _, s := testHTTPServer(t)728 defer s.Close()729 // subscribe to events with a message filter730 client := NewClient(s.URL)731 events := make(chan *Event, 10)732 opts := SubscribeOpts{733 Filter: "dum:0",734 }735 sub, err := client.SubscribeNetwork(events, opts)736 if err != nil {737 t.Fatalf("error subscribing to network events: %s", err)738 }739 defer sub.Unsubscribe()740 // start a simulation network741 startTestNetwork(t, client)742 // check we got the expected events743 x := &expectEvents{t, events, sub}744 x.expectMsgs(map[MsgFilter]int{745 {"dum", 0}: 2,746 })747}748// TestMsgFilterPassSingle tests streaming message events using an invalid749// filter750func TestMsgFilterFailBadParams(t *testing.T) {751 // start the server752 _, s := testHTTPServer(t)753 defer s.Close()754 client := NewClient(s.URL)755 events := make(chan *Event, 10)756 opts := SubscribeOpts{757 Filter: "foo:",758 }759 _, err := client.SubscribeNetwork(events, opts)760 if err == nil {761 t.Fatalf("expected event subscription to fail but succeeded!")762 }763 opts.Filter = "bzz:aa"764 _, err = client.SubscribeNetwork(events, opts)...
event_test.go
Source:event_test.go
...20 "testing"21 "time"22)23type testEvent int24func TestSubCloseUnsub(t *testing.T) {25 // the point of this test is **not** to panic26 var mux TypeMux27 mux.Stop()28 sub := mux.Subscribe(int(0))29 sub.Unsubscribe()30}31func TestSub(t *testing.T) {32 mux := new(TypeMux)33 defer mux.Stop()34 sub := mux.Subscribe(testEvent(0))35 go func() {36 if err := mux.Post(testEvent(5)); err != nil {37 t.Errorf("Post returned unexpected error: %v", err)38 }39 }()40 ev := <-sub.Chan()41 if ev.Data.(testEvent) != testEvent(5) {42 t.Errorf("Got %v (%T), expected event %v (%T)",43 ev, ev, testEvent(5), testEvent(5))44 }45}46func TestMuxErrorAfterStop(t *testing.T) {47 mux := new(TypeMux)48 mux.Stop()49 sub := mux.Subscribe(testEvent(0))50 if _, isopen := <-sub.Chan(); isopen {51 t.Errorf("subscription channel was not closed")52 }53 if err := mux.Post(testEvent(0)); err != ErrMuxClosed {54 t.Errorf("Post error mismatch, got: %s, expected: %s", err, ErrMuxClosed)55 }56}57func TestUnsubscribeUnblockPost(t *testing.T) {58 mux := new(TypeMux)59 defer mux.Stop()60 sub := mux.Subscribe(testEvent(0))61 unblocked := make(chan bool)62 go func() {63 mux.Post(testEvent(5))64 unblocked <- true65 }()66 select {67 case <-unblocked:68 t.Errorf("Post returned before Unsubscribe")69 default:70 sub.Unsubscribe()71 <-unblocked72 }73}74func TestSubscribeDuplicateType(t *testing.T) {75 mux := new(TypeMux)76 expected := "event: duplicate type event.testEvent in Subscribe"77 defer func() {78 err := recover()79 if err == nil {80 t.Errorf("Subscribe didn't panic for duplicate type")81 } else if err != expected {82 t.Errorf("panic mismatch: got %#v, expected %#v", err, expected)83 }84 }()85 mux.Subscribe(testEvent(1), testEvent(2))86}87func TestMuxConcurrent(t *testing.T) {88 rand.Seed(time.Now().Unix())89 mux := new(TypeMux)90 defer mux.Stop()91 recv := make(chan int)92 poster := func() {93 for {94 err := mux.Post(testEvent(0))95 if err != nil {96 return97 }98 }99 }100 sub := func(i int) {101 time.Sleep(time.Duration(rand.Intn(99)) * time.Millisecond)...
Test
Using AI Code Generation
1import (2type Event struct {3}4func (e *Event) String() string {5 return fmt.Sprintf("%v %s", e.When, e.What)6}7func (e *Event) Test() {8 fmt.Println("Test method")9}10func main() {11 fmt.Println("Hello, 世界")12 e := new(Event)13 e.Test()14}
Test
Using AI Code Generation
1import "fmt"2type Event struct {3}4func (e *Event) Test() {5 fmt.Println("Test")6}7func main() {8 e := Event{"Test Event"}9 e.Test()10}11Methods and pointer indirection (2)12import "fmt"13type Event struct {14}15func (e Event) Test() {16 fmt.Println("Test")17}18func main() {19 e := Event{"Test Event"}20 e.Test()21}22Methods and pointer indirection (3)23import "fmt"24type Event struct {25}26func (e *Event) Test() {27 fmt.Println("Test")28}29func main() {30 e := Event{"Test Event"}31 e.Test()32}
Test
Using AI Code Generation
1import (2type Event struct {3}4func (e Event) Test() {5 fmt.Println("Event", e.id, ":", e.name)6}7func main() {8 e := Event{1, "Test Event"}9 e.Test()10}11import (12type Event struct {13}14func (e *Event) Test() {15 fmt.Println("Event", e.id, ":", e.name)16}17func main() {18 e := Event{1, "Test Event"}19 e.Test()20}21e.Test()
Test
Using AI Code Generation
1import "fmt"2type Event struct {3}4func (e *Event) Test() {5 fmt.Println("Test method of event class")6}7func main() {8 e := Event{"Event1", 101}9 e.Test()10}11import "fmt"12type Event struct {13}14func (e *Event) Test() {15 fmt.Println("Test method of event class")16}17type Event1 struct {18}19func (e *Event1) Test() {20 fmt.Println("Test method of event1 class")21}22func main() {23 e := Event1{Event{"Event1", 101}}24 e.Test()25}26import "fmt"27type Event struct {28}29func (e *Event) Test() {30 fmt.Println("Test method of event class")31}32func (e *Event) Test1(i int
Test
Using AI Code Generation
1import (2func main() {3 e := event.NewEvent()4 e.Test()5 fmt.Println("Hello, playground")6}7import "fmt"8type Event struct {9}10func NewEvent() *Event {11 return &Event{}12}13func (e *Event) Test() {14 fmt.Println("Event.Test()")15}16I am trying to create a new package and import it in my main function. But I am getting the following error:-17 /usr/local/go/src/pkg/event (from $GOROOT)18 /Users/rahul/go/src/pkg/event (from $GOPATH)19How can I import my own package in my main file?
Test
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 e.Test()5}6import (7func main() {8 fmt.Println("Hello, playground")9 e.Test()10}11I have two files 1.go and 2.go. Both files have same package name and same function name. I am calling Test() method from both the files. But only one file is getting compiled. How can I compile both the files?12import (13type User struct {14}15func main() {16 session, err := mgo.Dial("localhost")17 if err != nil {18 panic(err)19 }20 defer session.Close()21 session.SetMode(mgo.Monotonic, true)22 c := session.DB("test").C("users")23 err = c.Insert(&User{Username: "admin", Password: "admin"})24 if err != nil {25 panic(err)26 }27 fmt.Println("Inserted")28}29panic(0x6b0c0, 0xc82000e1d0)30main.main()
Test
Using AI Code Generation
1import (2type Event struct {3}4func (e *Event) Test() {5 fmt.Println("Test is called")6}7func main() {8 e := &Event{Id: 1, Name: "Event1"}9 go e.Test()10 time.Sleep(10 * time.Millisecond)11}
Test
Using AI Code Generation
1import (2func main() {3 event := NewEvent("Gophercon India", time.Now())4 event.Test()5}6import (7func main() {8 event := NewEvent("Gophercon India", time.Now())9 event.Test()10}11import (12func main() {13 event := NewEvent("Gophercon India", time.Now())14 event.Test()15}16import (17func main() {18 event := NewEvent("Gophercon India", time.Now())19 event.Test()20}21import (22func main() {23 event := NewEvent("Gophercon India", time.Now())24 event.Test()25}26import (27func main() {28 event := NewEvent("Gophercon India", time.Now())29 event.Test()30}31import (32func main() {33 event := NewEvent("Gophercon India", time.Now())34 event.Test()35}36import (37func main() {38 event := NewEvent("Gophercon India", time.Now())39 event.Test()40}41import (42func main() {43 event := NewEvent("Gophercon India", time.Now())44 event.Test()45}46import (47func main() {48 event := NewEvent("Gophercon India", time.Now())49 event.Test()50}
Test
Using AI Code Generation
1import (2func main() {3 e := NewEvent()4 e.Register(func() {5 fmt.Println("I am called by the event!")6 })7 e.Test()8}9import (10func main() {11 e := NewEvent()12 e.Register(func() {13 fmt.Println("I am called by the event!")14 })15 e.Test()16}17import (18func main() {19 e := NewEvent()20 e.Register(func() {21 fmt.Println("I am called by the event!")22 })23 e.Test()24}25import (26func main() {27 e := NewEvent()28 e.Register(func() {29 fmt.Println("I am called by the event!")30 })31 e.Test()32}33import (34func main() {35 e := NewEvent()36 e.Register(func() {37 fmt.Println("I am called by the event!")38 })39 e.Test()40}41import (42func main() {43 e := NewEvent()44 e.Register(func() {45 fmt.Println("I am called by the event!")46 })47 e.Test()48}
Test
Using AI Code Generation
1import (2func main() {3 event := Event{StartDate: "2019-01-01", EndDate: "2019-01-01", StartTime: "10:00", EndTime: "11:00"}4 event.Test()5 fmt.Println(event)6}7import (8func main() {9 event := Event{StartDate: "2019-01-01", EndDate: "2019-01-01", StartTime: "10:00", EndTime: "11:00"}10 event.Test()11 fmt.Println(event)12}13import (14func main() {15 event := Event{StartDate: "2019-01-01", EndDate: "2019-01-01", StartTime: "10:00", EndTime: "11:00"}16 event.Test()17 fmt.Println(event)18}19import (20func main() {21 event := Event{StartDate: "2019-01-01", EndDate: "2019-01-01", StartTime: "10:00", EndTime: "11:00"}22 event.Test()23 fmt.Println(event)24}25import (26func main() {27 event := Event{StartDate: "2019-01-01", EndDate: "2019-01-01", StartTime: "10:00", EndTime: "11:00"}28 event.Test()29 fmt.Println(event)30}
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!!