doukuang8166 2017-12-04 16:02
浏览 263
已采纳

在golang中为ws创建单元测试

I use the gorilla web socket framework and use the following client to run the web socket locally and debug it

https://github.com/gorilla/websocket

ws = new WebSocket("ws://localhost:8080/mypath")
ws.onmessage = function(ev) { console.log(ev.data) }
ws.send("hello")

This is working when I use it in the chrome console but my question if there is a way to do some unit test in go and avoid using the chrome console?

  • 写回答

1条回答 默认 最新

  • douzi2785 2017-12-04 16:21
    关注

    Create a test server using the net/http/httptest package. Connect to that server using the Gorilla client. Read and write messages to test the connection.

    package main
    
    import (
        "net/http"
        "net/http/httptest"
        "strings"
        "testing"
    
        "github.com/gorilla/websocket"
    )
    
    var upgrader = websocket.Upgrader{}
    
    func echo(w http.ResponseWriter, r *http.Request) {
        c, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            return
        }
        defer c.Close()
        for {
            mt, message, err := c.ReadMessage()
            if err != nil {
                break
            }
            err = c.WriteMessage(mt, message)
            if err != nil {
                break
            }
        }
    }
    
    func TestExample(t *testing.T) {
        // Create test server with the echo handler.
        s := httptest.NewServer(http.HandlerFunc(echo))
        defer s.Close()
    
        // Convert http://127.0.0.1 to ws://127.0.0.
        u := "ws" + strings.TrimPrefix(s.URL, "http")
    
        // Connect to the server
        ws, _, err := websocket.DefaultDialer.Dial(u, nil)
        if err != nil {
            t.Fatalf("%v", err)
        }
        defer ws.Close()
    
        // Send message to server, read response and check to see if it's what we expect.
        for i := 0; i < 10; i++ {
            if err := ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
                t.Fatalf("%v", err)
            }
            _, p, err := ws.ReadMessage()
            if err != nil {
                t.Fatalf("%v", err)
            }
            if string(p) != "hello" {
                t.Fatalf("bad message")
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?