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.

78 lines
2.0 KiB

  1. package debug
  2. import (
  3. "bytes"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. )
  9. var (
  10. // mux is the HTTP request multiplexer used with the test server.
  11. mux *http.ServeMux
  12. // server is a test HTTP server used to provide mock API responses.
  13. server *httptest.Server
  14. )
  15. // setup sets up a test HTTP server along with a cos.Client that is
  16. // configured to talk to that test server. Tests should register handlers on
  17. // mux which provide mock responses for the API method being tested.
  18. func setup() {
  19. // test server
  20. mux = http.NewServeMux()
  21. server = httptest.NewServer(mux)
  22. }
  23. // teardown closes the test HTTP server.
  24. func teardown() {
  25. server.Close()
  26. }
  27. func TestDebugRequestTransport(t *testing.T) {
  28. setup()
  29. defer teardown()
  30. mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  31. w.Header().Add("X-Test-Response", "2333")
  32. w.WriteHeader(http.StatusBadGateway)
  33. w.Write([]byte("test response body"))
  34. })
  35. w := bytes.NewBufferString("")
  36. client := http.Client{}
  37. client.Transport = &DebugRequestTransport{
  38. RequestHeader: true,
  39. RequestBody: true,
  40. ResponseHeader: true,
  41. ResponseBody: true,
  42. Writer: w,
  43. }
  44. body := bytes.NewReader([]byte("test_request body"))
  45. req, _ := http.NewRequest("GET", server.URL, body)
  46. req.Header.Add("X-Test-Debug", "123")
  47. client.Do(req)
  48. b := make([]byte, 800)
  49. w.Read(b)
  50. info := string(b)
  51. if !strings.Contains(info, "GET / HTTP/1.1\r\n") ||
  52. !strings.Contains(info, "X-Test-Debug: 123\r\n") {
  53. t.Errorf("DebugRequestTransport debug info %#v don't contains request header", info)
  54. }
  55. if !strings.Contains(info, "\r\n\r\ntest_request body") {
  56. t.Errorf("DebugRequestTransport debug info %#v don't contains request body", info)
  57. }
  58. if !strings.Contains(info, "HTTP/1.1 502 Bad Gateway\r\n") ||
  59. !strings.Contains(info, "X-Test-Response: 2333\r\n") {
  60. t.Errorf("DebugRequestTransport debug info %#v don't contains response header", info)
  61. }
  62. if !strings.Contains(info, "\r\n\r\ntest response body") {
  63. t.Errorf("DebugRequestTransport debug info %#v don't contains response body", info)
  64. }
  65. }