1// +build js,wasm 2 3package websocket 4 5import ( 6 "bufio" 7 "context" 8 "testing" 9 "time" 10 11 "github.com/libp2p/go-libp2p-core/sec/insecure" 12 mplex "github.com/libp2p/go-libp2p-mplex" 13 tptu "github.com/libp2p/go-libp2p-transport-upgrader" 14 ma "github.com/multiformats/go-multiaddr" 15) 16 17func TestInBrowser(t *testing.T) { 18 tpt := New(&tptu.Upgrader{ 19 Secure: insecure.New("browserPeer"), 20 Muxer: new(mplex.Transport), 21 }) 22 addr, err := ma.NewMultiaddr("/ip4/127.0.0.1/tcp/5555/ws") 23 if err != nil { 24 t.Fatal("could not parse multiaddress:" + err.Error()) 25 } 26 conn, err := tpt.Dial(context.Background(), addr, "serverPeer") 27 if err != nil { 28 t.Fatal("could not dial server:" + err.Error()) 29 } 30 defer conn.Close() 31 32 stream, err := conn.AcceptStream() 33 if err != nil { 34 t.Fatal("could not accept stream:" + err.Error()) 35 } 36 defer stream.Close() 37 38 buf := bufio.NewReader(stream) 39 msg, err := buf.ReadString('\n') 40 if err != nil { 41 t.Fatal("could not read ping message:" + err.Error()) 42 } 43 expected := "ping\n" 44 if msg != expected { 45 t.Fatalf("Received wrong message. Expected %q but got %q", expected, msg) 46 } 47 48 _, err = stream.Write([]byte("pong\n")) 49 if err != nil { 50 t.Fatal("could not write pong message:" + err.Error()) 51 } 52 53 // TODO(albrow): This hack is necessary in order to give the reader time to 54 // finish. As soon as this test function returns, the browser window is 55 // closed, which means there is no time for the other end of the connection to 56 // read the "pong" message. We should find some way to remove this hack if 57 // possible. 58 time.Sleep(1 * time.Second) 59} 60