forked from TheCacophonyProject/go-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_test.go
358 lines (295 loc) · 9.54 KB
/
api_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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// go-api - Client for the Cacophony API server.
// Copyright (C) 2018, The Cacophony Project
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
package api
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
yaml "gopkg.in/yaml.v2"
)
// tests against cacophony-api require apiURL to be pointing
// to a valid cacophony-api server and test-seed.sql to be run
const (
apiURL = "http://localhost:1080"
defaultDevice = "test-device"
defaultPassword = "test-password"
defaultGroup = "test-group"
)
var responseHeader = http.StatusOK
var rawThermalData = randString(100)
var testEventDetail = `{"description": {"type": "test-id", "details": {"tail":"fuzzy"} } }`
//Tests against httptest
func TestRegistrationHttpRequest(t *testing.T) {
ts := GetRegisterServer(t)
defer ts.Close()
api := getAPI(ts.URL, "", false)
err := api.register()
assert.NoError(t, err)
}
func TestNewTokenHttpRequest(t *testing.T) {
ts := GetNewAuthenticateServer(t)
defer ts.Close()
api := getAPI(ts.URL, "", true)
err := api.authenticate()
assert.NoError(t, err)
}
func TestUploadThermalRawHttpRequest(t *testing.T) {
ts := GetUploadThermalRawServer(t)
defer ts.Close()
api := getAPI(ts.URL, "", true)
reader := strings.NewReader(rawThermalData)
err := api.UploadThermalRaw(reader)
assert.NoError(t, err)
}
func getTokenResponse() *tokenResponse {
return &tokenResponse{
Messages: []string{},
Token: "tok-" + randString(20),
}
}
func getJSONRequestMap(r *http.Request) map[string]string {
var requestJson = map[string]string{}
decoder := json.NewDecoder(r.Body)
decoder.Decode(&requestJson)
return requestJson
}
// GetRegisterServer returns a test server that checks that register posts contain
// password,group and devicename
func GetRegisterServer(t *testing.T) *httptest.Server {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestJson := getJSONRequestMap(r)
assert.Equal(t, http.MethodPost, r.Method)
assert.NotEmpty(t, requestJson["password"])
assert.NotEmpty(t, requestJson["group"])
assert.NotEmpty(t, requestJson["devicename"])
w.WriteHeader(responseHeader)
w.Header().Set("Content-Type", "application/json")
token := getTokenResponse()
json.NewEncoder(w).Encode(token)
}))
return ts
}
//GetNewAuthenticateServer returns a test server that checks that posts contains
// passowrd and devicename
func GetNewAuthenticateServer(t *testing.T) *httptest.Server {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestJson := getJSONRequestMap(r)
assert.Equal(t, http.MethodPost, r.Method)
assert.NotEmpty(t, requestJson["password"])
assert.NotEmpty(t, requestJson["devicename"])
w.WriteHeader(responseHeader)
w.Header().Set("Content-Type", "application/json")
token := getTokenResponse()
json.NewEncoder(w).Encode(token)
}))
return ts
}
//getMimeParts retrieves data and file:file and Value:data from a multipart request
func getMimeParts(r *http.Request) (string, string) {
partReader, err := r.MultipartReader()
var fileData, dataType string
form, err := partReader.ReadForm(1000)
if err != nil {
return "", ""
}
if val, ok := form.File["file"]; ok {
filePart := val[0]
file, _ := filePart.Open()
b := make([]byte, 1)
for {
n, err := file.Read(b)
fileData += string(b[:n])
if err == io.EOF {
break
}
}
}
if val, ok := form.Value["data"]; ok {
dataType = val[0]
}
return dataType, fileData
}
//GetUploadThermalRawServer checks that the message is multipart and contains the required multipartmime file:file and Value:data
//and Authorization header
func GetUploadThermalRawServer(t *testing.T) *httptest.Server {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodPost, r.Method)
assert.NotEmpty(t, r.Header.Get("Authorization"))
dataType, file := getMimeParts(r)
assert.Equal(t, "{\"type\":\"thermalRaw\"}", dataType)
assert.Equal(t, rawThermalData, file)
w.WriteHeader(responseHeader)
}))
return ts
}
//Tests against cacophony-api server running at apiURL
func TestAPIRegistration(t *testing.T) {
api := getAPI(apiURL, "", false)
err := api.authenticate()
assert.Error(t, err)
err = api.register()
assert.NoError(t, err)
assert.True(t, api.JustRegistered())
assert.NotEqual(t, "", api.device.password)
assert.NotEqual(t, "", api.token)
assert.True(t, api.JustRegistered())
err = api.authenticate()
assert.NoError(t, err)
}
func TestAPIAuthenticate(t *testing.T) {
api := getAPI(apiURL, defaultPassword, false)
api.device.name = defaultDevice
err := api.authenticate()
assert.NoError(t, err)
assert.NotEmpty(t, api.token)
}
func TestAPIUploadThermalRaw(t *testing.T) {
api := getAPI(apiURL, "", false)
err := api.register()
reader := strings.NewReader(rawThermalData)
err = api.UploadThermalRaw(reader)
assert.NoError(t, err)
}
func getTestEvent() ([]byte, []time.Time) {
details := []byte(testEventDetail)
timeStamps := []time.Time{time.Now()}
return details, timeStamps
}
func TestAPIReportEvent(t *testing.T) {
api := getAPI(apiURL, "", false)
err := api.register()
details, timeStamps := getTestEvent()
err = api.ReportEvent(details, timeStamps)
assert.NoError(t, err)
}
func getTempPasswordConfig(t *testing.T) (string, func(), *ConfigPassword, *ConfigPassword) {
tmpFile, err := ioutil.TempFile("", "test-password")
require.NoError(t, err, "Must be able to create test password file")
tmpFile.Close()
cleanUpFunc := func() {
_ = os.Remove(tmpFile.Name())
}
confPassword := NewConfigPassword(tmpFile.Name())
anotherConfPassword := NewConfigPassword(tmpFile.Name())
return tmpFile.Name(), cleanUpFunc, confPassword, anotherConfPassword
}
func TestPasswordLock(t *testing.T) {
filename, cleanUp, confPassword, anotherConfPassword := getTempPasswordConfig(t)
defer cleanUp()
tempPassword := randString(20)
err := confPassword.WritePassword(tempPassword)
assert.Error(t, err)
locked, err := confPassword.GetExLock()
defer confPassword.Unlock()
require.True(t, locked, "File lock must succeed")
require.NoError(t, err, "must be able to get lock "+filename)
err = confPassword.WritePassword(tempPassword)
require.NoError(t, err, "must be able to write to"+filename)
locked, err = anotherConfPassword.GetExLock()
assert.Error(t, err)
assert.False(t, locked)
err = anotherConfPassword.WritePassword(randString(20))
assert.Error(t, err)
confPassword.Unlock()
currentPassword, err := confPassword.ReadPassword()
assert.NoError(t, err)
assert.Equal(t, tempPassword, currentPassword)
tempPassword = randString(20)
locked, err = anotherConfPassword.GetExLock()
defer anotherConfPassword.Unlock()
assert.NoError(t, err)
assert.True(t, locked)
err = anotherConfPassword.WritePassword(tempPassword)
assert.NoError(t, err)
currentPassword, err = anotherConfPassword.ReadPassword()
assert.NoError(t, err)
assert.Equal(t, tempPassword, currentPassword)
err = os.Remove(filename)
}
func createTestConfig(t *testing.T) (string, func()) {
conf := &Config{
ServerURL: apiURL,
Group: defaultGroup,
DeviceName: randString(10),
}
d, err := yaml.Marshal(conf)
require.NoError(t, err, "Must be able to make Config yaml")
tmpFile, err := ioutil.TempFile("", "test-config")
require.NoError(t, err, "Must be able to make test-config")
_, err = tmpFile.Write(d)
require.NoError(t, err, "Must be able to write to "+tmpFile.Name())
cleanUpFunc := func() {
removeTestConfig(tmpFile.Name())
}
return tmpFile.Name(), cleanUpFunc
}
// runMultipleRegistrations registers supplied count APIs with configFile on multiple threads
// and returns a channel in which the registered passwords will be supplied
func runMultipleRegistrations(configFile string, count int) (int, chan string) {
messages := make(chan string)
for i := 0; i < count; i++ {
go func() {
api, err := NewAPIFromConfig(configFile)
if err != nil {
messages <- err.Error()
} else {
messages <- api.device.password
}
}()
}
return count, messages
}
func removeTestConfig(configFile string) {
_ = os.Remove(configFile)
_ = os.Remove(privConfigFilename(configFile))
}
func TestMultipleRegistrations(t *testing.T) {
configFile, cleanUp := createTestConfig(t)
defer cleanUp()
count, passwords := runMultipleRegistrations(configFile, 4)
password := <-passwords
for i := 1; i < count; i++ {
pass := <-passwords
assert.Equal(t, password, pass)
}
}
// getAPI returns a CacophonyAPI for testing purposes using provided url and password with random name
// if register is set will provide a random token and password and set justRegistered
func getAPI(url, password string, register bool) *CacophonyAPI {
client := &CacophonyDevice{
group: defaultGroup,
name: randString(10),
password: password,
}
api := &CacophonyAPI{
serverURL: url,
device: client,
httpClient: newHTTPClient(),
}
if register {
api.device.password = randString(20)
api.token = "tok-" + randString(20)
api.justRegistered = true
}
return api
}