-
Notifications
You must be signed in to change notification settings - Fork 0
/
shortner_test.go
76 lines (62 loc) · 1.83 KB
/
shortner_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
70
71
72
73
74
75
76
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestCreateAlias(t *testing.T) {
// Create a new Gin router
gin.SetMode(gin.TestMode)
r := gin.Default()
r.POST("/:alias", createAlias)
// Create a sample request to use
reqBody := strings.NewReader(`{"url":"https://example.com"}`)
req, err := http.NewRequest(http.MethodPost, "/alias", reqBody)
if err != nil {
t.Fatalf("Couldn't create request: %v\n", err)
}
// Record the response
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestGetAlias(t *testing.T) {
// Create a new Gin router
gin.SetMode(gin.TestMode)
r := gin.Default()
store.Set("alias", &URLData{URL: "https://example.com", Count: 0})
r.GET("/:alias", getAlias)
// Create a sample request to use
req, err := http.NewRequest(http.MethodGet, "/alias", nil)
if err != nil {
t.Fatalf("Couldn't create request: %v\n", err)
}
// Record the response
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusMovedPermanently, w.Code)
assert.Equal(t, "https://example.com", w.Header().Get("Location"))
// Assert we increased the count
assert.Equal(t, 1, store.urls["alias"].Count)
}
func TestListStats(t *testing.T) {
// Create a new Gin router
gin.SetMode(gin.TestMode)
r := gin.Default()
r.GET("/stats", listStats)
// Create a sample request to use
req, err := http.NewRequest(http.MethodGet, "/stats", nil)
if err != nil {
t.Fatalf("Couldn't create request: %v\n", err)
}
// Record the response
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
// JSON response you're expecting
expectedJSON := `{"alias":{"URL":"https://example.com","Count":1}}`
assert.Equal(t, http.StatusOK, w.Code)
assert.JSONEq(t, expectedJSON, w.Body.String())
}