Create unit test for WS in golang using Echo router

1.7k views Asked by At

I use gorilla/websocket for ws and labstack/echo as router. I need to create unit test for the handler. I find topic with solving this problem with default go router, but i don't understand how to use it with echo. I have this:

func TestWS(t *testing.T){
    provider := handler.New(coordinateservice.New())

    e := echo.New()
    rec := httptest.NewRecorder()

    req := httptest.NewRequest(http.MethodGet, "/admin/orders/:id/details", nil)

    c := e.NewContext(req, rec)

    c.SetPath("/admin/orders/:id/details")
    c.SetParamNames("id")
    c.SetParamValues("9999")

    if assert.NoError(t, provider.OrderHandler.OpenWs(c)) {
        assert.Equal(t, http.StatusOK, rec.Code)
    }

    u := url.URL{Scheme: "ws", Host: "127.0.0.1", Path: "/admin/orders/9999/details"}

    fmt.Println(u.String())

    // Connect to the server
    ws, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {
        t.Fatalf("%v", err)
    }
    defer ws.Close()

    _, p, err := ws.ReadMessage()
    if err != nil {
        t.Fatalf("%v", err)
    }

    fmt.Println(string(p))
}

And error websocket: the client is not using the websocket protocol: 'upgrade' token not found in 'Connection' header in this line:

    ws, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
    if err != nil {
        t.Fatalf("%v", err)
    }

What i need to do for connecting ws to the echo handler?

1

There are 1 answers

0
eudore On

The this is my golang unit test websocket example.

The stability of my httptest library is not guaranteed, but you can refer to using net.Pipe to create a connection for ws.

use echo:

func main() {
    app := echo.New()
    app.GET("/", hello)

    client := httptest.NewClient(app)
    go func() {
        // use http.Handler, if not has host.
        client.NewRequest("GET", "/example/wsio").WithWebsocket(handlerGobwasWebsocket).Do().Out()
        // use network
        client.NewRequest("GET", "http://localhost:8088/example/wsio").WithWebsocket(handlerGobwasWebsocket).Do().Out()
    }()

    app.Start(":8088")
}

func hello(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
}

func handlerGobwasWebsocket(conn net.Conn) {
    go func() {
        wsutil.WriteClientBinary(conn, []byte("aaaaaa"))
        wsutil.WriteClientBinary(conn, []byte("bbbbbb"))
        wsutil.WriteClientBinary(conn, []byte("ccccc"))
    }()

    defer conn.Close()
    for {
        b, err := wsutil.ReadServerBinary(conn)
        fmt.Println("ws io client read: ", string(b), err)
        if err != nil {
            fmt.Println("gobwas client err:", err)
            return
        }
    }
}