Repository navigation
Expand file tree
/
Copy pathClient_test.go
More file actions
477 lines (438 loc) · 17.2 KB
/
Copy pathClient_test.go
File metadata and controls
477 lines (438 loc) · 17.2 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package client
import (
"errors"
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/NeedleInAJayStack/haystack"
"github.com/NeedleInAJayStack/haystack/io"
"github.com/stretchr/testify/assert"
)
func TestClientAuth_NoAuth(t *testing.T) {
client := &Client{
clientHTTP: &clientHTTPNoAuth{},
uri: "http://localhost:8080/api/demo/",
username: "test",
password: "test",
}
openErr := client.Open()
if openErr != nil {
t.Error(openErr)
}
}
// clientHTTPNoAuth just returns a 200 for all requests
type clientHTTPNoAuth struct{}
func (clientHTTPNoAuth *clientHTTPNoAuth) do(req *http.Request) (*http.Response, error) {
response := http.Response{
Header: make(http.Header),
Body: http.NoBody,
}
switch req.Method {
case "GET":
response.StatusCode = 200
return &response, nil
}
return &response, nil
}
func TestClientAuth_BasicAuth(t *testing.T) {
client := &Client{
clientHTTP: &clientHTTPBasicAuth{},
uri: "http://localhost:8080/api/demo/",
username: "test",
password: "test",
}
openErr := client.Open()
if openErr != nil {
t.Error(openErr)
}
}
// clientHTTPBasicAuth validates the basic authentication
type clientHTTPBasicAuth struct{}
func (clientHTTPBasicAuth *clientHTTPBasicAuth) do(req *http.Request) (*http.Response, error) {
response := http.Response{
Header: make(http.Header),
Body: http.NoBody,
}
switch req.Method {
case "GET":
if req.Header.Get("Authorization") == "Basic dGVzdDp0ZXN0" {
response.StatusCode = 200
} else {
response.StatusCode = 401
response.Header.Set("WWW-Authenticate", "Basic realm=\"Haystack\"")
}
return &response, nil
}
return &response, nil
}
func TestClientAuth_Plaintext(t *testing.T) {
client := &Client{
clientHTTP: &clientHTTPPlaintextAuth{},
uri: "http://localhost:8080/api/demo/",
username: "test",
password: "test",
}
openErr := client.Open()
if openErr != nil {
t.Error(openErr)
}
}
// clientHTTPPlaintextAuth validates the plaintext haystack authentication
// https://project-haystack.org/doc/docHaystack/Auth#plaintext
type clientHTTPPlaintextAuth struct{}
func (clientHTTPPlaintextAuth *clientHTTPPlaintextAuth) do(req *http.Request) (*http.Response, error) {
response := http.Response{
Header: make(http.Header),
Body: http.NoBody,
}
switch req.Method {
case "GET":
if req.Header.Get("Authorization") == "Bearer pretend-this-is-a-token" {
response.StatusCode = 200
} else if req.Header.Get("Authorization") == "PLAINTEXT username=dGVzdA, password=dGVzdA" {
response.StatusCode = 200
response.Header.Set("Authentication-Info", "authToken=pretend-this-is-a-token")
} else {
response.StatusCode = 401
response.Header.Set("WWW-Authenticate", "PLAINTEXT realm=\"Haystack\"")
}
return &response, nil
}
return &response, nil
}
// TODO: SCRAM
func TestClient_Open(t *testing.T) {
client := testClient()
openErr := client.Open()
if openErr != nil {
t.Error(openErr)
}
}
func TestClient_Call(t *testing.T) {
client := testClient()
actual, err := client.Call("about", haystack.EmptyGrid())
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_about, t)
}
func TestClient_About(t *testing.T) {
client := testClient()
actual, aboutErr := client.About()
if aboutErr != nil {
t.Error(aboutErr)
}
// About returns a Dict so get the first value of expected manually
expectedZinc := clientHTTPMock_about
var reader io.ZincReader
reader.InitString(expectedZinc)
expectedGrid, err := reader.ReadVal()
if err != nil {
t.Error(err)
}
expected := expectedGrid.(haystack.Grid).RowAt(0).ToDict()
assert.Equal(t, actual, expected)
}
func TestClient_Close(t *testing.T) {
client := testClient()
err := client.Close()
if err != nil {
t.Error(err)
}
}
func TestClient_Filetypes(t *testing.T) {
client := testClient()
actual, err := client.Filetypes()
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_filetypes, t)
}
func TestClient_Ops(t *testing.T) {
client := testClient()
actual, err := client.Ops()
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_ops, t)
}
func TestClient_Read(t *testing.T) {
client := testClient()
actual, err := client.Read("site")
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_readSites, t)
}
func TestClient_ReadLimit(t *testing.T) {
client := testClient()
actual, err := client.ReadLimit("point", 1)
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_readPoint, t)
}
func TestClient_ReadByIds(t *testing.T) {
client := testClient()
points, pointsErr := client.ReadLimit("point", 1)
if pointsErr != nil {
t.Error(pointsErr)
} else {
pointRef := points.RowAt(0).Get("id").(haystack.Ref)
actual, err := client.ReadByIds([]haystack.Ref{pointRef})
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_readPoint, t)
}
}
func TestClient_HisRead(t *testing.T) {
client := testClient()
points, pointsErr := client.ReadLimit("point", 1)
if pointsErr != nil {
t.Error(pointsErr)
} else {
pointRef := points.RowAt(0).Get("id").(haystack.Ref)
actual, err := client.HisRead(pointRef, "yesterday")
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_hisRead20210103, t)
}
}
func TestClient_HisReadAbsDate(t *testing.T) {
client := testClient()
points, pointsErr := client.ReadLimit("point", 1)
if pointsErr != nil {
t.Error(pointsErr)
} else {
pointRef := points.RowAt(0).Get("id").(haystack.Ref)
fromDate := haystack.NewDate(2020, 10, 4)
toDate := haystack.NewDate(2020, 10, 5)
actual, err := client.HisReadAbsDate(pointRef, fromDate, toDate)
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_hisRead20201004to6, t)
}
}
func TestClient_HisReadAbsDateTime(t *testing.T) {
client := testClient()
points, pointsErr := client.ReadLimit("point", 1)
if pointsErr != nil {
t.Error(pointsErr)
} else {
pointRef := points.RowAt(0).Get("id").(haystack.Ref)
fromTs, _ := haystack.NewDateTimeFromString("2020-10-04T00:00:00-07:00 Los_Angeles")
toTs, _ := haystack.NewDateTimeFromString("2020-10-05T00:00:00-07:00 Los_Angeles")
actual, err := client.HisReadAbsDateTime(pointRef, fromTs, toTs)
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_hisReadDateTimes, t)
}
}
func TestClient_WatchSubCreate(t *testing.T) {
client := testClient()
actual, err := client.WatchSubCreate(
"abc",
haystack.NewNumber(1, "min"),
[]haystack.Ref{haystack.NewRef("abc-123", "")},
)
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, emptyRes, t)
}
func TestClient_WatchSubAdd(t *testing.T) {
client := testClient()
actual, err := client.WatchSubAdd(
"abc",
haystack.NewNumber(1, "min"),
[]haystack.Ref{haystack.NewRef("abc-123", "")},
)
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, emptyRes, t)
}
func TestClient_WatchUnsub(t *testing.T) {
client := testClient()
actual, err := client.WatchUnsub("abc", []haystack.Ref{haystack.NewRef("abc-123", "")})
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, emptyRes, t)
}
func TestClient_Eval(t *testing.T) {
client := testClient()
actual, err := client.Eval("read(point)")
if err != nil {
t.Error(err)
}
testClient_ValZinc(actual, clientHTTPMock_readPoint, t)
}
func testClient_ValZinc(actual haystack.Val, expectedZinc string, t *testing.T) {
var reader io.ZincReader
reader.InitString(expectedZinc)
expected, err := reader.ReadVal()
if err != nil {
t.Error(err)
}
assert.Equal(t, actual, expected, "\nACTUAL:\n"+actual.ToZinc()+"\n\nEXPECT:\n"+expected.ToZinc())
}
func testClient() *Client {
return &Client{
clientHTTP: &clientHTTPMock{},
uri: "http://localhost:8080/api/demo/",
username: "test",
password: "test",
}
}
// clientHTTPMock allows us to remove the HTTP dependency within tests
type clientHTTPMock struct{}
func (clientHTTPMock *clientHTTPMock) do(req *http.Request) (*http.Response, error) {
response := http.Response{
Header: make(http.Header),
Body: http.NoBody,
}
switch req.Method {
case "GET":
// GET is only used in authentication. Short-circuit and return a 200
response.StatusCode = 200
return &response, nil
case "POST":
response.StatusCode = 200
urlSlice := strings.Split(req.URL.Path, "/")
op := urlSlice[len(urlSlice)-1]
reqBody, err := ioutil.ReadAll(req.Body)
if err != nil {
return &response, err
}
responseBody, err := clientHTTPMock.postResponse(op, string(reqBody))
if err != nil {
return &response, err
}
response.Body = ioutil.NopCloser(strings.NewReader(responseBody))
return &response, nil
}
return &response, nil
}
func (clientHTTPMock *clientHTTPMock) postResponse(op string, reqBody string) (string, error) {
// These are taken from a SkySpark 3.0.26 demo project on 2021-01-03
switch op {
case "about":
// Can't use string literal because of Uri backticks
return clientHTTPMock_about, nil
case "close":
return emptyRes, nil
case "filetypes":
return clientHTTPMock_filetypes, nil
case "ops":
return clientHTTPMock_ops, nil
case "read":
if reqBody == "ver:\"3.0\"\nfilter, limit\n\"site\", N" { // readAll sites
return clientHTTPMock_readSites, nil
} else if reqBody == "ver:\"3.0\"\nfilter, limit\n\"point\", 1" { // readLimit point
return clientHTTPMock_readPoint, nil
} else if reqBody == "ver:\"3.0\"\nid\n@p:demo:r:2725da26-1dda68ee \"Gaithersburg RTU-1 Fan\"" { // readById
return clientHTTPMock_readPoint, nil
}
return emptyRes, errors.New("'read' argument not supported by mock class")
case "hisRead":
if reqBody == "ver:\"3.0\"\nid, range\n@p:demo:r:2725da26-1dda68ee \"Gaithersburg RTU-1 Fan\", \"yesterday\"" { // hisRead relative
return clientHTTPMock_hisRead20210103, nil
} else if reqBody == "ver:\"3.0\"\nid, range\n@p:demo:r:2725da26-1dda68ee \"Gaithersburg RTU-1 Fan\", \"2020-10-04,2020-10-05\"" { // hisRead absolute dates
return clientHTTPMock_hisRead20201004to6, nil
} else if reqBody == "ver:\"3.0\"\nid, range\n@p:demo:r:2725da26-1dda68ee \"Gaithersburg RTU-1 Fan\", \"2020-10-04T00:00:00-07:00 Los_Angeles,2020-10-05T00:00:00-07:00 Los_Angeles\"" { // hisRead absolute datetimes
return clientHTTPMock_hisReadDateTimes, nil
}
return emptyRes, errors.New("'hisRead' argument not supported by mock class")
case "watchSub":
return emptyRes, nil
case "watchUnsub":
return emptyRes, nil
case "eval":
if reqBody == "ver:\"3.0\"\nexpr\n\"read(point)\"" { // eval read(point)
return clientHTTPMock_readPoint, nil
}
return emptyRes, errors.New("'eval' argument not supported by mock class")
default:
return emptyRes, errors.New("haystack op not supported by mock class: " + op)
}
}
const (
clientHTTPMock_about string = "ver:\"3.0\"\n" + // Can't use string literal because of Uri backticks
"haystackVersion,projName,serverName,serverBootTime,serverTime,productName,productUri,productVersion,moduleName,moduleVersion,tz,whoami,hostDis,hostModel,hostId\n" +
"\"3.0\",\"demo\",\"JaysDesktop\",2021-01-03T00:21:01.588-07:00 Denver,2021-01-03T00:21:43.799-07:00 Denver,\"SkySpark\",`http://skyfoundry.com/skyspark`,\"3.0.26\",\"skyarcd\",\"3.0.26\",\"Denver\",\"test\",\"Linux amd64 5.4.0-58-generic\",\"Linux amd64 5.4.0-58-generic\",NA\n"
clientHTTPMock_filetypes string = `ver:"3.0"
name,dis,mime,receive,send
"zinc","Zinc","text/plain",M,M
"csv","CSV","text/csv",M,M
"excel","Excel","application/vnd.ms-excel",,M
"json","JSON","application/json",M,M
"jsonld","JSON-LD","application/ld+json",,M
"pdf","PDF","application/pdf",,M
"svg","SVG","image/svg+xml",,M
"trio","Trio","text/trio",M,M
"turtle","Turtle","text/turtle",,M
"xml","XML","text/xml",,M
"zinc","Zinc","text/zinc",M,M
`
clientHTTPMock_ops string = `ver:"3.0"
def, doc, is, lib, noSideEffects, typeName
^op:invokeAction, "Invoke a user action on a target entity.\nSee docHaystack::Ops#invokeAction chapter.", [^op], ^lib:phIoT, N, N
^op:hisWrite, "Write historized time series data from a his-point.\nSee docHaystack::Ops#hisWrite chapter.", [^op], ^lib:phIoT, N, "hx::HxHisWriteOp"
^op:watchUnsub, "Unsubscribe to entity data.\nSee docHaystack::Ops#watchUnsub chapter.", [^op], ^lib:ph, N, "hx::HxWatchUnsubOp"
^op:read, "Query the a set of entity records by id or by filter.\nSee docHaystack::Ops#read chapter.", [^op], ^lib:ph, M, "hx::HxReadOp"
^op:ops, "Query the op defs in the current namespace.\nSee docHaystack::Ops#ops chapter.", [^op], ^lib:ph, M, "hx::HxOpsOp"
^op:close, "Close the current session and cancel the auth bearer token.\nSee docHaystack::Ops#close chapter.", [^op], ^lib:ph, N, "hx::HxCloseOp"
^op:defs, "Query the definitions in the current namespace.\nSee docHaystack::Ops#defs chapter.", [^op], ^lib:ph, M, "hx::HxDefsOp"
^op:hisRead, "Read historized time series data from a his-point.\nSee docHaystack::Ops#hisRead chapter.", [^op], ^lib:phIoT, M, "hx::HxHisReadOp"
^op:watchSub, "Subscribe to entity data.\nSee docHaystack::Ops#watchSub chapter.", [^op], ^lib:ph, N, "hx::HxWatchSubOp"
^op:pointWrite, "Read or command a writable-point.\nSee docHaystack::Ops#pointWrite chapter.", [^op], ^lib:phIoT, N, "hx::HxPointWriteOp"
^op:eval, "Evaluate an Axon expression", [^op], ^lib:hx, N, "hx::HxEvalOp"
^op:libs, "Query the lib defs in the current namespace.\nSee docHaystack::Ops#libs chapter.", [^op], ^lib:ph, M, "hx::HxLibsOp"
^op:watchPoll, "Poll a watch subscription.\nSee docHaystack::Ops#watchPoll chapter.", [^op], ^lib:ph, N, "hx::HxWatchPollOp"
^op:filetypes, "Query the filetype defs in the current namespace.\nSee docHaystack::Ops#filetypes chapter.", [^op], ^lib:ph, M, "hx::HxFiletypesOp"
^op:commit, "Commit one or more diffs to the Folio database", [^op], ^lib:hx, N, "hx::HxCommitOp"
^op:about, "Query basic information about the server.\nSee docHaystack::Ops#about chapter.", [^op], ^lib:ph, M, "hx::HxAboutOp"
^op:nav, "Query the navigation tree for discovery.\nSee docHaystack::Ops#nav chapter.", [^op], ^lib:ph, M, "hx::HxNavOp"
`
clientHTTPMock_readSites string = `ver:"3.0"
id,area,dis,geoAddr,geoCity,geoCoord,geoCountry,geoPostalCode,geoState,geoStreet,hq,metro,occupiedEnd,occupiedStart,primaryFunction,regionRef,site,store,storeNum,tz,weatherStationRef,yearBuilt,mod
@p:demo:r:2725da26-ac563571 "Headquarters",140797ft²,"Headquarters","600 W Main St, Richmond, VA","Richmond",C(37.545826,-77.449188),"US","23220","VA","600 W Main St",M,"Richmond",18:00:00,08:00:00,"Office",@p:demo:r:2725da26-f3e488bc "Richmond",M,,,"New_York",@p:demo:r:2725da26-9fd27896 "Richmond, VA",1999,2020-10-23T18:15:02.701Z
@p:demo:r:2725da26-3ca6125c "Gaithersburg",8013ft²,"Gaithersburg","18212 Montgomery Village Ave, Gaithersburg, MD","Gaithersburg",C(39.154824,-77.209002),"US","20879","MD","18212 Montgomery Village Ave",,"Washington DC",21:00:00,09:00:00,"Retail Store",@p:demo:r:2725da26-e77a16f1 "Washington DC",M,M,4,"New_York",@p:demo:r:2725da26-9bb170b8 "Washington, DC",2001,2020-10-23T18:15:02.797Z
@p:demo:r:2725da26-d280b1b5 "Short Pump",17122ft²,"Short Pump","11282 W Broad St, Richmond, VA","Glen Allen",C(37.650338,-77.606105),"US","23060","VA","11282 W Broad St",,"Richmond",21:00:00,10:00:00,"Retail Store",@p:demo:r:2725da26-f3e488bc "Richmond",M,M,3,"New_York",@p:demo:r:2725da26-9fd27896 "Richmond, VA",1999,2020-10-23T18:15:02.763Z
@p:demo:r:2725da26-505b4ae8 "Carytown",3149ft²,"Carytown","3504 W Cary St, Richmond, VA","Richmond",C(37.555385,-77.486903),"US","23221","VA","3504 W Cary St",,"Richmond",20:00:00,10:00:00,"Retail Store",@p:demo:r:2725da26-f3e488bc "Richmond",M,M,1,"New_York",@p:demo:r:2725da26-9fd27896 "Richmond, VA",1996,2020-10-23T18:15:02.742Z
`
clientHTTPMock_readPoint string = `ver:"3.0"
id,navName,disMacro,point,his,siteRef,equipRef,curVal,curStatus,hisEnd,hisSize,hisStart,kind,tz,cmd,elecRef,cur,regionRef,fan,discharge,air,hisMode,enum,mod
@p:demo:r:2725da26-1dda68ee "Gaithersburg RTU-1 Fan","Fan","\\$equipRef \\$navName",M,M,@p:demo:r:2725da26-3ca6125c "Gaithersburg",@p:demo:r:2725da26-1d885a68 "Gaithersburg RTU-1",F,"ok",2021-01-21T22:15:00-05:00 New_York,2625,2019-01-01T00:00:00-05:00 New_York,"Bool","New_York",M,@p:demo:r:2725da26-8ddc7cf5 "Gaithersburg ElecMeter-Hvac",M,@p:demo:r:2725da26-e77a16f1 "Washington DC",M,M,M,"cov","off,on",2020-10-23T18:15:02.83Z
`
clientHTTPMock_hisRead20210103 string = `ver:"3.0" id:@p:demo:r:2725da26-1dda68ee "Gaithersburg RTU-1 Fan" hisStart:2021-01-02T00:00:00-05:00 New_York hisEnd:2021-01-03T00:00:00-05:00 New_York
ts,val
2021-01-02T00:00:00-05:00 New_York,F
2021-01-02T09:00:00-05:00 New_York,T
2021-01-02T21:15:00-05:00 New_York,F
`
clientHTTPMock_hisRead20201004to6 string = `ver:"3.0" id:@p:demo:r:2725da26-1dda68ee "Gaithersburg RTU-1 Fan" hisStart:2020-10-04T00:00:00-04:00 New_York hisEnd:2020-10-06T00:00:00-04:00 New_York
ts,val
2020-10-04T00:00:00-04:00 New_York,F
2020-10-04T09:00:00-04:00 New_York,T
2020-10-04T21:15:00-04:00 New_York,F
2020-10-05T00:00:00-04:00 New_York,F
2020-10-05T09:00:00-04:00 New_York,T
2020-10-05T21:15:00-04:00 New_York,F
`
clientHTTPMock_hisReadDateTimes string = `ver:"3.0" id:@p:demo:r:2725da26-1dda68ee "Gaithersburg RTU-1 Fan" hisStart:2020-10-04T03:00:00-04:00 New_York hisEnd:2020-10-05T03:00:00-04:00 New_York
ts,val
2020-10-04T09:00:00-04:00 New_York,T
2020-10-04T21:15:00-04:00 New_York,F
2020-10-05T00:00:00-04:00 New_York,F
`
emptyRes string = `ver:"3.0"
empty
`
)