package wsrpc_test import ( "fmt" "net/http" "net/http/httptest" "net/url" "testing" "github.com/gohxs/prettylog" "golang.org/x/net/websocket" "dev.hexasoftware.com/stdio/wsrpc" ) func init() { prettylog.Global() } var ( ready = make(chan struct{}) ) /////////////////////////// // TESTS ////////////// func TestCall(t *testing.T) { ws := prepareClient(t) // Prepare a temp server and a client // Sending callObj := wsrpc.CallObj{ OP: "call", ID: "123", Method: "hello", Params: []interface{}{1, 2}, } websocket.JSON.Send(ws, callObj) //Receive res := wsrpc.CallObj{} err := websocket.JSON.Receive(ws, &res) if err != nil { t.Fatal("Read error", err) } if res.OP != "response" || res.Response != "Hello world" { t.Fatal("Failed, invalid response") } if res.Error != "" { t.Fatal("Remote error", res.Error) } } func TestParams(t *testing.T) { ws := prepareClient(t) cli := wsrpc.NewClient(ws) go cli.Process() res, err := cli.Call("sum", 1, 2) if err != nil { t.Fatal(err) } if res != float64(3) { t.Fatal("Message error") } } func TestError(t *testing.T) { ws := prepareClient(t) cli := wsrpc.NewClient(ws) go cli.Process() _, err := cli.Call("nomethod", 1, 2, 3, 4) if err == nil { t.Fatal("It should return an error but didn't") } _, err = cli.Call("hello", 1, 2, 3) if err != nil { t.Fatal("Ups") } } ////////////////////// // HELPERS //////// func cliTest(ws *wsrpc.ClientCtx) { ws.Define("hello", func(params ...interface{}) (interface{}, error) { return "Hello world", nil }) ws.Define("done", func(params ...interface{}) (interface{}, error) { return nil, nil }) ws.Define("sum", func(params ...interface{}) (interface{}, error) { return params[0].(float64) + params[1].(float64), nil }) ready <- struct{}{} } func prepareClient(t *testing.T) *websocket.Conn { mux := http.NewServeMux() mux.Handle("/", wsrpc.New(cliTest)) serv := httptest.NewServer(mux) u, err := url.Parse(serv.URL) if err != nil { t.Fatal(err) } wsURL := fmt.Sprintf("ws://%s:%s/wsrpc", u.Hostname(), u.Port()) ws, err := websocket.Dial(wsURL, "", "http://localhost/") if err != nil { t.Fatal(err) } <-ready // wait until define ready return ws }