/
Assertions.scala
1314 lines (1264 loc) · 61.1 KB
/
Assertions.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
/*
* Copyright 2001-2013 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest
import org.scalactic.{Resources => _, FailureMessages => _, _}
import Requirements._
import scala.reflect.ClassTag
import Assertions.areEqualComparingArraysStructurally
import org.scalatest.exceptions.StackDepthException
import org.scalatest.exceptions.StackDepthException.toExceptionFunction
import org.scalatest.exceptions.TestFailedException
import org.scalatest.exceptions.TestPendingException
import org.scalatest.exceptions.TestCanceledException
import ArrayHelper.deep
import org.scalactic.anyvals.NonEmptyArray
/**
* Trait that contains ScalaTest's basic assertion methods.
*
* <p>
* You can use the assertions provided by this trait in any ScalaTest <code>Suite</code>,
* because <a href="Suite.html"><code>Suite</code></a>
* mixes in this trait. This trait is designed to be used independently of anything else in ScalaTest, though, so you
* can mix it into anything. (You can alternatively import the methods defined in this trait. For details, see the documentation
* for the <a href="Assertions$.html"><code>Assertions</code> companion object</a>.
* </p>
*
* <p>
* In any Scala program, you can write assertions by invoking <code>assert</code> and passing in a <code>Boolean</code> expression,
* such as:
* </p>
*
* <pre class="stHighlighted">
* <span class="stReserved">val</span> left = <span class="stLiteral">2</span>
* <span class="stReserved">val</span> right = <span class="stLiteral">1</span>
* assert(left == right)
* </pre>
*
* <p>
* If the passed expression is <code>true</code>, <code>assert</code> will return normally. If <code>false</code>,
* Scala's <code>assert</code> will complete abruptly with an <code>AssertionError</code>. This behavior is provided by
* the <code>assert</code> method defined in object <code>Predef</code>, whose members are implicitly imported into every
* Scala source file. This <code>Assertions</code> trait defines another <code>assert</code> method that hides the
* one in <code>Predef</code>. It behaves the same, except that if <code>false</code> is passed it throws
* <a href="exceptions/TestFailedException.html"><code>TestFailedException</code></a> instead of <code>AssertionError</code>.
* Why? Because unlike <code>AssertionError</code>, <code>TestFailedException</code> carries information about exactly
* which item in the stack trace represents
* the line of test code that failed, which can help users more quickly find an offending line of code in a failing test.
* In addition, ScalaTest's <code>assert</code> provides better error messages than Scala's <code>assert</code>.
* <p>
*
* <p>
* If you pass the previous <code>Boolean</code> expression, <code>left == right</code> to <code>assert</code> in a ScalaTest test,
* a failure will be reported that, because <code>assert</code> is implemented as a macro,
* includes reporting the left and right values.
* For example, given the same code as above but using ScalaTest assertions:
*
* <pre class="stHighlighted">
* <span class="stReserved">import</span> org.scalatest.Assertions._
* <span class="stReserved">val</span> left = <span class="stLiteral">2</span>
* <span class="stReserved">val</span> right = <span class="stLiteral">1</span>
* assert(left == right)
* </pre>
*
* <p>
* The detail message in the thrown <code>TestFailedException</code> from this <code>assert</code>
* will be: "2 did not equal 1".
* </p>
*
* <p>
* ScalaTest's <code>assert</code> macro works by recognizing patterns in the AST of the expression passed to <code>assert</code> and,
* for a finite set of common expressions, giving an error message that an equivalent ScalaTest matcher
* expression would give. Here are some examples, where <code>a</code> is 1, <code>b</code> is 2, <code>c</code> is 3, <code>d</code>
* is 4, <code>xs</code> is <code>List(a, b, c)</code>, and <code>num</code> is 1.0:
* </p>
*
* <pre class="stHighlighted">
* assert(a == b || c >= d)
* <span class="stLineComment">// Error message: 1 did not equal 2, and 3 was not greater than or equal to 4</span>
* <br/>assert(xs.exists(_ == <span class="stLiteral">4</span>))
* <span class="stLineComment">// Error message: List(1, 2, 3) did not contain 4</span>
* <br/>assert(<span class="stQuotedString">"hello"</span>.startsWith(<span class="stQuotedString">"h"</span>) && <span class="stQuotedString">"goodbye"</span>.endsWith(<span class="stQuotedString">"y"</span>))
* <span class="stLineComment">// Error message: "hello" started with "h", but "goodbye" did not end with "y"</span>
* <br/>assert(num.isInstanceOf[<span class="stType">Int</span>])
* <span class="stLineComment">// Error message: 1.0 was not instance of scala.Int</span>
* <br/>assert(<span class="stType">Some</span>(<span class="stLiteral">2</span>).isEmpty)
* <span class="stLineComment">// Error message: Some(2) was not empty</span>
* </pre>
*
* <p>
* For expressions that are not recognized, the macro currently prints out a string
* representation of the (desugared) AST and adds <code>"was false"</code>. Here are some examples of
* error messages for unrecognized expressions:
* </p>
*
* <pre class="stHighlighted">
* assert(None.isDefined)
* <span class="stLineComment">// Error message: scala.None.isDefined was false</span>
* <br/>assert(xs.exists(i => i > <span class="stLiteral">10</span>))
* <span class="stLineComment">// Error message: xs.exists(((i: Int) => i.>(10))) was false</span>
* </pre>
*
* <p>
* You can augment the standard error message by providing a <code>String</code> as a second argument
* to <code>assert</code>, like this:
* </p>
*
* <pre class="stHighlighted">
* <span class="stReserved">val</span> attempted = <span class="stLiteral">2</span>
* assert(attempted == <span class="stLiteral">1</span>, <span class="stQuotedString">"Execution was attempted "</span> + left + <span class="stQuotedString">" times instead of 1 time"</span>)
* </pre>
*
* <p>
* Using this form of <code>assert</code>, the failure report will be more specific to your problem domain, thereby
* helping you debug the problem. This <code>Assertions</code> trait also mixes in the
* <a href="../scalactic/TripleEquals.html"><code>TripleEquals</code></a>, which gives you a <code>===</code> operator
* that allows you to customize <a href="../scalactic/Equality.html"><code>Equality</code></a>, perform equality checks with numeric
* <a href="../scalactic/Tolerance.html"><code>Tolerance</code></a>, and enforce type constraints at compile time with
* sibling traits <a href="TypeCheckedTripleEquals.html"><code>TypeCheckedTripleEquals</code></a> and
* <a href="ConversionCheckedTripleEquals.html"><code>ConversionCheckedTripleEquals</code></a>.
* </p>
*
* <a name="expectedResults"></a>
* <h2>Expected results</h2>
*
* Although the <code>assert</code> macro provides a natural, readable extension to Scala's <code>assert</code> mechanism that
* provides good error messages, as the operands become lengthy, the code becomes less readable. In addition, the error messages
* generated for <code>==</code> and <code>===</code> comparisons
* don't distinguish between actual and expected values. The operands are just called <code>left</code> and <code>right</code>,
* because if one were named <code>expected</code> and the other <code>actual</code>, it would be difficult for people to
* remember which was which. To help with these limitations of assertions, <code>Suite</code> includes a method called <code>assertResult</code> that
* can be used as an alternative to <code>assert</code>. To use <code>assertResult</code>, you place
* the expected value in parentheses after <code>assertResult</code>, followed by curly braces containing code
* that should result in the expected value. For example:
*
* <pre class="stHighlighted">
* <span class="stReserved">val</span> a = <span class="stLiteral">5</span>
* <span class="stReserved">val</span> b = <span class="stLiteral">2</span>
* assertResult(<span class="stLiteral">2</span>) {
* a - b
* }
* </pre>
*
* <p>
* In this case, the expected value is <code>2</code>, and the code being tested is <code>a - b</code>. This assertion will fail, and
* the detail message in the <code>TestFailedException</code> will read, "Expected 2, but got 3."
* </p>
*
* <a name="forcingFailures"></a>
* <h2>Forcing failures</h2>
*
* <p>
* If you just need the test to fail, you can write:
* </p>
*
* <pre class="stHighlighted">
* fail()
* </pre>
*
* <p>
* Or, if you want the test to fail with a message, write:
* </p>
*
* <pre class="stHighlighted">
* fail(<span class="stQuotedString">"I've got a bad feeling about this"</span>)
* </pre>
*
* <a name="achievingSuccess"></a>
* <h2>Achieving success</h2>
*
* <p>
* In async style tests, you must end your test body with either <code>Future[Assertion]</code> or
* <code>Assertion</code>. ScalaTest's assertions (including matcher expressions) have result type
* <code>Assertion</code>, so ending with an assertion will satisfy the compiler.
* If a test body or function body passed to <code>Future.map</code> does
* <em>not</em> end with type <code>Assertion</code>, however, you can fix the type error by placing
* <code>succeed</code> at the end of the
* test or function body:
* </p>
*
* <pre class="stHighlighted">
* succeed <span class="stLineComment">// Has type Assertion</span>
* </pre>
*
* <a name="interceptedExceptions"></a>
* <a name="expectedExceptions"></a>
* <h2>Expected exceptions</h2>
*
* <p>
* Sometimes you need to test whether a method throws an expected exception under certain circumstances, such
* as when invalid arguments are passed to the method. You can do this in the JUnit 3 style, like this:
* </p>
*
* <pre class="stHighlighted">
* <span class="stReserved">val</span> s = <span class="stQuotedString">"hi"</span>
* <span class="stReserved">try</span> {
* s.charAt(-<span class="stLiteral">1</span>)
* fail()
* }
* <span class="stReserved">catch</span> {
* <span class="stReserved">case</span> _: <span class="stType">IndexOutOfBoundsException</span> => <span class="stLineComment">// Expected, so continue</span>
* }
* </pre>
*
* <p>
* If <code>charAt</code> throws <code>IndexOutOfBoundsException</code> as expected, control will transfer
* to the catch case, which does nothing. If, however, <code>charAt</code> fails to throw an exception,
* the next statement, <code>fail()</code>, will be run. The <code>fail</code> method always completes abruptly with
* a <code>TestFailedException</code>, thereby signaling a failed test.
* </p>
*
* <p>
* To make this common use case easier to express and read, ScalaTest provides two methods:
* <code>assertThrows</code> and <code>intercept</code>.
* Here's how you use <code>assertThrows</code>:
* </p>
*
* <a name="assertThrowsMethod"></a>
* <pre class="stHighlighted">
* <span class="stReserved">val</span> s = <span class="stQuotedString">"hi"</span>
* assertThrows[<span class="stType">IndexOutOfBoundsException</span>] { <span class="stLineComment">// Result type: Assertion</span>
* s.charAt(-<span class="stLiteral">1</span>)
* }
* </pre>
*
* <p>
* This code behaves much like the previous example. If <code>charAt</code> throws an instance of <code>IndexOutOfBoundsException</code>,
* <code>assertThrows</code> will return <code>Succeeded</code>. But if <code>charAt</code> completes normally, or throws a different
* exception, <code>assertThrows</code> will complete abruptly with a <code>TestFailedException</code>.
* </p>
*
* <p>
* The <code>intercept</code> method behaves the same as <code>assertThrows</code>, except that instead of returning <code>Succeeded</code>,
* <code>intercept</code> returns the caught exception so that you can inspect it further if you wish. For example, you may need
* to ensure that data contained inside the exception have expected values. Here's an example:
* </p>
*
* <a name="interceptMethod"></a>
* <pre class="stHighlighted">
* <span class="stReserved">val</span> s = <span class="stQuotedString">"hi"</span>
* <span class="stReserved">val</span> caught =
* intercept[<span class="stType">IndexOutOfBoundsException</span>] { <span class="stLineComment">// Result type: IndexOutOfBoundsException</span>
* s.charAt(-<span class="stLiteral">1</span>)
* }
* assert(caught.getMessage.indexOf(<span class="stQuotedString">"-1"</span>) != -<span class="stLiteral">1</span>)
* </pre>
*
* <a name="checkingThatCodeDoesNotCompile"></a>
* <h2>Checking that a snippet of code does or does not compile</h2>
*
* <p>
* Often when creating libraries you may wish to ensure that certain arrangements of code that
* represent potential “user errors” do not compile, so that your library is more error resistant.
* ScalaTest's <code>Assertions</code> trait includes the following syntax for that purpose:
* </p>
*
* <pre class="stHighlighted">
* assertDoesNotCompile(<span class="stQuotedString">"val a: String = 1"</span>)
* </pre>
*
* <p>
* If you want to ensure that a snippet of code does not compile because of a type error (as opposed
* to a syntax error), use:
* </p>
*
* <pre class="stHighlighted">
* assertTypeError(<span class="stQuotedString">"val a: String = 1"</span>)
* </pre>
*
* <p>
* Note that the <code>assertTypeError</code> call will only succeed if the given snippet of code does not
* compile because of a type error. A syntax error will still result on a thrown <code>TestFailedException</code>.
* </p>
*
* <p>
* If you want to state that a snippet of code <em>does</em> compile, you can make that
* more obvious with:
* </p>
*
* <pre class="stHighlighted">
* assertCompiles(<span class="stQuotedString">"val a: Int = 1"</span>)
* </pre>
*
* <p>
* Although the previous three constructs are implemented with macros that determine at compile time whether
* the snippet of code represented by the string does or does not compile, errors
* are reported as test failures at runtime.
* </p>
*
* <a name="assumptions"></a>
* <h2>Assumptions</h2>
*
* <p>
* Trait <code>Assertions</code> also provides methods that allow you to <em>cancel</em> a test.
* You would cancel a test if a resource required by the test was unavailable. For example, if a test
* requires an external database to be online, and it isn't, the test could be canceled to indicate
* it was unable to run because of the missing database. Such a test <em>assumes</em> a database is
* available, and you can use the <code>assume</code> method to indicate this at the beginning of
* the test, like this:
* </p>
*
* <pre class="stHighlighted">
* assume(database.isAvailable)
* </pre>
*
* <p>
* For each overloaded <code>assert</code> method, trait <code>Assertions</code> provides an
* overloaded <code>assume</code> method with an identical signature and behavior, except the
* <code>assume</code> methods throw <a href="exceptions/TestCanceledException.html"><code>TestCanceledException</code></a> whereas the
* <code>assert</code> methods throw <code>TestFailedException</code>. As with <code>assert</code>,
* <code>assume</code> hides a Scala method in <code>Predef</code> that performs a similar
* function, but throws <code>AssertionError</code>. And just as you can with <code>assert</code>,
* you will get an error message extracted by a macro from the AST passed to <code>assume</code>, and can
* optionally provide a clue string to augment this error message. Here are some examples:
* </p>
*
* <pre class="stHighlighted">
* assume(database.isAvailable, <span class="stQuotedString">"The database was down again"</span>)
* assume(database.getAllUsers.count === <span class="stLiteral">9</span>)
* </pre>
*
* <a name="forcingCancelations"></a>
* <h2>Forcing cancelations</h2>
*
* <p>
* For each overloaded <code>fail</code> method, there's a corresponding <code>cancel</code> method
* with an identical signature and behavior, except the <code>cancel</code> methods throw
* <code>TestCanceledException</code> whereas the <code>fail</code> methods throw
* <code>TestFailedException</code>. Thus if you just need to cancel a test, you can write:
* </p>
*
* <pre class="stHighlighted">
* cancel()
* </pre>
*
* <p>
* If you want to cancel the test with a message, just place the message in the parentheses:
* </p>
*
* <pre class="stHighlighted">
* cancel(<span class="stQuotedString">"Can't run the test because no internet connection was found"</span>)
* </pre>
*
* <a name="gettingAClue"></a>
* <h2>Getting a clue</h2>
*
* <p>
* If you want more information that is provided by default by the methods if this trait,
* you can supply a "clue" string in one of several ways.
* The extra information (or "clues") you provide will
* be included in the detail message of the thrown exception. Both
* <code>assert</code> and <code>assertResult</code> provide a way for a clue to be
* included directly, <code>intercept</code> does not.
* Here's an example of clues provided directly in <code>assert</code>:
* </p>
*
* <pre class="stHighlighted">
* assert(<span class="stLiteral">1</span> + <span class="stLiteral">1</span> === <span class="stLiteral">3</span>, <span class="stQuotedString">"this is a clue"</span>)
* </pre>
*
* <p>
* and in <code>assertResult</code>:
* </p>
*
* <pre class="stHighlighted">
* assertResult(<span class="stLiteral">3</span>, <span class="stQuotedString">"this is a clue"</span>) { <span class="stLiteral">1</span> + <span class="stLiteral">1</span> }
* </pre>
*
* <p>
* The exceptions thrown by the previous two statements will include the clue
* string, <code>"this is a clue"</code>, in the exception's detail message.
* To get the same clue in the detail message of an exception thrown
* by a failed <code>intercept</code> call requires using <code>withClue</code>:
* </p>
*
* <pre class="stHighlighted">
* withClue(<span class="stQuotedString">"this is a clue"</span>) {
* intercept[<span class="stType">IndexOutOfBoundsException</span>] {
* <span class="stQuotedString">"hi"</span>.charAt(-<span class="stLiteral">1</span>)
* }
* }
* </pre>
*
* <p>
* The <code>withClue</code> method will only prepend the clue string to the detail
* message of exception types that mix in the <code>ModifiableMessage</code> trait.
* See the documentation for <a href="ModifiableMessage.html"><code>ModifiableMessage</code></a> for more information.
* If you wish to place a clue string after a block of code, see the documentation for
* <a href="AppendedClues.html"><code>AppendedClues</code></a>.
* </p>
*
* <p>
* <em>Note: ScalaTest's <code>assertTypeError</code> construct is in part inspired by the <code>illTyped</code> macro
* of <a href="https://github.com/milessabin/shapeless" target="_blank">shapeless</a>.</em>
* </p>
*
* @author Bill Venners
*/
trait Assertions extends TripleEquals {
//implicit val prettifier = Prettifier.default
import language.experimental.macros
/**
* Assert that a boolean condition is true.
* If the condition is <code>true</code>, this method returns normally.
* Else, it throws <code>TestFailedException</code>.
*
* <p>
* This method is implemented in terms of a Scala macro that will generate a more helpful error message
* for expressions of this form:
* </p>
*
* <ul>
* <li>assert(a == b)</li>
* <li>assert(a != b)</li>
* <li>assert(a === b)</li>
* <li>assert(a !== b)</li>
* <li>assert(a > b)</li>
* <li>assert(a >= b)</li>
* <li>assert(a < b)</li>
* <li>assert(a <= b)</li>
* <li>assert(a startsWith "prefix")</li>
* <li>assert(a endsWith "postfix")</li>
* <li>assert(a contains "something")</li>
* <li>assert(a eq b)</li>
* <li>assert(a ne b)</li>
* <li>assert(a > 0 && b > 5)</li>
* <li>assert(a > 0 || b > 5)</li>
* <li>assert(a.isEmpty)</li>
* <li>assert(!a.isEmpty)</li>
* <li>assert(a.isInstanceOf[String])</li>
* <li>assert(a.length == 8)</li>
* <li>assert(a.size == 8)</li>
* <li>assert(a.exists(_ == 8))</li>
* </ul>
*
* <p>
* At this time, any other form of expression will get a <code>TestFailedException</code> with message saying the given
* expression was false. In the future, we will enhance this macro to give helpful error messages in more situations.
* In ScalaTest 2.0, however, this behavior was sufficient to allow the <code>===</code> that returns <code>Boolean</code>
* to be the default in tests. This makes <code>===</code> consistent between tests and production
* code.
* </p>
*
* @param condition the boolean condition to assert
* @throws TestFailedException if the condition is <code>false</code>.
*/
def assert(condition: Boolean)(implicit prettifier: Prettifier, pos: source.Position): Assertion = macro AssertionsMacro.assert
private[scalatest] def newAssertionFailedException(optionalMessage: Option[String], optionalCause: Option[Throwable], pos: source.Position, analysis: scala.collection.immutable.IndexedSeq[String]): Throwable =
new org.scalatest.exceptions.TestFailedException(toExceptionFunction(optionalMessage), optionalCause, Left(pos), None, analysis)
private[scalatest] def newTestCanceledException(optionalMessage: Option[String], optionalCause: Option[Throwable], pos: source.Position): Throwable =
new TestCanceledException(toExceptionFunction(optionalMessage), optionalCause, pos, None)
/**
* Assert that a boolean condition, described in <code>String</code>
* <code>message</code>, is true.
* If the condition is <code>true</code>, this method returns normally.
* Else, it throws <code>TestFailedException</code> with a helpful error message
* appended with the <code>String</code> obtained by invoking <code>toString</code> on the
* specified <code>clue</code> as the exception's detail message.
*
* <p>
* This method is implemented in terms of a Scala macro that will generate a more helpful error message
* for expressions of this form:
* </p>
*
* <ul>
* <li>assert(a == b, "a good clue")</li>
* <li>assert(a != b, "a good clue")</li>
* <li>assert(a === b, "a good clue")</li>
* <li>assert(a !== b, "a good clue")</li>
* <li>assert(a > b, "a good clue")</li>
* <li>assert(a >= b, "a good clue")</li>
* <li>assert(a < b, "a good clue")</li>
* <li>assert(a <= b, "a good clue")</li>
* <li>assert(a startsWith "prefix", "a good clue")</li>
* <li>assert(a endsWith "postfix", "a good clue")</li>
* <li>assert(a contains "something", "a good clue")</li>
* <li>assert(a eq b, "a good clue")</li>
* <li>assert(a ne b, "a good clue")</li>
* <li>assert(a > 0 && b > 5, "a good clue")</li>
* <li>assert(a > 0 || b > 5, "a good clue")</li>
* <li>assert(a.isEmpty, "a good clue")</li>
* <li>assert(!a.isEmpty, "a good clue")</li>
* <li>assert(a.isInstanceOf[String], "a good clue")</li>
* <li>assert(a.length == 8, "a good clue")</li>
* <li>assert(a.size == 8, "a good clue")</li>
* <li>assert(a.exists(_ == 8), "a good clue")</li>
* </ul>
*
* <p>
* At this time, any other form of expression will just get a <code>TestFailedException</code> with message saying the given
* expression was false. In the future, we will enhance this macro to give helpful error messages in more situations.
* In ScalaTest 2.0, however, this behavior was sufficient to allow the <code>===</code> that returns <code>Boolean</code>
* to be the default in tests. This makes <code>===</code> consistent between tests and production
* code.
* </p>
*
* @param condition the boolean condition to assert
* @param clue An objects whose <code>toString</code> method returns a message to include in a failure report.
* @throws TestFailedException if the condition is <code>false</code>.
* @throws NullArgumentException if <code>message</code> is <code>null</code>.
*/
def assert(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: source.Position): Assertion = macro AssertionsMacro.assertWithClue
/**
* Assume that a boolean condition is true.
* If the condition is <code>true</code>, this method returns normally.
* Else, it throws <code>TestCanceledException</code>.
*
* <p>
* This method is implemented in terms of a Scala macro that will generate a more helpful error message
* for expressions of this form:
* </p>
*
* <ul>
* <li>assume(a == b)</li>
* <li>assume(a != b)</li>
* <li>assume(a === b)</li>
* <li>assume(a !== b)</li>
* <li>assume(a > b)</li>
* <li>assume(a >= b)</li>
* <li>assume(a < b)</li>
* <li>assume(a <= b)</li>
* <li>assume(a startsWith "prefix")</li>
* <li>assume(a endsWith "postfix")</li>
* <li>assume(a contains "something")</li>
* <li>assume(a eq b)</li>
* <li>assume(a ne b)</li>
* <li>assume(a > 0 && b > 5)</li>
* <li>assume(a > 0 || b > 5)</li>
* <li>assume(a.isEmpty)</li>
* <li>assume(!a.isEmpty)</li>
* <li>assume(a.isInstanceOf[String])</li>
* <li>assume(a.length == 8)</li>
* <li>assume(a.size == 8)</li>
* <li>assume(a.exists(_ == 8))</li>
* </ul>
*
* <p>
* At this time, any other form of expression will just get a <code>TestCanceledException</code> with message saying the given
* expression was false. In the future, we will enhance this macro to give helpful error messages in more situations.
* In ScalaTest 2.0, however, this behavior was sufficient to allow the <code>===</code> that returns <code>Boolean</code>
* to be the default in tests. This makes <code>===</code> consistent between tests and production
* code.
* </p>
*
* @param condition the boolean condition to assume
* @throws TestCanceledException if the condition is <code>false</code>.
*/
def assume(condition: Boolean)(implicit prettifier: Prettifier, pos: source.Position): Assertion = macro AssertionsMacro.assume
/**
* Assume that a boolean condition, described in <code>String</code>
* <code>message</code>, is true.
* If the condition is <code>true</code>, this method returns normally.
* Else, it throws <code>TestCanceledException</code> with a helpful error message
* appended with <code>String</code> obtained by invoking <code>toString</code> on the
* specified <code>clue</code> as the exception's detail message.
*
* <p>
* This method is implemented in terms of a Scala macro that will generate a more helpful error message
* for expressions of this form:
* </p>
*
* <ul>
* <li>assume(a == b, "a good clue")</li>
* <li>assume(a != b, "a good clue")</li>
* <li>assume(a === b, "a good clue")</li>
* <li>assume(a !== b, "a good clue")</li>
* <li>assume(a > b, "a good clue")</li>
* <li>assume(a >= b, "a good clue")</li>
* <li>assume(a < b, "a good clue")</li>
* <li>assume(a <= b, "a good clue")</li>
* <li>assume(a startsWith "prefix", "a good clue")</li>
* <li>assume(a endsWith "postfix", "a good clue")</li>
* <li>assume(a contains "something", "a good clue")</li>
* <li>assume(a eq b, "a good clue")</li>
* <li>assume(a ne b, "a good clue")</li>
* <li>assume(a > 0 && b > 5, "a good clue")</li>
* <li>assume(a > 0 || b > 5, "a good clue")</li>
* <li>assume(a.isEmpty, "a good clue")</li>
* <li>assume(!a.isEmpty, "a good clue")</li>
* <li>assume(a.isInstanceOf[String], "a good clue")</li>
* <li>assume(a.length == 8, "a good clue")</li>
* <li>assume(a.size == 8, "a good clue")</li>
* <li>assume(a.exists(_ == 8), "a good clue")</li>
* </ul>
*
* <p>
* At this time, any other form of expression will just get a <code>TestCanceledException</code> with message saying the given
* expression was false. In the future, we will enhance this macro to give helpful error messages in more situations.
* In ScalaTest 2.0, however, this behavior was sufficient to allow the <code>===</code> that returns <code>Boolean</code>
* to be the default in tests. This makes <code>===</code> consistent between tests and production
* code.
* </p>
*
* @param condition the boolean condition to assume
* @param clue An objects whose <code>toString</code> method returns a message to include in a failure report.
* @throws TestCanceledException if the condition is <code>false</code>.
* @throws NullArgumentException if <code>message</code> is <code>null</code>.
*/
def assume(condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: source.Position): Assertion = macro AssertionsMacro.assumeWithClue
/**
* Asserts that a given string snippet of code does not pass the Scala type checker, failing if the given
* snippet does not pass the Scala parser.
*
* <p>
* Often when creating libraries you may wish to ensure that certain arrangements of code that
* represent potential “user errors” do not compile, so that your library is more error resistant.
* ScalaTest's <code>Assertions</code> trait includes the following syntax for that purpose:
* </p>
*
* <pre class="stHighlighted">
* assertTypeError(<span class="stQuotedString">"val a: String = 1"</span>)
* </pre>
*
* <p>
* Although <code>assertTypeError</code> is implemented with a macro that determines at compile time whether
* the snippet of code represented by the passed string type checks, errors (<em>i.e.</em>,
* snippets of code that <em>do</em> type check) are reported as test failures at runtime.
* </p>
*
* <p>
* Note that the difference between <code>assertTypeError</code> and <code>assertDoesNotCompile</code> is
* that <code>assertDoesNotCompile</code> will succeed if the given code does not compile for any reason,
* whereas <code>assertTypeError</code> will only succeed if the given code does not compile because of
* a type error. If the given code does not compile because of a syntax error, for example, <code>assertDoesNotCompile</code>
* will return normally but <code>assertTypeError</code> will throw a <code>TestFailedException</code>.
* </p>
*
* @param code the snippet of code that should not type check
*/
def assertTypeError(code: String)(implicit pos: source.Position): Assertion = macro CompileMacro.assertTypeErrorImpl
/**
* Asserts that a given string snippet of code does not pass either the Scala parser or type checker.
*
* <p>
* Often when creating libraries you may wish to ensure that certain arrangements of code that
* represent potential “user errors” do not compile, so that your library is more error resistant.
* ScalaTest's <code>Assertions</code> trait includes the following syntax for that purpose:
* </p>
*
* <pre class="stHighlighted">
* assertDoesNotCompile(<span class="stQuotedString">"val a: String = \"a string"</span>)
* </pre>
*
* <p>
* Although <code>assertDoesNotCompile</code> is implemented with a macro that determines at compile time whether
* the snippet of code represented by the passed string doesn't compile, errors (<em>i.e.</em>,
* snippets of code that <em>do</em> compile) are reported as test failures at runtime.
* </p>
*
* <p>
* Note that the difference between <code>assertTypeError</code> and <code>assertDoesNotCompile</code> is
* that <code>assertDoesNotCompile</code> will succeed if the given code does not compile for any reason,
* whereas <code>assertTypeError</code> will only succeed if the given code does not compile because of
* a type error. If the given code does not compile because of a syntax error, for example, <code>assertDoesNotCompile</code>
* will return normally but <code>assertTypeError</code> will throw a <code>TestFailedException</code>.
* </p>
*
* @param code the snippet of code that should not type check
*/
def assertDoesNotCompile(code: String)(implicit pos: source.Position): Assertion = macro CompileMacro.assertDoesNotCompileImpl
/**
* Asserts that a given string snippet of code passes both the Scala parser and type checker.
*
* <p>
* You can use this to make sure a snippet of code compiles:
* </p>
*
* <pre class="stHighlighted">
* assertCompiles(<span class="stQuotedString">"val a: Int = 1"</span>)
* </pre>
*
* <p>
* Although <code>assertCompiles</code> is implemented with a macro that determines at compile time whether
* the snippet of code represented by the passed string compiles, errors (<em>i.e.</em>,
* snippets of code that <em>do not</em> compile) are reported as test failures at runtime.
* </p>
*
* @param code the snippet of code that should compile
*/
def assertCompiles(code: String)(implicit pos: source.Position): Assertion = macro CompileMacro.assertCompilesImpl
/**
* Intercept and return an exception that's expected to
* be thrown by the passed function value. The thrown exception must be an instance of the
* type specified by the type parameter of this method. This method invokes the passed
* function. If the function throws an exception that's an instance of the specified type,
* this method returns that exception. Else, whether the passed function returns normally
* or completes abruptly with a different exception, this method throws <code>TestFailedException</code>.
*
* <p>
* Note that the type specified as this method's type parameter may represent any subtype of
* <code>AnyRef</code>, not just <code>Throwable</code> or one of its subclasses. In
* Scala, exceptions can be caught based on traits they implement, so it may at times make sense
* to specify a trait that the intercepted exception's class must mix in. If a class instance is
* passed for a type that could not possibly be used to catch an exception (such as <code>String</code>,
* for example), this method will complete abruptly with a <code>TestFailedException</code>.
* </p>
*
* <p>
* Also note that the difference between this method and <code>assertThrows</code> is that this method
* returns the expected exception, so it lets you perform further assertions on
* that exception. By contrast, the <code>assertThrows</code> method returns <code>Succeeded</code>, which means it can
* serve as the last statement in an async- or safe-style suite. <code>assertThrows</code> also indicates to the reader
* of the code that nothing further is expected about the thrown exception other than its type.
* The recommended usage is to use <code>assertThrows</code> by default, <code>intercept</code> only when you
* need to inspect the caught exception further.
* </p>
*
* @param f the function value that should throw the expected exception
* @param classTag an implicit <code>ClassTag</code> representing the type of the specified
* type parameter.
* @return the intercepted exception, if it is of the expected type
* @throws TestFailedException if the passed function does not complete abruptly with an exception
* that's an instance of the specified type.
*/
def intercept[T <: AnyRef](f: => Any)(implicit classTag: ClassTag[T], pos: source.Position): T = {
val clazz = classTag.runtimeClass
val caught = try {
f
None
}
catch {
case u: Throwable => {
if (!clazz.isAssignableFrom(u.getClass)) {
val s = Resources.wrongException(clazz.getName, u.getClass.getName)
throw newAssertionFailedException(Some(s), Some(u), pos, Vector.empty)
}
else {
Some(u)
}
}
}
caught match {
case None =>
val message = Resources.exceptionExpected(clazz.getName)
throw newAssertionFailedException(Some(message), None, pos, Vector.empty)
case Some(e) => e.asInstanceOf[T] // I know this cast will succeed, becuase isAssignableFrom succeeded above
}
}
/**
* Ensure that an expected exception is thrown by the passed function value. The thrown exception must be an instance of the
* type specified by the type parameter of this method. This method invokes the passed
* function. If the function throws an exception that's an instance of the specified type,
* this method returns <code>Succeeded</code>. Else, whether the passed function returns normally
* or completes abruptly with a different exception, this method throws <code>TestFailedException</code>.
*
* <p>
* Note that the type specified as this method's type parameter may represent any subtype of
* <code>AnyRef</code>, not just <code>Throwable</code> or one of its subclasses. In
* Scala, exceptions can be caught based on traits they implement, so it may at times make sense
* to specify a trait that the intercepted exception's class must mix in. If a class instance is
* passed for a type that could not possibly be used to catch an exception (such as <code>String</code>,
* for example), this method will complete abruptly with a <code>TestFailedException</code>.
* </p>
*
* <p>
* Also note that the difference between this method and <code>intercept</code> is that this method
* does not return the expected exception, so it does not let you perform further assertions on
* that exception. Instead, this method returns <code>Succeeded</code>, which means it can
* serve as the last statement in an async- or safe-style suite. It also indicates to the reader
* of the code that nothing further is expected about the thrown exception other than its type.
* The recommended usage is to use <code>assertThrows</code> by default, <code>intercept</code> only when you
* need to inspect the caught exception further.
* </p>
*
* @param f the function value that should throw the expected exception
* @param classTag an implicit <code>ClassTag</code> representing the type of the specified
* type parameter.
* @return the <code>Succeeded</code> singleton, if an exception of the expected type is thrown
* @throws TestFailedException if the passed function does not complete abruptly with an exception
* that's an instance of the specified type.
*/
def assertThrows[T <: AnyRef](f: => Any)(implicit classTag: ClassTag[T], pos: source.Position): Assertion = {
val clazz = classTag.runtimeClass
val threwExpectedException =
try {
f
false
}
catch {
case u: Throwable => {
if (!clazz.isAssignableFrom(u.getClass)) {
val s = Resources.wrongException(clazz.getName, u.getClass.getName)
throw newAssertionFailedException(Some(s), Some(u), pos, Vector.empty)
}
else true
}
}
if (threwExpectedException) {
Succeeded
}
else {
val message = Resources.exceptionExpected(clazz.getName)
throw newAssertionFailedException(Some(message), None, pos, Vector.empty)
}
}
/**
* Assert that the value passed as <code>expected</code> equals the value passed as <code>actual</code>.
* If the <code>actual</code> equals the <code>expected</code>
* (as determined by <code>==</code>), <code>assertResult</code> returns
* normally. Else, if <code>actual</code> is not equal to <code>expected</code>, <code>assertResult</code> throws a
* <code>TestFailedException</code> whose detail message includes the expected and actual values, as well as the <code>String</code>
* obtained by invoking <code>toString</code> on the passed <code>clue</code>.
*
* @param expected the expected value
* @param clue An object whose <code>toString</code> method returns a message to include in a failure report.
* @param actual the actual value, which should equal the passed <code>expected</code> value
* @throws TestFailedException if the passed <code>actual</code> value does not equal the passed <code>expected</code> value.
*/
def assertResult(expected: Any, clue: Any)(actual: Any)(implicit prettifier: Prettifier, pos: source.Position): Assertion = {
if (!areEqualComparingArraysStructurally(actual, expected)) {
val (act, exp) = Suite.getObjectsForFailureMessage(actual, expected)
val s = FailureMessages.expectedButGot(prettifier, exp, act)
val fullMsg = AppendedClues.appendClue(s, clue.toString)
throw newAssertionFailedException(Some(fullMsg), None, pos, Vector.empty)
}
Succeeded
}
/**
* Assert that the value passed as <code>expected</code> equals the value passed as <code>actual</code>.
* If the <code>actual</code> value equals the <code>expected</code> value
* (as determined by <code>==</code>), <code>assertResult</code> returns
* normally. Else, <code>assertResult</code> throws a
* <code>TestFailedException</code> whose detail message includes the expected and actual values.
*
* @param expected the expected value
* @param actual the actual value, which should equal the passed <code>expected</code> value
* @throws TestFailedException if the passed <code>actual</code> value does not equal the passed <code>expected</code> value.
*/
def assertResult(expected: Any)(actual: Any)(implicit prettifier: Prettifier, pos: source.Position): Assertion = {
if (!areEqualComparingArraysStructurally(actual, expected)) {
val (act, exp) = Suite.getObjectsForFailureMessage(actual, expected)
val s = FailureMessages.expectedButGot(prettifier, exp, act)
throw newAssertionFailedException(Some(s), None, pos, Vector.empty)
}
Succeeded
}
/*
* TODO: Delete this if sticking with Nothing instead of Unit as result type of fail.
* <p>
* The result type of this and the other overloaded <code>fail</code> methods is
* <code>Unit</code> instead of <code>Nothing</code>, because <code>Nothing</code>
* is a subtype of all other types. If the result type of <code>fail</code> were
* <code>Nothing</code>, a block of code that ends in a call to <code>fail()</code> may
* fail to compile if the block being passed as a by-name parameter or function to an
* overloaded method. The reason is that the compiler selects which overloaded
* method to call based on the static types of the parameters passed. Since
* <code>Nothing</code> is an instance of everything, it can often make the overloaded
* method selection ambiguous.
* </p>
*
* <p>
* For a concrete example, the <code>Conductor</code> class
* in package <code>org.scalatest.concurrent</code> has two overloaded variants of the
* <code>thread</code> method:
* </p>
*
* <pre class="stHighlighted">
* <span class="stReserved">def</span> thread[T](fun: => T): <span class="stType">Thread</span>
* <br/><span class="stReserved">def</span> thread[T](name: <span class="stType">String</span>)(fun: => T): <span class="stType">Thread</span>
* </pre>
*
* <p>
* Given these two overloaded methods, the following code will compile given the result type
* of <code>fail</code> is <code>Unit</code>, but would not compile if the result type were
* <code>Nothing</code>:
* </p>
*
* <pre class="stHighlighted">
* thread { fail() }
* </pre>
*
* <p>
* If the result type of <code>fail</code> were <code>Nothing</code>, the type of the by-name parameter
* would be inferred to be <code>Nothing</code>, which is a subtype of both <code>T</code> and
* <code>String</code>. Thus the call is ambiguous, because the type matches the first parameter type
* of both overloaded <code>thread</code> methods. <code>Unit</code>, by constrast, is <em>not</em>
* a subtype of <code>String</code>, so it only matches one overloaded variant and compiles just fine.
* </p>
*/
/**
* Throws <code>TestFailedException</code> to indicate a test failed.
*/
def fail()(implicit pos: source.Position): Nothing = { throw newAssertionFailedException(None, None, pos, Vector.empty) }
/**
* Throws <code>TestFailedException</code>, with the passed
* <code>String</code> <code>message</code> as the exception's detail
* message, to indicate a test failed.
*
* @param message A message describing the failure.
* @throws NullArgumentException if <code>message</code> is <code>null</code>
*/
def fail(message: String)(implicit pos: source.Position): Nothing = {
requireNonNull(message)
throw newAssertionFailedException(Some(message), None, pos, Vector.empty)
}
/**
* Throws <code>TestFailedException</code>, with the passed
* <code>String</code> <code>message</code> as the exception's detail
* message and <code>Throwable</code> cause, to indicate a test failed.
*
* @param message A message describing the failure.
* @param cause A <code>Throwable</code> that indicates the cause of the failure.
* @throws NullArgumentException if <code>message</code> or <code>cause</code> is <code>null</code>
*/
def fail(message: String, cause: Throwable)(implicit pos: source.Position): Nothing = {
requireNonNull(message, cause)
throw newAssertionFailedException(Some(message), Some(cause), pos, Vector.empty)
}
/**
* Throws <code>TestFailedException</code>, with the passed
* <code>Throwable</code> cause, to indicate a test failed.
* The <code>getMessage</code> method of the thrown <code>TestFailedException</code>
* will return <code>cause.toString</code>.
*
* @param cause a <code>Throwable</code> that indicates the cause of the failure.
* @throws NullArgumentException if <code>cause</code> is <code>null</code>
*/
def fail(cause: Throwable)(implicit pos: source.Position): Nothing = {
requireNonNull(cause)
throw newAssertionFailedException(None, Some(cause), pos, Vector.empty)
}
/**
* Throws <code>TestCanceledException</code> to indicate a test was canceled.
*/
def cancel()(implicit pos: source.Position): Nothing = { throw newTestCanceledException(None, None, pos) }
/**
* Throws <code>TestCanceledException</code>, with the passed
* <code>String</code> <code>message</code> as the exception's detail
* message, to indicate a test was canceled.
*
* @param message A message describing the cancellation.
* @throws NullArgumentException if <code>message</code> is <code>null</code>
*/
def cancel(message: String)(implicit pos: source.Position): Nothing = {
requireNonNull(message)
throw newTestCanceledException(Some(message), None, pos)
}
/**
* Throws <code>TestCanceledException</code>, with the passed
* <code>String</code> <code>message</code> as the exception's detail
* message and <code>Throwable</code> cause, to indicate a test failed.
*
* @param message A message describing the failure.
* @param cause A <code>Throwable</code> that indicates the cause of the failure.
* @throws NullArgumentException if <code>message</code> or <code>cause</code> is <code>null</code>
*/
def cancel(message: String, cause: Throwable)(implicit pos: source.Position): Nothing = {
requireNonNull(message, cause)
throw newTestCanceledException(Some(message), Some(cause), pos)
}
/**
* Throws <code>TestCanceledException</code>, with the passed
* <code>Throwable</code> cause, to indicate a test failed.