選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

84 行
2.0 KiB

  1. package handlers
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. func TestContext(t *testing.T) {
  9. key := "key"
  10. val := 10
  11. body := "this is the output"
  12. h2 := wrappedHandler(t, key, val, body)
  13. // Create the context handler with a wrapped handler
  14. h := ContextHandler(http.HandlerFunc(
  15. func(w http.ResponseWriter, r *http.Request) {
  16. ctx, _ := GetContext(w)
  17. assertTrue(ctx != nil, "expected context to be non-nil", t)
  18. assertTrue(len(ctx) == 0, fmt.Sprintf("expected context to be empty, got %d", len(ctx)), t)
  19. ctx[key] = val
  20. h2.ServeHTTP(w, r)
  21. }), 2)
  22. s := httptest.NewServer(h)
  23. defer s.Close()
  24. // First call
  25. res, err := http.DefaultClient.Get(s.URL)
  26. if err != nil {
  27. panic(err)
  28. }
  29. res.Body.Close()
  30. // Second call, context should be cleaned at start
  31. res, err = http.DefaultClient.Get(s.URL)
  32. if err != nil {
  33. panic(err)
  34. }
  35. assertStatus(http.StatusOK, res.StatusCode, t)
  36. assertBody([]byte(body), res, t)
  37. }
  38. func TestWrappedContext(t *testing.T) {
  39. key := "key"
  40. val := 10
  41. body := "this is the output"
  42. h2 := wrappedHandler(t, key, val, body)
  43. h := ContextHandler(LogHandler(http.HandlerFunc(
  44. func(w http.ResponseWriter, r *http.Request) {
  45. ctx, _ := GetContext(w)
  46. if !assertTrue(ctx != nil, "expected context to be non-nil", t) {
  47. panic("ctx is nil")
  48. }
  49. assertTrue(len(ctx) == 0, fmt.Sprintf("expected context to be empty, got %d", len(ctx)), t)
  50. ctx[key] = val
  51. h2.ServeHTTP(w, r)
  52. }), NewLogOptions(nil, "%s", "url")), 2)
  53. s := httptest.NewServer(h)
  54. defer s.Close()
  55. res, err := http.DefaultClient.Get(s.URL)
  56. if err != nil {
  57. panic(err)
  58. }
  59. assertStatus(http.StatusOK, res.StatusCode, t)
  60. assertBody([]byte(body), res, t)
  61. }
  62. func wrappedHandler(t *testing.T, k, v interface{}, body string) http.Handler {
  63. return http.HandlerFunc(
  64. func(w http.ResponseWriter, r *http.Request) {
  65. ctx, _ := GetContext(w)
  66. ac := ctx[k]
  67. assertTrue(ac == v, fmt.Sprintf("expected value to be %v, got %v", v, ac), t)
  68. // Actually write something
  69. _, err := w.Write([]byte(body))
  70. if err != nil {
  71. panic(err)
  72. }
  73. })
  74. }