/
main_test.go
95 lines (80 loc) · 2.07 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
package main
import (
"net/http"
"net/http/httptest"
"testing"
"encoding/json"
"time"
"strconv"
"github.com/netwars/api/cache"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"golang.org/x/net/context"
)
func TestTopicGetHandler(t *testing.T) {
now := time.Now()
success := map[int]*Topic{
1: {
ID: 1,
ForumID: 1,
Title: "test",
UpdatedAt: &now,
},
2: {
ID: 111241241,
ForumID: 235352,
Title: "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
UpdatedAt: &now,
},
}
// ------------
// ---Server---
// ------------
client := &ClientMock{}
for id, topic := range success {
client.On("FetchTopic", id).Return(topic, nil)
}
server := setupTestServer(client)
defer server.Close()
// ------------
// ----Test----
// ------------
for id, topic := range success {
res, err := http.Get(server.URL + "/topic/" + strconv.FormatInt(int64(id), 10))
if !assert.NoError(t, err) {
return
}
var requestedTopic *Topic
err = json.NewDecoder(res.Body).Decode(&requestedTopic)
if assert.NoError(t, err) {
assert.Equal(t, requestedTopic.ID, topic.ID)
assert.Equal(t, requestedTopic.ForumID, topic.ForumID)
assert.Equal(t, requestedTopic.Title, topic.Title)
assert.Equal(t, requestedTopic.Posts, topic.Posts)
assert.Equal(t, requestedTopic.UpdatedAt.Unix(), topic.UpdatedAt.Unix())
}
}
}
func setupTestServer(client Client) *httptest.Server {
topicCache := cache.NewCache(cache.CacheOpts{
Expiration: 1000000 * time.Hour,
Interval: 1000000 * time.Hour,
})
topicStorage := NewTopicStore(client, topicCache, TopicStoreOpts{
WarmUp: warmUp,
})
go logErrorChannel("topic-storage", topicStorage.Err())
ctx := context.Background()
ctx = NewTopicStorageContext(ctx, topicStorage)
return httptest.NewServer(buildRoutes(ctx))
}
type ClientMock struct {
mock.Mock
}
func (cm *ClientMock) FetchTopic(id int) (*Topic, error) {
args := cm.Called(id)
return args.Get(0).(*Topic), args.Error(1)
}
func (cm *ClientMock) FetchTopics(int, chan<- *Topic) error {
return nil
}