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 !location.IsAbs() { t.Logf("Existing short URL redirection is not absolute: %s", target) t.FailNow() } 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) } }