-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-handler_test.go
More file actions
856 lines (766 loc) · 31.4 KB
/
api-handler_test.go
File metadata and controls
856 lines (766 loc) · 31.4 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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/indexdata/crosslink/broker/common"
"github.com/indexdata/crosslink/broker/vcs"
"github.com/indexdata/crosslink/iso18626"
"github.com/jackc/pgx/v5/pgtype"
"github.com/stretchr/testify/assert"
"github.com/google/uuid"
"github.com/indexdata/crosslink/broker/api"
"github.com/indexdata/crosslink/broker/app"
"github.com/indexdata/crosslink/broker/events"
"github.com/indexdata/crosslink/broker/ill_db"
"github.com/indexdata/crosslink/broker/oapi"
apptest "github.com/indexdata/crosslink/broker/test/apputils"
mocks "github.com/indexdata/crosslink/broker/test/mocks"
test "github.com/indexdata/crosslink/broker/test/utils"
"github.com/indexdata/crosslink/directory"
"github.com/indexdata/go-utils/utils"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/modules/postgres"
"github.com/testcontainers/testcontainers-go/wait"
)
var illRepo ill_db.IllRepo
var eventRepo events.EventRepo
var sseBroker *api.SseBroker
var mockIllRepoError = new(mocks.MockIllRepositoryError)
var mockEventRepoError = new(mocks.MockEventRepositoryError)
var handlerMock = api.NewApiHandler(mockEventRepoError, mockIllRepoError, common.NewTenant(""), api.LIMIT_DEFAULT)
func TestMain(m *testing.M) {
app.TENANT_TO_SYMBOL = "ISIL:DK-{tenant}"
ctx := context.Background()
app.DB_PROVISION = true
pgContainer, err := postgres.Run(ctx, "postgres",
postgres.WithDatabase("crosslink"),
postgres.WithUsername("crosslink"),
postgres.WithPassword("crosslink"),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).WithStartupTimeout(5*time.Second)),
)
test.Expect(err, "failed to start db container")
connStr, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
test.Expect(err, "failed to get conn string")
app.ConnectionString = connStr
app.MigrationsFolder = "file://../../migrations"
app.HTTP_PORT = utils.Must(test.GetFreePort())
ctx, cancel := context.WithCancel(context.Background())
appContext := apptest.StartAppReturnContext(ctx)
illRepo = appContext.IllRepo
eventRepo = appContext.EventRepo
sseBroker = appContext.SseBroker
test.WaitForServiceUp(app.HTTP_PORT)
defer cancel()
code := m.Run()
test.Expect(pgContainer.Terminate(ctx), "failed to stop db container")
os.Exit(code)
}
func TestGetIndex(t *testing.T) {
httpGet(t, "/", "", http.StatusOK)
body := getResponseBody(t, "/")
var resp oapi.Index
err := json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, vcs.GetCommit(), resp.Revision)
assert.Equal(t, vcs.GetSignature(), resp.Signature)
assert.Equal(t, getLocalhostWithPort()+api.ILL_TRANSACTIONS_PATH, resp.Links.IllTransactionsLink)
assert.Equal(t, getLocalhostWithPort()+api.EVENTS_PATH, resp.Links.EventsLink)
assert.Equal(t, getLocalhostWithPort()+api.PEERS_PATH, resp.Links.PeersLink)
assert.Equal(t, getLocalhostWithPort()+api.LOCATED_SUPPLIERS_PATH, resp.Links.LocatedSuppliersLink)
}
func TestGetEvents(t *testing.T) {
illId := apptest.GetIllTransId(t, illRepo)
eventId := apptest.GetEventId(t, eventRepo, illId, events.EventTypeNotice, events.EventStatusSuccess, events.EventNameMessageRequester)
httpGet(t, "/events", "", http.StatusBadRequest)
body := getResponseBody(t, "/events?ill_transaction_id="+illId)
var resp oapi.Events
err := json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.GreaterOrEqual(t, len(resp.Items), 1)
assert.GreaterOrEqual(t, resp.About.Count, int64(1))
assert.GreaterOrEqual(t, resp.About.Count, int64(len(resp.Items)))
assert.Equal(t, eventId, resp.Items[0].Id)
body = getResponseBody(t, "/events?ill_transaction_id=not-exists")
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 0)
assert.Equal(t, []oapi.Event{}, resp.Items)
}
func TestGetIllTransactions(t *testing.T) {
id := apptest.GetIllTransId(t, illRepo)
ctx := common.CreateExtCtxWithArgs(context.Background(), nil)
trans, err := illRepo.GetIllTransactionById(ctx, id)
assert.NoError(t, err)
reqReqId := uuid.NewString()
trans.RequesterRequestID = pgtype.Text{
String: reqReqId,
Valid: true,
}
trans, err = illRepo.SaveIllTransaction(ctx, ill_db.SaveIllTransactionParams(trans))
assert.NoError(t, err)
body := getResponseBody(t, "/ill_transactions")
var resp oapi.IllTransactions
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.GreaterOrEqual(t, len(resp.Items), 1)
assert.Equal(t, resp.About.Count, int64(len(resp.Items)))
// Query
body = getResponseBody(t, "/ill_transactions?requester_req_id="+url.QueryEscape(reqReqId))
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, reqReqId, resp.Items[0].RequesterRequestID)
body = getResponseBody(t, "/ill_transactions?requester_req_id=not-exists")
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 0)
assert.Equal(t, []oapi.IllTransaction{}, resp.Items)
for i := range 2 * api.LIMIT_DEFAULT {
requester := "ISIL:DK-BIB1"
if i > api.LIMIT_DEFAULT+3 {
requester = "ISIL:DK-BIB2"
}
illId := uuid.NewString()
reqReqId := uuid.NewString()
_, err := illRepo.SaveIllTransaction(common.CreateExtCtxWithArgs(context.Background(), nil), ill_db.SaveIllTransactionParams{
ID: illId,
RequesterSymbol: pgtype.Text{
String: requester,
Valid: true,
},
RequesterRequestID: pgtype.Text{
String: reqReqId,
Valid: true,
},
Timestamp: test.GetNow(),
})
assert.NoError(t, err)
}
body = getResponseBody(t, "/ill_transactions")
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, int(api.LIMIT_DEFAULT), len(resp.Items))
count := resp.About.Count
assert.GreaterOrEqual(t, count, int64(1+2*api.LIMIT_DEFAULT))
assert.LessOrEqual(t, count, int64(3*api.LIMIT_DEFAULT))
assert.Nil(t, resp.About.PrevLink)
assert.NotNil(t, resp.About.NextLink)
assert.NotNil(t, resp.About.LastLink)
assert.Equal(t, getLocalhostWithPort()+"/ill_transactions?offset=10", *resp.About.NextLink)
assert.Equal(t, getLocalhostWithPort()+"/ill_transactions?offset=20", *resp.About.LastLink)
body = getResponseBody(t, "/ill_transactions?offset=1000")
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, count, resp.About.Count)
body = getResponseBody(t, "/ill_transactions?limit=0")
resp.About.LastLink = nil
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, count, resp.About.Count)
assert.Nil(t, resp.About.LastLink)
body = getResponseBody(t, "/ill_transactions?offset=3&limit="+strconv.Itoa(int(api.LIMIT_DEFAULT)))
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.GreaterOrEqual(t, resp.About.Count, int64(1+2*api.LIMIT_DEFAULT))
assert.LessOrEqual(t, resp.About.Count, int64(3*api.LIMIT_DEFAULT))
prevLink := *resp.About.PrevLink
assert.Contains(t, prevLink, "offset=0")
body = getResponseBody(t, "/broker/ill_transactions?requester_symbol="+url.QueryEscape("ISIL:DK-BIB1"))
resp.About.NextLink = nil
resp.About.PrevLink = nil
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, int(api.LIMIT_DEFAULT), len(resp.Items))
assert.GreaterOrEqual(t, resp.About.Count, int64(3+api.LIMIT_DEFAULT))
assert.LessOrEqual(t, resp.About.Count, int64(2*api.LIMIT_DEFAULT))
assert.Nil(t, resp.About.PrevLink)
assert.NotNil(t, resp.About.NextLink)
assert.NotNil(t, resp.About.LastLink)
nextLink := *resp.About.NextLink
lastLink := *resp.About.LastLink
assert.True(t, strings.HasPrefix(nextLink, getLocalhostWithPort()+"/broker/ill_transactions?"))
assert.Contains(t, nextLink, "requester_symbol="+url.QueryEscape("ISIL:DK-BIB1"))
assert.True(t, strings.HasPrefix(lastLink, getLocalhostWithPort()+"/broker/ill_transactions?"))
assert.Contains(t, lastLink, "requester_symbol="+url.QueryEscape("ISIL:DK-BIB1"))
assert.Contains(t, lastLink, "offset=10")
// we have estblished that the next link is correct, now we will check if it works
hres, err := http.Get(nextLink) // nolint:gosec
assert.NoError(t, err)
defer hres.Body.Close()
body, err = io.ReadAll(hres.Body)
assert.NoError(t, err)
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.NotNil(t, resp.About.PrevLink)
prevLink = *resp.About.PrevLink
assert.True(t, strings.HasPrefix(prevLink, getLocalhostWithPort()+"/broker/ill_transactions?"))
assert.Contains(t, prevLink, "offset=0")
body = getResponseBody(t, "/ill_transactions?cql="+url.QueryEscape("requester_symbol = ISIL:DK-BIB1"))
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 10)
body = getResponseBody(t, "/ill_transactions?cql="+url.QueryEscape("requester_symbol = ISIL:DK-BIB2"))
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 6)
body = getResponseBody(t, "/ill_transactions?cql="+url.QueryEscape("requester_symbol <> ISIL:DK-BIB2"))
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 10)
body = getResponseBody(t, "/ill_transactions?cql="+url.QueryEscape("requester_symbol = ISIL:DK-BIB3"))
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 0)
body = getResponseBody(t, "/ill_transactions?cql="+url.QueryEscape("requester_symbol = ISIL:DK-BIB3 or requester_symbol = ISIL:DK-BIB2"))
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 6)
}
func TestGetIllTransactionsId(t *testing.T) {
illId := apptest.GetIllTransId(t, illRepo)
body := getResponseBody(t, "/ill_transactions/"+illId)
var resp oapi.IllTransaction
err := json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, illId, resp.Id)
assert.Equal(t, getLocalhostWithPort()+"/events?ill_transaction_id="+url.PathEscape(illId), resp.EventsLink)
assert.Equal(t, getLocalhostWithPort()+"/located_suppliers?ill_transaction_id="+url.PathEscape(illId), resp.LocatedSuppliersLink)
// Delete peer
httpRequest(t, "DELETE", "/ill_transactions/"+illId, nil, "", http.StatusNoContent)
httpRequest(t, "DELETE", "/ill_transactions/"+illId, nil, "", http.StatusNotFound)
}
func TestGetLocatedSuppliers(t *testing.T) {
illId := apptest.GetIllTransId(t, illRepo)
peer := apptest.CreatePeer(t, illRepo, "ISIL:LOC_SUP", "")
locSup := apptest.CreateLocatedSupplier(t, illRepo, illId, peer.ID, "ISIL:LOC_SUP", string(iso18626.TypeStatusLoaned))
httpGet(t, "/located_suppliers", "", http.StatusBadRequest)
var resp oapi.LocatedSuppliers
body := getResponseBody(t, "/located_suppliers?ill_transaction_id="+illId)
err := json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.GreaterOrEqual(t, len(resp.Items), 1)
assert.Equal(t, resp.Items[0].Id, locSup.ID)
assert.GreaterOrEqual(t, resp.About.Count, int64(len(resp.Items)))
body = getResponseBody(t, "/located_suppliers?ill_transaction_id=not-exists")
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 0)
assert.Equal(t, []oapi.LocatedSupplier{}, resp.Items)
}
func TestBrokerCRUD(t *testing.T) {
// app.TENANT_TO_SYMBOL = "ISIL:DK-{tenant}"
illId := uuid.New().String()
reqReqId := uuid.New().String()
_, err := illRepo.SaveIllTransaction(common.CreateExtCtxWithArgs(context.Background(), nil), ill_db.SaveIllTransactionParams{
ID: illId,
RequesterSymbol: pgtype.Text{
String: "ISIL:DK-DIKU",
Valid: true,
},
RequesterRequestID: pgtype.Text{
String: reqReqId,
Valid: true,
},
Timestamp: test.GetNow(),
})
assert.NoError(t, err)
body := httpGet(t, "/broker/ill_transactions/"+illId, "diku", http.StatusOK)
var tran oapi.IllTransaction
err = json.Unmarshal(body, &tran)
assert.NoError(t, err)
assert.Equal(t, illId, tran.Id)
assert.Equal(t, getLocalhostWithPort()+"/broker/events?ill_transaction_id="+url.PathEscape(illId), tran.EventsLink)
assert.Equal(t, getLocalhostWithPort()+"/broker/located_suppliers?ill_transaction_id="+url.PathEscape(illId), tran.LocatedSuppliersLink)
httpGet(t, "/broker/ill_transactions/"+illId+"?requester_symbol="+url.QueryEscape("ISIL:DK-DIKU"), "diku", http.StatusOK)
httpGet(t, "/broker/ill_transactions/"+illId+"?requester_symbol="+url.QueryEscape("ISIL:DK-DIKU"), "ruc", http.StatusNotFound)
httpGet(t, "/broker/ill_transactions/"+illId, "ruc", http.StatusNotFound)
httpGet(t, "/broker/ill_transactions/"+illId, "", http.StatusNotFound)
body = httpGet(t, "/broker/ill_transactions/"+illId+"?requester_symbol="+url.QueryEscape("ISIL:DK-DIKU"), "", http.StatusOK)
err = json.Unmarshal(body, &tran)
assert.NoError(t, err)
assert.Equal(t, illId, tran.Id)
assert.Equal(t, 1, len(httpGetTrans(t, "/broker/ill_transactions", "diku", http.StatusOK)))
assert.Equal(t, 1, len(httpGetTrans(t, "/broker/ill_transactions?cql="+url.QueryEscape("requester_symbol=ISIL:DK-DIKU"), "diku", http.StatusOK)))
assert.Equal(t, 0, len(httpGetTrans(t, "/broker/ill_transactions?cql="+url.QueryEscape("requester_symbol=ISIL:DK-RUC"), "diku", http.StatusOK)))
assert.Equal(t, 0, len(httpGetTrans(t, "/broker/ill_transactions", "ruc", http.StatusOK)))
assert.Equal(t, 0, len(httpGetTrans(t, "/broker/ill_transactions", "", http.StatusOK)))
body = httpGet(t, "/broker/ill_transactions?requester_req_id="+url.QueryEscape(reqReqId), "diku", http.StatusOK)
var resp oapi.IllTransactions
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Len(t, resp.Items, 1)
assert.Equal(t, illId, resp.Items[0].Id)
peer := apptest.CreatePeer(t, illRepo, "ISIL:LOC_OTHER", "")
locSup := apptest.CreateLocatedSupplier(t, illRepo, illId, peer.ID, "ISIL:LOC_OTHER", string(iso18626.TypeStatusLoaned))
body = httpGet(t, "/broker/located_suppliers?requester_req_id="+url.QueryEscape(reqReqId), "diku", http.StatusOK)
var supps oapi.LocatedSuppliers
err = json.Unmarshal(body, &supps)
assert.NoError(t, err)
assert.Len(t, supps.Items, 1)
assert.Equal(t, locSup.ID, supps.Items[0].Id)
body = httpGet(t, "/broker/located_suppliers?ill_transaction_id="+url.QueryEscape(illId), "diku", http.StatusOK)
err = json.Unmarshal(body, &supps)
assert.NoError(t, err)
assert.Len(t, supps.Items, 1)
assert.Equal(t, locSup.ID, supps.Items[0].Id)
body = httpGet(t, "/broker/located_suppliers?requester_req_id="+url.QueryEscape(reqReqId), "ruc", http.StatusOK)
err = json.Unmarshal(body, &supps)
assert.NoError(t, err)
assert.Len(t, supps.Items, 0)
body = httpGet(t, "/broker/located_suppliers?requester_req_id="+url.QueryEscape(uuid.NewString()), "diku", http.StatusOK)
err = json.Unmarshal(body, &supps)
assert.NoError(t, err)
assert.Len(t, supps.Items, 0)
eventId := apptest.GetEventId(t, eventRepo, illId, events.EventTypeNotice, events.EventStatusSuccess, events.EventNameMessageRequester)
body = httpGet(t, "/broker/events?requester_req_id="+url.QueryEscape(reqReqId), "diku", http.StatusOK)
var events oapi.Events
err = json.Unmarshal(body, &events)
assert.NoError(t, err)
assert.Len(t, events.Items, 1)
assert.Equal(t, eventId, events.Items[0].Id)
body = httpGet(t, "/broker/events?requester_req_id="+url.QueryEscape(reqReqId)+"&requester_symbol="+url.QueryEscape("ISIL:DK-DIKU"), "", http.StatusOK)
err = json.Unmarshal(body, &events)
assert.NoError(t, err)
assert.Len(t, events.Items, 1)
assert.Equal(t, eventId, events.Items[0].Id)
body = httpGet(t, "/broker/events?ill_transaction_id="+url.QueryEscape(illId), "diku", http.StatusOK)
err = json.Unmarshal(body, &events)
assert.NoError(t, err)
assert.Len(t, events.Items, 1)
assert.Equal(t, eventId, events.Items[0].Id)
body = httpGet(t, "/broker/events?requester_req_id="+url.QueryEscape(reqReqId), "ruc", http.StatusOK)
err = json.Unmarshal(body, &events)
assert.NoError(t, err)
assert.Len(t, events.Items, 0)
body = httpGet(t, "/broker/events?requester_req_id="+url.QueryEscape(uuid.NewString()), "diku", http.StatusOK)
err = json.Unmarshal(body, &events)
assert.NoError(t, err)
assert.Len(t, events.Items, 0)
}
func TestPeersLinks(t *testing.T) {
for i := 0; i < 2*int(api.LIMIT_DEFAULT); i++ {
peer := "ISIL:DK-PEER" + strconv.Itoa(i)
toCreate := oapi.Peer{
Id: uuid.New().String(),
Name: peer,
Url: "https://url.com",
Symbols: []string{peer},
RefreshPolicy: oapi.Transaction,
}
apptest.CreatePeer(t, illRepo, toCreate.Symbols[0], "")
}
resp := getPeers(t)
assert.Len(t, resp.Items, int(api.LIMIT_DEFAULT))
assert.GreaterOrEqual(t, int(resp.About.Count), int(2*api.LIMIT_DEFAULT))
assert.NotNil(t, resp.About.NextLink)
assert.NotNil(t, resp.About.LastLink)
assert.True(t, strings.HasPrefix(*resp.About.NextLink, getLocalhostWithPort()+"/peers?"))
assert.Contains(t, *resp.About.NextLink, "offset="+strconv.Itoa(int(api.LIMIT_DEFAULT)))
expectedLastOffset := int(((resp.About.Count - 1) / int64(api.LIMIT_DEFAULT)) * int64(api.LIMIT_DEFAULT))
assert.Contains(t, *resp.About.LastLink, "offset="+strconv.Itoa(expectedLastOffset))
assert.Nil(t, resp.About.PrevLink)
body := getResponseBody(t, "/peers?offset="+strconv.Itoa(int(api.LIMIT_DEFAULT)-1))
err := json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.NotNil(t, resp.About.PrevLink)
assert.Contains(t, *resp.About.PrevLink, "offset=0")
assert.NotNil(t, resp.About.NextLink)
}
func TestPeersNoHeaders(t *testing.T) {
// Create peer
toCreate := oapi.Peer{
// No ID
Name: "Peer",
Url: "https://url.com",
Symbols: []string{"ISIL:PEER"},
RefreshPolicy: oapi.Transaction,
}
jsonBytes, err := json.Marshal(toCreate)
assert.NoError(t, err)
body := httpRequest(t, "POST", "/peers", jsonBytes, "", http.StatusCreated)
var respPeer oapi.Peer
err = json.Unmarshal(body, &respPeer)
assert.NoError(t, err)
// Delete peer
httpRequest(t, "DELETE", "/peers/"+respPeer.Id, nil, "", http.StatusNoContent)
httpRequest(t, "DELETE", "/peers/"+respPeer.Id, nil, "", http.StatusNotFound)
}
func TestPeersCRUD(t *testing.T) {
headers := map[string]string{
"X-Okapi-Tenant": "diku",
"X-Okapi-Url": "http://localhost:1234",
}
email := "v2"
custom := directory.Entry{
Name: "v1",
Email: &email,
}
// Create peer
loanCount := int32(5)
borrowCount := int32(10)
toCreate := oapi.Peer{
Id: uuid.New().String(),
Name: "Peer",
Url: "https://url.com",
Symbols: []string{"ISIL:PEER"},
RefreshPolicy: oapi.Transaction,
CustomData: &custom,
HttpHeaders: &headers,
BranchSymbols: &[]string{"ISIL:PEER-Branch"},
LoansCount: &loanCount,
BorrowsCount: &borrowCount,
}
jsonBytes, err := json.Marshal(toCreate)
assert.NoError(t, err)
body := httpRequest(t, "POST", "/peers", jsonBytes, "", http.StatusCreated)
var respPeer oapi.Peer
err = json.Unmarshal(body, &respPeer)
assert.NoError(t, err)
assert.Equal(t, toCreate.Id, respPeer.Id)
assert.Equal(t, "diku", (*toCreate.HttpHeaders)["X-Okapi-Tenant"])
var respPeers oapi.Peers
// Query the just POSTed peer
body = getResponseBody(t, "/peers?cql="+url.QueryEscape("symbol any ISIL:PEER"))
err = json.Unmarshal(body, &respPeers)
assert.NoError(t, err)
assert.Equal(t, toCreate.Id, respPeers.Items[0].Id)
assert.GreaterOrEqual(t, len(respPeers.Items), 1)
assert.Equal(t, "Peer", respPeers.Items[0].Name)
assert.Equal(t, "ISIL:PEER", respPeers.Items[0].Symbols[0])
assert.Equal(t, "https://url.com", respPeers.Items[0].Url)
assert.Equal(t, oapi.Opaque, respPeers.Items[0].BrokerMode)
assert.Equal(t, "Unknown", respPeers.Items[0].Vendor)
assert.NotNil(t, respPeers.Items[0].CustomData)
assert.Equal(t, "v1", respPeers.Items[0].CustomData.Name)
if assert.NotNil(t, respPeers.Items[0].CustomData.Email) {
assert.Equal(t, "v2", *respPeers.Items[0].CustomData.Email)
}
assert.Equal(t, "http://localhost:1234", (*respPeers.Items[0].HttpHeaders)["X-Okapi-Url"])
assert.Equal(t, int32(5), *respPeers.Items[0].LoansCount)
assert.Equal(t, int32(10), *respPeers.Items[0].BorrowsCount)
// Cannot post same again
httpRequest(t, "POST", "/peers", jsonBytes, "", http.StatusBadRequest)
// Update peer
toCreate.Name = "Updated"
toCreate.Symbols = append(toCreate.Symbols, "ISIL:UPDATED")
branchSymbols := []string{}
if toCreate.BranchSymbols != nil {
branchSymbols = *toCreate.BranchSymbols
}
branchSymbols = append(branchSymbols, "ISIL:UPDATED-Branch")
toCreate.BranchSymbols = &branchSymbols
toCreate.Url = "https://url2.com"
toCreate.BrokerMode = oapi.Transparent
toCreate.Vendor = "Known"
updLoanCount := int32(10)
toCreate.LoansCount = &updLoanCount
updBorrowCount := int32(15)
toCreate.BorrowsCount = &updBorrowCount
jsonBytes, err = json.Marshal(toCreate)
assert.NoError(t, err)
body = httpRequest(t, "PUT", "/peers/"+toCreate.Id, jsonBytes, "", http.StatusOK)
err = json.Unmarshal(body, &respPeer)
assert.NoError(t, err)
assert.Equal(t, toCreate.Id, respPeer.Id)
assert.Equal(t, "Updated", respPeer.Name)
assert.Len(t, respPeer.Symbols, 2)
assert.Equal(t, 2, len(*respPeer.BranchSymbols))
assert.Equal(t, "https://url2.com", respPeer.Url)
assert.Equal(t, oapi.Transparent, respPeer.BrokerMode)
assert.Equal(t, "Known", respPeer.Vendor)
assert.Equal(t, int32(10), *respPeer.LoansCount)
assert.Equal(t, int32(15), *respPeer.BorrowsCount)
// Get peer
respPeer = getPeerById(t, toCreate.Id)
assert.Equal(t, toCreate.Id, respPeer.Id)
assert.Equal(t, "Updated", respPeer.Name)
assert.Equal(t, int32(10), *respPeer.LoansCount)
assert.Equal(t, int32(15), *respPeer.BorrowsCount)
// Get peers
respPeers = getPeers(t)
assert.GreaterOrEqual(t, len(respPeers.Items), 1)
body = getResponseBody(t, "/peers?offset=0&limit=1")
err = json.Unmarshal(body, &respPeers)
assert.NoError(t, err)
assert.GreaterOrEqual(t, respPeers.About.Count, int64(1))
body = getResponseBody(t, "/peers?limit=0")
err = json.Unmarshal(body, &respPeers)
assert.NoError(t, err)
assert.Equal(t, []oapi.Peer{}, respPeers.Items)
httpGet(t, "/peers?cql="+url.QueryEscape("badfield any ISIL:PEER"), "", http.StatusBadRequest)
httpGet(t, "/peers?cql="+url.QueryEscape("("), "", http.StatusBadRequest)
// Query peers
body = getResponseBody(t, "/peers?cql="+url.QueryEscape("symbol any ISIL:PEER"))
err = json.Unmarshal(body, &respPeers)
assert.NoError(t, err)
assert.GreaterOrEqual(t, len(respPeers.Items), 1)
assert.Equal(t, toCreate.Id, respPeers.Items[0].Id)
assert.NotNil(t, respPeers.Items[0].CustomData)
assert.Equal(t, "v1", respPeers.Items[0].CustomData.Name)
if assert.NotNil(t, respPeers.Items[0].CustomData.Email) {
assert.Equal(t, "v2", *respPeers.Items[0].CustomData.Email)
}
assert.Equal(t, "http://localhost:1234", (*respPeers.Items[0].HttpHeaders)["X-Okapi-Url"])
// Delete peer
httpRequest(t, "DELETE", "/peers/"+toCreate.Id, nil, "", http.StatusNoContent)
httpRequest(t, "DELETE", "/peers/"+toCreate.Id, nil, "", http.StatusNotFound)
// Check no peers left
respPeers = getPeers(t)
for _, p := range respPeers.Items {
assert.NotEqual(t, toCreate.Id, p.Id)
}
}
func TestNotFound(t *testing.T) {
tests := []struct {
name string
endpoint string
method string
}{
{
name: "peers",
endpoint: "/peers/not_found",
method: "GET",
},
{
name: "illTransaction",
endpoint: "/ill_transactions/not_found",
method: "GET",
},
{
name: "peersPut",
endpoint: "/peers/not_found",
method: "PUT",
},
{
name: "peersDelete",
endpoint: "/peers/not_found",
method: "DELETE",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
httpRequest(t, tt.method, tt.endpoint, nil, "", http.StatusNotFound)
})
}
}
func TestGetEventsDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
reqId := uuid.New().String()
handlerMock.GetEvents(rr, req, oapi.GetEventsParams{RequesterReqId: &reqId})
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestGetIllTransactionsDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handlerMock.GetIllTransactions(rr, req, oapi.GetIllTransactionsParams{})
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestGetIllTransactionsIdDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handlerMock.GetIllTransactionsId(rr, req, "id", oapi.GetIllTransactionsIdParams{})
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestGetPeersDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handlerMock.GetPeers(rr, req, oapi.GetPeersParams{})
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestPostPeersDbError(t *testing.T) {
toCreate := oapi.Peer{
Id: uuid.New().String(),
Name: "Peer",
Url: "https://url.com",
Symbols: []string{"ISIL:PEER"},
RefreshPolicy: oapi.Transaction,
}
jsonBytes, err := json.Marshal(toCreate)
if err != nil {
t.Errorf("Error marshaling JSON: %s", err)
}
req, _ := http.NewRequest("GET", "/", bytes.NewBuffer(jsonBytes))
rr := httptest.NewRecorder()
handlerMock.PostPeers(rr, req)
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestPostPeersError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", bytes.NewBuffer([]byte{}))
rr := httptest.NewRecorder()
handlerMock.PostPeers(rr, req)
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestDeletePeersSymbolDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handlerMock.DeletePeersId(rr, req, "s")
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestGetPeersSymbolDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handlerMock.GetPeersId(rr, req, "s")
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestPutPeersSymbolDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
handlerMock.PutPeersId(rr, req, "s")
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestGetLocatedSuppliersDbError(t *testing.T) {
req, _ := http.NewRequest("GET", "/", nil)
rr := httptest.NewRecorder()
reqReqId := uuid.New().String()
handlerMock.GetLocatedSuppliers(rr, req, oapi.GetLocatedSuppliersParams{RequesterReqId: &reqReqId})
if status := rr.Code; status != http.StatusInternalServerError {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusInternalServerError)
}
}
func TestPostArchiveIllTransactions(t *testing.T) {
// Loan Completed
minus5days := pgtype.Timestamp{
Time: time.Now().Add(-(24 * 5 * time.Hour)),
Valid: true,
}
ctx := common.CreateExtCtxWithArgs(context.Background(), nil)
illId := apptest.GetIllTransId(t, illRepo)
illTr, err := illRepo.GetIllTransactionById(ctx, illId)
assert.Nil(t, err)
illTr.LastSupplierStatus = apptest.CreatePgText(string(iso18626.TypeStatusLoanCompleted))
illTr.Timestamp = minus5days
_, err = illRepo.SaveIllTransaction(ctx, ill_db.SaveIllTransactionParams(illTr))
assert.Nil(t, err)
peer := apptest.CreatePeer(t, illRepo, "ISIL:LOC_SUP", "")
apptest.CreateLocatedSupplier(t, illRepo, illId, peer.ID, "ISIL:LOC_SUP", string(iso18626.TypeStatusLoaned))
apptest.GetEventId(t, eventRepo, illId, events.EventTypeTask, events.EventStatusSuccess, events.EventNameSelectSupplier)
// Unfilled
illId2 := apptest.GetIllTransId(t, illRepo)
illTr, err = illRepo.GetIllTransactionById(ctx, illId2)
assert.Nil(t, err)
illTr.LastSupplierStatus = apptest.CreatePgText(string(iso18626.TypeStatusUnfilled))
illTr.Timestamp = minus5days
_, err = illRepo.SaveIllTransaction(ctx, ill_db.SaveIllTransactionParams(illTr))
assert.Nil(t, err)
// Loaned
illId3 := apptest.GetIllTransId(t, illRepo)
illTr, err = illRepo.GetIllTransactionById(ctx, illId3)
assert.Nil(t, err)
illTr.LastSupplierStatus = apptest.CreatePgText(string(iso18626.TypeStatusLoaned))
illTr.Timestamp = minus5days
_, err = illRepo.SaveIllTransaction(ctx, ill_db.SaveIllTransactionParams(illTr))
assert.Nil(t, err)
body := httpRequest(t, "POST", "/archive_ill_transactions?archive_delay=1d&archive_status=LoanCompleted,CopyCompleted,Unfilled", nil, "", http.StatusOK)
var resp oapi.StatusMessage
err = json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, "Archive process started", resp.Status)
test.WaitForPredicateToBeTrue(func() bool {
_, err = illRepo.GetIllTransactionById(ctx, illId)
return errors.Is(err, pgx.ErrNoRows)
})
_, err = illRepo.GetIllTransactionById(ctx, illId)
assert.True(t, errors.Is(err, pgx.ErrNoRows))
_, err = illRepo.GetIllTransactionById(ctx, illId2)
assert.True(t, errors.Is(err, pgx.ErrNoRows))
illTr, err = illRepo.GetIllTransactionById(ctx, illId3)
assert.Nil(t, err)
assert.Equal(t, illId3, illTr.ID)
}
func TestPostArchiveIllTransactionsBadRequest(t *testing.T) {
body := httpRequest(t, "POST", "/archive_ill_transactions?archive_delay=2x&archive_status=LoanCompleted,CopyCompleted,Unfilled", nil, "", http.StatusBadRequest)
var resp oapi.Error
err := json.Unmarshal(body, &resp)
assert.NoError(t, err)
assert.Equal(t, "time: unknown unit \"x\" in duration \"2x\"", *resp.Error)
}
func getPeers(t *testing.T) oapi.Peers {
body := getResponseBody(t, "/peers")
var respPeers oapi.Peers
err := json.Unmarshal(body, &respPeers)
assert.NoError(t, err)
return respPeers
}
func getPeerById(t *testing.T, symbol string) oapi.Peer {
body := getResponseBody(t, "/peers/"+symbol)
var resp oapi.Peer
err := json.Unmarshal(body, &resp)
assert.NoError(t, err)
return resp
}
func getResponseBody(t *testing.T, endpoint string) []byte {
return httpGet(t, endpoint, "", http.StatusOK)
}
func httpRequest(t *testing.T, method string, uriPath string, reqbytes []byte, tenant string, expectStatus int) []byte {
client := http.DefaultClient
hreq, err := http.NewRequest(method, getLocalhostWithPort()+uriPath, bytes.NewBuffer(reqbytes))
assert.NoError(t, err)
if tenant != "" {
hreq.Header.Set("X-Okapi-Tenant", tenant)
}
if method == "POST" || method == "PUT" {
hreq.Header.Set("Content-Type", "application/json")
}
hres, err := client.Do(hreq)
assert.NoError(t, err)
defer hres.Body.Close()
body, err := io.ReadAll(hres.Body)
assert.Equal(t, expectStatus, hres.StatusCode, string(body))
assert.NoError(t, err)
return body
}
func httpGetTrans(t *testing.T, uriPath string, tenant string, expectStatus int) []oapi.IllTransaction {
body := httpRequest(t, "GET", uriPath, nil, tenant, expectStatus)
var res oapi.IllTransactions
err := json.Unmarshal(body, &res)
assert.NoError(t, err)
return res.Items
}
func httpGet(t *testing.T, uriPath string, tenant string, expectStatus int) []byte {
return httpRequest(t, "GET", uriPath, nil, tenant, expectStatus)
}
func getLocalhostWithPort() string {
return "http://localhost:" + strconv.Itoa(app.HTTP_PORT)
}