-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers_test.go
209 lines (180 loc) · 5.74 KB
/
helpers_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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/*
helpers for *_test.go code
*/
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Pallinder/go-randomdata"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/mysql"
_ "github.com/golang-migrate/migrate/v4/source/file"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"io"
"io/ioutil"
"log"
"math/rand"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
)
var s Server
const testB64PubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvxvSoA5+YJ0dK3HFy9ccnalbqSgVGJYmQXl/1JBcN1zZGUrsBDAPRdX+TTgWbW4Ah8C+PUVmf6YbA5d+ZWmBUIYds4Ft/v2qbh3/rBEFvNw+/HhspclzwI1On6EcnylLalpF6JYYjuw4QqIJd/CsnABZwAFQ8czdtUbomic7gh9UdjkEFed5C3QqD3Nes7w7glkrEocTzwizLuxnpQZFhDEjGgONgGJSi92yf8eh0STSLGrWjT8+nw/Dw6RSWQAZviEyRtJ52WdFHIsQEAU81N5NpCr7rDPr9GHFU8sdo8Lp3fQntOIvyjpIzKUXWyp+QVJAh6GMw2Fn16S+Jg127wIDAQAB"
func initDB(t *testing.M) {
rand.Seed(time.Now().UTC().UnixNano())
TESTDBNAME := "transfermeit_test"
// initialise db
db, err := dbConn(os.Getenv("db") + "/?multiStatements=True&loc=" + time.Local.String())
if err != nil {
panic(err.Error())
}
defer db.Close()
_, err = db.Exec(fmt.Sprintf(`DROP DATABASE IF EXISTS %[1]v;
CREATE DATABASE %[1]v;`, TESTDBNAME))
if err != nil {
panic(err)
}
db.Close()
// apply patches
dbConnStr := os.Getenv("db") + "/" + TESTDBNAME
m, err := migrate.New("file://sql/", "mysql://"+dbConnStr)
if err != nil {
panic(err)
}
// test up and down commands work
if err := m.Up(); err != nil {
panic(err)
}
if err := m.Down(); err != nil {
panic(err)
}
if err := m.Up(); err != nil {
panic(err)
}
db, err = dbConn(dbConnStr + "?parseTime=true&loc=" + time.Local.String())
s = Server{db: db}
code := t.Run() // RUN THE TEST
os.Exit(code)
}
func postRequest(form url.Values, handler http.HandlerFunc) *httptest.ResponseRecorder {
req, _ := http.NewRequest("POST", "", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
return rr
}
func genUser() (user User, form url.Values) {
form = url.Values{}
UUID, _ := uuid.NewRandom()
form.Set("UUID", UUID.String())
form.Set("public_key", testB64PubKey)
rr := postRequest(form, http.HandlerFunc(s.CreateCodeHandler))
if err := json.Unmarshal(rr.Body.Bytes(), &user); err != nil {
log.Fatal(err)
}
time.Sleep(time.Millisecond * time.Duration(10))
return
}
func genCreditUser(credit float64) (user User, form url.Values) {
user, form = genUser()
creditCode := RandomString(CreditCodeLen)
generateProCredit(creditCode, credit)
form.Set("UUID_key", user.UUIDKey)
form.Set("credit_code", creditCode)
_ = postRequest(form, http.HandlerFunc(s.RegisterCreditHandler))
return
}
func connectWSS(user User, form url.Values) (*httptest.Server, *http.Response, *websocket.Conn, error) {
wsheader := http.Header{}
wsheader.Set("UUID", form.Get("UUID"))
wsheader.Set("UUID-key", user.UUIDKey)
wsheader.Set("Version", "1.0")
return connectWSSHeader(wsheader)
}
func readSocketMessage(ws *websocket.Conn) (message SocketMessage) {
_, mess, err := ws.ReadMessage()
if err != nil {
Handle(err)
return
}
_ = json.Unmarshal(mess, &message)
return
}
func connectWSSHeader(wsheader http.Header) (*httptest.Server, *http.Response, *websocket.Conn, error) {
server := httptest.NewServer(http.HandlerFunc(s.WSHandler))
ws, res, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http"), wsheader)
Handle(err)
if err == nil {
// add ws read timeout
_ = ws.SetReadDeadline(time.Now().Add(5000 * time.Millisecond))
}
return server, res, ws, err
}
func generateProCredit(activationCode string, credit float64) {
_, err := s.db.Exec(`
INSERT INTO credit (activation_dttm, activation_code, credit, email)
VALUES (NOW(), ?, ?, ?)
`, activationCode, credit, randomdata.Email())
Handle(err)
}
func removeUUIDKey(form url.Values) {
Handle(UpdateErr(s.db.Exec(`
UPDATE user
SET UUID_key=''
WHERE UUID = ?
`, Hash(form.Get("UUID")))))
}
func upload(t *testing.T, user1 User, user2 User, form1 url.Values, fileSize int) string {
////////////
// UPLOAD //
////////////
// create a file
f, _ := os.Create("foo.bar")
defer f.Close()
defer os.Remove("foo.bar")
_ = f.Truncate(int64(fileSize))
// initial upload handler
initUploadR := initUpload(form1, user1, user2, fileSize)
if initUploadR.Code != 200 {
t.Errorf("Got %v (%v) expected %v", initUploadR.Code, initUploadR.Body, 200)
} else if initUploadR.Body.String() != testB64PubKey {
t.Errorf("Got '%v' expected '%v'", initUploadR.Body, testB64PubKey)
}
// actual file upload handler
password := RandomString(10)
uploadR := uploadFile(f, initUploadR.Header().Get("Set-Cookie"), password)
if uploadR.Code != 200 {
t.Errorf("Got %v (%v) expected %v", uploadR.Code, uploadR.Body, 200)
}
return password
}
func initUpload(form1 url.Values, user1 User, user2 User, fileSize int) *httptest.ResponseRecorder {
form1.Set("UUID_key", user1.UUIDKey)
form1.Set("code", user2.Code)
form1.Set("filesize", strconv.Itoa(fileSize))
return postRequest(form1, http.HandlerFunc(s.InitUploadHandler))
}
func uploadFile(f *os.File, initCookie string, pass string) *httptest.ResponseRecorder {
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", f.Name())
fileContents, _ := ioutil.ReadAll(f)
_, _ = part.Write(fileContents)
_ = writer.WriteField("password", pass)
_ = writer.Close()
_, _ = io.Copy(part, f)
req, _ := http.NewRequest("POST", "", body)
req.Header.Set("Cookie", initCookie)
req.Header.Set("Content-Type", writer.FormDataContentType())
uploadR := httptest.NewRecorder()
http.HandlerFunc(s.UploadHandler).ServeHTTP(uploadR, req)
return uploadR
}