get_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package api
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/gorilla/mux"
  7. "code.osinet.fr/fgm/kurz/domain"
  8. )
  9. func setupGet() (*httptest.Server, *http.Client) {
  10. router := mux.NewRouter()
  11. router.HandleFunc("/{short}", handleGetShort)
  12. ts := httptest.NewServer(router)
  13. c := ts.Client()
  14. c.CheckRedirect = doNotFollowRedirects
  15. return ts, c
  16. }
  17. func TestHandleGetShortHappy(t *testing.T) {
  18. // Ensure storage contains the expected mapping.
  19. sr := make(domain.MockShortRepo)
  20. sr[domain.ShortURL{URL: sampleShort}] = domain.TargetURL{URL: sampleTarget}
  21. domain.RegisterRepositories(sr, nil)
  22. ts, c := setupGet()
  23. defer ts.Close()
  24. res, err := c.Get(ts.URL + "/" + sampleShort)
  25. if err != nil {
  26. t.Log("Getting an existing short URL should not fail")
  27. t.FailNow()
  28. }
  29. res.Body.Close()
  30. if res.StatusCode != http.StatusTemporaryRedirect {
  31. t.Logf("Existing short URL returned %d, expected %d", res.StatusCode, http.StatusTemporaryRedirect)
  32. t.FailNow()
  33. }
  34. location, err := res.Location()
  35. if err == http.ErrNoLocation {
  36. t.Log("Existing short URL returned a redirect without a Location header")
  37. t.FailNow()
  38. }
  39. if err != nil {
  40. t.Log(err)
  41. t.FailNow()
  42. }
  43. target := location.String()
  44. if !location.IsAbs() {
  45. t.Logf("Existing short URL redirection is not absolute: %s", target)
  46. t.FailNow()
  47. }
  48. if target != sampleTarget {
  49. t.Logf("Existing short URL redirected to %s instead of expected location", target)
  50. t.FailNow()
  51. }
  52. }
  53. func TestHandleGetShortSadNotFound(t *testing.T) {
  54. // Ensure empty storage.
  55. sr := make(domain.MockShortRepo)
  56. domain.RegisterRepositories(sr, nil)
  57. ts, c := setupGet()
  58. defer ts.Close()
  59. res, err := c.Get(ts.URL + "/" + sampleShort)
  60. if err != nil {
  61. t.Error("Getting an nonexistent short URL should not fail")
  62. }
  63. res.Body.Close()
  64. if res.StatusCode != http.StatusNotFound {
  65. t.Errorf("Undefined short URL returned %d, expected %d", res.StatusCode, http.StatusNotFound)
  66. }
  67. }