This repository has been archived by the owner on Mar 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
SMonoTest.scala
1335 lines (1202 loc) · 48.2 KB
/
SMonoTest.scala
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
package reactor.core.scala.publisher
import java.nio.file.Files
import java.util.concurrent._
import java.util.concurrent.atomic.{AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference}
import java.util.function.Supplier
import io.micrometer.core.instrument.Metrics
import io.micrometer.core.instrument.simple.SimpleMeterRegistry
import org.mockito.{ArgumentMatchersSugar, IdiomaticMockito}
import org.reactivestreams.Subscription
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.should.Matchers
import reactor.core.Disposable
import reactor.core.publisher.{BaseSubscriber, Signal, SynchronousSink, Mono => JMono}
import reactor.core.scala.Scannable
import reactor.core.scala.publisher.SMono.just
import reactor.core.scala.publisher.ScalaConverters._
import reactor.core.scala.publisher.model.TestSupport
import reactor.core.scheduler.{Scheduler, Schedulers}
import reactor.test.scheduler.VirtualTimeScheduler
import reactor.test.{StepVerifier, StepVerifierOptions}
import reactor.util.context.Context
import reactor.util.scala.retry.SRetry
import scala.concurrent.Future
import scala.concurrent.duration._
import scala.io.Source
import scala.language.postfixOps
import scala.math.ScalaNumber
import scala.util.{Failure, Random, Success, Try}
class SMonoTest extends AnyFreeSpec with Matchers with TestSupport with IdiomaticMockito with ArgumentMatchersSugar {
private val randomValue = Random.nextLong()
private def supplier[T](supply: => SMono[T]) = new Supplier[SMono[T]] {
def get(): SMono[T] = supply
}
"SMono" - {
".create should create a Mono" in {
StepVerifier.create(SMono.create[Long](monoSink => monoSink.success(randomValue)))
.expectNext(randomValue)
.expectComplete()
.verify()
}
".defer should create a Mono with deferred Mono" in {
StepVerifier.create(SMono.defer(() => just(randomValue)))
.expectNext(randomValue)
.expectComplete()
.verify()
}
".delay should create a Mono with the first element delayed according to the provided" - {
"duration" in {
StepVerifier.withVirtualTime(supplier[Long](SMono.delay(5 days)))
.thenAwait(5 days)
.expectNextCount(1)
.expectComplete()
.verify()
}
"duration in millis with given TimeScheduler" in {
val vts = VirtualTimeScheduler.getOrSet()
StepVerifier.create(SMono.delay(50 seconds, vts))
.`then`(() => vts.advanceTimeBy(50 seconds))
.expectNextCount(1)
.expectComplete()
.verify()
}
}
".empty " - {
"without source should create an empty Mono" in {
StepVerifier.create(SMono.empty)
.verifyComplete()
}
}
".firstEmitter" - {
"with varargs should create mono that emit the first item" in {
StepVerifier.withVirtualTime(supplier[Int](
SMono.firstEmitter(just(1).delaySubscription(3 seconds), just(2).delaySubscription(2 seconds))))
.thenAwait(3 seconds)
.expectNext(2)
.verifyComplete()
}
}
".from" - {
"a publisher should ensure that the publisher will emit 0 or 1 item." in {
StepVerifier.create(SMono.fromPublisher(SFlux.just(1, 2, 3, 4, 5)))
.expectNext(1)
.expectComplete()
.verify()
}
"a callable should ensure that Mono will return a value from the Callable" in {
StepVerifier.create(SMono.fromCallable(() => randomValue))
.expectNext(randomValue)
.expectComplete()
.verify()
}
"source direct should return mono of the source" in {
StepVerifier.create(SMono.fromDirect(SFlux.just(1, 2, 3)))
.expectNext(1, 2, 3)
.verifyComplete()
}
"a future should result Mono that will return the value from the future object" in {
import scala.concurrent.ExecutionContext.Implicits.global
StepVerifier.create(SMono.fromFuture(Future {
randomValue
}))
.expectNext(randomValue)
.verifyComplete()
}
"a Try should result SMono that when it is a" - {
"Success will emit the value of the Try" in {
def aSuccess = Try(randomValue)
StepVerifier.create(SMono.fromTry(aSuccess))
.expectNext(randomValue)
.verifyComplete()
}
"Failure will emit onError with the exception" in {
def aFailure = Try(throw new RuntimeException("error message"))
StepVerifier.create(SMono.fromTry(aFailure))
.expectErrorMessage("error message")
.verify()
}
}
}
".ignoreElements should ignore all elements from a publisher and just react on completion signal" in {
StepVerifier.create(SMono.ignoreElements(just(randomValue)))
.expectComplete()
.verify()
}
".just should emit the specified item" in {
StepVerifier.create(just(randomValue))
.expectNext(randomValue)
.verifyComplete()
}
".justOrEmpty" - {
"with Option should" - {
"emit the specified item if the option is not empty" in {
StepVerifier.create(SMono.justOrEmpty(Option(randomValue)))
.expectNext(randomValue)
.verifyComplete()
}
"just react on completion signal if the option is empty" in {
StepVerifier.create(SMono.justOrEmpty(Option.empty))
.expectComplete()
.verify()
}
}
"with data should" - {
"emit the specified item if it is not null" in {
val mono = SMono.justOrEmpty(randomValue)
StepVerifier.create(mono)
.expectNext(randomValue)
.verifyComplete()
}
"just react on completion signal if it is null" in {
val nullData:Any = null
val mono = SMono.justOrEmpty(nullData)
StepVerifier.create(mono)
.expectComplete()
.verify()
}
}
}
".metrics should enable Micrometer metrics" in {
val registry = new SimpleMeterRegistry
Metrics.globalRegistry add registry
try {
StepVerifier.create(
SMono.just("plain awesome")
.name("SMonoTest")
.metrics
).expectNext("plain awesome")
.verifyComplete()
registry.find("reactor.flow.duration")
.tag("flow","SMonoTest")
.timer.count shouldEqual 1d
}
finally Metrics.globalRegistry remove registry
}
".never will never signal any data, error or completion signal" in {
StepVerifier.create(SMono.never)
.expectSubscription()
.expectNoEvent(1 second)
}
".name should give name to this sequence" in {
val name = "one two three four"
val scannable: Scannable = Scannable.from(Option(just(randomValue).name(name)))
scannable.name shouldBe name
}
".sequenceEqual should" - {
"emit Boolean.TRUE when both publisher emit the same value" in {
StepVerifier.create(SMono.sequenceEqual(just(1), just(1)))
.expectNext(true)
.verifyComplete()
}
"emit true when both publisher emit the same value according to the isEqual function" in {
val mono = SMono.sequenceEqual(just(10), just(100), (t1: Int, t2: Int) => t1 % 10 == t2 % 10)
StepVerifier.create(mono)
.expectNext(true)
.verifyComplete()
}
"emit true when both publisher emit the same value according to the isEqual function with bufferSize" in {
val mono = SMono.sequenceEqual(just(10), just(100), (t1: Int, t2: Int) => t1 % 10 == t2 % 10, 2)
StepVerifier.create(mono)
.expectNext(true)
.verifyComplete()
}
}
".error should create Mono that emit error" in {
StepVerifier.create(SMono.error(new RuntimeException("runtime error")))
.expectError(classOf[RuntimeException])
.verify()
}
".raiseError should create Mono that emit error" in {
StepVerifier.create(SMono.error(new RuntimeException("runtime error")))
.expectError(classOf[RuntimeException])
.verify()
}
".when" - {
"with iterable" - {
"of publisher of unit should return when all of the sources has fulfilled" in {
val completed = new ConcurrentHashMap[String, Boolean]()
val mono = SMono.when(Iterable(
just({
completed.put("first", true)
()
}),
just({
completed.put("second", true)
()
})
))
StepVerifier.create(mono)
.expectComplete()
completed should contain key "first"
completed should contain key "second"
}
}
"with varargs of publisher should return when all of the resources has fulfilled" in {
val completed = new ConcurrentHashMap[String, Boolean]()
val sources = Seq(just({
completed.put("first", true)
()
}),
just[Unit]({
completed.put("second", true)
()
})
)
StepVerifier.create(SMono.when(sources.toArray: _*))
.expectComplete()
completed should contain key "first"
completed should contain key "second"
}
}
".zipDelayError" - {
"with p1 and p2 should merge when both Monos are fulfilled" in {
StepVerifier.create(SMono.zipDelayError(just(1), just("one")))
.expectNext((1, "one"))
.verifyComplete()
}
"with p1, p2 and p3 should merge when all Monos are fulfilled" in {
StepVerifier.create(SMono.zipDelayError(just(1), just("one"), just(1L)))
.expectNext((1, "one", 1L))
.verifyComplete()
}
"with p1, p2, p3 and p4 should merge when all Monos are fulfilled" in {
StepVerifier.create(SMono.zipDelayError(just(1), just(2), just(3), just(4)))
.expectNext((1, 2, 3, 4))
.verifyComplete()
}
"with p1, p2, p3, p4 and p5 should merge when all Monos are fulfilled" in {
StepVerifier.create(SMono.zipDelayError(just(1), just(2), just(3), just(4), just(5)))
.expectNext((1, 2, 3, 4, 5))
.verifyComplete()
}
"with p1, p2, p3, p4, p5 and p6 should merge when all Monos are fulfilled" in {
StepVerifier.create(SMono.zipDelayError(just(1), just(2), just(3), just(4), just(5), just(6)))
.expectNext((1, 2, 3, 4, 5, 6))
.verifyComplete()
}
"with iterable" - {
"of publisher of unit should return when all of the sources has fulfilled" in {
val completed = new ConcurrentHashMap[String, Boolean]()
val mono: SMono[Unit] = SMono.whenDelayError(Iterable(
just({
completed.put("first", true)
1
}),
just({
completed.put("second", true)
2
})
))
StepVerifier.create(mono)
.expectComplete()
completed should contain key "first"
completed should contain key "second"
}
"of combinator function and monos should emit the value after combined by combinator function" in {
StepVerifier.create(SMono.zipDelayError((values: Array[Any]) => s"${values(0).toString}-${values(1).toString}", just(1), just("one")))
.expectNext("1-one")
.verifyComplete()
}
}
}
".zip" - {
val combinator: Array[AnyRef] => String = { datas => datas.map(_.toString).foldLeft("") { (acc, v) => if (acc.isEmpty) v else s"$acc-$v" } }
"with combinator function and varargs of mono should fullfill when all Monos are fulfilled" in {
val mono = SMono.zip(combinator, just(1), just(2))
StepVerifier.create(mono)
.expectNext("1-2")
.verifyComplete()
}
"with combinator function and Iterable of mono should fulfill when all Monos are fulfilled" in {
val mono = SMono.zip(Iterable(just(1), just("2")), combinator)
StepVerifier.create(mono)
.expectNext("1-2")
.verifyComplete()
}
}
".and" - {
"should combine this mono and the other" in {
StepVerifier.create(just(1) and just(2))
.verifyComplete()
}
}
".as should transform the Mono to whatever the transformer function is provided" in {
val mono = just(randomValue)
StepVerifier.create(mono.as(m => SFlux.fromPublisher(m)))
.expectNext(randomValue)
.verifyComplete()
}
".asJava should convert to java" in {
just(randomValue).asJava() shouldBe a[JMono[_]]
}
".asScala should transform Mono to SMono" in {
JMono.just(randomValue).asScala shouldBe an[SMono[_]]
}
".asScala and .asJava should be" - {
val jMono: JMono[Long] = JMono.just(randomValue)
"compile" in {
//noinspection ScalaUnusedSymbol
"val x: JMono[Long] = jMono.asScala.asJava()" should compile
}
"symmetrical" in {
jMono.asScala.asJava() should be theSameInstanceAs jMono
}
}
".block" - {
"should block the mono to get the value" in {
just(randomValue).block() shouldBe randomValue
}
"with duration should block the mono up to the duration" in {
just(randomValue).block(10 seconds) shouldBe randomValue
}
}
".blockOption" - {
"without duration" - {
"should block the mono to get value" in {
just(randomValue).blockOption() shouldBe Some(randomValue)
}
"should return None if mono is empty" in {
SMono.empty.blockOption() shouldBe None
}
}
"with duration" - {
"should block the mono up to the duration" in {
just(randomValue).blockOption(10 seconds) shouldBe Some(randomValue)
}
"shouldBlock the mono up to the duration and return None" in {
StepVerifier.withVirtualTime(supplier[Option[Unit]](
just(SMono.empty.blockOption(10 seconds))))
.thenAwait(10 seconds)
.expectNext(None)
.verifyComplete()
}
}
}
".bracket should always release all resources properly" in {
import java.io.PrintWriter
val file = Files.createTempFile(s"bracketCase-smono", ".tmp").toFile
new PrintWriter(file) { write("smono"); close() }
file.exists() shouldBe true
val sMono = SMono.just(file)
.using(_ => SMono.error(new RuntimeException("Always throw exception")))(file => file.delete())
StepVerifier.create(sMono)
.expectError(classOf[RuntimeException])
.verify()
file.exists() shouldBe false
}
".bracketCase" - {
"should release all resources properly" in {
import java.io.PrintWriter
val file = Files.createTempFile(s"bracketCase-smono", ".tmp").toFile
new PrintWriter(file) { write("smono"); close() }
file.exists() shouldBe true
val sMono = SMono.just(file)
.usingWhen(f => {
val br = Source.fromFile(f)
val line = br.getLines().mkString
br.close()
SMono.just(line)
})((file, _) => file.delete())
StepVerifier.create(sMono)
.expectNext("smono")
.verifyComplete()
file.exists() shouldBe false
}
"should handle ExitCase.error" - {
"when the error happens inside the generated flux" in {
import java.io.PrintWriter
val file = Files.createTempFile(s"bracketCase-smono", ".tmp").toFile
new PrintWriter(file) { write("smono"); close() }
try {
file.exists() shouldBe true
val sMono = SMono.just(file)
.usingWhen(_ => {
SMono.error(new RuntimeException("Always throw exception"))
})((file, exitCase) => {
exitCase match {
case Error(_) => ()
case _ => file.delete()
}
})
StepVerifier.create(sMono)
.expectError(classOf[RuntimeException])
.verify()
file.exists() shouldBe true
} finally {
file.delete()
}
}
"when the error happens while generating the mono" in {
import java.io.PrintWriter
val file = Files.createTempFile(s"bracketCase-smono", ".tmp").toFile
new PrintWriter(file) { write("smono"); close() }
try {
file.exists() shouldBe true
val sMono = SMono.just(file)
.usingWhen(_ => throw new RuntimeException)((file, exitCase) => {
exitCase match {
case Error(_) => ()
case _ => file.delete()
}
})
StepVerifier.create(sMono)
.expectError(classOf[RuntimeException])
.verify()
file.exists() shouldBe true
} finally {
file.delete()
}
}
}
}
".cast (deprecated) should cast the underlying value" in {
val number = SMono.just(BigDecimal("123")).cast(classOf[ScalaNumber]).block()
number shouldBe a[ScalaNumber]
}
".cast should cast the underlying value" in {
val number = SMono.just(BigDecimal("123")).cast[ScalaNumber].block()
number shouldBe a[ScalaNumber]
}
".cache" - {
"should cache the value" in {
val queue = new ArrayBlockingQueue[Int](1)
queue.put(1)
val mono = SMono.create[Int](sink => {
sink.success(queue.poll())
}).cache()
StepVerifier.create(mono)
.expectNext(1)
.verifyComplete()
StepVerifier.create(mono)
.expectNext(1)
.verifyComplete()
}
"with ttl cache the value up to specific time" in {
import reactor.test.scheduler.VirtualTimeScheduler
val timeScheduler = VirtualTimeScheduler.getOrSet
val queue = new ArrayBlockingQueue[Int](1)
queue.put(1)
val mono = SMono.create[Int](sink => {
sink.success(queue.poll())
}).cache(1 minute)
StepVerifier.create(mono)
.expectNext(1)
.verifyComplete()
timeScheduler.advanceTimeBy(59 second)
StepVerifier.create(mono)
.expectNext(1)
.verifyComplete()
timeScheduler.advanceTimeBy(2 minute)
StepVerifier.create(mono)
.verifyComplete()
}
}
".cancelOn should cancel the subscriber on a particular scheduler" in {
val jMono = spy(JMono.just(1))
new ReactiveSMono[Int](jMono).cancelOn(Schedulers.immediate())
jMono.cancelOn(any[Scheduler]) was called
}
".compose (deprecated) should defer creating the target mono type" in {
StepVerifier.create(just(1).compose[String](m => SFlux.fromPublisher(m.map(_.toString))))
.expectNext("1")
.verifyComplete()
}
".transformDeferred should defer creating the target mono type" in {
StepVerifier.create(SMono.just(1).transformDeferred(m => SFlux.fromPublisher(m.map(_.toString))))
.expectNext("1")
.verifyComplete()
}
".concatWith should concatenate mono with another source" in {
StepVerifier.create(just(1).concatWith(just(2)))
.expectNext(1)
.expectNext(2)
.verifyComplete()
}
"+ should sum up element in this SMono and element from the other SMono" in {
StepVerifier.create(just(9) + just(8))
.expectNext(17)
.verifyComplete()
}
"- should subtract element in this SMono with the element from the other SMono" in {
StepVerifier.create(just(11) - just(7))
.expectNext(4)
.verifyComplete()
}
"* should multiply element in this SMono and element from the other SMono" in {
StepVerifier.create(just(9) * just(8))
.expectNext(72)
.verifyComplete()
}
"++ should concatenate mono with another source" in {
StepVerifier.create(just(1) ++ just(2))
.expectNext(1)
.expectNext(2)
.verifyComplete()
}
".defaultIfEmpty should use the provided default value if the mono is empty" in {
StepVerifier.create(SMono.empty.defaultIfEmpty(-1))
.expectNext(-1)
.verifyComplete()
}
".delayElement" - {
"should delay the element" in {
StepVerifier.withVirtualTime(supplier[Long](just(randomValue).delayElement(5 seconds)))
.thenAwait(5 seconds)
.expectNext(randomValue)
.verifyComplete()
}
"with timer should delay using timer" in {
StepVerifier.withVirtualTime(supplier[Long](just(randomValue).delayElement(5 seconds, Schedulers.immediate())))
.thenAwait(5 seconds)
.expectNext(randomValue)
.verifyComplete()
}
}
".delaySubscription" - {
"with delay duration should delay subscription as long as the provided duration" in {
StepVerifier.withVirtualTime(supplier[Int](just(1).delaySubscription(1 hour)))
.thenAwait(1 hour)
.expectNext(1)
.verifyComplete()
}
"with delay duration and scheduler should delay subscription as long as the provided duration" in {
StepVerifier.withVirtualTime(supplier[Int](just(1).delaySubscription(1 hour, Schedulers.single())))
.thenAwait(1 hour)
.expectNext(1)
.verifyComplete()
}
"with another publisher should delay the current subscription until the other publisher completes" in {
StepVerifier.withVirtualTime(supplier[Int](just(1).delaySubscription(just("one").delaySubscription(1 hour))))
.thenAwait(1 hour)
.expectNext(1)
.verifyComplete()
}
}
".delayUntil should delay until the other provider terminate" in {
StepVerifier.withVirtualTime(supplier[Long](just(randomValue).delayUntil(_ => SFlux.just(1, 2).delayElements(2 seconds))))
.thenAwait(4 seconds)
.expectNext(randomValue)
.verifyComplete()
}
".dematerialize should dematerialize the underlying mono" in {
StepVerifier.create(just(Signal.next(randomValue)).dematerialize())
.expectNext(randomValue)
.verifyComplete()
}
".doAfterSuccessOrError (deprecated) should call the callback function after the mono is terminated" in {
val atomicBoolean = new AtomicBoolean(false)
StepVerifier.create(just(randomValue)
.doAfterSuccessOrError { t =>
atomicBoolean.compareAndSet(false, true) shouldBe true
t shouldBe Success(randomValue)
})
.expectNext(randomValue)
.verifyComplete()
atomicBoolean shouldBe Symbol("get")
val exception = new RuntimeException
StepVerifier.create(SMono.error[Long](exception)
.doAfterSuccessOrError { t =>
atomicBoolean.compareAndSet(true, false) shouldBe true
t shouldBe Failure(exception)
})
.expectError()
.verify()
atomicBoolean.get() shouldBe false
}
".doAfterTerminate should call the callback function after the mono is terminated" in {
val atomicBoolean = new AtomicBoolean(false)
StepVerifier.create(just(randomValue).doAfterTerminate(() => atomicBoolean.compareAndSet(false, true)))
.expectNext(randomValue)
.verifyComplete()
atomicBoolean shouldBe Symbol("get")
}
".doFinally should call the callback" in {
val atomicBoolean = new AtomicBoolean(false)
StepVerifier.create(just(randomValue)
.doFinally(_ => atomicBoolean.compareAndSet(false, true) shouldBe true))
.expectNext(randomValue)
.verifyComplete()
atomicBoolean shouldBe Symbol("get")
}
".doOnCancel should call the callback function when the subscription is cancelled" in {
val atomicBoolean = new AtomicBoolean(false)
val mono = SMono.delay(1 minute)
.doOnCancel(() => {
atomicBoolean.compareAndSet(false, true) shouldBe true
})
val subscriptionReference = new AtomicReference[Subscription]()
mono.subscribe(new BaseSubscriber[Long] {
override def hookOnSubscribe(subscription: Subscription): Unit = {
subscriptionReference.set(subscription)
subscription.request(1)
}
override def hookOnNext(value: Long): Unit = ()
})
subscriptionReference.get().cancel()
atomicBoolean shouldBe Symbol("get")
}
".doOnNext should call the callback function when the mono emit data successfully" in {
val atomicLong = new AtomicLong()
StepVerifier.create(just(randomValue)
.doOnNext(t => atomicLong.compareAndSet(0, t)))
.expectNext(randomValue)
.verifyComplete()
atomicLong.get() shouldBe randomValue
}
".doOnSuccess should call the callback function when the mono completes successfully" in {
val atomicBoolean = new AtomicBoolean(false)
StepVerifier.create(SMono.empty[Int]
.doOnSuccess(_ => atomicBoolean.compareAndSet(false, true) shouldBe true))
.verifyComplete()
atomicBoolean shouldBe Symbol("get")
}
".doOnError" - {
"with callback function should call the callback function when the mono encounter error" in {
val atomicBoolean = new AtomicBoolean(false)
StepVerifier.create(SMono.error(new RuntimeException())
.doOnError(_ => atomicBoolean.compareAndSet(false, true) shouldBe true))
.expectError(classOf[RuntimeException])
.verify()
atomicBoolean shouldBe Symbol("get")
}
}
".doOnRequest should call the callback function when subscriber request data" in {
val atomicLong = new AtomicLong(0)
just(randomValue)
.doOnRequest(l => atomicLong.compareAndSet(0, l)).subscribe(new BaseSubscriber[Long] {
override def hookOnSubscribe(subscription: Subscription): Unit = {
subscription.request(1)
()
}
override def hookOnNext(value: Long): Unit = ()
})
atomicLong.get() shouldBe 1
}
".doOnSubscribe should call the callback function when the mono is subscribed" in {
val atomicBoolean = new AtomicBoolean(false)
StepVerifier.create(just(randomValue)
.doOnSubscribe(_ => atomicBoolean.compareAndSet(false, true)))
.expectNextCount(1)
.verifyComplete()
atomicBoolean shouldBe Symbol("get")
}
".doOnTerminate should do something on terminate" in {
val atomicLong = new AtomicLong()
StepVerifier.create(just(randomValue).doOnTerminate { () => atomicLong.set(randomValue) })
.expectNext(randomValue)
.expectComplete()
.verify()
atomicLong.get() shouldBe randomValue
}
".elapsed" - {
"should provide the time elapse when this mono emit value" in {
StepVerifier.withVirtualTime(supplier[(Long, Long)](just(randomValue).delaySubscription(1 second).elapsed()))
.thenAwait(1 second)
.expectNextMatches {
case (time, data) => time >= 1000 && data == randomValue
}
.verifyComplete()
}
"with TimedScheduler should provide the time elapsed using the provided scheduler when this mono emit value" in {
val virtualTimeScheduler = VirtualTimeScheduler.getOrSet()
StepVerifier.create(just(randomValue)
.delaySubscription(1 second, virtualTimeScheduler)
.elapsed(virtualTimeScheduler), 1)
.`then`(() => virtualTimeScheduler.advanceTimeBy(1 second))
.expectNextMatches {
case (time, data) => time >= 1000 && data == randomValue
}
.verifyComplete()
}
}
".expandDeep" - {
"should expand the mono" in {
StepVerifier.create(just("a").expandDeep(s => just(s"$s$s")).take(3))
.expectNext("a", "aa", "aaaa")
.verifyComplete()
}
"with capacity hint should expand the mono" in {
StepVerifier.create(just("a").expandDeep(s => just(s"$s$s"), 10).take(3))
.expectNext("a", "aa", "aaaa")
.verifyComplete()
}
}
".expand" - {
"should expand the mono" in {
StepVerifier.create(just("a").expand(s => just(s"$s$s")).take(3))
.expectNext("a", "aa", "aaaa")
.verifyComplete()
}
"with capacity hint should expand the mono" in {
StepVerifier.create(just("a").expand(s => just(s"$s$s"), 10).take(3))
.expectNext("a", "aa", "aaaa")
.verifyComplete()
}
}
".filter should filter the value of mono where it pass the provided predicate" in {
StepVerifier.create(just(10)
.filter(i => i < 10))
.verifyComplete()
}
".filterWhen should replay the value of mono if the first item emitted by the test is true" in {
StepVerifier.create(just(10).filterWhen((i: Int) => just(i % 2 == 0)))
.expectNext(10)
.verifyComplete()
}
".flatMap should flatmap the provided mono" in {
StepVerifier.create(SMono.just(randomValue).flatMap(l => SMono.just(l.toString)))
.expectNext(randomValue.toString)
.verifyComplete()
}
".flatMapMany" - {
"with a single mapper should flatmap the value mapped by the provided mapper" in {
StepVerifier.create(just(1).flatMapMany(i => SFlux.just(i, i * 2)))
.expectNext(1, 2)
.verifyComplete()
}
"with mapperOnNext, mapperOnError and mapperOnComplete should mapped each individual event into values emitted by flux" in {
StepVerifier.create(just(1)
.flatMapMany(
_ => just("one"),
_ => just("error"),
() => just("complete")
))
.expectNext("one", "complete")
.verifyComplete()
}
}
".flatMapIterable should flatmap the value mapped by the provided mapper" in {
StepVerifier.create(just("one").flatMapIterable(str => str.toCharArray))
.expectNext('o', 'n', 'e')
.verifyComplete()
}
".flux should convert this mono into a flux" in {
val flux = just(randomValue).flux()
StepVerifier.create(flux)
.expectNext(randomValue)
.verifyComplete()
flux shouldBe an[SFlux[Long]]
}
".hasElement should convert to another Mono that emit" - {
"true if it has element" in {
StepVerifier.create(just(1).hasElement)
.expectNext(true)
.verifyComplete()
}
"false if it is empty" in {
StepVerifier.create(SMono.empty.hasElement)
.expectNext(false)
.verifyComplete()
}
}
".handle should handle onNext, onError and onComplete" in {
StepVerifier.create(just(randomValue)
.handle((_: Long, s: SynchronousSink[String]) => {
s.next("One")
s.complete()
}))
.expectNext("One")
.verifyComplete()
}
".ignoreElement should only emit termination event" in {
StepVerifier.create(just(randomValue).ignoreElement)
.verifyComplete()
}
".map should map the type of Mono from T to R" in {
StepVerifier.create(just(randomValue).map(_.toString))
.expectNext(randomValue.toString)
.expectComplete()
.verify()
}
".mapError" - {
class MyCustomException(val message: String) extends Exception(message)
"with mapper should map the error to another error" in {
StepVerifier.create(SMono.error[Int](new RuntimeException("runtimeException"))
.onErrorMap { case t: Throwable => new MyCustomException(t.getMessage) })
.expectErrorMatches((t: Throwable) => {
t.getMessage shouldBe "runtimeException"
t should not be a[RuntimeException]
t shouldBe a[MyCustomException]
true
})
.verify()
}
"with an error type and mapper should" - {
"map the error to another type if the exception is according to the provided type" in {
StepVerifier.create(SMono.error[Int](new RuntimeException("runtimeException"))
.onErrorMap { case t: RuntimeException => new MyCustomException(t.getMessage) })
.expectErrorMatches((t: Throwable) => {
t.getMessage shouldBe "runtimeException"
t should not be a[RuntimeException]
t shouldBe a[MyCustomException]
true
})
.verify()
}
"not map the error if the exception is not the type of provided exception class" in {
StepVerifier.create(SMono.error[Int](new Exception("runtimeException"))
.onErrorMap {
case t: RuntimeException => new MyCustomException(t.getMessage)
})
.expectErrorMatches((t: Throwable) => {
t.getMessage shouldBe "runtimeException"
t should not be a[MyCustomException]
t shouldBe a[Exception]
true
})
.verify()
}
}
"with a predicate and mapper should" - {
"map the error to another type if the predicate returns true" in {
StepVerifier.create(SMono.error[Int](new RuntimeException("should map"))
.onErrorMap { case t: Throwable if t.getMessage == "should map" => new MyCustomException(t.getMessage) })
.expectError(classOf[MyCustomException])
.verify()
}
"not map the error to another type if the predicate returns false" in {
StepVerifier.create(SMono.error[Int](new RuntimeException("should not map"))
.onErrorMap { case t: Throwable if t.getMessage == "should map" => new MyCustomException(t.getMessage) })
.expectError(classOf[RuntimeException])
.verify()
}
}
}
".materialize should convert the mono into a mono that emit its signal" in {
StepVerifier.create(just(randomValue).materialize())
.expectNext(Signal.next(randomValue))
.verifyComplete()
}
".mergeWith should convert this mono to flux with value emitted from this mono followed by the other" in {
StepVerifier.create(just(1).mergeWith(just(2)))
.expectNext(1, 2)
.verifyComplete()
}
".ofType (deprecated) should" - {
"convert the Mono value type to the provided type if it can be casted" in {
StepVerifier.create(just(BigDecimal("1")).ofType(classOf[ScalaNumber]))
.expectNextCount(1)
.verifyComplete()
}
"ignore the Mono value if it can't be casted" in {
StepVerifier.create(just(1).ofType(classOf[String]))
.verifyComplete()
}
}
".ofType should" - {
"convert the Mono value type to the provided type if it can be casted" in {
StepVerifier.create(SMono.just(BigDecimal("1")).ofType[ScalaNumber])
.expectNextCount(1)
.verifyComplete()
}
"ignore the Mono value if it can't be casted" in {
StepVerifier.create(SMono.just(1).ofType[String])
.verifyComplete()
}
}
".onErrorRecover" - {
"should recover with a Mono of element that has been recovered" in {
StepVerifier.create(SMono.error(new RuntimeException("oops"))
.onErrorRecover { case _ => Truck(5) })