-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoshort_test.go
108 lines (93 loc) · 2.64 KB
/
goshort_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
package main
import (
"bytes"
"encoding/json"
"github.com/spf13/viper"
. "gopkg.in/check.v1"
"goshort/utils"
"net/http"
"net/http/httptest"
"testing"
)
func executeRequest(app App, req *http.Request) *httptest.ResponseRecorder {
rr := httptest.NewRecorder()
app.Router.ServeHTTP(rr, req)
return rr
}
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) SetUpSuite(_ *C) {
utils.SetupViper("")
viper.SetDefault("token", "demo")
AppObject = App{}
AppObject.Initialize()
}
func (s *MySuite) SetAndGetGeneric(c *C, jsonStr []byte, expectedURL *Url) {
req, err := http.NewRequest("POST", "/urls/", bytes.NewBuffer(jsonStr))
c.Check(err, Equals, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer demo")
response := executeRequest(AppObject, req)
c.Check(response.Code, Equals, 200)
var url Url
dec := json.NewDecoder(response.Body)
dec.DisallowUnknownFields()
err = dec.Decode(&url)
c.Check(err, Equals, nil)
if expectedURL.Key != "" {
c.Check(url.Key, Equals, expectedURL.Key)
} else {
expectedURL.Key = url.Key
}
c.Check(url.Url, Equals, expectedURL.Url)
c.Check(url.Code, Equals, expectedURL.Code)
c.Check(url.Autogenerated, Equals, expectedURL.Autogenerated)
req, _ = http.NewRequest("GET", "/"+expectedURL.Key, bytes.NewBuffer([]byte{}))
response = executeRequest(AppObject, req)
c.Check(response.Code, Equals, expectedURL.Code)
c.Check(response.Header().Get("Location"), Equals, expectedURL.Url)
}
func (s *MySuite) TestSimplePost(c *C) {
s.SetAndGetGeneric(
c,
[]byte(`{
"key": "yandex",
"url": "https://yandex.ru"
}`),
&Url{
Key: "yandex",
Url: "https://yandex.ru",
Code: 301,
Autogenerated: false,
})
}
func (s *MySuite) TestGenericPost(c *C) {
s.SetAndGetGeneric(
c,
[]byte(`{"url": "https://yandex.ru"}`),
&Url{
Key: "",
Url: "https://yandex.ru",
Code: 301,
Autogenerated: true,
})
}
func (s *MySuite) TestNotDuplicatingGenericUrl(c *C) {
url := Url{
Key: "",
Url: "https://fjhdsjkhk.ru",
Code: 301,
Autogenerated: true,
}
s.SetAndGetGeneric(c, []byte(`{"url": "https://fjhdsjkhk.ru"}`), &url)
s.SetAndGetGeneric(c, []byte(`{"url": "https://fjhdsjkhk.ru"}`), &url)
}
func (s *MySuite) TestBadToken(c *C) {
req, err := http.NewRequest("POST", "/urls/", bytes.NewBuffer([]byte("")))
c.Check(err, Equals, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer ddd")
response := executeRequest(AppObject, req)
c.Check(response.Code, Equals, 401)
}