requestparser_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package internal
  2. import (
  3. "net/http/httptest"
  4. "strings"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/zeromicro/go-zero/rest/pathvar"
  8. )
  9. func TestNewRequestParserNoVar(t *testing.T) {
  10. req := httptest.NewRequest("GET", "/", nil)
  11. parser, err := NewRequestParser(req, nil)
  12. assert.Nil(t, err)
  13. assert.NotNil(t, parser)
  14. }
  15. func TestNewRequestParserWithVars(t *testing.T) {
  16. req := httptest.NewRequest("GET", "/", nil)
  17. req = pathvar.WithVars(req, map[string]string{"a": "b"})
  18. parser, err := NewRequestParser(req, nil)
  19. assert.Nil(t, err)
  20. assert.NotNil(t, parser)
  21. }
  22. func TestNewRequestParserNoVarWithBody(t *testing.T) {
  23. req := httptest.NewRequest("GET", "/", strings.NewReader(`{"a": "b"}`))
  24. parser, err := NewRequestParser(req, nil)
  25. assert.Nil(t, err)
  26. assert.NotNil(t, parser)
  27. }
  28. func TestNewRequestParserWithVarsWithBody(t *testing.T) {
  29. req := httptest.NewRequest("GET", "/", strings.NewReader(`{"a": "b"}`))
  30. req = pathvar.WithVars(req, map[string]string{"c": "d"})
  31. parser, err := NewRequestParser(req, nil)
  32. assert.Nil(t, err)
  33. assert.NotNil(t, parser)
  34. }
  35. func TestNewRequestParserWithVarsWithWrongBody(t *testing.T) {
  36. req := httptest.NewRequest("GET", "/", strings.NewReader(`{"a": "b"`))
  37. req = pathvar.WithVars(req, map[string]string{"c": "d"})
  38. parser, err := NewRequestParser(req, nil)
  39. assert.NotNil(t, err)
  40. assert.Nil(t, parser)
  41. }
  42. func TestNewRequestParserWithForm(t *testing.T) {
  43. req := httptest.NewRequest("GET", "/val?a=b", nil)
  44. parser, err := NewRequestParser(req, nil)
  45. assert.Nil(t, err)
  46. assert.NotNil(t, parser)
  47. }
  48. func TestNewRequestParserWithBadForm(t *testing.T) {
  49. req := httptest.NewRequest("GET", "/val?a%1=b", nil)
  50. parser, err := NewRequestParser(req, nil)
  51. assert.NotNil(t, err)
  52. assert.Nil(t, parser)
  53. }
  54. func TestRequestParser_buildJsonRequestParser(t *testing.T) {
  55. parser, err := buildJsonRequestParser(map[string]interface{}{"a": make(chan int)}, nil)
  56. assert.NotNil(t, err)
  57. assert.Nil(t, parser)
  58. }