-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_test.go
More file actions
95 lines (77 loc) · 2.41 KB
/
integration_test.go
File metadata and controls
95 lines (77 loc) · 2.41 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//go:build integration
package handlers_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
db "github.com/joeynolan/go-http-server/internal/db"
apphttp "github.com/joeynolan/go-http-server/internal/http"
"github.com/joeynolan/go-http-server/internal/http/handlers"
ilog "github.com/joeynolan/go-http-server/internal/platform/log"
)
const testBaseURL = "https://jnshorter.com"
func startIntegrationServer(t *testing.T) (*httptest.Server, func()) {
t.Helper()
sqlDB, err := db.OpenAndMigrate(":memory:")
if err != nil {
t.Fatalf("open in-memory db: %v", err)
}
logger := ilog.New()
r := chi.NewRouter()
r.Use(apphttp.MetricsMiddleware)
r.Use(apphttp.RequestLogger(logger.Desugar()))
h := handlers.NewHandler(sqlDB, logger, testBaseURL)
apphttp.Register(r, h)
srv := httptest.NewServer(r)
cleanup := func() {
srv.Close()
_ = sqlDB.Close()
logger.Sync()
}
return srv, cleanup
}
func TestIntegration_ShortenAndRedirect(t *testing.T) {
srv, cleanup := startIntegrationServer(t)
defer cleanup()
shortenReq := `{"url":"example.com"}`
res, err := http.Post(srv.URL+"/shorten", "application/json", strings.NewReader(shortenReq))
if err != nil {
t.Fatalf("POST /shorten: %v", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
t.Fatalf("status = %d, want %d", res.StatusCode, http.StatusCreated)
}
var shortenResp map[string]string
if err := json.NewDecoder(res.Body).Decode(&shortenResp); err != nil {
t.Fatalf("decode shorten response: %v", err)
}
shortURL := shortenResp["short"]
if !strings.HasPrefix(shortURL, testBaseURL+"/r/") {
t.Fatalf("short url = %q, want %s/r/...", shortURL, testBaseURL)
}
code := strings.TrimPrefix(shortURL, testBaseURL+"/r/")
if code == "" {
t.Fatalf("no generated code")
}
client := &http.Client{
// do not follow redirects so we can assert Location
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
redirectRes, err := client.Get(srv.URL + "/r/" + code)
if err != nil {
t.Fatalf("GET /r/%s: %v", code, err)
}
defer redirectRes.Body.Close()
if redirectRes.StatusCode != http.StatusFound {
t.Fatalf("status = %d, want %d", redirectRes.StatusCode, http.StatusFound)
}
if loc := redirectRes.Header.Get("Location"); loc != "https://example.com" {
t.Fatalf("location = %q, want %q", loc, "https://example.com")
}
}