This repository has been archived by the owner on Jan 1, 2025. It is now read-only.
forked from akash-network/provider
-
Notifications
You must be signed in to change notification settings - Fork 1
/
order_test.go
718 lines (546 loc) · 22.5 KB
/
order_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
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
package bidengine
import (
"context"
"errors"
"testing"
"time"
"github.com/akash-network/provider/operator/waiter"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/akash-network/akash-api/go/node/types/constants"
"github.com/akash-network/akash-api/go/sdkutil"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
audittypes "github.com/akash-network/akash-api/go/node/audit/v1beta3"
dtypes "github.com/akash-network/akash-api/go/node/deployment/v1beta3"
mtypes "github.com/akash-network/akash-api/go/node/market/v1beta4"
ptypes "github.com/akash-network/akash-api/go/node/provider/v1beta3"
atypes "github.com/akash-network/akash-api/go/node/types/v1beta3"
broadcastmocks "github.com/akash-network/node/client/broadcaster/mocks"
clientmocks "github.com/akash-network/node/client/mocks"
"github.com/akash-network/node/pubsub"
"github.com/akash-network/node/testutil"
clustermocks "github.com/akash-network/provider/cluster/mocks"
"github.com/akash-network/provider/session"
)
type orderTestScaffold struct {
orderID mtypes.OrderID
groupID dtypes.GroupID
testBus pubsub.Bus
testAddr sdk.AccAddress
deploymentID dtypes.DeploymentID
bidID *mtypes.BidID
queryClient *clientmocks.QueryClient
client *clientmocks.Client
txClient *broadcastmocks.Client
cluster *clustermocks.Cluster
broadcasts chan sdk.Msg
reserveCallNotify chan int
}
type testBidPricingStrategy int64
type alwaysFailsBidPricingStrategy struct {
failure error
}
var _ BidPricingStrategy = (*testBidPricingStrategy)(nil)
var _ BidPricingStrategy = (*alwaysFailsBidPricingStrategy)(nil)
func makeMocks(s *orderTestScaffold) {
groupResult := &dtypes.QueryGroupResponse{}
groupResult.Group.GroupSpec.Name = "testGroupName"
groupResult.Group.GroupSpec.Resources = make(dtypes.ResourceUnits, 1)
cpu := atypes.CPU{}
cpu.Units = atypes.NewResourceValue(uint64(dtypes.GetValidationConfig().Unit.Min.CPU))
gpu := atypes.GPU{}
gpu.Units = atypes.NewResourceValue(uint64(dtypes.GetValidationConfig().Unit.Min.GPU))
memory := atypes.Memory{}
memory.Quantity = atypes.NewResourceValue(dtypes.GetValidationConfig().Unit.Min.Memory)
storage := atypes.Volumes{
atypes.Storage{
Quantity: atypes.NewResourceValue(dtypes.GetValidationConfig().Unit.Min.Storage),
},
}
clusterResources := atypes.Resources{
ID: 1,
CPU: &cpu,
GPU: &gpu,
Memory: &memory,
Storage: storage,
}
price := sdk.NewInt64DecCoin(testutil.CoinDenom, 23)
resource := dtypes.ResourceUnit{
Resources: clusterResources,
Count: 2,
Price: price,
}
groupResult.Group.GroupSpec.Resources[0] = resource
queryClientMock := &clientmocks.QueryClient{}
queryClientMock.On("Group", mock.Anything, mock.Anything).Return(groupResult, nil)
queryClientMock.On("Orders", mock.Anything, mock.Anything).Return(&mtypes.QueryOrdersResponse{}, nil)
queryClientMock.On("Provider", mock.Anything, mock.Anything).Return(&ptypes.QueryProviderResponse{}, nil)
txMocks := &broadcastmocks.Client{}
s.broadcasts = make(chan sdk.Msg, 1)
txMocks.On("Broadcast", mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
s.broadcasts <- args.Get(1).(sdk.Msg)
}).Return(nil)
clientMocks := &clientmocks.Client{}
clientMocks.On("Query").Return(queryClientMock)
clientMocks.On("Tx").Return(txMocks)
s.client = clientMocks
s.queryClient = queryClientMock
s.txClient = txMocks
mockReservation := &clustermocks.Reservation{}
mockReservation.On("OrderID").Return(s.orderID)
mockReservation.On("Resources").Return(groupResult.Group)
mockReservation.On("GetAllocatedResources").Return(groupResult.Group.GroupSpec.Resources)
s.cluster = &clustermocks.Cluster{}
s.reserveCallNotify = make(chan int, 1)
s.cluster.On("Reserve", s.orderID, &(groupResult.Group)).Run(func(args mock.Arguments) {
s.reserveCallNotify <- 0
time.Sleep(time.Second) // add a delay before returning response, to test race conditions
}).Return(mockReservation, nil)
s.cluster.On("Unreserve", s.orderID, mock.Anything).Return(nil)
}
type nullProviderAttrSignatureService struct{}
func (nullProviderAttrSignatureService) GetAuditorAttributeSignatures(_ string) ([]audittypes.Provider, error) {
return nil, nil // Return no attributes & no error
}
func (nullProviderAttrSignatureService) GetAttributes() (atypes.Attributes, error) {
return nil, nil // Return no attributes & no error
}
const testBidCreatedAt = 1234556789
func makeOrderForTest(
t *testing.T,
checkForExistingBid bool,
bidState mtypes.Bid_State,
pricing BidPricingStrategy,
callerConfig *Config,
sessionHeight int64,
) (*order, orderTestScaffold, <-chan int) {
if pricing == nil {
pricing = testBidPricingStrategy(1)
require.NotNil(t, pricing)
}
var scaffold orderTestScaffold
scaffold.deploymentID = testutil.DeploymentID(t)
scaffold.groupID = dtypes.MakeGroupID(scaffold.deploymentID, 2)
scaffold.orderID = mtypes.MakeOrderID(scaffold.groupID, 1356326)
myLog := testutil.Logger(t)
makeMocks(&scaffold)
scaffold.testAddr = testutil.AccAddress(t)
myProvider := &ptypes.Provider{
Owner: scaffold.testAddr.String(),
HostURI: "",
Attributes: nil,
}
mySession := session.New(myLog, scaffold.client, myProvider, sessionHeight)
scaffold.testBus = pubsub.NewBus()
var cfg Config
if callerConfig != nil {
cfg = *callerConfig // Copy values from caller
}
// Overwrite some with stuff built-in this function
cfg.PricingStrategy = pricing
cfg.Deposit = mtypes.DefaultBidMinDeposit
cfg.MaxGroupVolumes = constants.DefaultMaxGroupVolumes
myService, err := NewService(context.Background(), mySession, scaffold.cluster, scaffold.testBus, waiter.NewNullWaiter(), cfg)
require.NoError(t, err)
require.NotNil(t, myService)
serviceCast := myService.(*service)
if checkForExistingBid {
bidID := mtypes.MakeBidID(scaffold.orderID, mySession.Provider().Address())
scaffold.bidID = &bidID
queryBidRequest := &mtypes.QueryBidRequest{
ID: bidID,
}
response := &mtypes.QueryBidResponse{
Bid: mtypes.Bid{
BidID: bidID,
State: bidState,
Price: sdk.NewInt64DecCoin(testutil.CoinDenom, int64(testutil.RandRangeInt(100, 1000))),
CreatedAt: testBidCreatedAt,
},
}
scaffold.queryClient.On("Bid", mock.Anything, queryBidRequest).Return(response, nil)
}
reservationFulfilledNotify := make(chan int, 1)
order, err := newOrderInternal(serviceCast, scaffold.orderID, cfg, nullProviderAttrSignatureService{}, checkForExistingBid, reservationFulfilledNotify)
require.NoError(t, err)
require.NotNil(t, order)
return order, scaffold, reservationFulfilledNotify
}
func Test_BidOrderAndUnreserve(t *testing.T) {
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, nil, nil, testBidCreatedAt)
broadcast := testutil.ChannelWaitForValue(t, scaffold.broadcasts)
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
require.IsType(t, &mtypes.MsgCreateBid{}, broadcast)
createBidMsg := broadcast.(*mtypes.MsgCreateBid)
require.Equal(t, createBidMsg.Order, scaffold.orderID)
priceDenom := createBidMsg.Price.Denom
require.Equal(t, testutil.CoinDenom, priceDenom)
priceAmount := createBidMsg.Price.Amount
require.GreaterOrEqual(t, priceAmount.TruncateInt64(), int64(1))
require.Less(t, priceAmount.TruncateInt64(), int64(100))
// After the broadcast call shut the thing down
// and then check what was broadcast
order.lc.Shutdown(nil)
// Should have called unreserve once, nothing happened after the bid
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
func Test_BidOrderAndUnreserveOnTimeout(t *testing.T) {
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, nil, &Config{
BidTimeout: 5 * time.Second,
}, testBidCreatedAt)
broadcast := testutil.ChannelWaitForValue(t, scaffold.broadcasts)
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
require.IsType(t, &mtypes.MsgCreateBid{}, broadcast)
createBidMsg := broadcast.(*mtypes.MsgCreateBid)
require.Equal(t, createBidMsg.Order, scaffold.orderID)
priceDenom := createBidMsg.Price.Denom
require.Equal(t, testutil.CoinDenom, priceDenom)
priceAmount := createBidMsg.Price.Amount
require.True(t, priceAmount.GT(sdk.NewDec(0)))
require.True(t, priceAmount.LT(sdk.NewDec(100)))
// After the broadcast call the timeout should take effect
// and then close the bid, unreserving capacity in the process
broadcast = testutil.ChannelWaitForValue(t, scaffold.broadcasts)
require.IsType(t, &mtypes.MsgCloseBid{}, broadcast)
// After the broadcast call shut down happens automatically
order.lc.Shutdown(nil)
select {
case <-time.After(10 * time.Second):
t.Fatalf("timed out waiting on shutdown")
case <-order.lc.Done():
break
}
// Should have called unreserve once
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
func Test_BidOrderPriceTooHigh(t *testing.T) {
pricing := testBidPricingStrategy(9999999999)
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, pricing, nil, testBidCreatedAt)
select {
case <-order.lc.Done(): // Should stop on its own
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting in test")
}
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
select {
case <-scaffold.broadcasts:
t.Fatal("should not have broadcast anything")
default:
}
// Should have called unreserve once, nothing happened after the bid
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
func Test_BidOrderAndThenClosedUnreserve(t *testing.T) {
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, nil, nil, testBidCreatedAt)
testutil.ChannelWaitForValue(t, scaffold.broadcasts)
// Should have called reserve once at this point
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
ev := mtypes.EventOrderClosed{
Context: sdkutil.BaseModuleEvent{},
ID: scaffold.orderID,
}
err := scaffold.testBus.Publish(ev)
require.NoError(t, err)
// Wait for this to complete. An order close event has happened so it stops
// on its own
<-order.lc.Done()
// Should have called unreserve once
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
func Test_OrderCloseBeforeReserveReturn(t *testing.T) {
order, scaffold, reservationFulfilledNotify := makeOrderForTest(t, false, mtypes.BidStateInvalid, nil, nil, testBidCreatedAt)
testutil.ChannelWaitForValue(t, scaffold.reserveCallNotify)
// Should have called reserve once at this point
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
// reservationFulfilledNotify channel shouldn't have got any value yet because the Reserve call
// returns after a delay of one second
select {
case <-reservationFulfilledNotify:
t.Fatal("reservation shouldn't have been fulfilled")
default:
}
// close the order before Reserve call returns
ev := mtypes.EventOrderClosed{
Context: sdkutil.BaseModuleEvent{},
ID: scaffold.orderID,
}
err := scaffold.testBus.Publish(ev)
require.NoError(t, err)
// reservationFulfilledNotify channel can't get any value now because the order close event
// should take priority
select {
case <-reservationFulfilledNotify:
t.Fatal("reservation shouldn't have been fulfilled")
default:
}
// Wait for this to complete. An order close event has happened so it stops
// on its own
<-order.lc.Done()
// Should have called unreserve once
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
func Test_BidOrderAndThenLeaseCreated(t *testing.T) {
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, nil, nil, testBidCreatedAt)
// Wait for first broadcast
broadcast := testutil.ChannelWaitForValue(t, scaffold.broadcasts)
require.IsType(t, &mtypes.MsgCreateBid{}, broadcast)
createBidMsg := broadcast.(*mtypes.MsgCreateBid)
require.Equal(t, createBidMsg.Order, scaffold.orderID)
priceDenom := createBidMsg.Price.Denom
require.Equal(t, testutil.CoinDenom, priceDenom)
priceAmount := createBidMsg.Price.Amount
require.GreaterOrEqual(t, priceAmount.TruncateInt64(), int64(1))
require.Less(t, priceAmount.TruncateInt64(), int64(100))
leaseID := mtypes.MakeLeaseID(mtypes.MakeBidID(scaffold.orderID, scaffold.testAddr))
ev := mtypes.EventLeaseCreated{
Context: sdkutil.BaseModuleEvent{},
ID: leaseID,
Price: testutil.AkashDecCoin(t, 1),
}
require.Equal(t, order.orderID.GroupID(), ev.ID.GroupID())
err := scaffold.testBus.Publish(ev)
require.NoError(t, err)
// Wait for this to complete. The lease has been created so it
// stops on it own
<-order.lc.Done()
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
// Should not have called unreserve
scaffold.cluster.AssertNotCalled(t, "Unreserve", mock.Anything, mock.Anything)
}
func Test_BidOrderAndThenLeaseCreatedForDifferentDeployment(t *testing.T) {
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, nil, nil, testBidCreatedAt)
// Wait for first broadcast
broadcast := testutil.ChannelWaitForValue(t, scaffold.broadcasts)
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
require.IsType(t, &mtypes.MsgCreateBid{}, broadcast)
createBidMsg := broadcast.(*mtypes.MsgCreateBid)
require.Equal(t, createBidMsg.Order, scaffold.orderID)
otherOrderID := scaffold.orderID
otherOrderID.GSeq++
leaseID := mtypes.MakeLeaseID(mtypes.MakeBidID(otherOrderID, scaffold.testAddr))
ev := mtypes.EventLeaseCreated{
Context: sdkutil.BaseModuleEvent{},
ID: leaseID,
Price: testutil.AkashDecCoin(t, 1),
}
subscriber, err := scaffold.testBus.Subscribe()
require.NoError(t, err)
err = scaffold.testBus.Publish(ev)
require.NoError(t, err)
// Wait for the event to be published
testutil.ChannelWaitForValue(t, subscriber.Events())
// Should not have called unreserve yet
scaffold.cluster.AssertNotCalled(t, "Unreserve", mock.Anything, mock.Anything)
// Shutdown after the message has been published
order.lc.Shutdown(nil)
// Should have called unreserve
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
// The last call should be a broadcast to close the bid
txCalls := scaffold.txClient.Calls
require.NotEqual(t, 0, len(txCalls))
lastBroadcast := txCalls[len(txCalls)-1]
require.Equal(t, "Broadcast", lastBroadcast.Method)
msg := lastBroadcast.Arguments[1]
require.IsType(t, &mtypes.MsgCloseBid{}, msg)
closeBidMsg := msg.(*mtypes.MsgCloseBid)
expectedBidID := mtypes.MakeBidID(order.orderID, scaffold.testAddr)
require.Equal(t, closeBidMsg.BidID, expectedBidID)
}
func Test_ShouldNotBidWhenAlreadySet(t *testing.T) {
order, scaffold, reservationFulfilledNotify := makeOrderForTest(t, true, mtypes.BidOpen, nil, nil, testBidCreatedAt)
// Wait for a reserve call
testutil.ChannelWaitForValue(t, scaffold.reserveCallNotify)
// Should have queried for the bid
queryCalls := scaffold.queryClient.Calls
var lastBid mock.Call
for _, call := range queryCalls {
if call.Method == "Bid" {
lastBid = call
}
}
require.Equal(t, "Bid", lastBid.Method)
qResult := lastBid.Arguments[1]
require.IsType(t, &mtypes.QueryBidRequest{}, qResult)
query := qResult.(*mtypes.QueryBidRequest)
require.Equal(t, *scaffold.bidID, query.ID)
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
// Wait for the reservation to be processed
testutil.ChannelWaitForValue(t, reservationFulfilledNotify)
// Close the order
ev := mtypes.EventOrderClosed{
Context: sdkutil.BaseModuleEvent{},
ID: scaffold.orderID,
}
err := scaffold.testBus.Publish(ev)
require.NoError(t, err)
// Wait for it to stop
<-order.lc.Done()
// Should have called unreserve during shutdown
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
var broadcast sdk.Msg
select {
case broadcast = <-scaffold.broadcasts:
default:
}
// Should have broadcast
require.IsType(t, &mtypes.MsgCloseBid{}, broadcast)
closeBid := broadcast.(*mtypes.MsgCloseBid)
require.Equal(t, closeBid.BidID, *scaffold.bidID)
}
func Test_ShouldCloseBidWhenAlreadySetAndOld(t *testing.T) {
pricing, err := MakeRandomRangePricing()
require.NoError(t, err)
cfg := Config{
PricingStrategy: pricing,
Deposit: sdk.NewInt64Coin(testutil.CoinDenom, 1),
BidTimeout: time.Second,
Attributes: nil,
}
order, scaffold, _ := makeOrderForTest(t, true, mtypes.BidOpen, nil, &cfg, 1)
testutil.ChannelWaitForClose(t, order.lc.Done())
// Should not have called reserve
scaffold.cluster.AssertNotCalled(t, "Reserve", scaffold.orderID, mock.Anything)
// Should have closed the bid
scaffold.txClient.AssertCalled(t, "Broadcast", mock.Anything, &mtypes.MsgCloseBid{
BidID: mtypes.MakeBidID(order.orderID, scaffold.testAddr),
})
}
func Test_ShouldExitWhenAlreadySetAndLost(t *testing.T) {
pricing, err := MakeRandomRangePricing()
require.NoError(t, err)
cfg := Config{
PricingStrategy: pricing,
Deposit: sdk.NewInt64Coin(testutil.CoinDenom, 1),
BidTimeout: time.Minute,
Attributes: nil,
}
order, scaffold, _ := makeOrderForTest(t, true, mtypes.BidLost, nil, &cfg, testBidCreatedAt)
testutil.ChannelWaitForClose(t, order.lc.Done())
// Should not have called reserve
scaffold.cluster.AssertNotCalled(t, "Reserve", scaffold.orderID, mock.Anything)
// Should not have closed the bid
scaffold.txClient.AssertNotCalled(t, "Broadcast", mock.Anything, &mtypes.MsgCloseBid{
BidID: mtypes.MakeBidID(order.orderID, scaffold.testAddr),
})
}
func Test_ShouldCloseBidWhenAlreadySetAndThenTimeout(t *testing.T) {
pricing, err := MakeRandomRangePricing()
require.NoError(t, err)
cfg := Config{
PricingStrategy: pricing,
Deposit: sdk.NewInt64Coin(testutil.CoinDenom, 1),
BidTimeout: 6 * time.Second,
Attributes: nil,
}
order, scaffold, _ := makeOrderForTest(t, true, mtypes.BidOpen, nil, &cfg, testBidCreatedAt)
testutil.ChannelWaitForClose(t, order.lc.Done())
// Should have called reserve
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
// Should have closed the bid
scaffold.txClient.AssertCalled(t, "Broadcast", mock.Anything, &mtypes.MsgCloseBid{
BidID: mtypes.MakeBidID(order.orderID, scaffold.testAddr),
})
// Should have called unreserve
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID)
}
func Test_ShouldRecognizeLeaseCreatedIfBiddingIsSkipped(t *testing.T) {
order, scaffold, _ := makeOrderForTest(t, true, mtypes.BidOpen, nil, nil, testBidCreatedAt)
// Wait for a reserve call
testutil.ChannelWaitForValue(t, scaffold.reserveCallNotify)
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
// Should not have called unreserve
scaffold.cluster.AssertNotCalled(t, "Unreserve", mock.Anything, mock.Anything)
leaseID := mtypes.MakeLeaseID(mtypes.MakeBidID(scaffold.orderID, scaffold.testAddr))
ev := mtypes.EventLeaseCreated{
Context: sdkutil.BaseModuleEvent{},
ID: leaseID,
Price: testutil.AkashDecCoin(t, 1),
}
err := scaffold.testBus.Publish(ev)
require.NoError(t, err)
// Wait for it to stop
<-order.lc.Done()
// Should not have called unreserve during shutdown
scaffold.cluster.AssertNotCalled(t, "Unreserve", mock.Anything, mock.Anything)
var broadcast sdk.Msg
select {
case broadcast = <-scaffold.broadcasts:
default:
}
// Should never have broadcast
require.Nil(t, broadcast)
}
func (tbps testBidPricingStrategy) CalculatePrice(_ context.Context, _ Request) (sdk.DecCoin, error) {
return sdk.NewInt64DecCoin(testutil.CoinDenom, int64(tbps)), nil
}
func Test_BidOrderUsesBidPricingStrategy(t *testing.T) {
expectedBid := int64(37)
// Create a test strategy that gives a fixed price
pricing := testBidPricingStrategy(expectedBid)
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, pricing, nil, testBidCreatedAt)
broadcast := testutil.ChannelWaitForValue(t, scaffold.broadcasts)
require.IsType(t, &mtypes.MsgCreateBid{}, broadcast)
createBidMsg := broadcast.(*mtypes.MsgCreateBid)
require.Equal(t, createBidMsg.Order, scaffold.orderID)
priceDenom := createBidMsg.Price.Denom
require.Equal(t, testutil.CoinDenom, priceDenom)
priceAmount := createBidMsg.Price.Amount
require.Equal(t, priceAmount, sdk.NewDec(expectedBid))
// After the broadcast call shut the thing down
// and then check what was broadcast
order.lc.Shutdown(nil)
// Should have called unreserve once, nothing happened after the bid
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
func (afbps alwaysFailsBidPricingStrategy) CalculatePrice(_ context.Context, _ Request) (sdk.DecCoin, error) {
return sdk.DecCoin{}, afbps.failure
}
var errBidPricingAlwaysFails = errors.New("bid pricing fail in test")
func Test_BidOrderFailsAndAborts(t *testing.T) {
// Create a test strategy that gives a fixed price
pricing := alwaysFailsBidPricingStrategy{failure: errBidPricingAlwaysFails}
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, pricing, nil, testBidCreatedAt)
<-order.lc.Done() // Stops whenever the bid pricing is called and returns an errro
// Should have called reserve once
scaffold.cluster.AssertCalled(t, "Reserve", scaffold.orderID, mock.Anything)
var broadcast sdk.Msg
select {
case broadcast = <-scaffold.broadcasts:
default:
}
// Should never have broadcast since bid pricing failed
require.Nil(t, broadcast)
// Should have called unreserve once, nothing happened after the bid
scaffold.cluster.AssertCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
func Test_ShouldntBidIfOrderAttrsDontMatch(t *testing.T) {
// Create a config that only bids on orders with given attributes
cfg := &Config{Attributes: atypes.Attributes{
{
Key: "owner",
Value: "me",
},
}}
order, scaffold, _ := makeOrderForTest(t, false, mtypes.BidStateInvalid, nil, cfg, testBidCreatedAt)
<-order.lc.Done() // Stops whenever it figures it shouldn't bid
// Should not have called reserve ever
scaffold.cluster.AssertNotCalled(t, "Reserve", scaffold.orderID, mock.Anything)
var broadcast sdk.Msg
select {
case broadcast = <-scaffold.broadcasts:
default:
}
// Should never have broadcast since bid was declined
require.Nil(t, broadcast)
// Should not have called unreserve ever, as nothing was ever reserved
scaffold.cluster.AssertNotCalled(t, "Unreserve", scaffold.orderID, mock.Anything)
}
// TODO - add test failing the call to Broadcast on TxClient and
// and then confirm that the reservation is cancelled