Wstest
go websocket client for unit testing of a websocket handler
Install / Use
/learn @posener/WstestREADME
wstest
A websocket client for unit-testing a websocket server
The gorilla organization provides full featured websocket implementation that the standard library lacks.
The standard library provides a httptest.ResponseRecorder struct that test
an http.Handler without ListenAndServe, but is helpless when the connection is being hijacked
by an http upgrader. As for testing websockets, it has the httptest.NewServer that actually
listens on a socket on an arbitrary port.
This package provides a NewDialer function to test just the http.Handler that upgrades
the connection to a websocket session. It runs the handler function in a goroutine
without listening on any port. The returned websocket.Dialer then can be used to dial and communicate
with the given handler.
Get
go get -u github.com/posener/wstest
Examples
See the example test.
An example how to modify a test function from using
httptest.Server to use wstest.NewDialer function.
func TestHandler(t *testing.T) {
var err error
h := &myHandler{}
- s := httptest.NewServer(h)
- defer s.Close()
- d := websocket.Dialer{}
+ d := wstest.NewDialer(h)
- c, resp, err := d.Dial("ws://" + s.Listener.Addr().String() + "/ws", nil)
+ c, resp, err := d.Dial("ws://" + "whatever" + "/ws", nil)
if err != nil {
t.Fatal(err)
}
if got, want := resp.StatusCode, http.StatusSwitchingProtocols; got != want {
t.Errorf("resp.StatusCode = %q, want %q", got, want)
}
err = c.WriteJSON("test")
if err != nil {
t.Fatal(err)
}
}
Related Skills
canvas
347.0kCanvas Skill Display HTML content on connected OpenClaw nodes (Mac app, iOS, Android). Overview The canvas tool lets you present web content on any connected node's canvas view. Great for: -
node-connect
347.0kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
xurl
347.0kA CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with any X API v2 endpoint.
frontend-design
107.8kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
