get_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // Use the special case of ErrUseLastResponse to ignore redirects.
  10. func doNotFollowRedirects(_ *http.Request, _ []*http.Request) error {
  11. return http.ErrUseLastResponse
  12. }
  13. const SampleShort = "short"
  14. func setupGet() (*httptest.Server, *http.Client) {
  15. router := mux.NewRouter()
  16. router.HandleFunc("/{short}", HandleGetShort)
  17. ts := httptest.NewServer(router)
  18. c := ts.Client()
  19. c.CheckRedirect = doNotFollowRedirects
  20. return ts, c
  21. }
  22. func TestHandleGetShortHappy(t *testing.T) {
  23. const SampleTarget = "http://example.com/"
  24. // Ensure storage contains the expected mapping.
  25. sr := make(domain.MockShortRepo)
  26. sr[domain.ShortURL{URL: SampleShort}] = domain.TargetURL{URL: SampleTarget}
  27. domain.RegisterRepositories(sr, nil)
  28. ts, c := setupGet()
  29. defer ts.Close()
  30. res, err := c.Get(ts.URL + "/" + SampleShort)
  31. if err != nil {
  32. t.Error("Getting an existing short URL should not fail")
  33. }
  34. res.Body.Close()
  35. if res.StatusCode != http.StatusTemporaryRedirect {
  36. t.Errorf("Existing short URL returned %d, expected %d", res.StatusCode, http.StatusTemporaryRedirect)
  37. }
  38. }
  39. func TestHandleGetShortSadNotFound(t *testing.T) {
  40. // Ensure empty storage.
  41. sr := make(domain.MockShortRepo)
  42. domain.RegisterRepositories(sr, nil)
  43. ts, c := setupGet()
  44. defer ts.Close()
  45. res, err := c.Get(ts.URL + "/" + SampleShort)
  46. if err != nil {
  47. t.Error("Getting an nonexistent short URL should not fail")
  48. }
  49. res.Body.Close()
  50. if res.StatusCode != http.StatusNotFound {
  51. t.Errorf("Existing short URL returned %d, expected %d", res.StatusCode, http.StatusNotFound)
  52. }
  53. }