wsrpc_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package wsrpc_test
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "net/url"
  7. "testing"
  8. "github.com/gohxs/prettylog"
  9. "golang.org/x/net/websocket"
  10. "dev.hexasoftware.com/stdio/wsrpc"
  11. )
  12. func init() {
  13. prettylog.Global()
  14. }
  15. var (
  16. ready = make(chan struct{})
  17. )
  18. ///////////////////////////
  19. // TESTS
  20. //////////////
  21. func TestCall(t *testing.T) {
  22. ws := prepareClient(t) // Prepare a temp server and a client
  23. // Sending
  24. callObj := wsrpc.CallObj{
  25. OP: "call",
  26. ID: "123",
  27. Method: "hello",
  28. Params: []interface{}{1, 2},
  29. }
  30. websocket.JSON.Send(ws, callObj)
  31. //Receive
  32. res := wsrpc.CallObj{}
  33. err := websocket.JSON.Receive(ws, &res)
  34. if err != nil {
  35. t.Fatal("Read error", err)
  36. }
  37. if res.OP != "response" || res.Response != "Hello world" {
  38. t.Fatal("Failed, invalid response")
  39. }
  40. if res.Error != "" {
  41. t.Fatal("Remote error", res.Error)
  42. }
  43. }
  44. func TestParams(t *testing.T) {
  45. ws := prepareClient(t)
  46. cli := wsrpc.NewClient(ws)
  47. go cli.Process()
  48. res, err := cli.Call("sum", 1, 2)
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. if res != float64(3) {
  53. t.Fatal("Message error")
  54. }
  55. }
  56. func TestError(t *testing.T) {
  57. ws := prepareClient(t)
  58. cli := wsrpc.NewClient(ws)
  59. go cli.Process()
  60. _, err := cli.Call("nomethod", 1, 2, 3, 4)
  61. if err == nil {
  62. t.Fatal("It should return an error but didn't")
  63. }
  64. _, err = cli.Call("hello", 1, 2, 3)
  65. if err != nil {
  66. t.Fatal("Ups")
  67. }
  68. }
  69. //////////////////////
  70. // HELPERS
  71. ////////
  72. func cliTest(ws *wsrpc.ClientCtx) {
  73. ws.Define("hello", func(params ...interface{}) (interface{}, error) {
  74. return "Hello world", nil
  75. })
  76. ws.Define("done", func(params ...interface{}) (interface{}, error) {
  77. return nil, nil
  78. })
  79. ws.Define("sum", func(params ...interface{}) (interface{}, error) {
  80. return params[0].(float64) + params[1].(float64), nil
  81. })
  82. ready <- struct{}{}
  83. }
  84. func prepareClient(t *testing.T) *websocket.Conn {
  85. mux := http.NewServeMux()
  86. mux.Handle("/", wsrpc.New(cliTest))
  87. serv := httptest.NewServer(mux)
  88. u, err := url.Parse(serv.URL)
  89. if err != nil {
  90. t.Fatal(err)
  91. }
  92. wsURL := fmt.Sprintf("ws://%s:%s/wsrpc", u.Hostname(), u.Port())
  93. ws, err := websocket.Dial(wsURL, "", "http://localhost/")
  94. if err != nil {
  95. t.Fatal(err)
  96. }
  97. <-ready // wait until define ready
  98. return ws
  99. }