get_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.Error("Getting an existing short URL should not fail")
  27. }
  28. res.Body.Close()
  29. if res.StatusCode != http.StatusTemporaryRedirect {
  30. t.Errorf("Existing short URL returned %d, expected %d", res.StatusCode, http.StatusTemporaryRedirect)
  31. }
  32. }
  33. func TestHandleGetShortSadNotFound(t *testing.T) {
  34. // Ensure empty storage.
  35. sr := make(domain.MockShortRepo)
  36. domain.RegisterRepositories(sr, nil)
  37. ts, c := setupGet()
  38. defer ts.Close()
  39. res, err := c.Get(ts.URL + "/" + sampleShort)
  40. if err != nil {
  41. t.Error("Getting an nonexistent short URL should not fail")
  42. }
  43. res.Body.Close()
  44. if res.StatusCode != http.StatusNotFound {
  45. t.Errorf("Existing short URL returned %d, expected %d", res.StatusCode, http.StatusNotFound)
  46. }
  47. }