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.
 
 
 

69 lines
1.4 KiB

  1. package handlers
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "testing"
  9. )
  10. func assertTrue(cond bool, msg string, t *testing.T) bool {
  11. if !cond {
  12. t.Error(msg)
  13. return false
  14. }
  15. return true
  16. }
  17. func assertStatus(ex, ac int, t *testing.T) {
  18. if ex != ac {
  19. t.Errorf("expected status code to be %d, got %d", ex, ac)
  20. }
  21. }
  22. func assertBody(ex []byte, res *http.Response, t *testing.T) {
  23. buf, err := ioutil.ReadAll(res.Body)
  24. if err != nil {
  25. panic(err)
  26. }
  27. defer res.Body.Close()
  28. if !bytes.Equal(ex, buf) {
  29. t.Errorf("expected body to be '%s' (%d), got '%s' (%d)", ex, len(ex), buf, len(buf))
  30. }
  31. }
  32. func assertGzippedBody(ex []byte, res *http.Response, t *testing.T) {
  33. gr, err := gzip.NewReader(res.Body)
  34. if err != nil {
  35. panic(err)
  36. }
  37. defer res.Body.Close()
  38. buf := bytes.NewBuffer(nil)
  39. _, err = io.Copy(buf, gr)
  40. if err != nil {
  41. panic(err)
  42. }
  43. if !bytes.Equal(ex, buf.Bytes()) {
  44. t.Errorf("expected unzipped body to be '%s' (%d), got '%s' (%d)", ex, len(ex), buf.Bytes(), buf.Len())
  45. }
  46. }
  47. func assertHeader(hName, ex string, res *http.Response, t *testing.T) {
  48. hVal, ok := res.Header[hName]
  49. if (!ok || len(hVal) == 0) && len(ex) > 0 {
  50. t.Errorf("expected header %s to be %s, was not set", hName, ex)
  51. } else if len(hVal) > 0 && hVal[0] != ex {
  52. t.Errorf("expected header %s to be %s, got %s", hName, ex, hVal)
  53. }
  54. }
  55. func assertPanic(t *testing.T) {
  56. if err := recover(); err == nil {
  57. t.Error("expected a panic, got none")
  58. }
  59. }