-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshorty_test.go
69 lines (56 loc) · 1.7 KB
/
shorty_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package signup
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestShortenURL(t *testing.T) {
t.Run("calls shortening service", func(t *testing.T) {
apiKey := "TEST_API_KEY"
shortCode := "ahd2dh1xg2j"
wantURL := "https://ospk.org/" + shortCode
originalUrl := "http://thisisalongurl.gov/q?x=1&morestuff=everything"
mockSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("key") != apiKey {
fmt.Fprint(w, http.StatusUnauthorized)
return
}
var reqBody ShortLink
d := json.NewDecoder(r.Body)
err := d.Decode(&reqBody)
if err != nil {
t.Fatal(err)
}
assertEqual(t, reqBody.OriginalUrl, originalUrl)
resp := ShortLink{ShortURL: wantURL, Code: shortCode, OriginalUrl: reqBody.OriginalUrl}
e := json.NewEncoder(w)
err = e.Encode(resp)
assertNilError(t, err)
}))
shorty := NewURLShortener(ShortenerOpts{mockSrv.URL, apiKey})
got, err := shorty.ShortenURL(context.Background(), originalUrl)
if err != nil {
t.Fatal(err)
}
if got != wantURL {
t.Fatalf("want %q, but got %q", wantURL, got)
}
})
t.Run("returns the original URL if an error occurs", func(t *testing.T) {
originalURL := "http://thisisalongurl.gov/q?x=1&morestuff=everything"
wantURL := originalURL
shorty := NewURLShortener(ShortenerOpts{})
got, err := shorty.ShortenURL(context.Background(), originalURL)
if err == nil {
// Error should be EOF since there is no server to communicate with.
// The error type is irrelevant though.
t.Fatal("Error should not be nil")
}
if got != wantURL {
t.Fatalf("want original URL on errors:\n%q, but got:\n%q", wantURL, got)
}
})
}