123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- 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
- }
|