如何为Gorilla Websocket编写单元测试用例

huangapple go评论79阅读模式
英文:

How to write Unit Test Cases for Gorilla Websocket

问题

我需要为Gorilla Web-socket编写单元测试用例。

var upgrader = websocket.Upgrader{} // 使用默认选项

func socketHandler(w http.ResponseWriter, r *http.Request) {
    // 将原始的HTTP连接升级为基于websocket的连接
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Print("连接升级期间发生错误:", err)
        return
    }
    defer conn.Close()

    // 事件循环
    for {
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            log.Println("读取消息期间发生错误:", err)
            break
        }
        log.Printf("接收到消息: %s", message)
        err = conn.WriteMessage(messageType, message)
        if err != nil {
            log.Println("写入消息期间发生错误:", err)
            break
        }
    }
}

func home(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "首页")
}

func main() {
    http.HandleFunc("/socket", socketHandler)
    http.HandleFunc("/", home)
    log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

我想为socketHandler函数编写单元测试用例。我应该如何进行?

英文:

I need to write unit test cases for Gorilla Web-socket.

var upgrader = websocket.Upgrader{} // use default options
 
func socketHandler(w http.ResponseWriter, r *http.Request) {
    // Upgrade our raw HTTP connection to a websocket based one
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Print("Error during connection upgradation:", err)
        return
    }
    defer conn.Close()
 
    // The event loop
    for {
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            log.Println("Error during message reading:", err)
            break
        }
        log.Printf("Received: %s", message)
        err = conn.WriteMessage(messageType, message)
        if err != nil {
            log.Println("Error during message writing:", err)
            break
        }
    }
}
 
func home(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Index Page")
}
 
func main() {
    http.HandleFunc("/socket", socketHandler)
    http.HandleFunc("/", home)
    log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

I want to write the Unit Test case for socketHandler function. How should I go about it?

答案1

得分: 3

使用websocket端点启动一个httptest.Server。使用websocket客户端拨号服务器。根据需要发送和接收消息。

这是一个简单的示例:

func TestWs(t *testing.T) {
    s := httptest.NewServer(http.HandlerFunc(socketHandler))
    defer s.Close()
    wsURL := "ws" + strings.TrimPrefix(s.URL, "http")
    c, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
    if err != nil {
        t.Error(err)
    }
    defer c.Close()

    // 写入消息。
    c.WriteMessage(websocket.TextMessage, []byte("hello"))

    // 期望服务器回显消息。
    c.SetReadDeadline(time.Now().Add(time.Second * 2))
    mt, msg, err := c.ReadMessage()
    if err != nil {
        t.Error(err)
    }
    if mt != websocket.TextMessage || string(msg) != "hello" {
        t.Errorf("expected text hello, got %d: %s", mt, msg)
    }
}

在 playground 上运行示例

要测试客户端,请编写一个服务器端点,根据需要发送和接收消息以进行测试。对上述端点运行客户端代码。

英文:

Spin up an httptest.Server with the websocket endpoint. Dial the server with the websocket client. Send and receive messages as needed.

Here's a simple example:

func TestWs(t *testing.T) {
	s := httptest.NewServer(http.HandlerFunc(socketHandler))
	defer s.Close()
	wsURL := "ws" + strings.TrimPrefix(s.URL, "http")
	c, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
	if err != nil {
		t.Error(err)
	}
	defer c.Close()

	// Write a message.
	c.WriteMessage(websocket.TextMessage, []byte("hello"))

	// Expect the server to echo the message back.
	c.SetReadDeadline(time.Now().Add(time.Second * 2))
	mt, msg, err := c.ReadMessage()
    if err != nil {
        t.Error(err)
    }
	if mt != websocket.TextMessage || string(msg) != "hello" {
		t.Errorf("expected text hello, got %d: %s", mt, msg)
	}
}

Run the example on the playground.

To test a client, write a server endpoint that sends as receives messages as needed for a test. Run your client code against the endpoint as above.

huangapple
  • 本文由 发表于 2022年6月2日 10:54:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/72470140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定