context_17_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2018 Gin Core Team. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. // +build go1.7
  5. package gin
  6. import (
  7. "bytes"
  8. "context"
  9. "net/http"
  10. "net/http/httptest"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. )
  15. // Tests that the response is serialized as JSON
  16. // and Content-Type is set to application/json
  17. // and special HTML characters are preserved
  18. func TestContextRenderPureJSON(t *testing.T) {
  19. w := httptest.NewRecorder()
  20. c, _ := CreateTestContext(w)
  21. c.PureJSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})
  22. assert.Equal(t, http.StatusCreated, w.Code)
  23. assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())
  24. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  25. }
  26. func TestContextHTTPContext(t *testing.T) {
  27. c, _ := CreateTestContext(httptest.NewRecorder())
  28. req, _ := http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  29. ctx, cancelFunc := context.WithCancel(context.Background())
  30. defer cancelFunc()
  31. c.Request = req.WithContext(ctx)
  32. assert.NoError(t, c.Err())
  33. assert.NotNil(t, c.Done())
  34. select {
  35. case <-c.Done():
  36. assert.Fail(t, "context should not be canceled")
  37. default:
  38. }
  39. ti, ok := c.Deadline()
  40. assert.Equal(t, ti, time.Time{})
  41. assert.False(t, ok)
  42. assert.Equal(t, c.Value(0), c.Request)
  43. cancelFunc()
  44. assert.NotNil(t, c.Done())
  45. select {
  46. case <-c.Done():
  47. default:
  48. assert.Fail(t, "context should be canceled")
  49. }
  50. }
  51. func TestContextHTTPContextWithDeadline(t *testing.T) {
  52. c, _ := CreateTestContext(httptest.NewRecorder())
  53. req, _ := http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  54. location, _ := time.LoadLocation("Europe/Paris")
  55. assert.NotNil(t, location)
  56. date := time.Date(2031, 12, 27, 16, 00, 00, 00, location)
  57. ctx, cancelFunc := context.WithDeadline(context.Background(), date)
  58. defer cancelFunc()
  59. c.Request = req.WithContext(ctx)
  60. assert.NoError(t, c.Err())
  61. ti, ok := c.Deadline()
  62. assert.Equal(t, ti, date)
  63. assert.True(t, ok)
  64. }