You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.2 KiB

  1. package jsonrpc
  2. import (
  3. "bytes"
  4. "context"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "github.com/intel-go/fastjson"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. )
  12. type handler struct {
  13. F func(c context.Context, params *fastjson.RawMessage) (interface{}, *Error)
  14. }
  15. func (h *handler) ServeJSONRPC(c context.Context, params *fastjson.RawMessage) (interface{}, *Error) {
  16. return h.F(c, params)
  17. }
  18. func TestHandler(t *testing.T) {
  19. mr := NewMethodRepository()
  20. rec := httptest.NewRecorder()
  21. r, err := http.NewRequest("", "", nil)
  22. require.NoError(t, err)
  23. mr.ServeHTTP(rec, r)
  24. res := Response{}
  25. err = fastjson.NewDecoder(rec.Body).Decode(&res)
  26. require.NoError(t, err)
  27. assert.NotNil(t, res.Error)
  28. rec = httptest.NewRecorder()
  29. r, err = http.NewRequest("", "", bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":"test","method":"hello","params":{}}`)))
  30. require.NoError(t, err)
  31. r.Header.Set("Content-Type", "application/json")
  32. mr.ServeHTTP(rec, r)
  33. res = Response{}
  34. err = fastjson.NewDecoder(rec.Body).Decode(&res)
  35. require.NoError(t, err)
  36. assert.NotNil(t, res.Error)
  37. h1 := &handler{}
  38. h1.F = func(c context.Context, params *fastjson.RawMessage) (interface{}, *Error) {
  39. return "hello", nil
  40. }
  41. require.NoError(t, mr.RegisterMethod("hello", h1, nil, nil))
  42. h2 := &handler{}
  43. h2.F = func(c context.Context, params *fastjson.RawMessage) (interface{}, *Error) {
  44. return nil, ErrInternal()
  45. }
  46. require.NoError(t, mr.RegisterMethod("bye", h2, nil, nil))
  47. rec = httptest.NewRecorder()
  48. r, err = http.NewRequest("", "", bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":"test","method":"hello","params":{}}`)))
  49. require.NoError(t, err)
  50. r.Header.Set("Content-Type", "application/json")
  51. mr.ServeHTTP(rec, r)
  52. res = Response{}
  53. err = fastjson.NewDecoder(rec.Body).Decode(&res)
  54. require.NoError(t, err)
  55. assert.Nil(t, res.Error)
  56. assert.Equal(t, "hello", res.Result)
  57. rec = httptest.NewRecorder()
  58. r, err = http.NewRequest("", "", bytes.NewReader([]byte(`{"jsonrpc":"2.0","id":"test","method":"bye","params":{}}`)))
  59. require.NoError(t, err)
  60. r.Header.Set("Content-Type", "application/json")
  61. mr.ServeHTTP(rec, r)
  62. res = Response{}
  63. err = fastjson.NewDecoder(rec.Body).Decode(&res)
  64. require.NoError(t, err)
  65. assert.NotNil(t, res.Error)
  66. }