Skip to content

Commit 16f1d73

Browse files
committed
Added TypeCheckingExercises (using illTyped and assertTypeError)
1 parent b0af4c4 commit 16f1d73

File tree

3 files changed

+73
-1
lines changed

3 files changed

+73
-1
lines changed

src/main/scala/shapeless/ShapelessLib.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ object ShapelessLib extends exercise.Library {
2424
AutoTypeClassExercises,
2525
LazyExercises,
2626
SizedExercises,
27-
TypeSafeCastExercises
27+
TypeSafeCastExercises,
28+
TypeCheckingExercises
2829
)
2930
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package shapelessex
2+
3+
import org.scalatest.FlatSpec
4+
import org.scalatest.Matchers
5+
import org.scalatest._
6+
import shapeless._
7+
import shapelessex.TypeCheckingExercises._
8+
9+
import scala.util.Try
10+
11+
/** == Testing for non-compilation ==
12+
*
13+
* Libraries like shapeless which make extensive use of type-level computation and implicit resolution often need to
14+
* provide guarantees that certain expressions *don't* typecheck. Testing these guarantees is supported in shapeless via
15+
* the `illTyped` macro,
16+
* {{{
17+
* import shapeless.test.illTyped
18+
*
19+
* scala> illTyped { """1+1 : Boolean""" }
20+
*
21+
* scala> illTyped { """1+1 : Int""" }
22+
* <console>:19: error: Type-checking succeeded unexpectedly.
23+
* Expected some error.
24+
* illTyped { """1+1 : Int""" }
25+
* }}}
26+
*
27+
* @param name type_checking
28+
*/
29+
object TypeCheckingExercises extends FlatSpec with Matchers with exercise.Section {
30+
31+
/** The testing library ScalaTest also has a way of checking that a snippet of code
32+
* does not compile: pass it in to `assertTypeError`. What will happen if we combine
33+
* `illTyped` and `assertTypeError`? (Hint: it's like applying a double negative.)
34+
*/
35+
def typeCheckingTest(res0: Boolean, res1: Boolean) = {
36+
37+
import shapeless.test.illTyped
38+
39+
val matchedTypes = Try {
40+
assertTypeError("illTyped { \"val a: Int = 1\" }")
41+
true
42+
} getOrElse {
43+
false
44+
}
45+
matchedTypes should be(res0)
46+
47+
val mismatchedTypes = Try {
48+
assertTypeError("illTyped { \"val a: String = 1\" }")
49+
true
50+
} getOrElse {
51+
false
52+
}
53+
mismatchedTypes should be(res1)
54+
}
55+
56+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package test.scala.exercises.shapeless
2+
3+
import exercises.Test
4+
import shapelessex.TypeCheckingExercises
5+
6+
class TypeCheckingExercisesSpec extends Spec with Checkers {
7+
def `testing for non-compilation` = {
8+
check(
9+
Test.testSuccess(
10+
TypeCheckingExercises.typeCheckingTest _,
11+
true :: false :: HNil
12+
)
13+
)
14+
}
15+
}

0 commit comments

Comments
 (0)