-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
181 lines (153 loc) · 5.3 KB
/
main_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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
// setupRouter creates a test router with all routes configured
func setupRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.Default()
// Enable CORS
r.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
})
api := r.Group("/api")
{
api.GET("/stories", getStories)
api.GET("/stories/:type", getStories)
}
return r
}
// TestGetStoriesEndpoint tests the main stories endpoint
func TestGetStoriesEndpoint(t *testing.T) {
router := setupRouter()
tests := []struct {
name string
endpoint string
expectedStatus int
validateResponse func(*testing.T, []Story)
}{
{
name: "Get Top Stories",
endpoint: "/api/stories",
expectedStatus: http.StatusOK,
validateResponse: func(t *testing.T, stories []Story) {
assert.NotEmpty(t, stories, "Stories should not be empty")
for _, story := range stories {
assert.NotZero(t, story.ID, "Story ID should not be zero")
assert.NotEmpty(t, story.Title, "Story title should not be empty")
assert.NotEmpty(t, story.SubmittedBy, "Story submitter should not be empty")
assert.NotZero(t, story.CreatedAt, "Story creation time should not be zero")
assert.Contains(t, story.CommentsURL, "news.ycombinator.com/item", "Comments URL should be a valid HN URL")
assert.GreaterOrEqual(t, story.Comments, 0, "Comments count should be non-negative")
}
},
},
{
name: "Get Show HN Stories",
endpoint: "/api/stories/show",
expectedStatus: http.StatusOK,
validateResponse: func(t *testing.T, stories []Story) {
assert.NotEmpty(t, stories, "Stories should not be empty")
for _, story := range stories {
assert.Contains(t, story.Title, "Show HN:", "Show HN stories should have 'Show HN:' prefix")
assert.Equal(t, "show", story.Type, "Story type should be 'show'")
}
},
},
{
name: "Get Ask HN Stories",
endpoint: "/api/stories/ask",
expectedStatus: http.StatusOK,
validateResponse: func(t *testing.T, stories []Story) {
assert.NotEmpty(t, stories, "Stories should not be empty")
for _, story := range stories {
assert.Contains(t, story.Title, "Ask HN:", "Ask HN stories should have 'Ask HN:' prefix")
assert.Equal(t, "ask", story.Type, "Story type should be 'ask'")
}
},
},
{
name: "Invalid Story Type",
endpoint: "/api/stories/invalid",
expectedStatus: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", tt.endpoint, nil)
router.ServeHTTP(w, req)
assert.Equal(t, tt.expectedStatus, w.Code)
if tt.expectedStatus == http.StatusOK {
var stories []Story
err := json.Unmarshal(w.Body.Bytes(), &stories)
assert.NoError(t, err, "Should be able to unmarshal response")
if tt.validateResponse != nil {
tt.validateResponse(t, stories)
}
}
})
}
}
// TestCaching tests the caching functionality
func TestCaching(t *testing.T) {
// Reset cache for testing
cache = &StoriesCache{
stories: make(map[string][]Story),
lastUpdate: make(map[string]time.Time),
}
router := setupRouter()
// First request should hit the API
w1 := httptest.NewRecorder()
req1, _ := http.NewRequest("GET", "/api/stories", nil)
start := time.Now()
router.ServeHTTP(w1, req1)
firstDuration := time.Since(start)
assert.Equal(t, http.StatusOK, w1.Code)
// Second request should hit the cache
w2 := httptest.NewRecorder()
req2, _ := http.NewRequest("GET", "/api/stories", nil)
start = time.Now()
router.ServeHTTP(w2, req2)
secondDuration := time.Since(start)
assert.Equal(t, http.StatusOK, w2.Code)
assert.True(t, secondDuration < firstDuration, "Cached request should be faster")
// Verify responses are identical
assert.Equal(t, w1.Body.String(), w2.Body.String(), "Cached response should match original")
}
// TestErrorResponse tests error handling
func TestErrorResponse(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/stories/invalid", nil)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
var response ErrorResponse
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err, "Should be able to unmarshal error response")
assert.Contains(t, response.Error, "invalid story type", "Error message should indicate invalid type")
}
// TestCORSHeaders tests CORS headers
func TestCORSHeaders(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("OPTIONS", "/api/stories", nil)
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Equal(t, "*", w.Header().Get("Access-Control-Allow-Origin"))
assert.Equal(t, "GET, OPTIONS", w.Header().Get("Access-Control-Allow-Methods"))
assert.Equal(t, "Origin, Content-Type", w.Header().Get("Access-Control-Allow-Headers"))
}