-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathstub.js
More file actions
1510 lines (1187 loc) · 68.4 KB
/
stub.js
File metadata and controls
1510 lines (1187 loc) · 68.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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
*/
/* global */
const sinon = require('sinon');
const chai = require('chai');
chai.use(require('chai-as-promised'));
const { Timestamp } = require('google-protobuf/google/protobuf/timestamp_pb');
const Long = require('long');
// chai.config.truncateThreshold = 0;
const expect = chai.expect;
const rewire = require('rewire');
const {peer, msp, common} = require('@hyperledger/fabric-protos');
const Stub = rewire('../../lib/stub.js');
class DummyIterator {
constructor() {
this.items = [1, 2, 3, 4, 5];
this.count = 0;
this.closeCalled = false;
}
async next() {
return new Promise((resolve, reject) => {
if (this.count === this.items.length) {
resolve({done: true});
}
resolve({value: this.items[this.count], done: false});
this.count++;
});
}
async close() {
this.closeCalled = true;
return Promise.resolve();
}
}
describe('Stub', () => {
describe('validateCompositeKeyAttribute', () => {
const validateCompositeKeyAttribute = Stub.__get__('validateCompositeKeyAttribute');
it ('should throw an error if no attribute passed', () => {
expect(() => {
validateCompositeKeyAttribute();
}).to.throw(/object type or attribute not a non-zero length string/);
});
it ('should throw an error if attribute not string', () => {
expect(() => {
validateCompositeKeyAttribute(100);
}).to.throw(/object type or attribute not a non-zero length string/);
});
it ('should throw an error if attribute empty string', () => {
expect(() => {
validateCompositeKeyAttribute('');
}).to.throw(/object type or attribute not a non-zero length string/);
});
});
describe('computeProposalBinding', () => {
it ('should return hash of decodedSP', () => {
const computeProposalBinding = Stub.__get__('computeProposalBinding');
const decodedSP = {
proposal: {
header: {
signatureHeader: {
nonce: Buffer.from('100'),
creator_u8: Buffer.from('some creator')
},
channelHeader: {
getEpoch: () => {
return {high: 10, low: 1};
}
}
}
}
};
expect(computeProposalBinding(decodedSP)).to.deep.equal('44206e945c5cc2b752deacc05b2d6cd58a3799fec52143c986739bab57417aaf');
// note to future developers, there is some confusion over the exact use of this value and how critical it is to keep
// it consitent between releases. The previous tests had the value 'ff7e9beabf035d45cb5922278f423ba92f1e85d43d54c2304038f2f2b131625b')
// for logically the same input; however it is believed that included 'bits of the old protobuf' library.
// we therefore consider this update to be valid
});
});
describe('convertToAsyncIterator', () => {
let dummyIteratorPromise;
const convertToAsyncIterator = Stub.__get__('convertToAsyncIterator');
beforeEach(() => {
dummyIteratorPromise = Promise.resolve(new DummyIterator());
});
it('should inject a function into the promise that returns an object with the correct methods', () => {
const returnedPromise = convertToAsyncIterator(dummyIteratorPromise);
expect(returnedPromise[Symbol.asyncIterator]).to.be.a('function');
const returnedObj = returnedPromise[Symbol.asyncIterator]();
expect(returnedObj.next).to.be.a('function');
expect(returnedObj.return).to.be.a('function');
});
it('should be possible to iterate using async for of', async () => {
const returnedPromise = convertToAsyncIterator(dummyIteratorPromise);
const allResults = [];
for await (const res of returnedPromise) {
allResults.push(res);
}
expect(allResults).to.deep.equal([1, 2, 3, 4, 5]);
const iterator = await dummyIteratorPromise;
expect(iterator.closeCalled).to.be.true;
});
it('should close the iterator if we break out of the loop', async () => {
const returnedPromise = convertToAsyncIterator(dummyIteratorPromise);
const allResults = [];
let cc = 0;
for await (const res of returnedPromise) {
allResults.push(res);
cc++;
if (cc === 3) {
break;
}
}
expect(allResults).to.deep.equal([1, 2, 3]);
const iterator = await dummyIteratorPromise;
expect(iterator.closeCalled).to.be.true;
});
it('should close the iterator if we break out of the loop straight away', async () => {
const returnedPromise = convertToAsyncIterator(dummyIteratorPromise);
const allResults = [];
for await (const res of returnedPromise) {
res;
break;
}
expect(allResults).to.deep.equal([]);
const iterator = await dummyIteratorPromise;
expect(iterator.closeCalled).to.be.true;
});
it('should close the iterator if we throw out of the loop', async () => {
const returnedPromise = convertToAsyncIterator(dummyIteratorPromise);
const allResults = [];
let cc = 0;
try {
for await (const res of returnedPromise) {
allResults.push(res);
cc++;
if (cc === 3) {
throw new Error('get me out of here');
}
}
} catch (err) { // eslint-disable-noempty
}
expect(allResults).to.deep.equal([1, 2, 3]);
const iterator = await dummyIteratorPromise;
expect(iterator.closeCalled).to.be.true;
});
it('should work with a promise that returns an object with an iterator property deconstructed by the caller', async () => {
const dummyObjWithIteratorPromise = Promise.resolve({iterator: new DummyIterator(), metadata: 'stuff'})
.then((result) => result.iterator);
const returnedPromise = convertToAsyncIterator(dummyObjWithIteratorPromise);
const allResults = [];
for await (const res of returnedPromise) {
allResults.push(res);
}
expect(allResults).to.deep.equal([1, 2, 3, 4, 5]);
const iterator = await dummyObjWithIteratorPromise;
expect(iterator.closeCalled).to.be.true;
});
it('should work with a promise that returns an object with an iterator property not deconstructed by caller', async () => {
const dummyObjWithIteratorPromise = Promise.resolve({iterator: new DummyIterator(), metadata: 'stuff'});
const returnedPromise = convertToAsyncIterator(dummyObjWithIteratorPromise);
const allResults = [];
for await (const res of returnedPromise) {
allResults.push(res);
}
expect(allResults).to.deep.equal([1, 2, 3, 4, 5]);
const {iterator} = await dummyObjWithIteratorPromise;
expect(iterator.closeCalled).to.be.true;
});
it('should handle a promise rejection', async () => {
const dummyIteratorRejection = Promise.reject(new Error('im rejected'));
const returnedPromise = convertToAsyncIterator(dummyIteratorRejection);
const allResults = [];
try {
for await (const res of returnedPromise) {
allResults.push(res);
}
} catch (err) {
expect(err.message).to.equal('im rejected');
}
});
});
describe('ChaincodeStub', () => {
const sandbox = sinon.createSandbox();
const buf1 = Buffer.from('invoke');
const buf2 = Buffer.from('someKey');
const buf3 = Buffer.from('someValue');
const chaincodeInput = {
getArgsList_asU8 : () => {
return [buf1, buf2, buf3];
}
};
beforeEach(() => {
});
afterEach(() => {
sandbox.restore();
});
it ('should set up the vars and do nothing more with no signed proposal', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.handler).to.deep.equal('dummyClient');
expect(stub.channel_id).to.deep.equal('dummyChannelId');
expect(stub.txId).to.deep.equal('dummyTxid');
expect(stub.args).to.deep.equal(['invoke', 'someKey', 'someValue']);
});
it ('should throw an error for an invalid proposal', () => {
const badSignedProposal = {
getSignature: () => {
return 'sig';
},
getProposalBytes: sandbox.stub().throws()
};
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, badSignedProposal);
}).to.throw(/Failed extracting proposal from signedProposal/);
});
it ('should throw an error for a proposal with an empty header', () => {
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes('');
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
}).to.throw(/Proposal header is empty/);
});
it('should throw an error for a proposal with an empty payload', () => {
const proposalPB = new peer.Proposal();
proposalPB.setHeader('something');
proposalPB.setPayload('');
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes(proposalPB.serializeBinary());
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
}).to.throw(/Proposal payload is empty/);
});
it ('should throw an error for a proposal with an invalid header', () => {
const proposalPB = new peer.Proposal();
proposalPB.setHeader('something');
proposalPB.setPayload('wibble');
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes(proposalPB.serializeBinary());
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
}).to.throw(/Could not extract the header from the proposal/);
});
it('should throw an error for a proposal with an invalid signature header', () => {
const headerPB = new common.Header();
headerPB.setSignatureHeader('Something');
const proposalPB = new peer.Proposal();
proposalPB.setHeader(headerPB.serializeBinary());
proposalPB.setPayload('wibble');
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes(proposalPB.serializeBinary());
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
}).to.throw(/Decoding SignatureHeader failed/);
});
it ('should throw an error for a proposal with an invalid creator', () => {
const signatureHeaderPB = new common.SignatureHeader();
signatureHeaderPB.setCreator('something');
const headerPB = new common.Header();
headerPB.setSignatureHeader(signatureHeaderPB.serializeBinary());
const proposalPB = new peer.Proposal();
proposalPB.setHeader(headerPB.serializeBinary());
proposalPB.setPayload('wibble');
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes(proposalPB.serializeBinary());
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
}).to.throw(/Decoding SerializedIdentity failed/);
});
it ('should throw an error for a proposal with an invalid channelHeader', () => {
const creatorPB = new msp.SerializedIdentity();
creatorPB.setMspid('mspid');
creatorPB.setIdBytes(Buffer.from('x509'));
const signatureHeaderPB = new common.SignatureHeader();
signatureHeaderPB.setCreator(creatorPB.serializeBinary());
const headerPB = new common.Header();
headerPB.setSignatureHeader(signatureHeaderPB.serializeBinary());
headerPB.setChannelHeader('something');
const proposalPB = new peer.Proposal();
proposalPB.setHeader(headerPB.serializeBinary());
proposalPB.setPayload('wibble');
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes(proposalPB.serializeBinary());
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
}).to.throw(/Decoding ChannelHeader failed/);
});
it('should throw an error for a proposal with an invalid payload', () => {
const creatorPB = new msp.SerializedIdentity();
creatorPB.setMspid('mspid');
creatorPB.setIdBytes(Buffer.from('x509'));
const signatureHeaderPB = new common.SignatureHeader();
signatureHeaderPB.setCreator(creatorPB.serializeBinary());
const headerPB = new common.Header();
headerPB.setSignatureHeader(signatureHeaderPB.serializeBinary());
const channelHeaderPB = new common.ChannelHeader();
headerPB.setChannelHeader(channelHeaderPB.serializeBinary());
const proposalPB = new peer.Proposal();
proposalPB.setHeader(headerPB.serializeBinary());
proposalPB.setPayload('wibble');
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes(proposalPB.serializeBinary());
expect(() => {
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
}).to.throw(/Decoding ChaincodeProposalPayload failed/);
});
it('should correctly create the stub', () => {
const creatorPB = new msp.SerializedIdentity();
creatorPB.setMspid('mspid');
creatorPB.setIdBytes(Buffer.from('x509'));
const signatureHeaderPB = new common.SignatureHeader();
signatureHeaderPB.setCreator(creatorPB.serializeBinary());
const headerPB = new common.Header();
headerPB.setSignatureHeader(signatureHeaderPB.serializeBinary());
const channelHeaderPB = new common.ChannelHeader();
headerPB.setChannelHeader(channelHeaderPB.serializeBinary());
const ccpp = new peer.ChaincodeProposalPayload();
ccpp.setInput('wibble');
const map = ccpp.getTransientmapMap();
map.set('key', 'value');
const proposalPB = new peer.Proposal();
proposalPB.setHeader(headerPB.serializeBinary());
proposalPB.setPayload(ccpp.serializeBinary());
const signedPb = new peer.SignedProposal();
signedPb.setProposalBytes(proposalPB.serializeBinary());
new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput, signedPb);
});
describe('getArgs', () => {
it ('should return the args', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.getArgs()).to.deep.equal(['invoke', 'someKey', 'someValue']);
});
});
describe('getStringArgs', () => {
it ('should return the args', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.getStringArgs()).to.deep.equal(['invoke', 'someKey', 'someValue']);
});
});
describe('getBufferArgs', () => {
it ('should return the args', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.getBufferArgs()).to.deep.equal([buf1, buf2, buf3]);
});
});
describe('getFunctionAndParameters', () => {
it ('should return the function name parameters', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.getFunctionAndParameters()).to.deep.equal({
fcn: 'invoke',
params: ['someKey', 'someValue']
});
});
it ('should return string for function and empty array as param if only one arg', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', {
getArgsList_asU8 : () => {
return [buf1];
}
});
expect(stub.getFunctionAndParameters()).to.deep.equal({
fcn: 'invoke',
params: []
});
});
it ('should return empty string for function and empty array for params if no args', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', {
getArgsList_asU8 : () => {
return [];
}
});
expect(stub.getFunctionAndParameters()).to.deep.equal({
fcn: '',
params: []
});
});
});
describe('getTxID', () => {
it ('should return txId', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.getTxID()).to.deep.equal('dummyTxid');
});
});
describe('getChannelID', () => {
it ('should return channel_id', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.getChannelID()).to.deep.equal('dummyChannelId');
});
});
describe('getCreator', () => {
it ('should return creator', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
stub.creator = 'some creator';
expect(stub.getCreator()).to.deep.equal('some creator');
});
});
describe('getMspID', () => {
let mspID;
beforeEach(() => {
if ('CORE_PEER_LOCALMSPID' in process.env) {
mspID = process.env.CORE_PEER_LOCALMSPID;
}
});
afterEach(() => {
delete process.env.CORE_PEER_LOCALMSPID;
if (mspID) {
process.env.CORE_PEER_LOCALMSPID = mspID;
}
});
it ('should return MSPID', () => {
process.env.CORE_PEER_LOCALMSPID = 'some MSPID';
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(stub.getMspID()).to.deep.equal('some MSPID');
});
it ('should throw Error if MSPID is not available', () => {
delete process.env.CORE_PEER_LOCALMSPID;
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
expect(() => {
stub.getMspID();
}).to.throw('CORE_PEER_LOCALMSPID is unset in chaincode process');
});
});
describe('getTransient', () => {
it ('should return transient map', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
stub.transientMap = 'some transient map';
expect(stub.getTransient()).to.deep.equal('some transient map');
});
});
describe('getSignedProposal', () => {
it ('should return signed proposal', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
stub.signedProposal = 'some signed proposal';
expect(stub.getSignedProposal()).to.deep.equal('some signed proposal');
});
});
describe('getTxTimestamp', () => {
it ('should return transaction timestamp', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
const millis = Date.now();
const seconds = Math.trunc(millis / 1000);
const nanos = (millis - (seconds * 1000)) * 1e6;
const timestamp = new Timestamp();
timestamp.setSeconds(seconds);
timestamp.setNanos(nanos);
stub.txTimestamp = timestamp;
const actual = stub.getTxTimestamp();
expect(actual).to.deep.include({
nanos,
seconds: Long.fromNumber(seconds, true),
});
});
});
describe('getDateTimestamp', () => {
it ('should return transaction date as Node.js Date object', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
const now = new Date();
const timestamp = Timestamp.fromDate(now);
stub.txTimestamp = timestamp;
expect(stub.getDateTimestamp().toISOString()).to.equal(now.toISOString());
});
});
describe('getBinding', () => {
it ('should return binding', () => {
const stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
stub.binding = 'some binding';
expect(stub.getBinding()).to.deep.equal('some binding');
});
});
describe('getState', () => {
it ('should return handler.handleGetState', async () => {
const handleGetStateStub = sinon.stub().resolves('some state');
const stub = new Stub({
handleGetState: handleGetStateStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getState('a key');
expect(result).to.deep.equal('some state');
expect(handleGetStateStub.calledOnce).to.be.true;
expect(handleGetStateStub.firstCall.args).to.deep.equal(['', 'a key', 'dummyChannelId', 'dummyTxid']);
});
});
describe('getMultipleStates', () => {
it('should call handler.handleGetMultipleStates with the keys array', async () => {
const handleGetMultipleStatesStub = sinon.stub().resolves([Buffer.from('dummy')]);
const stub = new Stub({
handleGetMultipleStates: handleGetMultipleStatesStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getMultipleStates(['key1', 'key2']);
expect(result).to.deep.equal([Buffer.from('dummy')]);
sinon.assert.calledOnce(handleGetMultipleStatesStub);
sinon.assert.calledWith(handleGetMultipleStatesStub, ['key1', 'key2'], 'dummyChannelId', 'dummyTxid');
});
});
describe('getMultiplePrivateData', () => {
it('should call handler.handleGetMultiplePrivateData with the collection and keys array', async () => {
const handleGetMultiplePrivateDataStub = sinon.stub().resolves([Buffer.from('dummy')]);
const stub = new Stub({
handleGetMultiplePrivateData: handleGetMultiplePrivateDataStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getMultiplePrivateData('myCollection', ['key1', 'key2']);
expect(result).to.deep.equal([Buffer.from('dummy')]);
sinon.assert.calledOnce(handleGetMultiplePrivateDataStub);
sinon.assert.calledWith(handleGetMultiplePrivateDataStub, 'myCollection', ['key1', 'key2'], 'dummyChannelId', 'dummyTxid');
});
});
describe('putState', () => {
it ('should return handler.handlePutState', async () => {
const handlePutStateStub = sinon.stub().resolves('some state');
const stub = new Stub({
handlePutState: handlePutStateStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.putState('a key', 'a value');
expect(result).to.deep.equal('some state');
expect(handlePutStateStub.calledOnce).to.be.true;
expect(handlePutStateStub.firstCall.args).to.deep.equal(['', 'a key', Buffer.from('a value'), 'dummyChannelId', 'dummyTxid']);
});
it ('should return handler.handlePutState', async () => {
const handlePutStateStub = sinon.stub().resolves('some state');
const stub = new Stub({
handlePutState: handlePutStateStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.putState('a key', {a:'value'});
expect(result).to.deep.equal('some state');
expect(handlePutStateStub.calledOnce).to.be.true;
expect(handlePutStateStub.firstCall.args).to.deep.equal(['', 'a key', {a:'value'}, 'dummyChannelId', 'dummyTxid']);
});
});
describe('deleteState', () => {
it ('should return handler.handleDeleteState', async () => {
const handleDeleteStateStub = sinon.stub().resolves('some state');
const stub = new Stub({
handleDeleteState: handleDeleteStateStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.deleteState('a key');
expect(result).to.deep.equal('some state');
expect(handleDeleteStateStub.calledOnce).to.be.true;
expect(handleDeleteStateStub.firstCall.args).to.deep.equal(['', 'a key', 'dummyChannelId', 'dummyTxid']);
});
});
describe('setStateValidationParameter', () => {
it('should return handler.handlePutStateMetadata', async () => {
const handlePutStateMetadataStub = sinon.stub().resolves('nothing');
const stub = new Stub({
handlePutStateMetadata: handlePutStateMetadataStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const ep = Buffer.from('someEndorsementPolicy');
const nothing = await stub.setStateValidationParameter('aKey', ep);
expect(nothing).to.deep.equal('nothing');
sinon.assert.calledOnce(handlePutStateMetadataStub);
sinon.assert.calledWith(handlePutStateMetadataStub, '', 'aKey', 'VALIDATION_PARAMETER', ep, 'dummyChannelId', 'dummyTxid');
});
});
describe('getStateValidationParameter', () => {
it('should return handler.handleGetStateMetadata', async () => {
const handleGetStateMetadataStub = sinon.stub().resolves({VALIDATION_PARAMETER: 'some metadata'});
const stub = new Stub({
handleGetStateMetadata: handleGetStateMetadataStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const ep = await stub.getStateValidationParameter('aKey');
expect(ep).to.deep.equal('some metadata');
sinon.assert.calledOnce(handleGetStateMetadataStub);
sinon.assert.calledWith(handleGetStateMetadataStub, '', 'aKey', 'dummyChannelId', 'dummyTxid');
});
});
describe('getStateByRange', () => {
it ('should return handler.handleGetStateByRange', async () => {
const handleGetStateByRangeStub = sinon.stub().resolves({iterator: 'some state'});
const stub = new Stub({
handleGetStateByRange: handleGetStateByRangeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getStateByRange('start key', 'end key');
expect(result).to.deep.equal('some state');
expect(handleGetStateByRangeStub.calledOnce).to.be.true;
expect(handleGetStateByRangeStub.firstCall.args).to.deep.equal(['', 'start key', 'end key', 'dummyChannelId', 'dummyTxid']);
});
it ('should return handler.handleGetStateByRange using empty key substitute', async () => {
const handleGetStateByRangeStub = sinon.stub().resolves({iterator: 'some state'});
const stub = new Stub({
handleGetStateByRange: handleGetStateByRangeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const EMPTY_KEY_SUBSTITUTE = Stub.__get__('EMPTY_KEY_SUBSTITUTE');
const result = await stub.getStateByRange(null, 'end key');
expect(result).to.deep.equal('some state');
expect(handleGetStateByRangeStub.calledOnce).to.be.true;
expect(handleGetStateByRangeStub.firstCall.args).to.deep.equal(['', EMPTY_KEY_SUBSTITUTE, 'end key', 'dummyChannelId', 'dummyTxid']);
});
it('should throw error if using compositekey', async () => {
const handleGetStateByRangeStub = sinon.stub().resolves({iterator: 'some state'});
const stub = new Stub({
handleGetStateByRange: handleGetStateByRangeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const compositeStartKey = stub.createCompositeKey('obj', ['attr1']);
expect(stub.getStateByRange(compositeStartKey, 'end key'))
.eventually
.be
// eslint-disable-next-line no-control-regex
.rejectedWith(/first character of the key \[\u0000obj\u0000attr1\u0000] contains a null character which is not allowed/);
});
});
describe('getStateByRangeWithPagination', () => {
it('should throw error if using compositekey', async () => {
const handleGetStateByRangeStub = sinon.stub().resolves({iterator: 'some state'});
const stub = new Stub({
handleGetStateByRange: handleGetStateByRangeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const compositeStartKey = stub.createCompositeKey('obj', ['attr1']);
expect(stub.getStateByRangeWithPagination(compositeStartKey, 'end key', 3, ''))
.eventually
.be
// eslint-disable-next-line no-control-regex
.rejectedWith(/first character of the key \[\u0000obj\u0000attr1\u0000] contains a null character which is not allowed/);
});
it('should have default startKey eqls EMPTY_KEY_SUBSTITUTE', async () => {
const EMPTY_KEY_SUBSTITUTE = Stub.__get__('EMPTY_KEY_SUBSTITUTE');
const handleGetStateByRangeStub = sinon.stub().resolves('some state');
const stub = new Stub({
handleGetStateByRange: handleGetStateByRangeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getStateByRangeWithPagination(null, 'end key', 3);
expect(result).to.deep.equal('some state');
expect(handleGetStateByRangeStub.calledOnce).to.be.true;
const metaPb = new peer.QueryResponseMetadata();
metaPb.setBookmark('');
metaPb.setFetchedRecordsCount(3);
const metadataBuffer = metaPb.serializeBinary();
expect(handleGetStateByRangeStub.firstCall.args).to.deep.equal(['', EMPTY_KEY_SUBSTITUTE, 'end key', 'dummyChannelId', 'dummyTxid', metadataBuffer]);
});
it('should have default bookmark eqls an empty string', async () => {
const handleGetStateByRangeStub = sinon.stub().resolves('some state');
const stub = new Stub({
handleGetStateByRange: handleGetStateByRangeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getStateByRangeWithPagination('start key', 'end key', 3);
expect(result).to.deep.equal('some state');
expect(handleGetStateByRangeStub.calledOnce).to.be.true;
const metaPb = new peer.QueryResponseMetadata();
metaPb.setBookmark('');
metaPb.setFetchedRecordsCount(3);
const metadataBuffer = metaPb.serializeBinary();
expect(handleGetStateByRangeStub.firstCall.args).to.deep.equal(['', 'start key', 'end key', 'dummyChannelId', 'dummyTxid', metadataBuffer]);
});
it('should have default bookmark eqls an empty string', async () => {
const handleGetStateByRangeStub = sinon.stub().resolves('some state');
const stub = new Stub({
handleGetStateByRange: handleGetStateByRangeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getStateByRangeWithPagination('start key', 'end key', 3, 'a bookmark');
expect(result).to.deep.equal('some state');
expect(handleGetStateByRangeStub.calledOnce).to.be.true;
const metaPb = new peer.QueryResponseMetadata();
metaPb.setBookmark('a bookmark');
metaPb.setFetchedRecordsCount(3);
const metadataBuffer = metaPb.serializeBinary();
expect(handleGetStateByRangeStub.firstCall.args).to.deep.equal(['', 'start key', 'end key', 'dummyChannelId', 'dummyTxid', metadataBuffer]);
});
});
describe('getQueryResult', () => {
it ('should return handler.handleGetQueryResult', async () => {
const handleGetQueryResultStub = sinon.stub().resolves({iterator: 'some query result'});
const stub = new Stub({
handleGetQueryResult: handleGetQueryResultStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getQueryResult('a query');
expect(result).to.deep.equal('some query result');
expect(handleGetQueryResultStub.calledOnce).to.be.true;
expect(handleGetQueryResultStub.firstCall.args).to.deep.equal(['', 'a query', null, 'dummyChannelId', 'dummyTxid']);
});
});
describe('getQueryResultWithPagination', () => {
it('should have default bookmark equals an empty string', async () => {
const handleGetQueryResultStub = sinon.stub().resolves('some query result');
const stub = new Stub({
handleGetQueryResult: handleGetQueryResultStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getQueryResultWithPagination('a query', 3);
expect(result).to.deep.equal('some query result');
expect(handleGetQueryResultStub.calledOnce).to.be.true;
const metadata = handleGetQueryResultStub.firstCall.args[2];
const decoded = peer.QueryMetadata.deserializeBinary(metadata);
expect(decoded.getPagesize()).to.equal(3);
expect(decoded.getBookmark()).to.equal('');
});
it('should have default bookmark equals an empty string', async () => {
const handleGetQueryResultStub = sinon.stub().resolves('some query result');
const stub = new Stub({
handleGetQueryResult: handleGetQueryResultStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getQueryResultWithPagination('a query', 3, 'a bookmark');
expect(result).to.deep.equal('some query result');
expect(handleGetQueryResultStub.calledOnce).to.be.true;
const metadata = handleGetQueryResultStub.firstCall.args[2];
const decoded = peer.QueryMetadata.deserializeBinary(metadata);
expect(decoded.getPagesize()).to.equal(3);
expect(decoded.getBookmark()).to.equal('a bookmark');
});
});
describe('getHistoryForKey', () => {
it ('should return handler.handleGetHistoryForKey', async () => {
const handleGetHistoryForKeyStub = sinon.stub().resolves('some history');
const stub = new Stub({
handleGetHistoryForKey: handleGetHistoryForKeyStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
const result = await stub.getHistoryForKey('a key');
expect(result).to.deep.equal('some history');
expect(handleGetHistoryForKeyStub.calledOnce).to.be.true;
expect(handleGetHistoryForKeyStub.firstCall.args).to.deep.equal(['a key', 'dummyChannelId', 'dummyTxid']);
});
});
describe('invokeChaincode', () => {
let stub;
let handleInvokeChaincodeStub;
beforeEach(() => {
handleInvokeChaincodeStub = sinon.stub().resolves('invoked');
stub = new Stub({
handleInvokeChaincode: handleInvokeChaincodeStub
}, 'dummyChannelId', 'dummyTxid', chaincodeInput);
});
it ('should return handler.handleInvokeChaincode', async () => {
const result = await stub.invokeChaincode('chaincodeName', ['some', 'args'], 'someChannel');
expect(result).to.deep.equal('invoked');
expect(handleInvokeChaincodeStub.calledOnce).to.be.true;
expect(handleInvokeChaincodeStub.firstCall.args).to.deep.equal(['chaincodeName/someChannel', ['some', 'args'], 'dummyChannelId', 'dummyTxid']);
});
it ('should return handler.handleInvokeChaincode handling no channel passed', async () => {
const result = await stub.invokeChaincode('chaincodeName', ['some', 'args']);
expect(result).to.deep.equal('invoked');
expect(handleInvokeChaincodeStub.calledOnce).to.be.true;
expect(handleInvokeChaincodeStub.firstCall.args).to.deep.equal(['chaincodeName', ['some', 'args'], 'dummyChannelId', 'dummyTxid']);
});
});
describe('setEvent', () => {
let stub;
beforeEach(() => {
stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
});
it ('should throw an error when name is not a string', () => {
expect(() => {
stub.setEvent();
}).to.throw(/Event name must be a non-empty string/);
});
it ('should throw an error when name is empty string', () => {
expect(() => {
stub.setEvent('');
}).to.throw(/Event name must be a non-empty string/);
});
it ('should set an event', () => {
stub.setEvent('some name', Buffer.from('some payload'));
expect(stub.chaincodeEvent.getEventName()).to.equal('some name');
expect(stub.chaincodeEvent.getPayload()).to.deep.equal(Buffer.from('some payload'));
});
});
describe('createCompositeKey', () => {
const saveValidate = Stub.__get__('validateCompositeKeyAttribute');
let stub;
let mockValidate;
beforeEach(() => {
mockValidate = sinon.stub().returns();
Stub.__set__('validateCompositeKeyAttribute', mockValidate);
stub = new Stub('dummyClient', 'dummyChannelId', 'dummyTxid', chaincodeInput);
});
after(() => {
Stub.__set__('validateCompositeKeyAttribute', saveValidate);
});
it ('should throw an error if attributes is not an array', () => {
expect(() => {
stub.createCompositeKey('some type', 'some attributes');
}).to.throw(/attributes must be an array/);
expect(mockValidate.calledOnce).to.be.true;
expect(mockValidate.firstCall.args).to.deep.equal(['some type']);
});
it ('should return a composite key', () => {
const COMPOSITEKEY_NS = Stub.__get__('COMPOSITEKEY_NS');
const MIN_UNICODE_RUNE_VALUE = Stub.__get__('MIN_UNICODE_RUNE_VALUE');
const result = stub.createCompositeKey('some type', ['attr1', 'attr2']);
expect(result).to.deep.equal(`${COMPOSITEKEY_NS}some type${MIN_UNICODE_RUNE_VALUE}attr1${MIN_UNICODE_RUNE_VALUE}attr2${MIN_UNICODE_RUNE_VALUE}`);
expect(mockValidate.calledThrice).to.be.true;
expect(mockValidate.firstCall.args).to.deep.equal(['some type']);