-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
context.unit.ts
1021 lines (907 loc) · 31.3 KB
/
context.unit.ts
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. 2018,2019. All Rights Reserved.
// Node module: @loopback/context
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {expect} from '@loopback/testlab';
import {
Binding,
BindingCreationPolicy,
BindingKey,
BindingScope,
BindingTag,
BindingType,
Context,
ContextEventObserver,
filterByTag,
isPromiseLike,
Provider,
} from '../..';
/**
* Create a subclass of context so that we can access parents and registry
* for assertions
*/
class TestContext extends Context {
observers: Set<ContextEventObserver> | undefined;
get parent() {
return this._parent;
}
get bindingMap() {
const map = new Map(this.registry);
return map;
}
get eventListener() {
return this.parentEventListener;
}
get tagIndex() {
return this.bindingsIndexedByTag;
}
findByTagInvoked = false;
_findByTagIndex(tag: BindingTag | RegExp) {
this.findByTagInvoked = true;
return super._findByTagIndex(tag);
}
}
describe('Context constructor', () => {
it('generates uuid name if not provided', () => {
const ctx = new Context();
expect(ctx.name).to.match(
/^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
);
});
it('generates unique names for different instances', () => {
const ctx1 = new Context();
const ctx2 = new Context();
expect(ctx1.name).to.not.eql(ctx2.name);
});
it('accepts a name', () => {
const ctx = new Context('my-context');
expect(ctx.name).to.eql('my-context');
});
it('accepts a parent context', () => {
const c1 = new Context('c1');
const ctx = new TestContext(c1);
expect(ctx.parent).to.eql(c1);
});
it('accepts a parent context and a name', () => {
const c1 = new Context('c1');
const ctx = new TestContext(c1, 'c2');
expect(ctx.name).to.eql('c2');
expect(ctx.parent).to.eql(c1);
});
});
describe('Context', () => {
let ctx: TestContext;
beforeEach('given a context', createContext);
describe('bind', () => {
it('adds a binding into the registry', () => {
ctx.bind('foo');
const result = ctx.contains('foo');
expect(result).to.be.true();
});
it('returns a binding', () => {
const binding = ctx.bind('foo');
expect(binding).to.be.instanceOf(Binding);
});
it('rejects a key containing property separator', () => {
const key = 'a' + BindingKey.PROPERTY_SEPARATOR + 'b';
expect(() => ctx.bind(key)).to.throw(/Binding key .* cannot contain/);
});
it('rejects rebinding of a locked key', () => {
ctx.bind('foo').lock();
expect(() => ctx.bind('foo')).to.throw(
'Cannot rebind key "foo" to a locked binding',
);
});
it('indexes a binding by tag', () => {
const binding = ctx.bind('foo').tag('a', {b: 1});
assertBindingIndexedByTag(binding, 'a', 'b');
});
it('indexes a binding by tag after being bound', () => {
const binding = ctx.bind('foo');
assertBindingNotIndexedByTag(binding, 'a', 'b');
binding.tag('a', {b: 1});
assertBindingIndexedByTag(binding, 'a', 'b');
});
});
describe('add', () => {
it('accepts a binding', () => {
const binding = new Binding('foo').to('bar');
ctx.add(binding);
expect(ctx.getBinding(binding.key)).to.be.exactly(binding);
const result = ctx.contains('foo');
expect(result).to.be.true();
});
it('rejects rebinding of a locked key', () => {
ctx.bind('foo').lock();
expect(() => ctx.add(new Binding('foo'))).to.throw(
'Cannot rebind key "foo" to a locked binding',
);
});
it('indexes a binding by tag', () => {
const binding = new Binding('foo').to('bar').tag('a', {b: 1});
ctx.add(binding);
assertBindingIndexedByTag(binding, 'a', 'b');
});
it('indexes a binding by tag after being bound', () => {
const binding = new Binding('foo').to('bar');
ctx.add(binding);
assertBindingNotIndexedByTag(binding, 'a', 'b');
binding.tag('a', {b: 1});
assertBindingIndexedByTag(binding, 'a', 'b');
});
});
describe('contains', () => {
it('returns true when the key is the registry', () => {
ctx.bind('foo');
const result = ctx.contains('foo');
expect(result).to.be.true();
});
it('returns false when the key is not in the registry', () => {
const result = ctx.contains('bar');
expect(result).to.be.false();
});
it('returns false when the key is only in the parent context', () => {
ctx.bind('foo');
const childCtx = new Context(ctx);
const result = childCtx.contains('foo');
expect(result).to.be.false();
});
});
describe('isBound', () => {
it('returns true when the key is bound in the context', () => {
ctx.bind('foo');
const result = ctx.isBound('foo');
expect(result).to.be.true();
});
it('returns false when the key is not bound in the context', () => {
const result = ctx.isBound('bar');
expect(result).to.be.false();
});
it('returns true when the key is bound in the context hierarchy', () => {
ctx.bind('foo');
const childCtx = new Context(ctx);
const result = childCtx.isBound('foo');
expect(result).to.be.true();
});
it('returns false when the key is not bound in the context hierarchy', () => {
ctx.bind('foo');
const childCtx = new Context(ctx);
const result = childCtx.isBound('bar');
expect(result).to.be.false();
});
});
describe('unbind', () => {
it('removes a binding', () => {
ctx.bind('foo');
const result = ctx.unbind('foo');
expect(result).to.be.true();
expect(ctx.contains('foo')).to.be.false();
});
it('returns false if the binding key does not exist', () => {
ctx.bind('foo');
const result = ctx.unbind('bar');
expect(result).to.be.false();
});
it('cannot unbind a locked binding', () => {
ctx
.bind('foo')
.to('a')
.lock();
expect(() => ctx.unbind('foo')).to.throw(
`Cannot unbind key "foo" of a locked binding`,
);
});
it('does not remove a binding from parent contexts', () => {
ctx.bind('foo');
const childCtx = new Context(ctx);
const result = childCtx.unbind('foo');
expect(result).to.be.false();
expect(ctx.contains('foo')).to.be.true();
});
it('removes indexes for a binding by tag', () => {
const binding = ctx
.bind('foo')
.to('bar')
.tag('a', {b: 1});
assertBindingIndexedByTag(binding, 'a', 'b');
ctx.unbind(binding.key);
assertBindingNotIndexedByTag(binding, 'a', 'b');
});
});
describe('find', () => {
it('returns matching binding', () => {
const b1 = ctx.bind('foo');
ctx.bind('bar');
const result = ctx.find('foo');
expect(result).to.be.eql([b1]);
});
it('returns matching binding with *', () => {
const b1 = ctx.bind('foo');
const b2 = ctx.bind('bar');
const b3 = ctx.bind('baz');
let result = ctx.find('*');
expect(result).to.be.eql([b1, b2, b3]);
result = ctx.find('ba*');
expect(result).to.be.eql([b2, b3]);
});
it('returns matching binding with * respecting key separators', () => {
const b1 = ctx.bind('foo');
const b2 = ctx.bind('foo.bar');
const b3 = ctx.bind('foo:bar');
let result = ctx.find('*');
expect(result).to.be.eql([b1]);
result = ctx.find('*.*');
expect(result).to.be.eql([b2]);
result = ctx.find('*:ba*');
expect(result).to.be.eql([b3]);
});
it('returns matching binding with ? respecting separators', () => {
const b1 = ctx.bind('foo');
const b2 = ctx.bind('foo.bar');
const b3 = ctx.bind('foo:bar');
let result = ctx.find('???');
expect(result).to.be.eql([b1]);
result = ctx.find('???.???');
expect(result).to.be.eql([b2]);
result = ctx.find('???:???');
expect(result).to.be.eql([b3]);
result = ctx.find('?');
expect(result).to.be.eql([]);
result = ctx.find('???????');
expect(result).to.be.eql([]);
});
it('escapes reserved chars for regexp', () => {
ctx.bind('foo');
const b2 = ctx.bind('foo+bar');
const b3 = ctx.bind('foo|baz');
let result = ctx.find('fo+');
expect(result).to.be.eql([]);
result = ctx.find('foo+bar');
expect(result).to.be.eql([b2]);
result = ctx.find('foo|baz');
expect(result).to.be.eql([b3]);
});
it('returns matching binding with regexp', () => {
const b1 = ctx.bind('foo');
const b2 = ctx.bind('bar');
const b3 = ctx.bind('baz');
let result = ctx.find(/\w+/);
expect(result).to.be.eql([b1, b2, b3]);
result = ctx.find(/ba/);
expect(result).to.be.eql([b2, b3]);
});
it('returns matching binding with filter', () => {
const b1 = ctx.bind('foo').inScope(BindingScope.SINGLETON);
const b2 = ctx.bind('bar').tag('b');
const b3 = ctx.bind('baz').tag('b');
let result = ctx.find(() => true);
expect(result).to.be.eql([b1, b2, b3]);
result = ctx.find(() => false);
expect(result).to.be.eql([]);
result = ctx.find(binding => binding.key.startsWith('ba'));
expect(result).to.be.eql([b2, b3]);
result = ctx.find(binding => binding.scope === BindingScope.SINGLETON);
expect(result).to.be.eql([b1]);
result = ctx.find(binding => binding.tagNames.includes('b'));
expect(result).to.be.eql([b2, b3]);
});
it('leverages binding index by tag', () => {
ctx.bind('foo');
const b2 = ctx.bind('bar').tag('b');
const b3 = ctx.bind('baz').tag('b');
const result = ctx.find(filterByTag('b'));
expect(result).to.eql([b2, b3]);
expect(ctx.findByTagInvoked).to.be.true();
});
it('leverages binding index by tag wildcard', () => {
ctx.bind('foo');
const b2 = ctx.bind('bar').tag('b2');
const b3 = ctx.bind('baz').tag('b3');
const result = ctx.find(filterByTag('b?'));
expect(result).to.eql([b2, b3]);
expect(ctx.findByTagInvoked).to.be.true();
});
it('leverages binding index by tag regexp', () => {
ctx.bind('foo');
const b2 = ctx.bind('bar').tag('b2');
const b3 = ctx.bind('baz').tag('b3');
const result = ctx.find(filterByTag(/b\d/));
expect(result).to.eql([b2, b3]);
expect(ctx.findByTagInvoked).to.be.true();
});
it('leverages binding index by tag name/value pairs', () => {
ctx.bind('foo');
const b2 = ctx.bind('bar').tag({a: 1});
ctx.bind('baz').tag({a: 2, b: 1});
const result = ctx.find(filterByTag({a: 1}));
expect(result).to.eql([b2]);
expect(ctx.findByTagInvoked).to.be.true();
});
});
describe('findByTag with name pattern', () => {
it('returns matching binding', () => {
const b1 = ctx.bind('controllers.ProductController').tag('controller');
ctx.bind('repositories.ProductRepository').tag('repository');
const result = ctx.findByTag('controller');
expect(result).to.be.eql([b1]);
});
it('returns matching binding with *', () => {
const b1 = ctx.bind('controllers.ProductController').tag('controller');
const b2 = ctx.bind('controllers.OrderController').tag('controller');
const result = ctx.findByTag('c*');
expect(result).to.be.eql([b1, b2]);
});
it('returns matching binding with regexp', () => {
const b1 = ctx.bind('controllers.ProductController').tag('controller');
const b2 = ctx
.bind('controllers.OrderController')
.tag('controller', 'rest');
let result = ctx.findByTag(/controller/);
expect(result).to.be.eql([b1, b2]);
result = ctx.findByTag(/rest/);
expect(result).to.be.eql([b2]);
});
});
describe('findByTag with name/value filter', () => {
it('returns matching binding', () => {
const b1 = ctx
.bind('controllers.ProductController')
.tag({name: 'my-controller'});
ctx.bind('controllers.OrderController').tag('controller');
ctx.bind('dataSources.mysql').tag({dbType: 'mysql'});
const result = ctx.findByTag({name: 'my-controller'});
expect(result).to.be.eql([b1]);
});
it('returns matching binding for multiple tags', () => {
const b1 = ctx
.bind('controllers.ProductController')
.tag({name: 'my-controller'})
.tag('controller');
ctx.bind('controllers.OrderController').tag('controller');
ctx.bind('dataSources.mysql').tag({dbType: 'mysql'});
const result = ctx.findByTag({
name: 'my-controller',
controller: 'controller',
});
expect(result).to.be.eql([b1]);
});
it('returns empty array if one of the tags does not match', () => {
ctx
.bind('controllers.ProductController')
.tag({name: 'my-controller'})
.tag('controller');
ctx.bind('controllers.OrderController').tag('controller');
ctx.bind('dataSources.mysql').tag({dbType: 'mysql'});
const result = ctx.findByTag({
controller: 'controller',
name: 'your-controller',
});
expect(result).to.be.eql([]);
});
it('returns empty array if no matching tag value is found', () => {
ctx.bind('controllers.ProductController').tag({name: 'my-controller'});
ctx.bind('controllers.OrderController').tag('controller');
ctx.bind('dataSources.mysql').tag({dbType: 'mysql'});
const result = ctx.findByTag({name: 'your-controller'});
expect(result).to.be.eql([]);
});
});
describe('getBinding', () => {
it('returns the binding object registered under the given key', () => {
const expected = ctx.bind('foo');
const actual: Binding = ctx.getBinding('foo');
expect(actual).to.equal(expected);
});
it('reports an error when binding is not found', () => {
expect(() => ctx.getBinding('unknown-key')).to.throw(/unknown-key/);
});
it('returns undefined if an optional binding is not found', () => {
const actual = ctx.getBinding('unknown-key', {optional: true});
expect(actual).to.be.undefined();
});
it('rejects a key containing property separator', () => {
const key = 'a' + BindingKey.PROPERTY_SEPARATOR + 'b';
expect(() => ctx.getBinding(key)).to.throw(
/Binding key .* cannot contain/,
);
});
});
describe('findOrCreateBinding', () => {
context('with BindingCreationPolicy.ALWAYS_CREATE', () => {
it('creates a new binding even the key is bound', () => {
const current = ctx.bind('foo');
const actual: Binding = ctx.findOrCreateBinding(
'foo',
BindingCreationPolicy.ALWAYS_CREATE,
);
expect(actual).to.be.not.exactly(current);
});
it('creates a new binding if not bound', () => {
const binding = ctx.findOrCreateBinding(
'a-new-key',
BindingCreationPolicy.ALWAYS_CREATE,
);
expect(binding.key).to.eql('a-new-key');
});
});
context('with BindingCreationPolicy.NEVER_CREATE', () => {
it('returns the exiting binding if the key is bound', () => {
const current = ctx.bind('foo');
const actual: Binding = ctx.findOrCreateBinding(
'foo',
BindingCreationPolicy.NEVER_CREATE,
);
expect(actual).to.be.exactly(current);
});
it('throws an error if the key is not bound', () => {
expect(() =>
ctx.findOrCreateBinding(
'a-new-key',
BindingCreationPolicy.NEVER_CREATE,
),
).to.throw(/The key 'a-new-key' is not bound to any value in context/);
});
});
context('with BindingCreationPolicy.CREATE_IF_NOT_BOUND', () => {
it('returns the binding object registered under the given key', () => {
const expected = ctx.bind('foo');
const actual: Binding = ctx.findOrCreateBinding(
'foo',
BindingCreationPolicy.CREATE_IF_NOT_BOUND,
);
expect(actual).to.be.exactly(expected);
});
it('creates a new binding if the key is not bound', () => {
const binding = ctx.findOrCreateBinding(
'a-new-key',
BindingCreationPolicy.CREATE_IF_NOT_BOUND,
);
expect(binding.key).to.eql('a-new-key');
});
});
context(
'without bindingCreationPolicy (default: CREATE_IF_NOT_BOUND)',
() => {
it('returns the binding object registered under the given key', () => {
const expected = ctx.bind('foo');
const actual: Binding = ctx.findOrCreateBinding('foo');
expect(actual).to.be.exactly(expected);
});
it('creates a new binding if the key is not bound', () => {
const binding = ctx.findOrCreateBinding('a-new-key');
expect(binding.key).to.eql('a-new-key');
});
},
);
it('rejects a key containing property separator', () => {
const key = 'a' + BindingKey.PROPERTY_SEPARATOR + 'b';
expect(() => ctx.findOrCreateBinding(key)).to.throw(
/Binding key .* cannot contain/,
);
});
});
describe('getSync', () => {
it('returns the value immediately when the binding is sync', () => {
ctx.bind('foo').to('bar');
const result = ctx.getSync('foo');
expect(result).to.equal('bar');
});
it('returns undefined if an optional binding is not found', () => {
expect(ctx.getSync('unknown-key', {optional: true})).to.be.undefined();
});
it('returns the value with property separator', () => {
const SEP = BindingKey.PROPERTY_SEPARATOR;
const val = {x: {y: 'Y'}};
ctx.bind('foo').to(val);
const value = ctx.getSync(`foo${SEP}x`);
expect(value).to.eql({y: 'Y'});
});
it('throws a helpful error when the binding is async', () => {
ctx.bind('foo').toDynamicValue(() => Promise.resolve('bar'));
expect(() => ctx.getSync('foo')).to.throw(/foo.*the value is a promise/);
});
it('returns singleton value', () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => count++)
.inScope(BindingScope.SINGLETON);
let result = ctx.getSync('foo');
expect(result).to.equal(0);
result = ctx.getSync('foo');
expect(result).to.equal(0);
const childCtx = new Context(ctx);
result = childCtx.getSync('foo');
expect(result).to.equal(0);
});
it('returns singleton value triggered by the child context', () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => count++)
.inScope(BindingScope.SINGLETON);
const childCtx = new Context(ctx);
// Calculate the singleton value at child level 1st
let result = childCtx.getSync('foo');
expect(result).to.equal(0);
// Try twice from the parent ctx
result = ctx.getSync('foo');
expect(result).to.equal(0);
result = ctx.getSync('foo');
expect(result).to.equal(0);
// Try again from the child ctx
result = childCtx.getSync('foo');
expect(result).to.equal(0);
});
it('returns transient value', () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => count++)
.inScope(BindingScope.TRANSIENT);
let result = ctx.getSync('foo');
expect(result).to.equal(0);
result = ctx.getSync('foo');
expect(result).to.equal(1);
const childCtx = new Context(ctx);
result = childCtx.getSync('foo');
expect(result).to.equal(2);
});
it('returns context value', () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => count++)
.inScope(BindingScope.CONTEXT);
let result = ctx.getSync('foo');
expect(result).to.equal(0);
result = ctx.getSync('foo');
expect(result).to.equal(0);
});
it('returns context value from a child context', () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => count++)
.inScope(BindingScope.CONTEXT);
let result = ctx.getSync('foo');
expect(result).to.equal(0);
const childCtx = new Context(ctx);
result = childCtx.getSync('foo');
expect(result).to.equal(1);
result = childCtx.getSync('foo');
expect(result).to.equal(1);
const childCtx2 = new Context(ctx);
result = childCtx2.getSync('foo');
expect(result).to.equal(2);
result = childCtx.getSync('foo');
expect(result).to.equal(1);
});
});
describe('getOwnerContext', () => {
it('returns owner context', () => {
ctx.bind('foo').to('bar');
expect(ctx.getOwnerContext('foo')).to.equal(ctx);
});
it('returns owner context with parent', () => {
ctx.bind('foo').to('bar');
const childCtx = new Context(ctx, 'child');
childCtx.bind('xyz').to('abc');
expect(childCtx.getOwnerContext('foo')).to.equal(ctx);
expect(childCtx.getOwnerContext('xyz')).to.equal(childCtx);
});
});
describe('get', () => {
it('returns a promise when the binding is async', async () => {
ctx.bind('foo').toDynamicValue(() => Promise.resolve('bar'));
const result = await ctx.get('foo');
expect(result).to.equal('bar');
});
it('returns undefined if an optional binding is not found', async () => {
expect(await ctx.get('unknown-key', {optional: true})).to.be.undefined();
});
it('returns the value with property separator', async () => {
const SEP = BindingKey.PROPERTY_SEPARATOR;
const val = {x: {y: 'Y'}};
ctx.bind('foo').toDynamicValue(() => Promise.resolve(val));
const value = await ctx.get(`foo${SEP}x`);
expect(value).to.eql({y: 'Y'});
});
it('returns singleton value', async () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => Promise.resolve(count++))
.inScope(BindingScope.SINGLETON);
let result = await ctx.get('foo');
expect(result).to.equal(0);
result = await ctx.get('foo');
expect(result).to.equal(0);
const childCtx = new Context(ctx);
result = await childCtx.get('foo');
expect(result).to.equal(0);
});
it('returns context value', async () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => Promise.resolve(count++))
.inScope(BindingScope.CONTEXT);
let result = await ctx.get('foo');
expect(result).to.equal(0);
result = await ctx.get('foo');
expect(result).to.equal(0);
});
it('returns context value from a child context', async () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => Promise.resolve(count++))
.inScope(BindingScope.CONTEXT);
let result = await ctx.get('foo');
const childCtx = new Context(ctx);
expect(result).to.equal(0);
result = await childCtx.get('foo');
expect(result).to.equal(1);
result = await childCtx.get('foo');
expect(result).to.equal(1);
const childCtx2 = new Context(ctx);
result = await childCtx2.get('foo');
expect(result).to.equal(2);
result = await childCtx.get('foo');
expect(result).to.equal(1);
});
it('returns transient value', async () => {
let count = 0;
ctx
.bind('foo')
.toDynamicValue(() => Promise.resolve(count++))
.inScope(BindingScope.TRANSIENT);
let result = await ctx.get('foo');
expect(result).to.equal(0);
result = await ctx.get('foo');
expect(result).to.equal(1);
const childCtx = new Context(ctx);
result = await childCtx.get('foo');
expect(result).to.equal(2);
});
});
describe('getValueOrPromise', () => {
it('returns synchronously for constant values', () => {
ctx.bind('key').to('value');
const valueOrPromise = ctx.getValueOrPromise('key');
expect(valueOrPromise).to.equal('value');
});
it('returns undefined if an optional binding is not found', () => {
expect(
ctx.getValueOrPromise('unknown-key', {optional: true}),
).to.be.undefined();
});
it('returns promise for async values', async () => {
ctx.bind('key').toDynamicValue(() => Promise.resolve('value'));
const valueOrPromise = ctx.getValueOrPromise<string>('key');
expect(isPromiseLike(valueOrPromise)).to.be.true();
const value = await valueOrPromise;
expect(value).to.equal('value');
});
it('returns nested property (synchronously)', () => {
ctx.bind('key').to({test: 'test-value'});
const value = ctx.getValueOrPromise('key#test');
expect(value).to.equal('test-value');
});
it('returns nested property (asynchronously)', async () => {
ctx
.bind('key')
.toDynamicValue(() => Promise.resolve({test: 'test-value'}));
const valueOrPromise = ctx.getValueOrPromise<string>('key#test');
expect(isPromiseLike(valueOrPromise)).to.be.true();
const value = await valueOrPromise;
expect(value).to.equal('test-value');
});
it('supports deeply nested property path', () => {
ctx.bind('key').to({x: {y: 'z'}});
const value = ctx.getValueOrPromise('key#x.y');
expect(value).to.equal('z');
});
it('returns undefined when nested property does not exist', () => {
ctx.bind('key').to({test: 'test-value'});
const value = ctx.getValueOrPromise('key#x.y');
expect(value).to.equal(undefined);
});
it('honours TRANSIENT scope when retrieving a nested property', () => {
const state = {count: 0};
ctx
.bind('state')
.toDynamicValue(() => {
state.count++;
return state;
})
.inScope(BindingScope.TRANSIENT);
// verify the initial state & populate the cache
expect(ctx.getSync('state')).to.deepEqual({count: 1});
// retrieve a nested property (expect a new value)
expect(ctx.getSync('state#count')).to.equal(2);
// retrieve the full object again (expect another new value)
expect(ctx.getSync('state')).to.deepEqual({count: 3});
});
it('honours CONTEXT scope when retrieving a nested property', () => {
const state = {count: 0};
ctx
.bind('state')
.toDynamicValue(() => {
state.count++;
return state;
})
.inScope(BindingScope.CONTEXT);
// verify the initial state & populate the cache
expect(ctx.getSync('state')).to.deepEqual({count: 1});
// retrieve a nested property (expect the cached value)
expect(ctx.getSync('state#count')).to.equal(1);
// retrieve the full object again (verify that cache was not modified)
expect(ctx.getSync('state')).to.deepEqual({count: 1});
});
it('honours SINGLETON scope when retrieving a nested property', () => {
const state = {count: 0};
ctx
.bind('state')
.toDynamicValue(() => {
state.count++;
return state;
})
.inScope(BindingScope.SINGLETON);
// verify the initial state & populate the cache
expect(ctx.getSync('state')).to.deepEqual({count: 1});
// retrieve a nested property from a child context
const childContext1 = new Context(ctx);
expect(childContext1.getValueOrPromise('state#count')).to.equal(1);
// retrieve a nested property from another child context
const childContext2 = new Context(ctx);
expect(childContext2.getValueOrPromise('state#count')).to.equal(1);
// retrieve the full object again (verify that cache was not modified)
expect(ctx.getSync('state')).to.deepEqual({count: 1});
});
});
describe('close()', () => {
it('clears all observers', () => {
const childCtx = new TestContext(ctx);
childCtx.subscribe(() => {});
expect(childCtx.observers!.size).to.eql(1);
childCtx.close();
expect(childCtx.observers).to.be.undefined();
});
it('removes listeners from parent context', () => {
const childCtx = new TestContext(ctx);
childCtx.subscribe(() => {});
// Now we have one observer
expect(childCtx.observers!.size).to.eql(1);
expect(childCtx.eventListener).to.be.a.Function();
// Now clear subscriptions
childCtx.close();
// observers are gone
expect(childCtx.observers).to.be.undefined();
// listeners are removed from parent context
expect(childCtx.eventListener).to.be.undefined();
});
it('keeps parent and bindings', () => {
const childCtx = new TestContext(ctx);
childCtx.bind('foo').to('foo-value');
childCtx.close();
expect(childCtx.parent).to.equal(ctx);
expect(childCtx.contains('foo'));
});
});
describe('maxListeners', () => {
it('defaults to Infinity', () => {
expect(ctx.getMaxListeners()).to.equal(Infinity);
});
it('can be changed', () => {
ctx.setMaxListeners(128);
expect(ctx.getMaxListeners()).to.equal(128);
});
});
describe('toJSON() and inspect()', () => {
beforeEach(setupBindings);
const expectedBindings = {
a: {
key: 'a',
scope: BindingScope.TRANSIENT,
tags: {},
isLocked: true,
type: BindingType.CONSTANT,
},
b: {
key: 'b',
scope: BindingScope.SINGLETON,
tags: {X: 'X', Y: 'Y'},
isLocked: false,
type: BindingType.DYNAMIC_VALUE,
},
c: {
key: 'c',
scope: BindingScope.TRANSIENT,
tags: {Z: 'Z', a: 1},
isLocked: false,
type: BindingType.CONSTANT,
},
d: {
key: 'd',
scope: BindingScope.TRANSIENT,
tags: {},
isLocked: false,
type: BindingType.CLASS,
valueConstructor: 'MyService',
},
e: {
key: 'e',
scope: BindingScope.TRANSIENT,
tags: {},
isLocked: false,
type: BindingType.PROVIDER,
providerConstructor: 'MyServiceProvider',
},
};
it('converts to plain JSON object', () => {
expect(ctx.toJSON()).to.eql(expectedBindings);
});
it('inspects as plain JSON object', () => {
expect(ctx.inspect()).to.eql({
name: 'app',
bindings: expectedBindings,
});
});
it('inspects as plain JSON object to include parent', () => {
const childCtx = new TestContext(ctx, 'server');
childCtx.bind('foo').to('foo-value');
expect(childCtx.inspect()).to.eql({
name: 'server',
bindings: childCtx.toJSON(),
parent: {
name: 'app',
bindings: expectedBindings,
},
});
});
class MyService {}
class MyServiceProvider implements Provider<MyService> {
value() {
return new MyService();
}
}
function setupBindings() {
ctx
.bind('a')
.to('1')
.lock();
ctx
.bind('b')
.toDynamicValue(() => 2)
.inScope(BindingScope.SINGLETON)
.tag('X', 'Y');
ctx
.bind('c')
.to(3)
.tag('Z', {a: 1});
ctx.bind('d').toClass(MyService);
ctx.bind('e').toProvider(MyServiceProvider);
}
});
function createContext() {