-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
70 lines (57 loc) · 1.53 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
package main
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestFindAllPost(t *testing.T) {
app := newApp()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
posts, err := app.findAllPost(ctx)
if err != nil {
t.Error("Get All Posts failed.")
}
if len(posts) == 0 {
t.Error("Posts did not return any values.")
}
}
func TestGetPosts(t *testing.T) {
// Create a request to pass to our handler. We don't have any query parameters for now, so we'll
// pass 'nil' as the third parameter.
req := httptest.NewRequest("GET", "/posts", nil)
// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
app := newApp()
rr := httptest.NewRecorder()
handler := http.HandlerFunc(app.getPosts)
// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
// directly and pass in our Request and ResponseRecorder.
handler.ServeHTTP(rr, req)
// Check the status code is what we expect.
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
var posts []post
err := json.NewDecoder(rr.Body).Decode(&posts)
if err != nil {
t.Error(err.Error())
t.Error("Error retreiving list of posts.")
}
if len(posts) == 0 {
t.Error("Error retreiving list of posts.")
}
}
func newApp() apps {
cfg := config{
port: 8000,
dsn: "postgres://app:app@localhost/app?sslmode=disable",
}
db, _ := open(cfg)
return apps{
DB: db,
}
}