/
Diagrams.scala
394 lines (370 loc) · 15.2 KB
/
Diagrams.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
/*
* 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.diagrams
import org.scalactic._
import org.scalactic.Requirements._
import scala.collection.mutable.ListBuffer
import collection.immutable.TreeMap
import org.scalatest.{AnchorValue, Assertions, DiagrammedExpr, DiagrammedAssertionsMacro, Succeeded}
import org.scalatest.compatible.Assertion
/**
* Sub-trait of <code>Assertions</code> that override <code>assert</code> and <code>assume</code> methods to include
* a diagram showing the values of expression in the error message when the assertion or assumption fails.
*
* Here are some examples:
*
* <pre class="stREPL">
* scala> import DiagrammedAssertions._
* import DiagrammedAssertions._
*
* scala> assert(a == b || c >= d)
* org.scalatest.exceptions.TestFailedException:
*
* assert(a == b || c >= d)
* | | | | | | |
* 1 | 2 | 3 | 4
* | | false
* | false
* false
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* scala> assert(xs.exists(_ == 4))
* org.scalatest.exceptions.TestFailedException:
*
* assert(xs.exists(_ == 4))
* | |
* | false
* List(1, 2, 3)
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* scala> assert("hello".startsWith("h") && "goodbye".endsWith("y"))
* org.scalatest.exceptions.TestFailedException:
*
* assert("hello".startsWith("h") && "goodbye".endsWith("y"))
* | | | | | | |
* "hello" true "h" | "goodbye" false "y"
* false
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* scala> assert(num.isInstanceOf[Int])
* org.scalatest.exceptions.TestFailedException:
*
* assert(num.isInstanceOf[Int])
* | |
* 1.0 false
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* scala> assert(Some(2).isEmpty)
* org.scalatest.exceptions.TestFailedException:
*
* assert(Some(2).isEmpty)
* | | |
* | 2 false
* Some(2)
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* scala> assert(None.isDefined)
* org.scalatest.exceptions.TestFailedException:
*
* assert(None.isDefined)
* | |
* None false
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* scala> assert(xs.exists(i => i > 10))
* org.scalatest.exceptions.TestFailedException:
*
* assert(xs.exists(i => i > 10))
* | |
* | false
* List(1, 2, 3)
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* </pre>
*
* <p>
* If the expression passed to <code>assert</code> or <code>assume</code> spans more than one line, <code>DiagrammedAssertions</code> falls
* back to the default style of error message, since drawing a diagram would be difficult. Here's an example showing how
* <code>DiagrammedAssertions</code> will treat a multi-line assertion (<em>i.e.</em>, you don't get a diagram):
* </p>
*
* <pre class="stREPL">
* scala> assert("hello".startsWith("h") &&
* | "goodbye".endsWith("y"))
* org.scalatest.exceptions.TestFailedException: "hello" started with "h", but "goodbye" did not end with "y"
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
* </pre>
*
* <p>
* Also, since an expression diagram essentially represents multi-line ascii art, if a clue string is provided, it appears <em>above</em> the diagram, not after it. It will often also show up in the diagram:
* </p>
*
* <pre class="stREPL">
* scala> assert(None.isDefined, "Don't do this at home")
* org.scalatest.exceptions.TestFailedException: Don't do this at home
*
* assert(None.isDefined, "Don't do this at home")
* | |
* None false
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
*
* scala> assert(None.isDefined,
* | "Don't do this at home")
* org.scalatest.exceptions.TestFailedException: Don't do this at home
*
* assert(None.isDefined,
* | |
* None false
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* ...
* </pre>
*
* <p>Trait <code>DiagrammedAssertions</code> was inspired by Peter Niederwieser's work in <a href="http://code.google.com/p/spock/">Spock</a> and <a href="https://github.com/pniederw/expecty">Expecty</a>.
*/
trait Diagrams extends Assertions {
import scala.tasty._
import scala.quoted._
/**
* 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 that includes
* a diagram showing expression values.
* </p>
*
* <p>
* If multi-line <code>Boolean</code> is passed in, it will fallback to the macro implementation of <code>Assertions</code>
* that does not contain diagram.
* </p>
*
* @param condition the boolean condition to assert
* @throws TestFailedException if the condition is <code>false</code>.
*/
inline override def assert(inline condition: Boolean)(implicit prettifier: Prettifier, pos: source.Position): Assertion =
${ DiagrammedAssertionsMacro.assert('{condition}, '{prettifier}, '{pos}, '{""}) }
/**
* 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 the
* <code>String</code> obtained by invoking <code>toString</code> on the
* specified <code>clue</code> as the exception's detail message and a
* diagram showing expression values.
*
* <p>
* If multi-line <code>Boolean</code> is passed in, it will fallback to the macro implementation of <code>Assertions</code>
* that does not contain diagram.
* </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>.
*/
inline override def assert(inline condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: source.Position): Assertion =
${ DiagrammedAssertionsMacro.assert('condition, 'prettifier, 'pos, 'clue) }
/**
* 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 that includes
* a diagram showing expression values.
* </p>
*
* <p>
* If multi-line <code>Boolean</code> is passed in, it will fallback to the macro implementation of <code>Assertions</code>
* that does not contain diagram.
* </p>
*
* @param condition the boolean condition to assume
* @throws TestCanceledException if the condition is <code>false</code>.
*/
inline override def assume(inline condition: Boolean)(implicit prettifier: Prettifier, pos: source.Position): Assertion =
${ DiagrammedAssertionsMacro.assume('condition, 'prettifier, 'pos, '{""}) }
/**
* 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 the
* <code>String</code> obtained by invoking <code>toString</code> on the
* specified <code>clue</code> as the exception's detail message and a
* diagram showing expression values.
*
* <p>
* If multi-line <code>Boolean</code> is passed in, it will fallback to the macro implementation of <code>Assertions</code>
* that does not contain diagram.
* </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>.
*/
inline override def assume(inline condition: Boolean, clue: Any)(implicit prettifier: Prettifier, pos: source.Position): Assertion =
${ DiagrammedAssertionsMacro.assume('condition, 'prettifier, 'pos, 'clue) }
}
/**
* Companion object that facilitates the importing of <code>DiagrammedAssertions</code> members as
* an alternative to mixing it in. One use case is to import <code>DiagrammedAssertions</code> members so you can use
* them in the Scala interpreter:
*
* <pre class="stREPL">
* $scala -classpath scalatest.jar
* Welcome to Scala version 2.10.4.final (Java HotSpot(TM) Client VM, Java 1.6.0_45).
* Type in expressions to have them evaluated.
* Type :help for more information.
*
* scala> import org.scalatest.Assertions._
* import org.scalatest.Assertions._
*
* scala> assert(1 === 2)
* org.scalatest.exceptions.TestFailedException:
*
* assert(1 === 2)
* | | |
* 1 | 2
* false
*
* at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:422)
* at org.scalatest.DiagrammedAssertions$.newAssertionFailedException(DiagrammedAssertions.scala:249)
* at org.scalatest.DiagrammedAssertions$DiagrammedAssertionsHelper.macroAssert(DiagrammedAssertions.scala:111)
* at .<init>(<console>:20)
* at .<clinit>(<console>)
* at .<init>(<console>:7)
* at .<clinit>(<console>)
* at $print(<console>)
* at sun.reflect.NativeMethodAccessorImpl.invoke...
* </pre>
*/
object Diagrams extends Diagrams {
/**
* Helper class used by code generated by the overriden <code>assert</code> macro.
*/
class DiagrammedAssertionsHelper {
// this is taken from expecty
private[this] def fits(line: StringBuilder, str: String, anchor: Int): Boolean =
line.slice(anchor, anchor + str.length + 1).forall(_.isWhitespace)
// this is taken from expecty
private[this] def placeString(line: StringBuilder, str: String, anchor: Int): Unit = {
val diff = anchor - line.length
for (i <- 1 to diff) line.append(' ')
if (line.length == anchor)
line.append(str)
else
line.replace(anchor, anchor + str.length(), str)
}
// this is taken from expecty and modified
private[this] def renderValue(value: Any): String = {
value match {
case aEqualizer: org.scalactic.TripleEqualsSupport#Equalizer[_] => Prettifier.default(aEqualizer.leftSide)
case aEqualizer: org.scalactic.TripleEqualsSupport#CheckingEqualizer[_] => Prettifier.default(aEqualizer.leftSide)
case _ => Prettifier.default(value)
}
}
// this is taken from expecty
private[this] def placeValue(lines: ListBuffer[StringBuilder], value: Any, col: Int): Unit = {
val str = renderValue(value)
placeString(lines(0), "|", col)
for (line <- lines.drop(1)) {
if (fits(line, str, col)) {
placeString(line, str, col)
return
}
placeString(line, "|", col)
}
val newLine = new StringBuilder()
placeString(newLine, str, col)
lines.append(newLine)
}
// this is taken from expecty
private[this] def filterAndSortByAnchor(anchorValues: List[AnchorValue]): Traversable[AnchorValue] = {
var map = TreeMap[Int, AnchorValue]()(Ordering.by(-_))
// values stemming from compiler generated code often have the same anchor as regular values
// and get recorded before them; let's filter them out
for (value <- anchorValues) if (!map.contains(value.anchor)) map += (value.anchor -> value)
map.values
}
// this is taken from expecty
private[this] def renderDiagram(sourceText: String, anchorValues: List[AnchorValue]): String = {
val offset = sourceText.prefixLength(_.isWhitespace)
val intro = new StringBuilder().append(sourceText.trim())
val lines = ListBuffer(new StringBuilder)
val rightToLeft = filterAndSortByAnchor(anchorValues)
for (anchorValue <- rightToLeft) placeValue(lines, anchorValue.value, anchorValue.anchor - offset)
lines.prepend(intro)
lines.append(new StringBuilder)
lines.mkString(Prettifier.lineSeparator)
}
/**
* Assert that the passed in <code>Bool</code> is <code>true</code>, else fail with <code>TestFailedException</code>
* with error message that include a diagram showing expression values.
*
* @param bool the <code>Bool</code> to assert for
* @param clue optional clue to be included in <code>TestFailedException</code>'s error message when assertion failed
*/
def macroAssert(bool: DiagrammedExpr[Boolean], clue: Any, sourceText: String, pos: source.Position): Assertion = {
requireNonNull(clue)
if (!bool.value) {
val failureMessage =
Some(clue.toString + Prettifier.lineSeparator + Prettifier.lineSeparator + renderDiagram(sourceText, bool.anchorValues))
throw newAssertionFailedException(failureMessage, None, pos, Vector.empty)
}
Succeeded
}
/**
* Assume that the passed in <code>Bool</code> is <code>true</code>, else throw <code>TestCanceledException</code>
* with error message that include a diagram showing expression values.
*
* @param bool the <code>Bool</code> to assume for
* @param clue optional clue to be included in <code>TestCanceledException</code>'s error message when assertion failed
*/
def macroAssume(bool: DiagrammedExpr[Boolean], clue: Any, sourceText: String, pos: source.Position): Assertion = {
requireNonNull(clue)
if (!bool.value) {
val failureMessage =
Some(clue.toString + Prettifier.lineSeparator + Prettifier.lineSeparator + renderDiagram(sourceText, bool.anchorValues))
throw newTestCanceledException(failureMessage, None, pos)
}
Succeeded
}
}
/**
* Helper instance used by code generated by the overriden macro assertion.
*/
val diagrammedAssertionsHelper = new DiagrammedAssertionsHelper
}