123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package api
- import (
- "net/http"
- "net/http/httptest"
- "testing"
- "github.com/gorilla/mux"
- "code.osinet.fr/fgm/kurz/domain"
- )
- func setupGet() (*httptest.Server, *http.Client) {
- router := mux.NewRouter()
- router.HandleFunc("/{short}", HandleGetShort)
- ts := httptest.NewServer(router)
- c := ts.Client()
- c.CheckRedirect = doNotFollowRedirects
- return ts, c
- }
- func TestHandleGetShortHappy(t *testing.T) {
- // Ensure storage contains the expected mapping.
- sr := make(domain.MockShortRepo)
- sr[domain.ShortURL{URL: sampleShort}] = domain.TargetURL{URL: sampleTarget}
- domain.RegisterRepositories(sr, nil)
- ts, c := setupGet()
- defer ts.Close()
- res, err := c.Get(ts.URL + "/" + sampleShort)
- if err != nil {
- t.Log("Getting an existing short URL should not fail")
- t.FailNow()
- }
- res.Body.Close()
- if res.StatusCode != http.StatusTemporaryRedirect {
- t.Logf("Existing short URL returned %d, expected %d", res.StatusCode, http.StatusTemporaryRedirect)
- t.FailNow()
- }
- location, err := res.Location()
- if err == http.ErrNoLocation {
- t.Log("Existing short URL returned a redirect without a Location header")
- t.FailNow()
- }
- if err != nil {
- t.Log(err)
- t.FailNow()
- }
- target := location.String()
- if target != sampleTarget {
- t.Logf("Existing short URL redirected to %s instead of expected location", target)
- t.FailNow()
- }
- }
- func TestHandleGetShortSadNotFound(t *testing.T) {
- // Ensure empty storage.
- sr := make(domain.MockShortRepo)
- domain.RegisterRepositories(sr, nil)
- ts, c := setupGet()
- defer ts.Close()
- res, err := c.Get(ts.URL + "/" + sampleShort)
- if err != nil {
- t.Error("Getting an nonexistent short URL should not fail")
- }
- res.Body.Close()
- if res.StatusCode != http.StatusNotFound {
- t.Errorf("Undefined short URL returned %d, expected %d", res.StatusCode, http.StatusNotFound)
- }
- }
|